Skip to main content

baracuda_kernels/quantize/
per_channel_backward.rs

1//! `quantize_per_channel` backward plan via STE.
2//!
3//! `dx[i] = (dy[i] / scale[c]) * 1[qmin <= round(x[i]/scale[c])+zp[c] <= qmax]`,
4//! where `c = coord(i)[axis]`. In-range mask recomputed from saved `x`.
5
6use core::ffi::c_void;
7use core::marker::PhantomData;
8
9use baracuda_cutlass::{Error, Result};
10use baracuda_driver::Stream;
11use baracuda_kernels_types::{
12    Element, ElementKind, IntElement, KernelSku, PlanPreference, PrecisionGuarantee, QuantizeKind,
13    TensorMut, TensorRef, Workspace,
14};
15
16use super::map_status;
17use super::per_channel::MAX_RANK;
18use super::per_tensor::build_sku;
19use super::{validate_input_element, validate_output_element};
20
21/// Descriptor for a `quantize_per_channel` backward op.
22#[derive(Copy, Clone, Debug)]
23pub struct QuantizePerChannelBackwardDescriptor {
24    /// 4-D shape (caller pads rank).
25    pub shape: [i32; MAX_RANK],
26    /// Logical rank.
27    pub rank: u8,
28    /// Axis index in `[0, 4)`.
29    pub axis: u8,
30    /// Lower clip bound from FW.
31    pub q_min: i32,
32    /// Upper clip bound from FW.
33    pub q_max: i32,
34    /// Input FP element kind.
35    pub input_element: ElementKind,
36    /// FW output int element kind (s8 or u8) — recorded for SKU parity.
37    pub output_element: ElementKind,
38}
39
40/// Args bundle for a `quantize_per_channel` backward launch.
41pub struct QuantizePerChannelBackwardArgs<'a, TIn: Element, TOut: IntElement> {
42    /// Saved FW input `[D0, D1, D2, D3]` in FP — required for mask
43    /// recomputation.
44    pub input: TensorRef<'a, TIn, 4>,
45    /// Per-channel scale `[C]` (same values used in FW).
46    pub scale: TensorRef<'a, TIn, 1>,
47    /// Per-channel zero point `[C]` (same values used in FW).
48    pub zero_point: TensorRef<'a, i32, 1>,
49    /// Upstream gradient `[D0, D1, D2, D3]` in FP.
50    pub d_output: TensorRef<'a, TIn, 4>,
51    /// Output `[D0, D1, D2, D3]` in FP.
52    pub d_input: TensorMut<'a, TIn, 4>,
53    /// Phantom for the int-output dtype.
54    pub _phantom: PhantomData<TOut>,
55}
56
57/// `quantize_per_channel` backward plan.
58///
59/// STE: `dx[..., c, ...] = (dy[..., c, ...] / scale[c]) * 1[qmin ≤ round(x/scale[c])+zp[c] ≤ qmax]`.
60/// Mask recomputed in-kernel from the saved FW input.
61///
62/// **When to use**: backward for
63/// [`QuantizePerChannelPlan`](crate::QuantizePerChannelPlan). Caller
64/// must retain FW input `x`, `scale[]`, `zero_point[]`.
65///
66/// **Dtypes**: gradients in `{f32, f64, f16, bf16}`; `TOut` carried
67/// for SKU consistency only (BW kernel does not consume an int operand).
68///
69/// **Shape limits**: rank-4 contiguous; `axis ∈ [0, 4)`; per-channel
70/// vectors of length `shape[axis]`.
71///
72/// **Workspace**: none.
73///
74/// **Precision guarantee**: deterministic, bit-stable.
75pub struct QuantizePerChannelBackwardPlan<TIn: Element, TOut: IntElement> {
76    desc: QuantizePerChannelBackwardDescriptor,
77    sku: KernelSku,
78    _marker: PhantomData<(TIn, TOut)>,
79}
80
81impl<TIn: Element, TOut: IntElement> QuantizePerChannelBackwardPlan<TIn, TOut> {
82    /// Pick a kernel.
83    pub fn select(
84        _stream: &Stream,
85        desc: &QuantizePerChannelBackwardDescriptor,
86        _pref: PlanPreference,
87    ) -> Result<Self> {
88        if desc.input_element != TIn::KIND {
89            return Err(Error::Unsupported(
90                "QuantizePerChannelBackwardPlan: descriptor input_element != TIn",
91            ));
92        }
93        if desc.output_element != TOut::KIND {
94            return Err(Error::Unsupported(
95                "QuantizePerChannelBackwardPlan: descriptor output_element != TOut",
96            ));
97        }
98        validate_input_element(
99            TIn::KIND,
100            "QuantizePerChannelBackwardPlan: unsupported TIn dtype",
101        )?;
102        validate_output_element(
103            TOut::KIND,
104            "QuantizePerChannelBackwardPlan: unsupported TOut dtype",
105        )?;
106        if (desc.axis as usize) >= MAX_RANK {
107            return Err(Error::InvalidProblem(
108                "QuantizePerChannelBackwardPlan: axis out of range",
109            ));
110        }
111        let sku = build_sku::<TIn, TOut>(QuantizeKind::PerChannelBackward);
112        Ok(Self {
113            desc: *desc,
114            sku,
115            _marker: PhantomData,
116        })
117    }
118
119    /// Validate args.
120    pub fn can_implement(
121        &self,
122        args: &QuantizePerChannelBackwardArgs<'_, TIn, TOut>,
123    ) -> Result<()> {
124        if args.input.shape != self.desc.shape
125            || args.d_output.shape != self.desc.shape
126            || args.d_input.shape != self.desc.shape
127        {
128            return Err(Error::InvalidProblem(
129                "QuantizePerChannelBackwardPlan: tensor shape mismatch",
130            ));
131        }
132        let c = self.desc.shape[self.desc.axis as usize];
133        if args.scale.shape != [c] || args.zero_point.shape != [c] {
134            return Err(Error::InvalidProblem(
135                "QuantizePerChannelBackwardPlan: scale / zero_point shape != [C]",
136            ));
137        }
138        Ok(())
139    }
140
141    /// Workspace bytes.
142    #[inline]
143    pub fn workspace_size(&self) -> usize {
144        0
145    }
146
147    /// Identity.
148    #[inline]
149    pub fn sku(&self) -> KernelSku {
150        self.sku
151    }
152
153    /// Numerical guarantees.
154    #[inline]
155    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
156        self.sku.precision_guarantee
157    }
158
159    /// Launch.
160    pub fn run(
161        &self,
162        stream: &Stream,
163        _workspace: Workspace<'_>,
164        args: QuantizePerChannelBackwardArgs<'_, TIn, TOut>,
165    ) -> Result<()> {
166        self.can_implement(&args)?;
167        let numel = args.d_output.numel();
168        if numel == 0 {
169            return Ok(());
170        }
171        let x_ptr = args.input.data.as_raw().0 as *const c_void;
172        let sc_ptr = args.scale.data.as_raw().0 as *const c_void;
173        let zp_ptr = args.zero_point.data.as_raw().0 as *const c_void;
174        let dy_ptr = args.d_output.data.as_raw().0 as *const c_void;
175        let dx_ptr = args.d_input.data.as_raw().0 as *mut c_void;
176        let stream_ptr = stream.as_raw() as *mut c_void;
177        let shape4 = self.desc.shape.as_ptr();
178        let axis = self.desc.axis as i32;
179        let qmin = self.desc.q_min;
180        let qmax = self.desc.q_max;
181
182        let status = match TIn::KIND {
183            ElementKind::F32 => unsafe {
184                baracuda_kernels_sys::baracuda_kernels_quantize_per_channel_backward_f32_run(
185                    numel, shape4, axis, qmin, qmax,
186                    x_ptr, sc_ptr, zp_ptr, dy_ptr, dx_ptr,
187                    core::ptr::null_mut(), 0, stream_ptr,
188                )
189            },
190            ElementKind::F16 => unsafe {
191                baracuda_kernels_sys::baracuda_kernels_quantize_per_channel_backward_f16_run(
192                    numel, shape4, axis, qmin, qmax,
193                    x_ptr, sc_ptr, zp_ptr, dy_ptr, dx_ptr,
194                    core::ptr::null_mut(), 0, stream_ptr,
195                )
196            },
197            ElementKind::Bf16 => unsafe {
198                baracuda_kernels_sys::baracuda_kernels_quantize_per_channel_backward_bf16_run(
199                    numel, shape4, axis, qmin, qmax,
200                    x_ptr, sc_ptr, zp_ptr, dy_ptr, dx_ptr,
201                    core::ptr::null_mut(), 0, stream_ptr,
202                )
203            },
204            ElementKind::F64 => unsafe {
205                baracuda_kernels_sys::baracuda_kernels_quantize_per_channel_backward_f64_run(
206                    numel, shape4, axis, qmin, qmax,
207                    x_ptr, sc_ptr, zp_ptr, dy_ptr, dx_ptr,
208                    core::ptr::null_mut(), 0, stream_ptr,
209                )
210            },
211            _ => return Err(Error::Unsupported(
212                "QuantizePerChannelBackwardPlan: unsupported TIn at run()",
213            )),
214        };
215        map_status(status)
216    }
217}