-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathdynamic_dispatch_cuda.rs
More file actions
432 lines (366 loc) · 15.1 KB
/
dynamic_dispatch_cuda.rs
File metadata and controls
432 lines (366 loc) · 15.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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
#![allow(clippy::unwrap_used)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::expect_used)]
use std::mem::size_of;
use std::sync::Arc;
use std::time::Duration;
use criterion::BenchmarkId;
use criterion::Criterion;
use criterion::Throughput;
use cudarc::driver::CudaSlice;
use cudarc::driver::DevicePtr;
use cudarc::driver::LaunchConfig;
use cudarc::driver::PushKernelArg;
use cudarc::driver::sys::CUevent_flags;
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::NonNullable;
use vortex::buffer::Buffer;
use vortex::dtype::PType;
use vortex::encodings::alp::ALPArray;
use vortex::encodings::alp::ALPFloat;
use vortex::encodings::alp::Exponents;
use vortex::encodings::alp::alp_encode;
use vortex::encodings::fastlanes::BitPackedArray;
use vortex::encodings::fastlanes::FoRArray;
use vortex::encodings::runend::RunEndArray;
use vortex::error::VortexExpect;
use vortex::error::VortexResult;
use vortex::error::vortex_err;
use vortex::session::VortexSession;
use vortex_cuda::CudaDeviceBuffer;
use vortex_cuda::CudaExecutionCtx;
use vortex_cuda::CudaSession;
use vortex_cuda::dynamic_dispatch::CudaDispatchPlan;
use vortex_cuda::dynamic_dispatch::DispatchPlan;
use vortex_cuda::dynamic_dispatch::MaterializedPlan;
use vortex_cuda_macros::cuda_available;
use vortex_cuda_macros::cuda_not_available;
const BENCH_ARGS: &[(usize, &str)] = &[
(1_000_000, "1M"),
(10_000_000, "10M"),
(100_000_000, "100M"),
];
/// Launch the dynamic_dispatch kernel and return GPU-timed duration.
///
/// This deliberately does not use `CudaDispatchPlan::execute` because the
/// benchmark pre-allocates the output buffer and device plan once, then reuses
/// them across iterations.
fn run_timed(
cuda_ctx: &mut CudaExecutionCtx,
array_len: usize,
output_buf: &CudaDeviceBuffer,
device_plan: &Arc<CudaSlice<u8>>,
shared_mem_bytes: u32,
) -> VortexResult<Duration> {
let cuda_function = cuda_ctx.load_function("dynamic_dispatch", &[PType::U32])?;
let array_len_u64 = array_len as u64;
let output_view = output_buf.as_view::<u32>();
let (output_ptr, record_output) = output_view.device_ptr(cuda_ctx.stream());
let (plan_ptr, record_plan) = device_plan.device_ptr(cuda_ctx.stream());
let stream = cuda_ctx.stream();
let ctx = stream.context();
let start_event = ctx
.new_event(Some(CUevent_flags::CU_EVENT_BLOCKING_SYNC))
.map_err(|e| vortex_err!("{e:?}"))?;
start_event
.record(stream)
.map_err(|e| vortex_err!("{e:?}"))?;
let mut launch_builder = cuda_ctx.stream().launch_builder(&cuda_function);
launch_builder.arg(&output_ptr);
launch_builder.arg(&array_len_u64);
launch_builder.arg(&plan_ptr);
let num_blocks = array_len.div_ceil(2048) as u32;
let config = LaunchConfig {
grid_dim: (num_blocks, 1, 1),
block_dim: (64, 1, 1),
shared_mem_bytes,
};
unsafe {
launch_builder
.launch(config)
.map_err(|e| vortex_err!("kernel launch failed: {e}"))?;
}
drop((record_output, record_plan));
let stream = cuda_ctx.stream();
let ctx = stream.context();
let end_event = ctx
.new_event(Some(CUevent_flags::CU_EVENT_BLOCKING_SYNC))
.map_err(|e| vortex_err!("{e:?}"))?;
end_event.record(stream).map_err(|e| vortex_err!("{e:?}"))?;
let elapsed_ms = start_event
.elapsed_ms(&end_event)
.map_err(|e| vortex_err!("{e:?}"))?;
Ok(Duration::from_secs_f32(elapsed_ms / 1000.0))
}
/// Benchmark runner: builds a dynamic plan and launches the kernel.
struct BenchRunner {
_plan: CudaDispatchPlan,
smem_bytes: u32,
len: usize,
device_plan: Arc<CudaSlice<u8>>,
output_buf: CudaDeviceBuffer,
_plan_buffers: Vec<vortex::array::buffer::BufferHandle>,
}
impl BenchRunner {
fn new(array: &vortex::array::ArrayRef, len: usize, cuda_ctx: &CudaExecutionCtx) -> Self {
let plan = match DispatchPlan::new(array).vortex_expect("build_dyn_dispatch_plan") {
DispatchPlan::Fused(plan) => plan,
_ => unreachable!("encoding not fusable"),
};
let MaterializedPlan {
dispatch_plan,
device_buffers,
shared_mem_bytes,
} = plan.materialize(cuda_ctx).vortex_expect("materialize plan");
let device_plan = Arc::new(
cuda_ctx
.stream()
.clone_htod(dispatch_plan.as_bytes())
.expect("htod plan"),
);
Self {
_plan: dispatch_plan,
smem_bytes: shared_mem_bytes,
len,
device_plan,
output_buf: CudaDeviceBuffer::new(
cuda_ctx
.device_alloc::<u32>(len.next_multiple_of(1024))
.expect("alloc output"),
),
_plan_buffers: device_buffers,
}
}
fn run(&self, cuda_ctx: &mut CudaExecutionCtx) -> Duration {
cuda_ctx.stream().synchronize().unwrap();
run_timed(
cuda_ctx,
self.len,
&self.output_buf,
&self.device_plan,
self.smem_bytes,
)
.unwrap()
}
}
// ---------------------------------------------------------------------------
// Benchmark: FoR(BitPacked)
// ---------------------------------------------------------------------------
fn bench_for_bitpacked(c: &mut Criterion) {
let mut group = c.benchmark_group("for_bitpacked_6bw");
group.sample_size(10);
let bit_width: u8 = 6;
let reference = 100_000u32;
for (len, len_str) in BENCH_ARGS {
group.throughput(Throughput::Bytes((len * size_of::<u32>()) as u64));
// FoR(BitPacked): residuals 0..max_val, reference adds 100_000
let max_val = (1u64 << bit_width).saturating_sub(1);
let residuals: Vec<u32> = (0..*len)
.map(|i| (i as u64 % (max_val + 1)) as u32)
.collect();
let prim = PrimitiveArray::new(Buffer::from(residuals), NonNullable);
let bp = BitPackedArray::encode(&prim.into_array(), bit_width).vortex_expect("bitpack");
let for_arr =
FoRArray::try_new(bp.into_array(), Scalar::from(reference)).vortex_expect("for");
let array = for_arr.into_array();
group.bench_with_input(
BenchmarkId::new("dynamic_dispatch_u32", len_str),
len,
|b, &n| {
let mut cuda_ctx =
CudaSession::create_execution_ctx(&VortexSession::empty()).vortex_expect("ctx");
let bench_runner = BenchRunner::new(&array, n, &cuda_ctx);
b.iter_custom(|iters| {
let mut total_time = Duration::ZERO;
for _ in 0..iters {
total_time += bench_runner.run(&mut cuda_ctx);
}
total_time
});
},
);
}
group.finish();
}
// ---------------------------------------------------------------------------
// Benchmark: Dict(codes=BitPacked, values=Primitive)
// ---------------------------------------------------------------------------
fn bench_dict_bp_codes(c: &mut Criterion) {
let mut group = c.benchmark_group("dict_256vals_bp8bw_codes");
group.sample_size(10);
let dict_size: usize = 256;
let dict_bit_width: u8 = 8;
let dict_values: Vec<u32> = (0..dict_size as u32).map(|i| i * 1000 + 42).collect();
for (len, len_str) in BENCH_ARGS {
group.throughput(Throughput::Bytes((len * size_of::<u32>()) as u64));
let codes: Vec<u32> = (0..*len).map(|i| (i % dict_size) as u32).collect();
let codes_prim = PrimitiveArray::new(Buffer::from(codes), NonNullable);
let codes_bp = BitPackedArray::encode(&codes_prim.into_array(), dict_bit_width)
.vortex_expect("bitpack codes");
let values_prim = PrimitiveArray::new(Buffer::from(dict_values.clone()), NonNullable);
let dict = DictArray::new(codes_bp.into_array(), values_prim.into_array());
let array = dict.into_array();
group.bench_with_input(
BenchmarkId::new("dynamic_dispatch_u32", len_str),
len,
|b, &n| {
let mut cuda_ctx =
CudaSession::create_execution_ctx(&VortexSession::empty()).vortex_expect("ctx");
let bench_runner = BenchRunner::new(&array, n, &cuda_ctx);
b.iter_custom(|iters| {
let mut total_time = Duration::ZERO;
for _ in 0..iters {
total_time += bench_runner.run(&mut cuda_ctx);
}
total_time
});
},
);
}
group.finish();
}
// ---------------------------------------------------------------------------
// Benchmark: RunEnd(ends=Prim, values=Prim)
// ---------------------------------------------------------------------------
fn bench_runend(c: &mut Criterion) {
let mut group = c.benchmark_group("runend_100runs");
group.sample_size(10);
let num_runs: usize = 100;
for (len, len_str) in BENCH_ARGS {
group.throughput(Throughput::Bytes((len * size_of::<u32>()) as u64));
let run_len = *len / num_runs;
let ends: Vec<u32> = (1..=num_runs).map(|i| (i * run_len) as u32).collect();
let values: Vec<u32> = (0..num_runs).map(|i| (i * 7 + 42) as u32).collect();
let ends_arr = PrimitiveArray::new(Buffer::from(ends), NonNullable).into_array();
let values_arr = PrimitiveArray::new(Buffer::from(values), NonNullable).into_array();
let re = RunEndArray::new(ends_arr, values_arr);
let array = re.into_array();
group.bench_with_input(
BenchmarkId::new("dynamic_dispatch_u32", len_str),
len,
|b, &n| {
let mut cuda_ctx =
CudaSession::create_execution_ctx(&VortexSession::empty()).vortex_expect("ctx");
let bench_runner = BenchRunner::new(&array, n, &cuda_ctx);
b.iter_custom(|iters| {
let mut total_time = Duration::ZERO;
for _ in 0..iters {
total_time += bench_runner.run(&mut cuda_ctx);
}
total_time
});
},
);
}
group.finish();
}
// ---------------------------------------------------------------------------
// Benchmark: Dict(codes=BitPacked, values=FoR(BitPacked))
// ---------------------------------------------------------------------------
fn bench_dict_bp_codes_bp_for_values(c: &mut Criterion) {
let mut group = c.benchmark_group("dict_64vals_bp6bw_codes_for_bp6bw_values");
group.sample_size(10);
let dict_size: usize = 64;
let dict_bit_width: u8 = 6;
let dict_reference = 1_000_000u32;
let codes_bit_width: u8 = 6;
// Dict values: residuals 0..63 bitpacked, FoR adds 1_000_000
let dict_residuals: Vec<u32> = (0..dict_size as u32).collect();
let dict_prim = PrimitiveArray::new(Buffer::from(dict_residuals), NonNullable);
let dict_bp = BitPackedArray::encode(&dict_prim.into_array(), dict_bit_width)
.vortex_expect("bitpack dict");
let dict_for = FoRArray::try_new(dict_bp.into_array(), Scalar::from(dict_reference))
.vortex_expect("for dict");
for (len, len_str) in BENCH_ARGS {
group.throughput(Throughput::Bytes((len * size_of::<u32>()) as u64));
let codes: Vec<u32> = (0..*len).map(|i| (i % dict_size) as u32).collect();
let codes_prim = PrimitiveArray::new(Buffer::from(codes), NonNullable);
let codes_bp = BitPackedArray::encode(&codes_prim.into_array(), codes_bit_width)
.vortex_expect("bitpack codes");
let dict = DictArray::new(codes_bp.into_array(), dict_for.clone().into_array());
let array = dict.into_array();
group.bench_with_input(
BenchmarkId::new("dynamic_dispatch_u32", len_str),
len,
|b, &n| {
let mut cuda_ctx =
CudaSession::create_execution_ctx(&VortexSession::empty()).vortex_expect("ctx");
let bench_runner = BenchRunner::new(&array, n, &cuda_ctx);
b.iter_custom(|iters| {
let mut total_time = Duration::ZERO;
for _ in 0..iters {
total_time += bench_runner.run(&mut cuda_ctx);
}
total_time
});
},
);
}
group.finish();
}
// ---------------------------------------------------------------------------
// Benchmark: ALP(FoR(BitPacked)) for f32
// ---------------------------------------------------------------------------
fn bench_alp_for_bitpacked(c: &mut Criterion) {
let mut group = c.benchmark_group("alp_for_bp_6bw_f32");
group.sample_size(10);
let exponents = Exponents { e: 2, f: 0 };
let bit_width: u8 = 6;
for (len, len_str) in BENCH_ARGS {
group.throughput(Throughput::Bytes((len * size_of::<f32>()) as u64));
// Generate f32 values that ALP-encode without patches.
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), NonNullable);
// Encode: ALP → FoR → BitPacked
let alp = alp_encode(&float_prim, Some(exponents)).vortex_expect("alp_encode");
assert!(alp.patches().is_none());
let for_arr = FoRArray::encode(alp.encoded().to_primitive()).vortex_expect("for encode");
let bp =
BitPackedArray::encode(for_arr.encoded(), bit_width).vortex_expect("bitpack encode");
let tree = ALPArray::new(
FoRArray::try_new(bp.into_array(), for_arr.reference_scalar().clone())
.vortex_expect("for_new")
.into_array(),
exponents,
None,
);
let array = tree.into_array();
group.bench_with_input(
BenchmarkId::new("dynamic_dispatch_f32", len_str),
len,
|b, &n| {
let mut cuda_ctx =
CudaSession::create_execution_ctx(&VortexSession::empty()).vortex_expect("ctx");
let bench_runner = BenchRunner::new(&array, n, &cuda_ctx);
b.iter_custom(|iters| {
let mut total_time = Duration::ZERO;
for _ in 0..iters {
total_time += bench_runner.run(&mut cuda_ctx);
}
total_time
});
},
);
}
group.finish();
}
fn benchmark_dynamic_dispatch(c: &mut Criterion) {
bench_for_bitpacked(c);
bench_dict_bp_codes(c);
bench_runend(c);
bench_dict_bp_codes_bp_for_values(c);
bench_alp_for_bitpacked(c);
}
criterion::criterion_group!(benches, benchmark_dynamic_dispatch);
#[cuda_available]
criterion::criterion_main!(benches);
#[cuda_not_available]
fn main() {}