Skip to main content

baracuda_kernels/quantize/
dynamic_range.rs

1//! `dynamic_range_quantize` — compose op (Phase 8 Milestone 8.3).
2//!
3//! Computes a `(scale, zero_point)` pair from the runtime dynamic range
4//! of the input — the canonical post-training-quantization-at-inference
5//! recipe — then quantizes. The Plan returns the quantized tensor AND
6//! the computed `scale` vector so the caller can later dequantize.
7//!
8//! ## Granularity
9//!
10//! [`DynamicRangeMode::Symmetric`] vs [`DynamicRangeMode::Asymmetric`]:
11//! - **Symmetric**: `max_abs = max |x|` over the segment; `scale =
12//!   max_abs / qmax`; `zero_point = 0`. Standard for activations.
13//! - **Asymmetric** (offset): `xmin / xmax` reduced separately; `scale
14//!   = (xmax - xmin) / (qmax - qmin)`; `zp = qmin - round(xmin / scale)`.
15//!
16//! ## Scope
17//!
18//! [`DynamicRangeScope::Token`] is the Phase 8.3 trailblazer
19//! — `[N, D]` input with one `(scale, zp)` pair per row, matching the
20//! LLM W8A8 activation-quantize recipe.
21//!
22//! [`DynamicRangeScope::Tensor`], [`DynamicRangeScope::Channel`] and
23//! [`DynamicRangeScope::Group`] are reserved scopes that return
24//! [`Error::Unsupported`] from [`DynamicRangeQuantizePlan::select`]
25//! today; they wire up in follow-up milestones by orchestrating the
26//! matching primitive [`ReducePlan`](crate::ReducePlan) + per-channel /
27//! per-group quantize plans (the per-tensor / per-channel / per-group
28//! quantize plans from 8.1 / 8.2 already exist).
29//!
30//! ## Dtype coverage (trailblazer)
31//!
32//! `TIn ∈ {f32, f64}`, `TOut = S8`. `f16` / `bf16` activation, `u8`
33//! output, and asymmetric mode are deferred.
34
35use core::ffi::c_void;
36use core::marker::PhantomData;
37
38use baracuda_cutlass::{Error, Result};
39use baracuda_driver::Stream;
40use baracuda_kernels_types::{
41    ArchSku, BackendKind, Element, ElementKind, IntElement, KernelSku, MathPrecision, OpCategory,
42    PlanPreference, PrecisionGuarantee, QuantizeKind, TensorMut, TensorRef, Workspace,
43};
44
45use super::{map_status, validate_input_element, validate_output_element};
46
47/// Symmetric vs asymmetric (offset) dynamic-range quantization.
48///
49/// Only [`DynamicRangeMode::Symmetric`] is wired in the 8.3
50/// trailblazer; [`DynamicRangeMode::Asymmetric`] returns
51/// [`Error::Unsupported`] and is reserved for a follow-up that wires
52/// the dual max + min reduction + offset compute kernel.
53#[derive(Copy, Clone, Debug, Eq, PartialEq)]
54#[non_exhaustive]
55pub enum DynamicRangeMode {
56    /// `scale = max_abs / qmax`, `zero_point = 0`.
57    Symmetric,
58    /// `scale = (xmax - xmin) / (qmax - qmin)`,
59    /// `zp = qmin - round(xmin / scale)`. Reserved.
60    Asymmetric,
61}
62
63/// Per-tensor / per-channel / per-token / per-group granularity for the
64/// scale + zero_point computation.
65///
66/// Only [`DynamicRangeScope::Token`] is wired in the 8.3 trailblazer.
67#[derive(Copy, Clone, Debug, Eq, PartialEq)]
68#[non_exhaustive]
69pub enum DynamicRangeScope {
70    /// One `(scale, zp)` for the whole tensor. Reserved.
71    Tensor,
72    /// One `(scale, zp)` per slice along `axis`. Reserved.
73    Channel {
74        /// Axis along which to slice.
75        axis: i32,
76    },
77    /// One `(scale, zp)` per token row (first axis of a `[N, D]`
78    /// tensor). Trailblazer scope.
79    Token,
80    /// One `(scale, zp)` per group along `axis`. Reserved.
81    Group {
82        /// Axis along which to group.
83        axis: i32,
84        /// Number of elements per group.
85        group_size: i32,
86    },
87}
88
89/// Descriptor for a `dynamic_range_quantize` op.
90#[derive(Copy, Clone, Debug)]
91pub struct DynamicRangeQuantizeDescriptor {
92    /// Number of token rows (first axis of input / output).
93    pub n: i32,
94    /// Feature dim (second axis).
95    pub d: i32,
96    /// Quantization range lower bound (e.g. `-127` for symmetric s8).
97    pub q_min: i32,
98    /// Quantization range upper bound (e.g. `127` for symmetric s8).
99    pub q_max: i32,
100    /// Symmetric / asymmetric mode.
101    pub mode: DynamicRangeMode,
102    /// Per-tensor / per-channel / per-token / per-group scope.
103    pub scope: DynamicRangeScope,
104    /// Input FP element kind. Must match `TIn::KIND`.
105    pub input_element: ElementKind,
106    /// Output int element kind (must match `TOut::KIND`). `S8` only.
107    pub output_element: ElementKind,
108}
109
110/// Args bundle for a `dynamic_range_quantize` launch.
111///
112/// Compared with [`super::QuantizePerTokenArgs`], the caller does NOT
113/// supply `scale` / `zero_point` — those are computed by the kernel
114/// from the runtime dynamic range. The plan writes `scale[N]` into the
115/// caller-supplied `scale_out` buffer so a downstream dequantize step
116/// has access to the same scale.
117///
118/// `zero_point` is implicit (= 0 for symmetric) and is not materialized.
119pub struct DynamicRangeQuantizeArgs<'a, TIn: Element, TOut: IntElement> {
120    /// Input `[N, D]` in FP.
121    pub input: TensorRef<'a, TIn, 2>,
122    /// Per-row scale `[N]` in FP — written by the kernel.
123    pub scale_out: TensorMut<'a, TIn, 1>,
124    /// Output `[N, D]` in int.
125    pub output: TensorMut<'a, TOut, 2>,
126}
127
128/// `dynamic_range_quantize` plan.
129///
130/// Composes per-row max-abs reduction + scale computation + per-row
131/// quantize into a single fused kernel launch (the dynamic-range
132/// recipe IS the fused composition — running the reduce and quantize
133/// as one kernel avoids a scale-buffer round-trip).
134///
135/// The trailblazer kernel is symmetric per-token only. Future fanout
136/// adds asymmetric mode (requires xmin + xmax reductions) and the
137/// other three scopes (tensor / channel / group) by orchestrating
138/// existing primitives.
139///
140/// **When to use**: post-training activation quantization at
141/// inference — compute scale from runtime range and quantize in
142/// one launch. No BW (inference-only).
143///
144/// **Dtypes (trailblazer)**: `TIn ∈ {f32, f64}`, `TOut = S8`.
145/// `f16` / `bf16` activation, `u8` output, and asymmetric mode
146/// gated as `Unsupported` until follow-up milestones wire the
147/// xmin/xmax reductions and offset-compute kernel.
148///
149/// **Shape limits**: rank-2 `[N, D]`; `N ≤ 65535` (block-per-row
150/// grid cap, lifts when row tiling lands); `q_max > 0` (symmetric
151/// divisor); `q_max ≥ q_min`.
152///
153/// **Workspace**: none — single-launch fused kernel.
154///
155/// **Precision guarantee**: deterministic, bit-stable. One block
156/// per row, no atomics; block-tree reduction is associative-stable
157/// on a single GPU.
158pub struct DynamicRangeQuantizePlan<TIn: Element, TOut: IntElement> {
159    desc: DynamicRangeQuantizeDescriptor,
160    sku: KernelSku,
161    _marker: PhantomData<(TIn, TOut)>,
162}
163
164impl<TIn: Element, TOut: IntElement> DynamicRangeQuantizePlan<TIn, TOut> {
165    /// Pick a kernel for `desc`.
166    pub fn select(
167        _stream: &Stream,
168        desc: &DynamicRangeQuantizeDescriptor,
169        _pref: PlanPreference,
170    ) -> Result<Self> {
171        if desc.input_element != TIn::KIND {
172            return Err(Error::Unsupported(
173                "DynamicRangeQuantizePlan: descriptor input_element != TIn",
174            ));
175        }
176        if desc.output_element != TOut::KIND {
177            return Err(Error::Unsupported(
178                "DynamicRangeQuantizePlan: descriptor output_element != TOut",
179            ));
180        }
181        validate_input_element(TIn::KIND, "DynamicRangeQuantizePlan: unsupported TIn")?;
182        validate_output_element(TOut::KIND, "DynamicRangeQuantizePlan: unsupported TOut")?;
183        // Trailblazer: TIn ∈ {f32, f64}, TOut = S8. f16/bf16/u8 deferred.
184        if !matches!(TIn::KIND, ElementKind::F32 | ElementKind::F64) {
185            return Err(Error::Unsupported(
186                "DynamicRangeQuantizePlan: 8.3 trailblazer only wires f32 / f64 \
187                 activation (f16 / bf16 deferred)",
188            ));
189        }
190        if TOut::KIND != ElementKind::S8 {
191            return Err(Error::Unsupported(
192                "DynamicRangeQuantizePlan: 8.3 trailblazer only wires s8 output \
193                 (u8 deferred)",
194            ));
195        }
196        if desc.mode != DynamicRangeMode::Symmetric {
197            return Err(Error::Unsupported(
198                "DynamicRangeQuantizePlan: 8.3 trailblazer only wires symmetric mode \
199                 (asymmetric deferred — requires xmin + xmax reductions and a \
200                 separate offset-compute kernel)",
201            ));
202        }
203        if desc.scope != DynamicRangeScope::Token {
204            return Err(Error::Unsupported(
205                "DynamicRangeQuantizePlan: 8.3 trailblazer only wires per-token scope \
206                 (tensor / channel / group deferred)",
207            ));
208        }
209        if desc.n < 0 || desc.d < 0 {
210            return Err(Error::InvalidProblem(
211                "DynamicRangeQuantizePlan: n and d must be non-negative",
212            ));
213        }
214        if desc.q_max <= 0 {
215            return Err(Error::InvalidProblem(
216                "DynamicRangeQuantizePlan: q_max must be > 0 (symmetric divisor)",
217            ));
218        }
219        if desc.q_max < desc.q_min {
220            return Err(Error::InvalidProblem(
221                "DynamicRangeQuantizePlan: q_max < q_min",
222            ));
223        }
224        // Grid limit on the kernel: one block per row, capped at 65535.
225        if desc.n > 65535 {
226            return Err(Error::Unsupported(
227                "DynamicRangeQuantizePlan: N > 65535 — block-per-row grid limit \
228                 (will be lifted when row tiling lands)",
229            ));
230        }
231        let sku = build_sku::<TIn, TOut>(QuantizeKind::DynamicRange);
232        Ok(Self {
233            desc: *desc,
234            sku,
235            _marker: PhantomData,
236        })
237    }
238
239    /// Validate args at run time.
240    pub fn can_implement(&self, args: &DynamicRangeQuantizeArgs<'_, TIn, TOut>) -> Result<()> {
241        if args.input.shape != [self.desc.n, self.desc.d] {
242            return Err(Error::InvalidProblem(
243                "DynamicRangeQuantizePlan: input shape != [n, d]",
244            ));
245        }
246        if args.output.shape != [self.desc.n, self.desc.d] {
247            return Err(Error::InvalidProblem(
248                "DynamicRangeQuantizePlan: output shape != [n, d]",
249            ));
250        }
251        if args.scale_out.shape != [self.desc.n] {
252            return Err(Error::InvalidProblem(
253                "DynamicRangeQuantizePlan: scale_out shape != [n]",
254            ));
255        }
256        Ok(())
257    }
258
259    /// Workspace bytes — none. The kernel is single-launch.
260    #[inline]
261    pub fn workspace_size(&self) -> usize {
262        0
263    }
264
265    /// Identity of the selected kernel.
266    #[inline]
267    pub fn sku(&self) -> KernelSku {
268        self.sku
269    }
270
271    /// Numerical guarantees.
272    #[inline]
273    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
274        self.sku.precision_guarantee
275    }
276
277    /// Launch.
278    pub fn run(
279        &self,
280        stream: &Stream,
281        _workspace: Workspace<'_>,
282        args: DynamicRangeQuantizeArgs<'_, TIn, TOut>,
283    ) -> Result<()> {
284        self.can_implement(&args)?;
285        let total = (self.desc.n as i64) * (self.desc.d as i64);
286        if total == 0 {
287            return Ok(());
288        }
289        let in_ptr = args.input.data.as_raw().0 as *const c_void;
290        let sc_ptr = args.scale_out.data.as_raw().0 as *mut c_void;
291        let out_ptr = args.output.data.as_raw().0 as *mut c_void;
292        let stream_ptr = stream.as_raw() as *mut c_void;
293
294        let status = match (TIn::KIND, TOut::KIND) {
295            (ElementKind::F32, ElementKind::S8) => unsafe {
296                baracuda_kernels_sys::baracuda_kernels_dynamic_range_quantize_per_token_sym_f32_s8_run(
297                    self.desc.n,
298                    self.desc.d,
299                    self.desc.q_min,
300                    self.desc.q_max,
301                    in_ptr, sc_ptr, out_ptr,
302                    core::ptr::null_mut(), 0, stream_ptr,
303                )
304            },
305            (ElementKind::F64, ElementKind::S8) => unsafe {
306                baracuda_kernels_sys::baracuda_kernels_dynamic_range_quantize_per_token_sym_f64_s8_run(
307                    self.desc.n,
308                    self.desc.d,
309                    self.desc.q_min,
310                    self.desc.q_max,
311                    in_ptr, sc_ptr, out_ptr,
312                    core::ptr::null_mut(), 0, stream_ptr,
313                )
314            },
315            _ => {
316                return Err(Error::Unsupported(
317                    "DynamicRangeQuantizePlan::run reached unsupported (TIn, TOut) \
318                     (select should have caught this)",
319                ))
320            }
321        };
322        map_status(status)
323    }
324}
325
326/// Build the [`KernelSku`] for a dynamic-range-quantize plan.
327fn build_sku<TIn: Element, TOut: IntElement>(op: QuantizeKind) -> KernelSku {
328    let precision_guarantee = PrecisionGuarantee {
329        math_precision: if TIn::KIND == ElementKind::F64 {
330            MathPrecision::F64
331        } else {
332            MathPrecision::F32
333        },
334        accumulator: ElementKind::F32,
335        // Deterministic — one block per row, no atomics. Block-tree
336        // reduction is associative-stable on a single GPU.
337        bit_stable_on_same_hardware: true,
338        deterministic: true,
339    };
340    KernelSku {
341        category: OpCategory::Quantization,
342        op: op as u16,
343        element: TIn::KIND,
344        aux_element: Some(TOut::KIND),
345        layout: None,
346        epilogue: None,
347        arch: ArchSku::Sm80,
348        backend: BackendKind::Bespoke,
349        precision_guarantee,
350    }
351}