Skip to main content

baracuda_kernels/quantize/
dequantize_per_tensor_backward.rs

1//! `dequantize_per_tensor` backward plan — `dq = dy * scale`.
2//!
3//! Linear identity scaled by `scale`. The integer `q` operand is
4//! non-differentiable; the BW returns a gradient in the FW input's FP
5//! dtype (the gradient continues to flow in FP space upstream of the
6//! dequant boundary).
7
8use core::ffi::c_void;
9use core::marker::PhantomData;
10
11use baracuda_cutlass::{Error, Result};
12use baracuda_driver::Stream;
13use baracuda_kernels_types::{
14    Element, ElementKind, IntElement, KernelSku, PlanPreference, PrecisionGuarantee, QuantizeKind,
15    ScalarType, TensorMut, TensorRef, Workspace,
16};
17
18use super::map_status;
19use super::per_tensor::build_sku;
20use super::{validate_input_element, validate_output_element};
21
22/// Descriptor for a `dequantize_per_tensor` backward op.
23#[derive(Copy, Clone, Debug)]
24pub struct DequantizePerTensorBackwardDescriptor {
25    /// Total element count.
26    pub numel: i32,
27    /// FP element kind (input gradient dtype).
28    pub input_element: ElementKind,
29    /// FW's int input element kind (s8 or u8).
30    pub output_element: ElementKind,
31}
32
33/// Args bundle for a `dequantize_per_tensor` backward launch.
34pub struct DequantizePerTensorBackwardArgs<'a, TIn: Element, TOut: IntElement> {
35    /// Scalar scale (same value used in FW).
36    pub scale: <TIn as Element>::Scalar,
37    /// Upstream gradient `[numel]` in FP.
38    pub d_output: TensorRef<'a, TIn, 1>,
39    /// Output `[numel]` in FP (gradient w.r.t. the FW's q-input,
40    /// surfaced as FP — same dtype as `d_output`).
41    pub d_input: TensorMut<'a, TIn, 1>,
42    /// Phantom for the int input dtype carried by the plan type
43    /// parameter (parity with FW Plan signature).
44    pub _phantom: PhantomData<TOut>,
45}
46
47/// `dequantize_per_tensor` backward plan.
48///
49/// Straight-through. The dequant FW is exactly linear in the int
50/// input (`x = scale * (q - zp)`), so `dq = scale * dy`. The int
51/// input itself is non-differentiable; this BW propagates the
52/// upstream gradient back into FP-typed `d_input` for autograd
53/// continuity.
54///
55/// **When to use**: backward for
56/// [`DequantizePerTensorPlan`](crate::DequantizePerTensorPlan).
57///
58/// **Dtypes**: gradients in `{f32, f64, f16, bf16}`; `TOut` carried
59/// for SKU parity with the FW Plan.
60///
61/// **Shape limits**: flat `[numel]`.
62///
63/// **Workspace**: none.
64///
65/// **Precision guarantee**: deterministic, bit-stable.
66pub struct DequantizePerTensorBackwardPlan<TIn: Element, TOut: IntElement> {
67    desc: DequantizePerTensorBackwardDescriptor,
68    sku: KernelSku,
69    _marker: PhantomData<(TIn, TOut)>,
70}
71
72impl<TIn: Element, TOut: IntElement> DequantizePerTensorBackwardPlan<TIn, TOut> {
73    /// Pick a kernel.
74    pub fn select(
75        _stream: &Stream,
76        desc: &DequantizePerTensorBackwardDescriptor,
77        _pref: PlanPreference,
78    ) -> Result<Self> {
79        if desc.input_element != TIn::KIND {
80            return Err(Error::Unsupported(
81                "DequantizePerTensorBackwardPlan: descriptor input_element != TIn",
82            ));
83        }
84        if desc.output_element != TOut::KIND {
85            return Err(Error::Unsupported(
86                "DequantizePerTensorBackwardPlan: descriptor output_element != TOut",
87            ));
88        }
89        validate_input_element(
90            TIn::KIND,
91            "DequantizePerTensorBackwardPlan: unsupported TIn dtype",
92        )?;
93        validate_output_element(
94            TOut::KIND,
95            "DequantizePerTensorBackwardPlan: unsupported TOut dtype",
96        )?;
97        if desc.numel < 0 {
98            return Err(Error::InvalidProblem(
99                "DequantizePerTensorBackwardPlan: numel must be non-negative",
100            ));
101        }
102        let sku = build_sku::<TIn, TOut>(QuantizeKind::DequantizePerTensorBackward);
103        Ok(Self {
104            desc: *desc,
105            sku,
106            _marker: PhantomData,
107        })
108    }
109
110    /// Validate args.
111    pub fn can_implement(
112        &self,
113        args: &DequantizePerTensorBackwardArgs<'_, TIn, TOut>,
114    ) -> Result<()> {
115        let expected = [self.desc.numel];
116        if args.d_output.shape != expected || args.d_input.shape != expected {
117            return Err(Error::InvalidProblem(
118                "DequantizePerTensorBackwardPlan: tensor shape != [numel]",
119            ));
120        }
121        Ok(())
122    }
123
124    /// Workspace bytes.
125    #[inline]
126    pub fn workspace_size(&self) -> usize {
127        0
128    }
129
130    /// Identity.
131    #[inline]
132    pub fn sku(&self) -> KernelSku {
133        self.sku
134    }
135
136    /// Numerical guarantees.
137    #[inline]
138    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
139        self.sku.precision_guarantee
140    }
141
142    /// Launch.
143    pub fn run(
144        &self,
145        stream: &Stream,
146        _workspace: Workspace<'_>,
147        args: DequantizePerTensorBackwardArgs<'_, TIn, TOut>,
148    ) -> Result<()> {
149        self.can_implement(&args)?;
150        let numel = self.desc.numel as i64;
151        if numel == 0 {
152            return Ok(());
153        }
154        let dy_ptr = args.d_output.data.as_raw().0 as *const c_void;
155        let dq_ptr = args.d_input.data.as_raw().0 as *mut c_void;
156        let stream_ptr = stream.as_raw() as *mut c_void;
157
158        let status = if <TIn::Scalar as ScalarType>::IS_F64 {
159            let scale_f64 = args.scale.to_f64();
160            unsafe {
161                baracuda_kernels_sys::baracuda_kernels_dequantize_per_tensor_backward_f64_run(
162                    numel, scale_f64, dy_ptr, dq_ptr,
163                    core::ptr::null_mut(), 0, stream_ptr,
164                )
165            }
166        } else {
167            let scale_f32 = args.scale.to_f32();
168            match TIn::KIND {
169                ElementKind::F32 => unsafe {
170                    baracuda_kernels_sys::baracuda_kernels_dequantize_per_tensor_backward_f32_run(
171                        numel, scale_f32, dy_ptr, dq_ptr,
172                        core::ptr::null_mut(), 0, stream_ptr,
173                    )
174                },
175                ElementKind::F16 => unsafe {
176                    baracuda_kernels_sys::baracuda_kernels_dequantize_per_tensor_backward_f16_run(
177                        numel, scale_f32, dy_ptr, dq_ptr,
178                        core::ptr::null_mut(), 0, stream_ptr,
179                    )
180                },
181                ElementKind::Bf16 => unsafe {
182                    baracuda_kernels_sys::baracuda_kernels_dequantize_per_tensor_backward_bf16_run(
183                        numel, scale_f32, dy_ptr, dq_ptr,
184                        core::ptr::null_mut(), 0, stream_ptr,
185                    )
186                },
187                _ => return Err(Error::Unsupported(
188                    "DequantizePerTensorBackwardPlan: unsupported TIn at run()",
189                )),
190            }
191        };
192        map_status(status)
193    }
194}