-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel_grid_stride.zig
More file actions
82 lines (74 loc) Β· 2.56 KB
/
kernel_grid_stride.zig
File metadata and controls
82 lines (74 loc) Β· 2.56 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
// kernels/grid_stride_demo.zig β Demo kernel showcasing Phase 3 high-level abstractions
//
// Demonstrates:
// 1. gridStrideLoop() β automatic work distribution
// 2. shared Vec3 types β host/device compatible
// 3. Fast math intrinsics β __fmaf_rn, rsqrtf
const cuda = @import("zcuda_kernel");
// ββ Grid-Stride Vector Scale ββ
// Scales every element in an array by a constant factor.
// Uses gridStrideLoop so a single kernel launch handles any array size.
export fn vectorScale(
data: [*]f32,
scale: f32,
n: u32,
) callconv(.kernel) void {
var iter = cuda.types.gridStrideLoop(n);
while (iter.next()) |i| {
data[i] = data[i] * scale;
}
}
// ββ SAXPY via FMA ββ
// y[i] = a * x[i] + y[i] β the classic BLAS Level-1 operation.
// Uses __fmaf_rn for fused multiply-add (single PTX instruction).
export fn saxpy(
x: [*]const f32,
y: [*]f32,
a: f32,
n: u32,
) callconv(.kernel) void {
var iter = cuda.types.gridStrideLoop(n);
while (iter.next()) |i| {
y[i] = cuda.__fmaf_rn(a, x[i], y[i]);
}
}
// ββ Vec3 Normalize ββ
// Normalizes an array of Vec3 vectors to unit length.
// Uses rsqrtf for fast reciprocal square root.
export fn vec3Normalize(
vectors: [*]cuda.shared.Vec3,
n: u32,
) callconv(.kernel) void {
var iter = cuda.types.gridStrideLoop(n);
while (iter.next()) |i| {
const v = vectors[i];
const len_sq = cuda.shared.Vec3.dot(v, v);
const inv_len = cuda.rsqrtf(len_sq);
vectors[i] = cuda.shared.Vec3.scale(v, inv_len);
}
}
// ββ Dot Product Reduction (Warp-level) ββ
// Computes dot product of two arrays using warp shuffle reduction.
export fn dotProduct(
a: [*]const f32,
b: [*]const f32,
result: *f32,
n: u32,
) callconv(.kernel) void {
var sum: f32 = 0.0;
// Grid-stride accumulation
var iter = cuda.types.gridStrideLoop(n);
while (iter.next()) |i| {
sum = cuda.__fmaf_rn(a[i], b[i], sum);
}
// Warp-level reduction via shuffle
sum += @bitCast(cuda.__shfl_down_sync(cuda.FULL_MASK, @bitCast(sum), 16, 32));
sum += @bitCast(cuda.__shfl_down_sync(cuda.FULL_MASK, @bitCast(sum), 8, 32));
sum += @bitCast(cuda.__shfl_down_sync(cuda.FULL_MASK, @bitCast(sum), 4, 32));
sum += @bitCast(cuda.__shfl_down_sync(cuda.FULL_MASK, @bitCast(sum), 2, 32));
sum += @bitCast(cuda.__shfl_down_sync(cuda.FULL_MASK, @bitCast(sum), 1, 32));
// Thread 0 of each warp atomically adds to the result
if (cuda.threadIdx().x % 32 == 0) {
_ = cuda.atomicAdd(result, sum);
}
}