-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathmod.rs
More file actions
2043 lines (1742 loc) · 74.1 KB
/
mod.rs
File metadata and controls
2043 lines (1742 loc) · 74.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
//! Host interface for dynamic CUDA kernel dispatch.
//!
//! [`DispatchPlan::new`] walks an encoding tree (e.g., `ALP(FoR(BitPacked))`)
//! in a single pass and returns one of three variants:
//!
//! - [`Fused`](DispatchPlan::Fused) — call [`FusedPlan::materialize`].
//! - [`PartiallyFused`](DispatchPlan::PartiallyFused) — execute pending
//! subtrees, then call [`FusedPlan::materialize_with_subtrees`].
//! - [`Unfused`](DispatchPlan::Unfused) — fall back to single-kernel dispatch.
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(clippy::cast_possible_truncation)]
use std::borrow::Borrow;
use std::mem::size_of;
use std::sync::Arc;
use cudarc::driver::DevicePtr;
use cudarc::driver::LaunchConfig;
use cudarc::driver::PushKernelArg;
use vortex::array::Canonical;
use vortex::array::IntoArray;
use vortex::array::arrays::ConstantArray;
use vortex::array::arrays::PrimitiveArray;
use vortex::array::buffer::BufferHandle;
use vortex::array::buffer::DeviceBufferExt;
use vortex::array::match_each_unsigned_integer_ptype;
use vortex::array::scalar::Scalar;
use vortex::array::validity::Validity;
use vortex::buffer::Alignment;
use vortex::buffer::ByteBuffer;
use vortex::buffer::ByteBufferMut;
use vortex::dtype::DType;
use vortex::dtype::Nullability;
use vortex::dtype::PType;
use vortex::error::VortexResult;
use vortex::error::vortex_bail;
use vortex::error::vortex_err;
use crate::CudaDeviceBuffer;
use crate::executor::CudaExecutionCtx;
pub(crate) mod plan_builder;
pub use plan_builder::DispatchPlan;
pub use plan_builder::FusedPlan;
pub use plan_builder::MaterializedPlan;
include!(concat!(env!("OUT_DIR"), "/dynamic_dispatch.rs"));
/// Convert a Rust `PType` to the C `PTypeTag` constant.
pub fn ptype_to_tag(ptype: PType) -> PTypeTag {
match ptype {
PType::U8 => PTypeTag_PTYPE_U8,
PType::U16 => PTypeTag_PTYPE_U16,
PType::U32 => PTypeTag_PTYPE_U32,
PType::U64 => PTypeTag_PTYPE_U64,
PType::I8 => PTypeTag_PTYPE_I8,
PType::I16 => PTypeTag_PTYPE_I16,
PType::I32 => PTypeTag_PTYPE_I32,
PType::I64 => PTypeTag_PTYPE_I64,
PType::F16 => unreachable!("F16 is not supported by CUDA dynamic dispatch"),
PType::F32 => PTypeTag_PTYPE_F32,
PType::F64 => PTypeTag_PTYPE_F64,
}
}
/// Convert a C `PTypeTag` back to a Rust `PType`.
pub fn tag_to_ptype(tag: PTypeTag) -> PType {
match tag {
PTypeTag_PTYPE_U8 => PType::U8,
PTypeTag_PTYPE_U16 => PType::U16,
PTypeTag_PTYPE_U32 => PType::U32,
PTypeTag_PTYPE_U64 => PType::U64,
PTypeTag_PTYPE_I8 => PType::I8,
PTypeTag_PTYPE_I16 => PType::I16,
PTypeTag_PTYPE_I32 => PType::I32,
PTypeTag_PTYPE_I64 => PType::I64,
PTypeTag_PTYPE_F32 => PType::F32,
PTypeTag_PTYPE_F64 => PType::F64,
_ => unreachable!("unknown PTypeTag {tag}"),
}
}
/// Serialize a `#[repr(C)]` struct to a byte vector for the packed plan.
///
/// Copies field data into a pre-zeroed buffer so padding holes are
/// deterministically zero, avoiding UB from reading uninitialised bytes.
fn as_bytes<T: Sized>(val: &T) -> Vec<u8> {
let n = size_of::<T>();
let mut buf = vec![0u8; n];
// SAFETY: T is a bindgen-generated #[repr(C)] struct with only
// integer/float/enum fields. We overwrite the zeroed buffer with
// the struct's bytes; padding holes keep their zero value.
unsafe {
std::ptr::copy_nonoverlapping(std::ptr::addr_of!(*val).cast::<u8>(), buf.as_mut_ptr(), n);
}
buf
}
/// A stage used to build a [`CudaDispatchPlan`] on the host side.
///
/// This is NOT a C ABI struct — it exists purely on the Rust side and is
/// serialized into the packed plan byte buffer by [`CudaDispatchPlan::new`].
#[derive(Clone)]
pub struct MaterializedStage {
/// Device pointer to the input buffer for this stage.
pub input_ptr: u64,
/// Byte offset into shared memory where this stage's data is stored.
pub smem_byte_offset: u32,
/// Number of elements in this stage.
pub len: u32,
/// PType tag for the source op's output type.
pub source_ptype: PTypeTag,
/// The source operation that produces the initial values (e.g. load, bitunpack, sequence).
pub source: SourceOp,
/// Chain of element-wise scalar operations applied after the source (e.g. frame-of-reference, zigzag, ALP).
pub scalar_ops: Vec<ScalarOp>,
}
impl MaterializedStage {
pub fn new(
input_ptr: u64,
smem_byte_offset: u32,
len: u32,
source_ptype: PTypeTag,
source: SourceOp,
scalar_ops: &[ScalarOp],
) -> Self {
Self {
input_ptr,
smem_byte_offset,
len,
source_ptype,
source,
scalar_ops: scalar_ops.to_vec(),
}
}
}
/// Read-only view of a parsed stage from a [`CudaDispatchPlan`].
///
/// Returned by [`CudaDispatchPlan::stage`] for test inspection.
#[derive(Clone)]
pub struct ParsedStage {
pub input_ptr: u64,
pub smem_byte_offset: u32,
pub len: u32,
pub source_ptype: PTypeTag,
pub source: SourceOp,
pub num_scalar_ops: u8,
pub scalar_ops: Vec<ScalarOp>,
}
/// A dispatch plan serialized as a packed byte buffer.
///
/// Matching the C-side `PlanHeader` + `PackedStage` ABI in `dynamic_dispatch.h`:
///
/// ```text
/// [PlanHeader] — sizeof(PlanHeader) bytes
/// [PackedStage 0][ScalarOp × N0] — variable
/// [PackedStage 1][ScalarOp × N1] — variable
/// ...
/// ```
#[derive(Clone)]
pub struct CudaDispatchPlan {
buffer: ByteBuffer,
}
impl CudaDispatchPlan {
/// Build a packed plan from a sequence of stages.
///
/// The last stage is the output pipeline; earlier stages are input stages.
///
/// # Panics
///
/// Panics if `stages` is empty or the serialized plan exceeds 65535 bytes.
pub fn new<I>(stages: I, output_ptype: PTypeTag) -> Self
where
I: IntoIterator,
I::Item: Borrow<MaterializedStage>,
{
let stages: Vec<MaterializedStage> =
stages.into_iter().map(|s| s.borrow().clone()).collect();
assert!(!stages.is_empty());
let header_size = size_of::<PlanHeader>();
let stage_header_size = size_of::<PackedStage>();
let scalar_op_size = size_of::<ScalarOp>();
// Calculate total size and validate.
let mut total_size = header_size;
for stage in &stages {
total_size += stage_header_size;
total_size += stage.scalar_ops.len() * scalar_op_size;
}
assert!(
total_size <= u16::MAX as usize,
"packed plan size {total_size} exceeds u16::MAX"
);
let mut buffer = ByteBufferMut::with_capacity_aligned(total_size, Alignment::of::<u32>());
let header = PlanHeader {
num_stages: stages.len() as u8,
output_ptype,
plan_size_bytes: total_size as u16,
};
buffer.extend_from_slice(&as_bytes(&header));
for stage in &stages {
let packed_stage = PackedStage {
input_ptr: stage.input_ptr,
smem_byte_offset: stage.smem_byte_offset,
len: stage.len,
source: stage.source,
num_scalar_ops: stage.scalar_ops.len() as u8,
source_ptype: stage.source_ptype,
};
buffer.extend_from_slice(&as_bytes(&packed_stage));
for op in &stage.scalar_ops {
buffer.extend_from_slice(&as_bytes(op));
}
}
assert_eq!(buffer.len(), total_size);
Self {
buffer: buffer.freeze(),
}
}
/// The raw packed plan bytes, ready for upload to the device.
pub fn as_bytes(&self) -> &[u8] {
self.buffer.as_ref()
}
/// Number of stages in the plan.
pub fn num_stages(&self) -> u8 {
self.header().num_stages
}
/// PType of the final output array.
pub fn output_ptype(&self) -> PType {
tag_to_ptype(self.header().output_ptype)
}
fn header(&self) -> PlanHeader {
unsafe { *self.buffer.as_ptr().cast() }
}
/// Parse and return a read-only view of the stage at `index`.
///
/// # Panics
///
/// Panics if `index >= num_stages()`.
pub fn stage(&self, index: usize) -> ParsedStage {
let header_size = size_of::<PlanHeader>();
let stage_header_size = size_of::<PackedStage>();
let scalar_op_size = size_of::<ScalarOp>();
let mut offset = header_size;
// Skip past stages before `index`.
for _ in 0..index {
assert!(offset + stage_header_size <= self.buffer.len());
let ps: PackedStage = unsafe { *self.buffer.as_ptr().add(offset).cast() };
offset += stage_header_size + ps.num_scalar_ops as usize * scalar_op_size;
}
assert!(offset + stage_header_size <= self.buffer.len());
let ps: PackedStage = unsafe { *self.buffer.as_ptr().add(offset).cast() };
offset += stage_header_size;
let mut scalar_ops = Vec::with_capacity(ps.num_scalar_ops as usize);
for _ in 0..ps.num_scalar_ops {
assert!(offset + scalar_op_size <= self.buffer.len());
let op: ScalarOp = unsafe { *self.buffer.as_ptr().add(offset).cast() };
scalar_ops.push(op);
offset += scalar_op_size;
}
ParsedStage {
input_ptr: ps.input_ptr,
smem_byte_offset: ps.smem_byte_offset,
len: ps.len,
source_ptype: ps.source_ptype,
source: ps.source,
num_scalar_ops: ps.num_scalar_ops,
scalar_ops,
}
}
}
impl SourceOp {
/// Unpack bit-packed data using FastLanes layout.
///
/// `element_offset` (0..1023) is the sub-block position within the first
/// FastLanes block. The device pointer already accounts for buffer slicing,
/// but sub-block alignment cannot be expressed as pointer arithmetic on
/// bit-packed data, so it is passed as a kernel parameter.
pub fn bitunpack(bit_width: u8, element_offset: u16) -> Self {
Self {
op_code: SourceOp_SourceOpCode_BITUNPACK,
params: SourceParams {
bitunpack: SourceParams_BitunpackParams {
bit_width,
element_offset: u32::from(element_offset),
},
},
}
}
/// Copy elements verbatim from global memory to shared memory.
pub fn load() -> Self {
Self {
op_code: SourceOp_SourceOpCode_LOAD,
params: unsafe { std::mem::zeroed() },
}
}
/// Decode run-end encoding.
///
/// # Arguments
///
/// * `ends_smem_byte_offset` - byte offset to decoded ends in smem
/// * `values_smem_byte_offset` - byte offset to decoded values in smem
/// * `num_runs` - number of runs (length of ends/values)
/// * `offset` - logical offset for sliced arrays
pub fn runend(
ends_smem_byte_offset: u32,
values_smem_byte_offset: u32,
num_runs: u64,
offset: u64,
) -> Self {
Self {
op_code: SourceOp_SourceOpCode_RUNEND,
params: SourceParams {
runend: SourceParams_RunEndParams {
ends_smem_byte_offset,
values_smem_byte_offset,
num_runs,
offset,
},
},
}
}
/// Generate a linear sequence: `value[i] = base + i * multiplier`.
/// Used for SequenceArray (e.g. monotonic run-end endpoints).
pub fn sequence(base: i64, multiplier: i64) -> Self {
Self {
op_code: SourceOp_SourceOpCode_SEQUENCE,
params: SourceParams {
sequence: SourceParams_SequenceParams { base, multiplier },
},
}
}
}
impl ScalarOp {
/// Frame-of-reference: add a constant.
pub fn frame_of_ref(reference: u64, output_ptype: PTypeTag) -> Self {
Self {
op_code: ScalarOp_ScalarOpCode_FOR,
output_ptype,
params: ScalarParams {
frame_of_ref: ScalarParams_FoRParams { reference },
},
}
}
/// Zigzag decode.
pub fn zigzag(output_ptype: PTypeTag) -> Self {
// SAFETY: Zigzag has no parameters; zeroed union is valid.
Self {
op_code: ScalarOp_ScalarOpCode_ZIGZAG,
output_ptype,
params: unsafe { std::mem::zeroed() },
}
}
/// ALP floating-point decode.
pub fn alp(f: f32, e: f32) -> Self {
Self {
op_code: ScalarOp_ScalarOpCode_ALP,
output_ptype: PTypeTag_PTYPE_F32,
params: ScalarParams {
alp: ScalarParams_AlpParams { f, e },
},
}
}
/// Dictionary gather: use current value as index into decoded values
/// in shared memory (populated by an earlier input stage).
pub fn dict(values_smem_byte_offset: u32, output_ptype: PTypeTag) -> Self {
Self {
op_code: ScalarOp_ScalarOpCode_DICT,
output_ptype,
params: ScalarParams {
dict: ScalarParams_DictParams {
values_smem_byte_offset,
},
},
}
}
}
impl MaterializedPlan {
pub fn execute(self, len: usize, ctx: &mut CudaExecutionCtx) -> VortexResult<Canonical> {
let output_ptype = self.dispatch_plan.output_ptype();
// All values are null — no need to touch the GPU.
if matches!(self.validity, Validity::AllInvalid) {
let dtype = DType::Primitive(output_ptype, Nullability::Nullable);
return ConstantArray::new(Scalar::null(dtype), len)
.into_array()
.to_canonical();
}
// The CUDA kernels are instantiated for unsigned integer types only;
// map signed/float ptypes to their same-width unsigned counterpart.
let unsigned_ptype = match output_ptype {
PType::U8 | PType::I8 => PType::U8,
PType::U16 | PType::I16 => PType::U16,
PType::U32 | PType::I32 | PType::F32 => PType::U32,
PType::U64 | PType::I64 => PType::U64,
other => vortex_bail!("dynamic dispatch does not support PType {:?}", other),
};
match_each_unsigned_integer_ptype!(unsigned_ptype, |T| {
self.execute_typed::<T>(output_ptype, len, ctx)
})
}
fn execute_typed<T>(
self,
output_ptype: PType,
len: usize,
ctx: &mut CudaExecutionCtx,
) -> VortexResult<Canonical>
where
T: cudarc::driver::DeviceRepr + vortex::dtype::NativePType,
{
let nullability = self.validity.nullability();
if len == 0 {
return Ok(Canonical::Primitive(PrimitiveArray::empty::<T>(
nullability,
)));
}
let output_buf = CudaDeviceBuffer::new(ctx.device_alloc::<T>(len.next_multiple_of(1024))?);
// Upload the packed plan bytes to the device.
let device_plan = Arc::new(
ctx.stream()
.clone_htod(self.dispatch_plan.as_bytes())
.map_err(|e| vortex_err!("copy plan to device: {e}"))?,
);
let cuda_function = ctx.load_function("dynamic_dispatch", &[T::PTYPE])?;
let num_blocks = u32::try_from(len.div_ceil(ELEMENTS_PER_BLOCK as usize))?;
let config = LaunchConfig {
grid_dim: (num_blocks, 1, 1),
block_dim: (BLOCK_SIZE, 1, 1),
shared_mem_bytes: self.shared_mem_bytes,
};
let output_ptr = output_buf.offset_ptr();
let plan_ptr = device_plan.device_ptr(ctx.stream()).0;
let array_len_u64 = len as u64;
ctx.launch_kernel_config(&cuda_function, config, len, |args| {
args.arg(&output_ptr);
args.arg(&array_len_u64);
args.arg(&plan_ptr);
})?;
Ok(Canonical::Primitive(PrimitiveArray::from_buffer_handle(
BufferHandle::new_device(output_buf.slice_typed::<T>(0..len)),
output_ptype,
self.validity,
)))
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use cudarc::driver::DevicePtr;
use cudarc::driver::LaunchConfig;
use cudarc::driver::PushKernelArg;
use rstest::rstest;
use vortex::array::IntoArray;
use vortex::array::ToCanonical;
use vortex::array::arrays::DictArray;
use vortex::array::arrays::PrimitiveArray;
use vortex::array::scalar::Scalar;
use vortex::array::validity::Validity;
use vortex::array::validity::Validity::NonNullable;
use vortex::buffer::Buffer;
use vortex::dtype::PType;
use vortex::encodings::alp::ALP;
use vortex::encodings::alp::ALPArrayExt;
use vortex::encodings::alp::ALPArraySlotsExt;
use vortex::encodings::alp::ALPFloat;
use vortex::encodings::alp::Exponents;
use vortex::encodings::alp::alp_encode;
use vortex::encodings::fastlanes::BitPacked;
use vortex::encodings::fastlanes::BitPackedArray;
use vortex::encodings::fastlanes::FoR;
use vortex::encodings::fastlanes::FoRArrayExt;
use vortex::encodings::runend::RunEnd;
use vortex::encodings::zigzag::ZigZag;
use vortex::error::VortexExpect;
use vortex::error::VortexResult;
use vortex::session::VortexSession;
use super::*;
use crate::CanonicalCudaExt;
use crate::CudaBufferExt;
use crate::CudaDeviceBuffer;
use crate::CudaExecutionCtx;
use crate::executor::CudaArrayExt;
use crate::hybrid_dispatch::try_gpu_dispatch;
use crate::session::CudaSession;
fn bitpacked_array_u32(bit_width: u8, len: usize) -> BitPackedArray {
let max_val = (1u64 << bit_width).saturating_sub(1);
let values: Vec<u32> = (0..len)
.map(|i| ((i as u64) % (max_val + 1)) as u32)
.collect();
let primitive = PrimitiveArray::new(Buffer::from(values), NonNullable);
BitPacked::encode(&primitive.into_array(), bit_width)
.vortex_expect("failed to create BitPacked array")
}
fn dispatch_plan(
array: &vortex::array::ArrayRef,
ctx: &CudaExecutionCtx,
) -> VortexResult<MaterializedPlan> {
match DispatchPlan::new(array)? {
DispatchPlan::Fused(plan) => plan.materialize(ctx),
_ => vortex_bail!("array encoding not fusable"),
}
}
#[crate::test]
fn test_max_scalar_ops() -> VortexResult<()> {
let bit_width: u8 = 6;
let len = 2050;
let references: [u32; 4] = [1, 2, 4, 8];
let total_reference: u32 = references.iter().sum();
let max_val = (1u64 << bit_width).saturating_sub(1);
let expected: Vec<u32> = (0..len)
.map(|i| ((i as u64) % (max_val + 1)) as u32 + total_reference)
.collect();
let bitpacked = bitpacked_array_u32(bit_width, len);
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let packed = bitpacked.packed().clone();
let device_input = futures::executor::block_on(cuda_ctx.ensure_on_device(packed))?;
let input_ptr = device_input.cuda_device_ptr()?;
let scalar_ops: Vec<ScalarOp> = references
.iter()
.map(|&r| ScalarOp::frame_of_ref(r as u64, PTypeTag_PTYPE_U32))
.collect();
let plan = CudaDispatchPlan::new(
[MaterializedStage::new(
input_ptr,
0,
len as u32,
PTypeTag_PTYPE_U32,
SourceOp::bitunpack(bit_width, 0),
&scalar_ops,
)],
PTypeTag_PTYPE_U32,
);
assert_eq!(plan.stage(0).num_scalar_ops, 4);
let actual = run_dynamic_dispatch_plan(&cuda_ctx, len, &plan, SMEM_TILE_SIZE * 4)?;
assert_eq!(actual, expected);
Ok(())
}
#[crate::test]
fn test_plan_structure() {
// Stage 0: input dict values (BP→FoR), 256 u32 elements → smem bytes [0..1024)
// Stage 1: output codes (BP→FoR→DICT), 1024 elements, gather from smem byte 0
let values_smem_bytes: u32 = 256 * 4; // 256 u32 elements × 4 bytes
let plan = CudaDispatchPlan::new(
[
MaterializedStage::new(
0xAAAA,
0,
256,
PTypeTag_PTYPE_U32,
SourceOp::bitunpack(4, 0),
&[ScalarOp::frame_of_ref(10, PTypeTag_PTYPE_U32)],
),
MaterializedStage::new(
0xBBBB,
values_smem_bytes,
1024,
PTypeTag_PTYPE_U32,
SourceOp::bitunpack(6, 0),
&[
ScalarOp::frame_of_ref(42, PTypeTag_PTYPE_U32),
ScalarOp::dict(0, PTypeTag_PTYPE_U32),
],
),
],
PTypeTag_PTYPE_U32,
);
assert_eq!(plan.num_stages(), 2);
// Input stage
let s0 = plan.stage(0);
assert_eq!(s0.smem_byte_offset, 0);
assert_eq!(s0.len, 256);
assert_eq!(s0.source_ptype, PTypeTag_PTYPE_U32);
assert_eq!(s0.input_ptr, 0xAAAA);
// Output stage
let s1 = plan.stage(1);
assert_eq!(s1.smem_byte_offset, values_smem_bytes);
assert_eq!(s1.len, SMEM_TILE_SIZE);
assert_eq!(s1.source_ptype, PTypeTag_PTYPE_U32);
assert_eq!(s1.input_ptr, 0xBBBB);
assert_eq!(s1.num_scalar_ops, 2);
assert_eq!(
unsafe { s1.scalar_ops[1].params.dict.values_smem_byte_offset },
0
);
}
/// Copy a raw u32 slice to device memory and return (device_ptr, handle).
fn copy_raw_to_device(
cuda_ctx: &CudaExecutionCtx,
data: &[u32],
) -> VortexResult<(u64, Arc<cudarc::driver::CudaSlice<u32>>)> {
let device_buf = Arc::new(cuda_ctx.stream().clone_htod(data).expect("htod"));
let (ptr, _) = device_buf.device_ptr(cuda_ctx.stream());
Ok((ptr, device_buf))
}
#[crate::test]
fn test_load_for_zigzag_alp() -> VortexResult<()> {
// Max scalar ops depth with LOAD source: LOAD → FoR → ZigZag → ALP
// (Exercises all four scalar op types without DICT)
let len = 2048;
let reference = 5u32;
let alp_f = 10.0f32;
let alp_e = 0.1f32;
let data: Vec<u32> = (0..len).map(|i| (i as u32) % 64).collect();
let expected: Vec<u32> = data
.iter()
.map(|&v| {
let after_for = v + reference;
let after_zz = (after_for >> 1) ^ (0u32.wrapping_sub(after_for & 1));
let float_val = (after_zz as i32) as f32 * alp_f * alp_e;
float_val.to_bits()
})
.collect();
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let (input_ptr, _di) = copy_raw_to_device(&cuda_ctx, &data)?;
let plan = CudaDispatchPlan::new(
[MaterializedStage::new(
input_ptr,
0,
len as u32,
PTypeTag_PTYPE_U32,
SourceOp::load(),
&[
ScalarOp::frame_of_ref(reference as u64, PTypeTag_PTYPE_U32),
ScalarOp::zigzag(PTypeTag_PTYPE_U32),
ScalarOp::alp(alp_f, alp_e),
],
)],
PTypeTag_PTYPE_U32,
);
let actual = run_dynamic_dispatch_plan(&cuda_ctx, len, &plan, SMEM_TILE_SIZE * 4)?;
assert_eq!(actual, expected);
Ok(())
}
/// Runs a dynamic dispatch plan on the GPU.
fn run_dynamic_dispatch_plan(
cuda_ctx: &CudaExecutionCtx,
output_len: usize,
plan: &CudaDispatchPlan,
shared_mem_bytes: u32,
) -> VortexResult<Vec<u32>> {
let output_slice = cuda_ctx
.device_alloc::<u32>(output_len)
.vortex_expect("alloc output");
let output_buf = CudaDeviceBuffer::new(output_slice);
let output_view = output_buf.as_view::<u32>();
let (output_ptr, record_output) = output_view.device_ptr(cuda_ctx.stream());
let device_plan = Arc::new(
cuda_ctx
.stream()
.clone_htod(plan.as_bytes())
.expect("copy plan to device"),
);
let (plan_ptr, record_plan) = device_plan.device_ptr(cuda_ctx.stream());
let array_len_u64 = output_len as u64;
cuda_ctx.stream().synchronize().expect("sync");
let cuda_function = cuda_ctx
.load_function("dynamic_dispatch", &[PType::U32])
.vortex_expect("load kernel");
let mut launch_builder = cuda_ctx.launch_builder(&cuda_function);
launch_builder.arg(&output_ptr);
launch_builder.arg(&array_len_u64);
launch_builder.arg(&plan_ptr);
let num_blocks = u32::try_from(output_len.div_ceil(ELEMENTS_PER_BLOCK as usize))?;
let config = LaunchConfig {
grid_dim: (num_blocks, 1, 1),
block_dim: (BLOCK_SIZE, 1, 1),
shared_mem_bytes,
};
unsafe {
launch_builder.launch(config).expect("kernel launch");
}
drop((record_output, record_plan));
Ok(cuda_ctx
.stream()
.clone_dtoh(&output_buf.as_view::<u32>())
.expect("copy back"))
}
fn run_dispatch_plan_f32(
cuda_ctx: &CudaExecutionCtx,
output_len: usize,
plan: &CudaDispatchPlan,
shared_mem_bytes: u32,
) -> VortexResult<Vec<f32>> {
let actual = run_dynamic_dispatch_plan(cuda_ctx, output_len, plan, shared_mem_bytes)?;
// SAFETY: f32 and u32 have identical size and alignment.
Ok(unsafe { std::mem::transmute::<Vec<u32>, Vec<f32>>(actual) })
}
#[crate::test]
fn test_bitpacked() -> VortexResult<()> {
let bit_width: u8 = 10;
let len = 3000;
let max_val = (1u64 << bit_width).saturating_sub(1);
let expected: Vec<u32> = (0..len)
.map(|i| ((i as u64) % (max_val + 1)) as u32)
.collect();
let bp = bitpacked_array_u32(bit_width, len);
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let plan = dispatch_plan(&bp.into_array(), &cuda_ctx)?;
let actual =
run_dynamic_dispatch_plan(&cuda_ctx, len, &plan.dispatch_plan, plan.shared_mem_bytes)?;
assert_eq!(actual, expected);
Ok(())
}
#[crate::test]
fn test_for_bitpacked() -> VortexResult<()> {
let bit_width: u8 = 6;
let len = 3000;
let reference = 42u32;
let max_val = (1u64 << bit_width).saturating_sub(1);
let raw: Vec<u32> = (0..len)
.map(|i| ((i as u64) % (max_val + 1)) as u32)
.collect();
let expected: Vec<u32> = raw.iter().map(|&v| v + reference).collect();
let bp = bitpacked_array_u32(bit_width, len);
let for_arr = FoR::try_new(bp.into_array(), Scalar::from(reference))?;
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let plan = dispatch_plan(&for_arr.into_array(), &cuda_ctx)?;
let actual =
run_dynamic_dispatch_plan(&cuda_ctx, len, &plan.dispatch_plan, plan.shared_mem_bytes)?;
assert_eq!(actual, expected);
Ok(())
}
#[crate::test]
fn test_runend() -> VortexResult<()> {
let ends: Vec<u32> = vec![1000, 2000, 3000];
let values: Vec<u32> = vec![10, 20, 30];
let len = 3000;
let mut expected = Vec::with_capacity(len);
for i in 0..len {
let run = ends.iter().position(|&e| (i as u32) < e).unwrap();
expected.push(values[run]);
}
let ends_arr = PrimitiveArray::new(Buffer::from(ends), NonNullable).into_array();
let values_arr = PrimitiveArray::new(Buffer::from(values), NonNullable).into_array();
let re = RunEnd::new(ends_arr, values_arr);
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let plan = dispatch_plan(&re.into_array(), &cuda_ctx)?;
let actual =
run_dynamic_dispatch_plan(&cuda_ctx, len, &plan.dispatch_plan, plan.shared_mem_bytes)?;
assert_eq!(actual, expected);
Ok(())
}
#[crate::test]
fn test_dict_for_bp_values_bp_codes() -> VortexResult<()> {
// Dict where both codes and values are BitPacked+FoR.
let dict_reference = 1_000_000u32;
let dict_residuals: Vec<u32> = (0..64).collect();
let dict_expected: Vec<u32> = dict_residuals.iter().map(|&r| r + dict_reference).collect();
let dict_size = dict_residuals.len();
let len = 3000;
let codes: Vec<u32> = (0..len).map(|i| (i % dict_size) as u32).collect();
let expected: Vec<u32> = codes.iter().map(|&c| dict_expected[c as usize]).collect();
// BitPack+FoR the dict values
let dict_prim = PrimitiveArray::new(Buffer::from(dict_residuals), NonNullable);
let dict_bp = BitPacked::encode(&dict_prim.into_array(), 6)?;
let dict_for = FoR::try_new(dict_bp.into_array(), Scalar::from(dict_reference))?;
// BitPack the codes
let codes_prim = PrimitiveArray::new(Buffer::from(codes), NonNullable);
let codes_bp = BitPacked::encode(&codes_prim.into_array(), 6)?;
let dict = DictArray::try_new(codes_bp.into_array(), dict_for.into_array())?;
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let plan = dispatch_plan(&dict.into_array(), &cuda_ctx)?;
let actual =
run_dynamic_dispatch_plan(&cuda_ctx, len, &plan.dispatch_plan, plan.shared_mem_bytes)?;
assert_eq!(actual, expected);
Ok(())
}
#[crate::test]
fn test_alp_for_bitpacked() -> VortexResult<()> {
// ALP(FoR(BitPacked)): encode each layer, then reassemble the tree
// bottom-up because encode() methods produce flat outputs.
let len = 3000;
let exponents = Exponents { e: 2, f: 0 };
let floats: Vec<f32> = (0..len)
.map(|i| <f32 as ALPFloat>::decode_single(10 + (i as i32 % 64), exponents))
.collect();
let float_prim = PrimitiveArray::new(Buffer::from(floats.clone()), NonNullable);
let alp = alp_encode(&float_prim, Some(exponents))?;
assert!(alp.patches().is_none());
let for_arr = FoR::encode(alp.encoded().to_primitive())?;
let bp = BitPacked::encode(for_arr.encoded(), 6)?;
let tree = ALP::new(
FoR::try_new(bp.into_array(), for_arr.reference_scalar().clone())?.into_array(),
exponents,
None,
);
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let plan = dispatch_plan(&tree.into_array(), &cuda_ctx)?;
let actual =
run_dispatch_plan_f32(&cuda_ctx, len, &plan.dispatch_plan, plan.shared_mem_bytes)?;
assert_eq!(actual, floats);
Ok(())
}
#[crate::test]
fn test_zigzag_bitpacked() -> VortexResult<()> {
// ZigZag(BitPacked): unpack then zigzag-decode.
let bit_width: u8 = 4;
let len = 3000;
let max_val = (1u64 << bit_width).saturating_sub(1);
let raw: Vec<u32> = (0..len)
.map(|i| ((i as u64) % (max_val + 1)) as u32)
.collect();
let expected: Vec<u32> = raw
.iter()
.map(|&v| (v >> 1) ^ (0u32.wrapping_sub(v & 1)))
.collect();
let prim = PrimitiveArray::new(Buffer::from(raw), NonNullable);
let bp = BitPacked::encode(&prim.into_array(), bit_width)?;
let zz = ZigZag::try_new(bp.into_array())?;
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let plan = dispatch_plan(&zz.into_array(), &cuda_ctx)?;
let actual =
run_dynamic_dispatch_plan(&cuda_ctx, len, &plan.dispatch_plan, plan.shared_mem_bytes)?;
assert_eq!(actual, expected);
Ok(())
}
#[crate::test]
fn test_for_runend() -> VortexResult<()> {
// FoR(RunEnd): expand runs then add constant.
let ends: Vec<u32> = vec![500, 1000, 1500, 2000, 2500, 3000];
let values: Vec<u32> = vec![1, 2, 3, 4, 5, 6];
let len = 3000;
let reference = 1000u32;
let mut expected = Vec::with_capacity(len);
for i in 0..len {
let run = ends.iter().position(|&e| (i as u32) < e).unwrap();
expected.push(values[run] + reference);
}
let ends_arr = PrimitiveArray::new(Buffer::from(ends), NonNullable).into_array();
let values_arr = PrimitiveArray::new(Buffer::from(values), NonNullable).into_array();
let re = RunEnd::new(ends_arr, values_arr);
let for_arr = FoR::try_new(re.into_array(), Scalar::from(reference))?;
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let plan = dispatch_plan(&for_arr.into_array(), &cuda_ctx)?;
let actual =
run_dynamic_dispatch_plan(&cuda_ctx, len, &plan.dispatch_plan, plan.shared_mem_bytes)?;
assert_eq!(actual, expected);
Ok(())
}
#[crate::test]
fn test_for_dict() -> VortexResult<()> {
// FoR(Dict(codes=Primitive, values=Primitive)): gather then add constant.
let dict_values: Vec<u32> = vec![100, 200, 300, 400];
let dict_size = dict_values.len();
let reference = 5000u32;
let len = 3000;
let codes: Vec<u32> = (0..len).map(|i| (i % dict_size) as u32).collect();
let expected: Vec<u32> = codes
.iter()
.map(|&c| dict_values[c as usize] + reference)
.collect();
let codes_prim = PrimitiveArray::new(Buffer::from(codes), NonNullable);
let values_prim = PrimitiveArray::new(Buffer::from(dict_values), NonNullable);
let dict = DictArray::try_new(codes_prim.into_array(), values_prim.into_array())?;
let for_arr = FoR::try_new(dict.into_array(), Scalar::from(reference))?;
let cuda_ctx = CudaSession::create_execution_ctx(&VortexSession::empty())?;
let plan = dispatch_plan(&for_arr.into_array(), &cuda_ctx)?;
let actual =
run_dynamic_dispatch_plan(&cuda_ctx, len, &plan.dispatch_plan, plan.shared_mem_bytes)?;
assert_eq!(actual, expected);
Ok(())
}
#[crate::test]
fn test_dict_for_bp_codes() -> VortexResult<()> {
// Dict(codes=FoR(BitPacked), values=primitive)
let dict_values: Vec<u32> = (0..8).map(|i| i * 1000 + 7).collect();
let dict_size = dict_values.len();
let len = 3000;
let codes: Vec<u32> = (0..len).map(|i| (i % dict_size) as u32).collect();
let expected: Vec<u32> = codes.iter().map(|&c| dict_values[c as usize]).collect();
// BitPack codes, then wrap in FoR (reference=0 so values unchanged)
let bit_width: u8 = 3;
let codes_prim = PrimitiveArray::new(Buffer::from(codes), NonNullable);
let codes_bp = BitPacked::encode(&codes_prim.into_array(), bit_width)?;
let codes_for = FoR::try_new(codes_bp.into_array(), Scalar::from(0u32))?;
let values_prim = PrimitiveArray::new(Buffer::from(dict_values), NonNullable);