Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 18 additions & 15 deletions vortex-cuda/kernels/src/alp.cu
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
// into shared memory before writing to global memory, mirroring the strategy
// used by bit_unpack. f = F10[exponents.f], e = IF10[exponents.e].
//
// Patch positions count from 1024-row chunks of the unsliced array, but `in` is already sliced, so
// blocks decode chunk-aligned rows shifted by `slice_shift`, the slice start modulo 1024. The
// caller trims the shift off the output.
//
// The cast from EncT to FloatT must preserve ALP's lossless contract: f32 is
// only encoded as i32, and f64 is only encoded as i64. The i64 → double cast
// is lossless for all values ALP can produce.
Expand All @@ -18,6 +22,7 @@ __device__ void alp_device(const EncT *__restrict in,
FloatT f,
FloatT e,
uint64_t array_len,
uint32_t slice_shift,
int thread_idx,
GPUPatches &patches) {
constexpr int ThreadCount = 32;
Expand All @@ -31,21 +36,21 @@ __device__ void alp_device(const EncT *__restrict in,
constexpr int per_thread = 1024 / ThreadCount;
uint64_t chunk_base = static_cast<uint64_t>(blockIdx.x) * 1024;

// Step 1: decode the chunk into shared memory. The tail block is bounds-checked;
// all interior blocks take the fast path with no per-element branch.
if (chunk_base + 1024 <= array_len) {
// Step 1: decode the chunk into shared memory. Full chunks of an unshifted array take the fast
// path with no per-element branch; the tail block and shifted arrays are bounds-checked.
if (slice_shift == 0 && chunk_base + 1024 <= array_len) {
#pragma unroll
for (int i = 0; i < per_thread; i++) {
int idx = i * ThreadCount + thread_idx;
shared_out[idx] = static_cast<FloatT>(in[idx]) * f * e;
shared_out[idx] = static_cast<FloatT>(in[chunk_base + idx]) * f * e;
}
} else {
#pragma unroll
for (int i = 0; i < per_thread; i++) {
int idx = i * ThreadCount + thread_idx;
uint64_t global_idx = chunk_base + static_cast<uint64_t>(idx);
if (global_idx < array_len) {
shared_out[idx] = static_cast<FloatT>(in[idx]) * f * e;
uint64_t aligned_row = chunk_base + static_cast<uint64_t>(idx);
if (aligned_row >= slice_shift && aligned_row - slice_shift < array_len) {
shared_out[idx] = static_cast<FloatT>(in[aligned_row - slice_shift]) * f * e;
} else {
shared_out[idx] = FloatT {};
}
Expand All @@ -63,13 +68,13 @@ __device__ void alp_device(const EncT *__restrict in,
__syncwarp();

// Step 3: coalesced write-out of the full 1024-element chunk. The caller
// allocates `full_out` rounded up to a multiple of 1024, so every block
// writes entirely within bounds. Positions in `[array_len, rounded_len)`
// of the tail chunk hold don't-care values; the caller slices them off.
// allocates `out` for every aligned row of every block, so each block writes
// entirely within bounds. Rows outside the slice hold don't-care values; the
// caller slices them off.
#pragma unroll
for (int i = 0; i < per_thread; i++) {
int idx = i * ThreadCount + thread_idx;
out[idx] = shared_out[idx];
out[chunk_base + idx] = shared_out[idx];
}
}

Expand All @@ -79,11 +84,9 @@ __device__ void alp_device(const EncT *__restrict in,
FloatT f, \
FloatT e, \
uint64_t array_len, \
uint32_t slice_shift, \
GPUPatches patches) { \
int thread_idx = threadIdx.x; \
auto in = full_in + (blockIdx.x * 1024); \
auto out = full_out + (blockIdx.x * 1024); \
alp_device<EncT, FloatT>(in, out, f, e, array_len, thread_idx, patches); \
alp_device<EncT, FloatT>(full_in, full_out, f, e, array_len, slice_shift, threadIdx.x, patches); \
}

// The only ALPInt bindings produced by the encoder are (f32, i32) and (f64, i64).
Expand Down
69 changes: 63 additions & 6 deletions vortex-cuda/src/kernel/encodings/alp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,6 @@ where
let device_input = ctx.ensure_on_device(buffer)?;
let input_view = device_input.cuda_view::<A::ALPInt>()?;

// Allocate output rounded up to a full chunk: the fused kernel writes a
// whole 1024-element chunk per block, and we slice off any padding below.
let mut output_slice = ctx.device_alloc::<A>(array_len.next_multiple_of(1024))?;

// Patch validity does not need to be scattered: the ALP encoder strips null
// positions from the exception list, so patches only exist at valid
// positions. load_device_patches additionally rejects patches without
Expand All @@ -98,26 +94,36 @@ where
};
let patches_arg = build_gpu_patches(device_patches.as_ref(), ctx.stream())?;

// The kernel decodes chunk-aligned rows to match the patch positions, writing a whole chunk
// per block; the shift is trimmed off below.
let slice_shift = device_patches
.as_ref()
.map_or(0, |patches| patches.offset % 1024);
let aligned_len = array_len + slice_shift;
let mut output_slice = ctx.device_alloc::<A>(aligned_len.next_multiple_of(1024))?;

// Load the kernel: alp_{enc}_{float}_32t
let enc_suffix = A::ALPInt::PTYPE.to_string();
let float_suffix = A::PTYPE.to_string();
let cuda_function = ctx
.load_function_with_suffixes("alp", &[enc_suffix.as_str(), float_suffix.as_str(), "32t"])?;

let num_blocks = u32::try_from(array_len.div_ceil(1024))?;
let num_blocks = u32::try_from(aligned_len.div_ceil(1024))?;
let config = LaunchConfig {
grid_dim: (num_blocks, 1, 1),
block_dim: (ALP_THREADS_PER_BLOCK, 1, 1),
shared_mem_bytes: 0,
};

let array_len_u64 = array_len as u64;
let slice_shift_u32 = u32::try_from(slice_shift)?;
ctx.launch_kernel_config(&cuda_function, config, array_len, |args| {
args.arg(&input_view)
.arg(&mut output_slice)
.arg(&f)
.arg(&e)
.arg(&array_len_u64)
.arg(&slice_shift_u32)
.arg(&patches_arg);
})?;

Expand All @@ -126,7 +132,8 @@ where
drop(device_patches);

let output_buf = CudaDeviceBuffer::new(output_slice)?;
let output_handle = BufferHandle::new_device(output_buf.slice_typed::<A>(0..array_len));
let output_handle =
BufferHandle::new_device(output_buf.slice_typed::<A>(slice_shift..aligned_len));
Ok(Canonical::Primitive(PrimitiveArray::from_buffer_handle(
output_handle,
A::PTYPE,
Expand All @@ -138,11 +145,13 @@ where
mod tests {
use std::f32;
use std::f64;
use std::ops::Range;
use std::sync::LazyLock;

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::patches::Patches;
use vortex::array::validity::Validity;
Expand Down Expand Up @@ -387,6 +396,54 @@ mod tests {
Ok(())
}

#[rstest]
#[case::inside_a_chunk(5..1000)]
#[case::across_a_boundary(1000..1100)]
#[case::from_a_chunk_start(1024..2048)]
#[case::tail(2000..3072)]
#[crate::test]
async fn test_cuda_alp_sliced_with_patches(#[case] range: Range<usize>) -> 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 values: Buffer<f64> = (0u32..3072)
.map(|i| {
if matches!(i, 5 | 500 | 1023 | 1024 | 1050 | 2100 | 3071) {
UNENCODABLE
} else {
i as f64
}
})
.collect();
let prim = PrimitiveArray::new(values, Validity::NonNullable);
let alp_array = alp_encode(prim.as_view(), None, &mut ctx)?;
let expected = prim.into_array().slice(range.clone())?;

// `slice` is lazy, so build the sliced ALP array the kernel receives directly.
let sliced = <ALP as SliceKernel>::slice(alp_array.as_view(), range.clone(), &mut ctx)?
.vortex_expect("ALP always slices itself");
let gpu_result = ALPExecutor
.execute(sliced, &mut cuda_ctx)
.await?
.into_host(cuda_ctx.execution_ctx())
.await?
.into_array();
assert_arrays_eq!(gpu_result, expected, &mut ctx);

// Scans pass the lazy slice instead.
let lazy_result = alp_array
.into_array()
.slice(range)?
.execute_cuda(&mut cuda_ctx)
.await?
.into_host(cuda_ctx.execution_ctx())
.await?
.into_array();
assert_arrays_eq!(lazy_result, expected, &mut ctx);
Ok(())
}

/// Single chunk with more patches than threads per block (32). Forces
/// `PatchesCursor` to split patches across multiple threads, exercising
/// the per-thread ceil-division and clamping math that no other test hits
Expand Down