diff --git a/vortex-cuda/src/kernel/encodings/bitpacked.rs b/vortex-cuda/src/kernel/encodings/bitpacked.rs index c3314dae5b4..9057832a8f3 100644 --- a/vortex-cuda/src/kernel/encodings/bitpacked.rs +++ b/vortex-cuda/src/kernel/encodings/bitpacked.rs @@ -202,7 +202,7 @@ where let device_patches = if let Some(patches) = patches { let mut device_patches = load_device_patches(&patches, ctx).await?; if let Some(range) = patch_range { - slice_device_patches(&patches, range, &mut device_patches); + slice_device_patches(range, &mut device_patches).await?; } Some(device_patches) } else { @@ -243,6 +243,7 @@ mod tests { use rstest::rstest; use vortex::array::IntoArray; use vortex::array::arrays::PrimitiveArray; + use vortex::array::arrays::slice::SliceKernel; use vortex::array::assert_arrays_eq; use vortex::array::dtype::NativePType; use vortex::array::optimizer::ArrayOptimizer; @@ -785,4 +786,66 @@ mod tests { Ok(()) } + + /// Decode a lazy slice of a BitPacked array whose patches were already sliced on the CPU, + /// exercising `load_device_patches` + `slice_device_patches` end to end on CUDA. + #[rstest] + #[case::same_chunk_nonzero_within(100..3000, 150..800)] + #[case::cross_chunk_nonzero_base_and_within(1200..4500, 1000..2200)] + #[case::cross_chunk_aligned_boundary(1200..4500, 848..1872)] + #[crate::test] + fn test_cuda_bitunpack_gpu_slice_of_cpu_sliced_patches( + #[case] cpu_range: Range, + #[case] gpu_range: Range, + ) -> VortexResult<()> { + let mut ctx = SESSION.create_execution_ctx(); + let mut cuda_ctx = CudaSession::create_execution_ctx(&crate::cuda_session()) + .vortex_expect("failed to create execution context"); + + let patch_positions = [ + 50usize, 200, 900, 1050, 1500, 1900, 2100, 2600, 3100, 4100, 4900, + ]; + let values: Buffer = (0u32..5120) + .map(|i| { + if patch_positions.contains(&(i as usize)) { + 1000 + i + } else { + i % 512 + } + }) + .collect(); + let bitpacked = BitPacked::encode( + &PrimitiveArray::new(values, NonNullable).into_array(), + 9, + &mut ctx, + )?; + + // First slice pushed into BitPacked on CPU so its Patches have nonzero offset / base. + let cpu_sliced = + ::slice(bitpacked.as_view(), cpu_range, &mut ctx)? + .vortex_expect("BitPacked SliceKernel should slice patched array"); + let cpu_bp = cpu_sliced.as_::(); + let cpu_patches = cpu_bp + .patches() + .vortex_expect("CPU-sliced BitPacked should retain patches"); + assert!(cpu_patches.offset() > 0); + assert!(cpu_patches.offset_within_chunk().unwrap_or_default() > 0); + + // Second slice stays lazy so BitPackedExecutor routes it through slice_device_patches. + let gpu_sliced = cpu_sliced.slice(gpu_range)?; + + let gpu_result = block_on(async { + BitPackedExecutor + .execute(gpu_sliced.clone(), &mut cuda_ctx) + .await + .vortex_expect("GPU decompression failed") + .into_host(cuda_ctx.execution_ctx()) + .await + .map(|a| a.into_array()) + })?; + + assert_arrays_eq!(gpu_result, gpu_sliced, &mut ctx); + + Ok(()) + } } diff --git a/vortex-cuda/src/kernel/patches/types.rs b/vortex-cuda/src/kernel/patches/types.rs index b4a969223db..64062f768af 100644 --- a/vortex-cuda/src/kernel/patches/types.rs +++ b/vortex-cuda/src/kernel/patches/types.rs @@ -11,6 +11,7 @@ use vortex::array::buffer::BufferHandle; use vortex::buffer::Alignment; use vortex::buffer::Buffer; use vortex::buffer::BufferMut; +use vortex::buffer::ByteBuffer; use vortex::buffer::ByteBufferMut; use vortex::dtype::PType; use vortex_array::match_each_unsigned_integer_ptype; @@ -18,6 +19,8 @@ use vortex_array::patches::PATCH_CHUNK_SIZE; use vortex_array::patches::Patches; use vortex_error::VortexResult; use vortex_error::vortex_bail; +use vortex_error::vortex_ensure; +use vortex_error::vortex_err; use crate::CudaBufferExt; use crate::CudaExecutionCtx; @@ -41,6 +44,51 @@ pub struct DevicePatches { pub(crate) indices_base: Option, } +fn decode_first_chunk_offset(buf: &ByteBuffer, ptype: PType) -> VortexResult { + if buf.is_empty() { + return Ok(0); + } + let width = ptype.byte_width(); + vortex_ensure!( + buf.len() >= width, + "chunk_offsets buffer shorter than one {ptype} element" + ); + match ptype { + PType::U8 => Ok(usize::from(buf[0])), + PType::U16 => Ok(usize::from(u16::from_le_bytes([buf[0], buf[1]]))), + PType::U32 => usize::try_from(u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]])) + .map_err(|_| vortex_err!("chunk offset does not fit in usize")), + PType::U64 => { + let bytes: [u8; 8] = buf[..8] + .try_into() + .map_err(|_| vortex_err!("chunk_offsets buffer shorter than u64"))?; + usize::try_from(u64::from_le_bytes(bytes)) + .map_err(|_| vortex_err!("chunk offset does not fit in usize")) + } + _ => vortex_bail!("Invalid PType for chunk_offsets: {ptype:?}"), + } +} + +async fn read_first_chunk_offset( + chunk_offsets: &BufferHandle, + ptype: PType, + n_chunks: usize, +) -> VortexResult { + if n_chunks == 0 { + return Ok(0); + } + if let Some(host_buf) = chunk_offsets.as_host_opt() { + return decode_first_chunk_offset(host_buf, ptype); + } + let width = ptype.byte_width(); + vortex_ensure!( + chunk_offsets.len() >= width, + "chunk_offsets buffer shorter than one {ptype} element" + ); + let first_elem = chunk_offsets.slice(0..width).try_to_host()?.await?; + decode_first_chunk_offset(&first_elem, ptype) +} + /// Build [`DevicePatches`] from patches by ensuring their buffers are on GPU. /// /// This prepares `chunk_offsets`, `indices`, and `values` as device buffers and collects the @@ -102,6 +150,24 @@ pub(crate) async fn load_device_patches( .await? .into_primitive(); + // Capture `indices_base` for free while `chunk_offsets` is still on the host; device-resident + // `chunk_offsets` stay `None` so unsliced loads derive the base on the GPU and only + // `slice_device_patches` performs a 1-element D2H read. + let indices_base = if let Some(host_buf) = chunk_offsets.as_host_opt() { + let first_chunk_offset = if n_chunks == 0 { + 0 + } else { + decode_first_chunk_offset(host_buf, chunk_offset_ptype)? + }; + Some( + first_chunk_offset + .checked_add(offset_within_chunk) + .ok_or_else(|| vortex_err!("patch indices_base overflow"))?, + ) + } else { + None + }; + // Ensure all on device let chunk_offsets = ctx.ensure_on_device(chunk_offsets)?; let indices = ctx.ensure_on_device(indices)?; @@ -118,7 +184,7 @@ pub(crate) async fn load_device_patches( offset_within_chunk, num_patches, n_chunks, - indices_base: None, + indices_base, }) } @@ -166,8 +232,8 @@ fn build_gpu_patches( /// Transfers patches to the GPU and builds a [`GPUPatches`] descriptor. /// -/// With `patch_range`, slices only `chunk_offsets` and sets `indices_base` so the kernel can keep -/// using the original `indices` and `values` buffers without host metadata reads. +/// With `patch_range`, slices only `chunk_offsets` while preserving `indices_base` so the kernel +/// can keep using the original `indices` and `values` buffers without slicing them. /// /// Returns the device pointer and all buffer handles that must be kept alive for the kernel launch. pub(crate) async fn load_patches_to_gpu( @@ -178,7 +244,7 @@ pub(crate) async fn load_patches_to_gpu( let mut device_patches = load_device_patches(patches, ctx).await?; if let Some(patch_range) = patch_range { - slice_device_patches(patches, patch_range, &mut device_patches); + slice_device_patches(patch_range, &mut device_patches).await?; } let (gpu_buf, ptr) = build_gpu_patches(&device_patches, ctx)?; @@ -191,32 +257,62 @@ pub(crate) async fn load_patches_to_gpu( Ok((ptr, vec![chunk_offsets, indices, values, gpu_buf])) } -pub(crate) fn slice_device_patches( - patches: &Patches, +pub(crate) async fn slice_device_patches( patch_range: Range, device_patches: &mut DevicePatches, -) { - let offset = patches.offset() + patch_range.start; - let len = patch_range.len(); - let chunk_start = offset / PATCH_CHUNK_SIZE; - let chunk_end = offset.saturating_add(len).div_ceil(PATCH_CHUNK_SIZE); - let first_chunk = patches.offset() / PATCH_CHUNK_SIZE; - let start = chunk_start.saturating_sub(first_chunk); - let end = (chunk_end.saturating_sub(first_chunk) + 1).min(device_patches.n_chunks); +) -> VortexResult<()> { + let base_offset = device_patches.offset; + let offset = base_offset.saturating_add(patch_range.start); + + if patch_range.is_empty() { + device_patches.chunk_offsets = device_patches.chunk_offsets.slice(0..0); + device_patches.n_chunks = 0; + device_patches.num_patches = 0; + device_patches.offset = offset; + device_patches.offset_within_chunk = 0; + device_patches.indices_base = Some(0); + return Ok(()); + } + + let chunk_relative_offset = base_offset % PATCH_CHUNK_SIZE; + let start = chunk_relative_offset.saturating_add(patch_range.start) / PATCH_CHUNK_SIZE; + let chunk_end = chunk_relative_offset + .saturating_add(patch_range.end) + .div_ceil(PATCH_CHUNK_SIZE); + let end = chunk_end.saturating_add(1).min(device_patches.n_chunks); if start < end { + if device_patches.indices_base.is_none() { + let first_chunk_offset = read_first_chunk_offset( + &device_patches.chunk_offsets, + device_patches.chunk_offset_ptype, + device_patches.n_chunks, + ) + .await?; + let indices_base = first_chunk_offset + .checked_add(device_patches.offset_within_chunk) + .ok_or_else(|| vortex_err!("patch indices_base overflow"))?; + device_patches.indices_base = Some(indices_base); + } + let width = device_patches.chunk_offset_ptype.byte_width(); device_patches.chunk_offsets = device_patches .chunk_offsets .slice(start * width..end * width); device_patches.n_chunks = end - start; + } else { + device_patches.chunk_offsets = device_patches.chunk_offsets.slice(0..0); + device_patches.n_chunks = 0; + device_patches.num_patches = 0; + device_patches.indices_base = Some(0); } - // Keep indices/values unsliced. This is a conservative chunk-aligned - // patch view for lookup-style consumers: patches outside `patch_range` may be - // scanned, but their indices cannot match positions inside the range. + // Keep indices/values unsliced and preserve `indices_base` derived from the pre-slice + // first chunk offset. This is a conservative chunk-aligned patch view for lookup-style + // consumers: patches outside `patch_range` may be scanned, but their indices cannot match + // positions inside the range. device_patches.offset = offset; device_patches.offset_within_chunk = 0; - device_patches.indices_base = Some(0); + Ok(()) } #[cfg(test)] @@ -229,19 +325,44 @@ mod tests { use vortex::array::buffer::BufferHandle; use vortex::array::validity::Validity::NonNullable; use vortex::buffer::Buffer; + use vortex::buffer::ByteBuffer; + use vortex::dtype::PType; use vortex::session::VortexSession; + use vortex_array::ExecutionCtx; use vortex_array::IntoArray; use vortex_array::VortexSessionExecute; use vortex_array::arrays::PrimitiveArray; use vortex_array::patches::Patches; use vortex_error::VortexResult; + use vortex_error::vortex_err; + use super::decode_first_chunk_offset; use super::load_device_patches; use super::slice_device_patches; use crate::CudaSession; static SESSION: LazyLock = LazyLock::new(VortexSession::empty); + fn build_multi_chunk_patches(ctx: &mut ExecutionCtx) -> VortexResult { + let indices = PrimitiveArray::from_iter([ + 50u32, 200, 900, // chunk 0: 3 patches + 1050, 1500, 1900, // chunk 1: 3 patches + 2100, 2600, // chunk 2: 2 patches + 3100, // chunk 3: 1 patch + 4100, 4900, // chunk 4: 2 patches + ]); + let values = PrimitiveArray::from_iter([10u32, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]); + let chunk_offsets = PrimitiveArray::from_iter([0u32, 3, 6, 8, 9]); + Patches::new( + 5120, + 0, + indices.into_array(), + values.into_array(), + Some(chunk_offsets.into_array()), + ctx, + ) + } + #[test] fn test_patches_with_chunk_offsets() -> VortexResult<()> { let mut ctx = SESSION.create_execution_ctx(); @@ -266,6 +387,138 @@ mod tests { Ok(()) } + #[test] + fn test_decode_first_chunk_offset_widths() -> VortexResult<()> { + assert_eq!( + decode_first_chunk_offset(&ByteBuffer::empty(), PType::U32)?, + 0 + ); + assert_eq!( + decode_first_chunk_offset(&ByteBuffer::copy_from([7u8, 12]), PType::U8)?, + 7 + ); + assert_eq!( + decode_first_chunk_offset(&ByteBuffer::copy_from(300u16.to_le_bytes()), PType::U16)?, + 300 + ); + assert_eq!( + decode_first_chunk_offset(&ByteBuffer::copy_from(70_000u32.to_le_bytes()), PType::U32)?, + 70_000 + ); + assert_eq!( + decode_first_chunk_offset(&ByteBuffer::copy_from(90_000u64.to_le_bytes()), PType::U64)?, + 90_000 + ); + assert!(decode_first_chunk_offset(&ByteBuffer::copy_from([1u8, 2]), PType::U32).is_err()); + + Ok(()) + } + + #[rstest::rstest] + #[case::same_chunk_0_nonzero_within(100..3000, 150..800, false, 250, 1, vec![0, 3])] + #[case::same_chunk_1_nonzero_base_and_within(1200..4500, 400..1500, false, 1600, 4, vec![3, 6, 8])] + #[case::cross_chunk_host(1200..4500, 1000..2200, false, 2200, 4, vec![6, 8, 9])] + #[case::cross_chunk_device_chunk_offsets(1200..4500, 1000..2200, true, 2200, 4, vec![6, 8, 9])] + #[case::empty_slice(1200..4500, 400..400, false, 1600, 0, vec![])] + #[crate::test] + async fn test_slice_device_patches_cpu_sliced( + #[case] range1: Range, + #[case] range2: Range, + #[case] device_resident_chunk_offsets: bool, + #[case] expected_offset: usize, + #[case] expected_indices_base: usize, + #[case] expected_chunk_offsets: Vec, + ) -> VortexResult<()> { + let mut cuda_ctx = CudaSession::create_execution_ctx(&crate::cuda_session())?; + let orig = build_multi_chunk_patches(cuda_ctx.execution_ctx())?; + let cpu_sliced = orig + .slice(range1, cuda_ctx.execution_ctx())? + .ok_or_else(|| vortex_err!("first slice should retain patches"))?; + + let patches_to_load = if device_resident_chunk_offsets { + let co = cpu_sliced + .chunk_offsets() + .as_ref() + .ok_or_else(|| vortex_err!("expected chunk_offsets"))? + .clone() + .execute::(cuda_ctx.execution_ctx())?; + let device_co = PrimitiveArray::from_buffer_handle( + cuda_ctx.ensure_on_device(co.buffer_handle().clone())?, + co.ptype(), + NonNullable, + ) + .into_array(); + // SAFETY: `device_co` has identical length, dtype, and values to `cpu_sliced`'s + // chunk_offsets (only relocated to device memory), and all other fields are unchanged. + unsafe { + Patches::new_unchecked( + cpu_sliced.array_len(), + cpu_sliced.offset(), + cpu_sliced.indices().clone(), + cpu_sliced.values().clone(), + Some(device_co), + cpu_sliced.offset_within_chunk(), + ) + } + } else { + cpu_sliced + }; + + let mut device_patches = load_device_patches(&patches_to_load, &mut cuda_ctx).await?; + assert_eq!( + device_patches.indices_base.is_none(), + device_resident_chunk_offsets + ); + slice_device_patches(range2.clone(), &mut device_patches).await?; + + let chunk_offsets = + Buffer::::from_byte_buffer(device_patches.chunk_offsets.to_host().await); + assert_eq!(chunk_offsets.as_slice(), expected_chunk_offsets.as_slice()); + assert_eq!(device_patches.n_chunks, expected_chunk_offsets.len()); + assert_eq!(device_patches.offset, expected_offset); + assert_eq!(device_patches.offset_within_chunk, 0); + assert_eq!(device_patches.indices_base, Some(expected_indices_base)); + if range2.is_empty() { + assert_eq!(device_patches.num_patches, 0); + } + + Ok(()) + } + + #[crate::test] + async fn test_load_device_patches_nonzero_base_below_chunk_size() -> VortexResult<()> { + let mut cuda_ctx = CudaSession::create_execution_ctx(&crate::cuda_session())?; + let indices = PrimitiveArray::from_iter([200u32, 900, 1050, 1500, 1900]).into_array(); + let values = PrimitiveArray::from_iter([20u32, 30, 40, 50, 60]).into_array(); + let host_co = PrimitiveArray::from_iter([5u32, 8, 11]); + let device_co = PrimitiveArray::from_buffer_handle( + cuda_ctx.ensure_on_device(host_co.buffer_handle().clone())?, + PType::U32, + NonNullable, + ) + .into_array(); + + // Device-resident chunk_offsets with offset < PATCH_CHUNK_SIZE and nonzero base. + // SAFETY: `indices` is strictly sorted within `[100, 3000)` and matches `values` in + // length; `device_co` is a non-nullable monotonic u32 chunk_offsets array spanning the 3 + // chunks of `[100, 3000)` with `offset_within_chunk = 1`. + let patches = + unsafe { Patches::new_unchecked(2900, 100, indices, values, Some(device_co), Some(1)) }; + + let mut device_patches = load_device_patches(&patches, &mut cuda_ctx).await?; + assert_eq!(device_patches.indices_base, None); + + slice_device_patches(1000..2000, &mut device_patches).await?; + let chunk_offsets = + Buffer::::from_byte_buffer(device_patches.chunk_offsets.to_host().await); + assert_eq!(chunk_offsets.as_slice(), &[8u32, 11]); + assert_eq!(device_patches.offset, 1100); + assert_eq!(device_patches.offset_within_chunk, 0); + assert_eq!(device_patches.indices_base, Some(6)); + + Ok(()) + } + #[rstest::rstest] #[case::full_range(0..5120, 0, vec![0, 1, 2, 3, 4, 5])] #[case::single_first_chunk(0..1024, 0, vec![0, 1])] @@ -295,7 +548,7 @@ mod tests { )?; let mut device_patches = load_device_patches(&patches, &mut cuda_ctx).await?; - slice_device_patches(&patches, range, &mut device_patches); + slice_device_patches(range, &mut device_patches).await?; let chunk_offsets = Buffer::::from_byte_buffer(device_patches.chunk_offsets.to_host().await); @@ -340,7 +593,7 @@ mod tests { )?; let mut device_patches = load_device_patches(&patches, &mut cuda_ctx).await?; - slice_device_patches(&patches, 1024..3000, &mut device_patches); + slice_device_patches(1024..3000, &mut device_patches).await?; let actual = PrimitiveArray::from_buffer_handle( BufferHandle::new_host(device_patches.chunk_offsets.to_host().await),