1use crate::runtime::ComputeDispatch;
5use crate::runtime::SemanticDispatch;
6use crate::runtime::{BufferBinding, KernelId, PushConstant};
7use crate::{DType, Error, Matrix, OpAttribute, Result};
8
9use crate::ml::{
10 autograd,
11 validation::{shader_u32, validate_f32_same_runtime},
12};
13
14#[non_exhaustive]
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum UpsampleMode {
18 Nearest,
20 Bilinear,
22}
23
24impl UpsampleMode {
25 pub(crate) const fn token(self) -> &'static str {
26 match self {
27 Self::Nearest => "nearest",
28 Self::Bilinear => "bilinear",
29 }
30 }
31}
32
33#[derive(Clone, Copy)]
34struct Upsample2dGeometry {
35 batch_size: u32,
36 channels: u32,
37 input_height: u32,
38 input_width: u32,
39 output_height: u32,
40 output_width: u32,
41 scale_factor: u32,
42}
43
44impl Upsample2dGeometry {
45 fn resolve(input: &Matrix, scale_factor: usize, operation: &'static str) -> Result<Self> {
46 let [batch_size, channels, input_height, input_width] = input.shape() else {
47 return Err(Error::invalid_argument(format!(
48 "{operation} input must have NCHW rank four; found {:?}",
49 input.shape()
50 )));
51 };
52 if [*batch_size, *channels, *input_height, *input_width]
53 .into_iter()
54 .any(|extent| extent == 0)
55 || scale_factor == 0
56 {
57 return Err(Error::invalid_argument(format!(
58 "{operation} input extents and scale factor must be nonzero"
59 )));
60 }
61 let output_height = input_height.checked_mul(scale_factor).ok_or_else(|| {
62 Error::invalid_argument(format!("{operation} output height overflows usize"))
63 })?;
64 let output_width = input_width.checked_mul(scale_factor).ok_or_else(|| {
65 Error::invalid_argument(format!("{operation} output width overflows usize"))
66 })?;
67 batch_size
68 .checked_mul(*channels)
69 .and_then(|value| value.checked_mul(output_height))
70 .and_then(|value| value.checked_mul(output_width))
71 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
72 let batch_size = shader_u32(*batch_size, "batch size", operation)?;
73 let channels = shader_u32(*channels, "channel count", operation)?;
74 batch_size.checked_mul(channels).ok_or_else(|| {
75 Error::invalid_argument(format!("{operation} batch-channel count exceeds u32"))
76 })?;
77 Ok(Self {
78 batch_size,
79 channels,
80 input_height: shader_u32(*input_height, "input height", operation)?,
81 input_width: shader_u32(*input_width, "input width", operation)?,
82 output_height: shader_u32(output_height, "output height", operation)?,
83 output_width: shader_u32(output_width, "output width", operation)?,
84 scale_factor: shader_u32(scale_factor, "scale factor", operation)?,
85 })
86 }
87
88 const fn push_constants(self) -> [PushConstant; 7] {
89 [
90 PushConstant::U32(self.batch_size),
91 PushConstant::U32(self.channels),
92 PushConstant::U32(self.input_height),
93 PushConstant::U32(self.input_width),
94 PushConstant::U32(self.output_height),
95 PushConstant::U32(self.output_width),
96 PushConstant::U32(self.scale_factor),
97 ]
98 }
99
100 const fn forward_workgroups(self) -> [u32; 3] {
101 [
102 self.output_width.div_ceil(16),
103 self.output_height.div_ceil(16),
104 self.batch_size * self.channels,
105 ]
106 }
107
108 const fn backward_workgroups(self) -> [u32; 3] {
109 [
110 self.input_width.div_ceil(16),
111 self.input_height.div_ceil(16),
112 self.batch_size * self.channels,
113 ]
114 }
115
116 fn output_shape(self) -> Vec<usize> {
117 vec![
118 self.batch_size as usize,
119 self.channels as usize,
120 self.output_height as usize,
121 self.output_width as usize,
122 ]
123 }
124}
125
126fn make_attributes(scale_factor: usize, mode: UpsampleMode) -> Result<[OpAttribute; 2]> {
127 Ok([
128 OpAttribute::UnsignedInteger {
129 name: "scale_factor".into(),
130 value: u64::try_from(scale_factor)
131 .map_err(|_| Error::invalid_argument("upsample scale factor exceeds u64"))?,
132 },
133 OpAttribute::Enum {
134 name: "mode".into(),
135 value: mode.token().into(),
136 },
137 ])
138}
139
140pub fn upsample_2d(input: &Matrix, scale_factor: usize, mode: UpsampleMode) -> Result<Matrix> {
148 let operation = crate::core::operation::ml::UPSAMPLE_2D.name();
149 validate_f32_same_runtime(operation, &[input])?;
150 let geometry = Upsample2dGeometry::resolve(input, scale_factor, operation)?;
151 let output_shape = geometry.output_shape();
152 let output_count = output_shape
153 .iter()
154 .try_fold(1_usize, |product, extent| product.checked_mul(*extent))
155 .ok_or_else(|| Error::invalid_argument(format!("{operation} output size overflows usize")))?;
156 let output = Matrix::allocate(input.runtime(), output_shape, output_count, DType::F32)?;
157 let kernel = match mode {
158 UpsampleMode::Nearest => KernelId::MlUpsample2dNearestF32,
159 UpsampleMode::Bilinear => KernelId::MlUpsample2dBilinearF32,
160 };
161 let buffers = [
162 BufferBinding::read(input.storage()),
163 BufferBinding::write(output.storage()),
164 ];
165 let push_constants = geometry.push_constants();
166 let attributes = make_attributes(scale_factor, mode)?;
167 {
168 let inputs: &[&Matrix] = &[input];
169 let outputs: &[&Matrix] = &[&output];
170 let attributes: &[OpAttribute] = &attributes;
171 let dispatch = ComputeDispatch {
172 kernel,
173 buffers: &buffers,
174 push_constants: &push_constants,
175 workgroups: geometry.forward_workgroups(),
176 indirect: None,
177 };
178 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
179 Error::internal(format!(
180 "lowering-only kernel {} cannot own one semantic ML operation",
181 dispatch.kernel.report_name()
182 ))
183 })?;
184 let runtime = inputs
185 .first()
186 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
187 .runtime();
188 runtime.record_semantic(
189 dispatch,
190 SemanticDispatch {
191 contract,
192 inputs,
193 outputs,
194 attributes,
195 },
196 )
197 }?;
198 autograd::record_upsample_2d(input, scale_factor, mode, &output)?;
199 Ok(output)
200}
201
202pub(in crate::ml) fn upsample_2d_backward(
203 input: &Matrix,
204 output_gradient: &Matrix,
205 scale_factor: usize,
206 mode: UpsampleMode,
207) -> Result<Matrix> {
208 let operation = crate::core::operation::ml::UPSAMPLE_2D_BACKWARD.name();
209 validate_f32_same_runtime(operation, &[input, output_gradient])?;
210 let geometry = Upsample2dGeometry::resolve(input, scale_factor, operation)?;
211 if output_gradient.shape() != geometry.output_shape() {
212 return Err(Error::invalid_argument(format!(
213 "{operation} output gradient shape {:?} does not match {:?}",
214 output_gradient.shape(),
215 geometry.output_shape()
216 )));
217 }
218 let input_gradient = Matrix::allocate(
219 input.runtime(),
220 input.shape().to_vec(),
221 input.num_elements(),
222 DType::F32,
223 )?;
224 let kernel = match mode {
225 UpsampleMode::Nearest => KernelId::MlUpsample2dNearestBackwardF32,
226 UpsampleMode::Bilinear => KernelId::MlUpsample2dBilinearBackwardF32,
227 };
228 let buffers = [
229 BufferBinding::read(output_gradient.storage()),
230 BufferBinding::write(input_gradient.storage()),
231 ];
232 let push_constants = geometry.push_constants();
233 let attributes = make_attributes(scale_factor, mode)?;
234 {
235 let inputs: &[&Matrix] = &[input, output_gradient];
236 let outputs: &[&Matrix] = &[&input_gradient];
237 let attributes: &[OpAttribute] = &attributes;
238 let dispatch = ComputeDispatch {
239 kernel,
240 buffers: &buffers,
241 push_constants: &push_constants,
242 workgroups: geometry.backward_workgroups(),
243 indirect: None,
244 };
245 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
246 Error::internal(format!(
247 "lowering-only kernel {} cannot own one semantic ML operation",
248 dispatch.kernel.report_name()
249 ))
250 })?;
251 let runtime = inputs
252 .first()
253 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
254 .runtime();
255 runtime.record_semantic(
256 dispatch,
257 SemanticDispatch {
258 contract,
259 inputs,
260 outputs,
261 attributes,
262 },
263 )
264 }?;
265 Ok(input_gradient)
266}