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
//! Normalization CUDA kernel launchers
//!
//! Provides launchers for RMSNorm, LayerNorm and GroupNorm. One fatbin per op:
//! `norm_rms`, `norm_layer`, `norm_group`. Every kernel is instantiated for
//! f32, f64, f16, bf16, fp8_e4m3 and fp8_e5m2.
use cudarc::driver::PushKernelArg;
use cudarc::driver::safe::CudaContext;
use std::sync::Arc;
use super::loader::{
BLOCK_SIZE, get_kernel_function, get_or_load_module, kernel_name, kernel_names, launch_config,
};
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::runtime::cuda::GuardedStream;
/// Elements per thread the register-cached RMSNorm kernel holds.
///
/// Must stay equal to `NORM_MAX_REGS_PER_THREAD` in `kernels/rms_norm_regs.cuh`;
/// the gate below is what keeps the launch inside the kernel's register array.
const NORM_MAX_REGS_PER_THREAD: usize = 32;
/// Threads per row for the RMSNorm kernels.
///
/// A function of the row width only, never of the batch, so a row normalizes
/// to the same bits whether it arrives alone or inside a batch. One thread per
/// quad of elements, rounded up to whole warps (the block sum shuffles with a
/// full warp mask), capped at `BLOCK_SIZE`. A wider block spreads a decode
/// row over more warps but costs the prefill grid resident blocks; the cap is
/// where the two meet.
#[inline]
fn rms_norm_block_size(hidden_size: usize) -> u32 {
let quads = hidden_size.div_ceil(4);
let warps = quads.div_ceil(32).max(1);
(warps * 32).min(BLOCK_SIZE as usize) as u32
}
/// Whether every RMSNorm operand can be moved four elements per access.
///
/// Needs the row width to be a multiple of four and each base pointer to be
/// aligned to the packed type; 16 bytes covers every dtype's packed width.
#[inline]
fn rms_norm_packed(hidden_size: usize, input_ptr: u64, weight_ptr: u64, output_ptr: u64) -> bool {
hidden_size.is_multiple_of(4)
&& input_ptr.is_multiple_of(16)
&& weight_ptr.is_multiple_of(16)
&& output_ptr.is_multiple_of(16)
}
/// Shared-memory element size for a normalization reduction.
///
/// F64 reduces in `double`; every other dtype reduces in `float`.
#[inline]
fn norm_shared_elem_size(dtype: DType) -> u32 {
match dtype {
DType::F64 => 8,
_ => 4,
}
}
/// Calculate launch configuration for normalization kernels.
///
/// One block per row (batch element), with threads cooperating to compute statistics.
/// Returns (grid_size, block_size).
///
/// Shared memory is NOT returned: each kernel lays its reduction out differently
/// (per-thread vs per-warp, one array vs two), so every launcher sizes it from
/// what its own kernel indexes.
#[inline]
fn norm_launch_config(batch_size: usize, hidden_size: usize) -> (u32, u32) {
let block_size = BLOCK_SIZE.min(hidden_size as u32);
let grid_size = batch_size as u32;
(grid_size, block_size)
}
/// Launch a RMSNorm (Root Mean Square Layer Normalization) kernel.
///
/// Computes: `output = input * rsqrt(mean(input^2) + eps) * weight`
///
/// RMSNorm is used in LLaMA and other modern transformer architectures.
/// It's simpler and faster than LayerNorm as it doesn't require computing mean.
///
/// Rows narrow enough to fit in a thread's register slice take the single-pass
/// `rms_norm_quad` kernel (packed four-element accesses) or, when the width or
/// a base pointer rules packing out, `rms_norm_regs` (scalar accesses, same
/// bits). Wider rows take the two-pass `rms_norm` kernel. The block size and
/// kernel choice depend on the row width and the operand alignment, never on
/// the batch.
///
/// # Arguments
///
/// * `input_ptr` - Device pointer to input tensor of shape [batch_size, hidden_size]
/// * `weight_ptr` - Device pointer to weight tensor of shape [hidden_size]
/// * `output_ptr` - Device pointer to output tensor of shape [batch_size, hidden_size]
/// * `batch_size` - Number of rows (batch dimension)
/// * `hidden_size` - Size of each row (hidden dimension)
/// * `eps` - Small constant for numerical stability (typically 1e-5 or 1e-6)
///
/// # Safety
///
/// - All pointers must be valid device memory
/// - `input_ptr` and `output_ptr` must have `batch_size * hidden_size` elements
/// - `weight_ptr` must have `hidden_size` elements
pub unsafe fn launch_rms_norm(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
dtype: DType,
input_ptr: u64,
weight_ptr: u64,
output_ptr: u64,
batch_size: usize,
hidden_size: usize,
eps: f32,
) -> Result<()> {
unsafe {
let module = get_or_load_module(context, device_index, kernel_names::NORM_RMS_MODULE)?;
let grid_size = batch_size as u32;
let block_size = rms_norm_block_size(hidden_size);
// RMSNorm is bandwidth-bound, so the two-pass kernel's second read of the
// row is close to pure cost. Take the register-cached single-pass kernel
// whenever the row fits in each thread's register slice; wider rows would
// spill that array to local memory, so they keep the two-pass kernel.
let fits_in_regs = hidden_size <= NORM_MAX_REGS_PER_THREAD * block_size as usize;
let base = if !fits_in_regs {
"rms_norm"
} else if rms_norm_packed(hidden_size, input_ptr, weight_ptr, output_ptr) {
"rms_norm_quad"
} else {
"rms_norm_regs"
};
let func_name = kernel_name(base, dtype);
let func = get_kernel_function(&module, &func_name)?;
// One accumulator slot per warp; the F64 kernels index doubles.
let shared_mem = block_size.div_ceil(32) * norm_shared_elem_size(dtype);
let batch = batch_size as u32;
let hidden = hidden_size as u32;
let eps_f64 = eps as f64;
let cfg = launch_config((grid_size, 1, 1), (block_size, 1, 1), shared_mem);
let mut builder = stream.launch_builder(&func);
builder.arg(&input_ptr);
builder.arg(&weight_ptr);
builder.arg(&output_ptr);
builder.arg(&batch);
builder.arg(&hidden);
// The F64 kernels take a `double` eps; pushing the f32 would leave the
// upper half of the parameter unwritten.
if dtype == DType::F64 {
builder.arg(&eps_f64);
} else {
builder.arg(&eps);
}
builder
.launch(cfg)
.map_err(|e| Error::Internal(format!("CUDA rms_norm kernel launch failed: {:?}", e)))?;
Ok(())
}
}
/// Launch a LayerNorm kernel.
///
/// Computes: `output = (input - mean) / sqrt(variance + eps) * weight + bias`
///
/// LayerNorm normalizes across the hidden dimension for each batch element.
///
/// # Arguments
///
/// * `input_ptr` - Device pointer to input tensor of shape [batch_size, hidden_size]
/// * `weight_ptr` - Device pointer to weight (gamma) tensor of shape [hidden_size]
/// * `bias_ptr` - Device pointer to bias (beta) tensor of shape [hidden_size]
/// * `output_ptr` - Device pointer to output tensor of shape [batch_size, hidden_size]
/// * `batch_size` - Number of rows (batch dimension)
/// * `hidden_size` - Size of each row (hidden dimension)
/// * `eps` - Small constant for numerical stability (typically 1e-5)
///
/// # Safety
///
/// - All pointers must be valid device memory
/// - `input_ptr` and `output_ptr` must have `batch_size * hidden_size` elements
/// - `weight_ptr` and `bias_ptr` must have `hidden_size` elements
pub unsafe fn launch_layer_norm(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
dtype: DType,
input_ptr: u64,
weight_ptr: u64,
bias_ptr: u64,
output_ptr: u64,
batch_size: usize,
hidden_size: usize,
eps: f32,
) -> Result<()> {
unsafe {
let module = get_or_load_module(context, device_index, kernel_names::NORM_LAYER_MODULE)?;
let func_name = kernel_name("layer_norm", dtype);
let func = get_kernel_function(&module, &func_name)?;
let (grid_size, block_size) = norm_launch_config(batch_size, hidden_size);
// The Welford merge stores one [count, mean, M2] triple PER WARP, not per
// thread, so the kernel indexes `3 * ceil(blockDim.x / 32)` elements. A
// per-thread estimate is short of that for a single-warp block.
// Sized from the reduction's accumulator: the F64 kernel merges in `double`.
let num_warps = block_size.div_ceil(32);
let shared_mem = 3 * num_warps * norm_shared_elem_size(dtype);
let batch = batch_size as u32;
let hidden = hidden_size as u32;
let eps_f64 = eps as f64;
let cfg = launch_config((grid_size, 1, 1), (block_size, 1, 1), shared_mem);
let mut builder = stream.launch_builder(&func);
builder.arg(&input_ptr);
builder.arg(&weight_ptr);
builder.arg(&bias_ptr);
builder.arg(&output_ptr);
builder.arg(&batch);
builder.arg(&hidden);
// The F64 kernel takes a `double` eps; pushing the f32 would leave the
// upper half of the parameter unwritten.
if dtype == DType::F64 {
builder.arg(&eps_f64);
} else {
builder.arg(&eps);
}
builder.launch(cfg).map_err(|e| {
Error::Internal(format!("CUDA layer_norm kernel launch failed: {:?}", e))
})?;
Ok(())
}
}
/// Launch a GroupNorm kernel.
///
/// Computes: Group normalization across divided channel groups
/// Input shape: [batch, channels, spatial...]
/// Divides channels into num_groups, normalizes each group separately
///
/// Computes for each (batch, group):
/// - mean and variance over channels_per_group * spatial elements
/// - Then: `output = (input - mean) / sqrt(variance + eps) * weight + bias`
///
/// # Arguments
///
/// * `input_ptr` - Device pointer to input tensor of shape [batch, channels, spatial...]
/// * `weight_ptr` - Device pointer to weight tensor of shape [channels]
/// * `bias_ptr` - Device pointer to bias tensor of shape [channels]
/// * `output_ptr` - Device pointer to output tensor of shape [batch, channels, spatial...]
/// * `batch` - Batch size
/// * `channels` - Number of channels
/// * `spatial` - Product of spatial dimensions (height * width for 4D tensors)
/// * `num_groups` - Number of groups to divide channels into
/// * `channels_per_group` - Channels per group (channels / num_groups)
/// * `eps` - Small constant for numerical stability (typically 1e-5)
///
/// # Safety
///
/// - All pointers must be valid device memory
/// - Input and output must have batch * channels * spatial elements
/// - Weight and bias must have channels elements
/// - channels must be divisible by num_groups
pub unsafe fn launch_group_norm(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
dtype: DType,
input_ptr: u64,
weight_ptr: u64,
bias_ptr: u64,
output_ptr: u64,
batch: usize,
channels: usize,
spatial: usize,
num_groups: usize,
channels_per_group: usize,
eps: f32,
) -> Result<()> {
unsafe {
let module = get_or_load_module(context, device_index, kernel_names::NORM_GROUP_MODULE)?;
let func_name = kernel_name("group_norm", dtype);
let func = get_kernel_function(&module, &func_name)?;
// One block per (batch, group) pair
let grid_size = (batch * num_groups) as u32;
let group_size = channels_per_group * spatial;
let block_size = BLOCK_SIZE.min(group_size as u32);
// The kernel splits its dynamic shared memory into two per-thread arrays,
// mean and variance, at `shared + blockDim.x`. Sized from the reduction's
// accumulator: the F64 kernel indexes doubles, not floats.
let shared_mem = block_size * 2 * norm_shared_elem_size(dtype);
let batch_u32 = batch as u32;
let channels_u32 = channels as u32;
let spatial_u32 = spatial as u32;
let num_groups_u32 = num_groups as u32;
let channels_per_group_u32 = channels_per_group as u32;
let eps_f64 = eps as f64;
let cfg = launch_config((grid_size, 1, 1), (block_size, 1, 1), shared_mem);
let mut builder = stream.launch_builder(&func);
builder.arg(&input_ptr);
builder.arg(&weight_ptr);
builder.arg(&bias_ptr);
builder.arg(&output_ptr);
builder.arg(&batch_u32);
builder.arg(&channels_u32);
builder.arg(&spatial_u32);
builder.arg(&num_groups_u32);
builder.arg(&channels_per_group_u32);
// The F64 kernel takes a `double` eps; pushing the f32 would leave the
// upper half of the parameter unwritten.
if dtype == DType::F64 {
builder.arg(&eps_f64);
} else {
builder.arg(&eps);
}
builder.launch(cfg).map_err(|e| {
Error::Internal(format!("CUDA group_norm kernel launch failed: {:?}", e))
})?;
Ok(())
}
}