1use crate::runtime::ComputeDispatch;
2use crate::runtime::SemanticDispatch;
3use crate::runtime::{BufferBinding, KernelId, PushConstant};
4use crate::{DType, Error, Matrix, OpAttribute, Result};
5
6use super::{
7 autograd,
8 validation::{shader_u32, validate_f32_same_runtime},
9};
10
11pub struct FlowMatchBatch {
13 pub state: Matrix,
15 pub velocity: Matrix,
17}
18
19pub fn linear_match(clean: &Matrix, noise: &Matrix, time: &Matrix) -> Result<FlowMatchBatch> {
30 let (state, velocity) = linear_match_dispatch(clean, noise, time)?;
31 autograd::record_flow_linear_match(clean, noise, time, &state, &velocity)?;
32 Ok(FlowMatchBatch { state, velocity })
33}
34
35pub fn euler_step(state: &Matrix, velocity: &Matrix, delta_time: f32) -> Result<Matrix> {
42 let output = euler_step_dispatch(state, velocity, delta_time)?;
43 autograd::record_flow_euler_step(state, velocity, delta_time, &output)?;
44 Ok(output)
45}
46
47pub fn masked_mse(prediction: &Matrix, target: &Matrix, mask: &Matrix) -> Result<Matrix> {
59 let (loss, denominator) = masked_mse_dispatch(prediction, target, mask)?;
60 autograd::record_flow_masked_mse(prediction, target, mask, &denominator, &loss)?;
61 Ok(loss)
62}
63
64fn linear_match_dispatch(
69 clean: &Matrix,
70 noise: &Matrix,
71 time: &Matrix,
72) -> Result<(Matrix, Matrix)> {
73 const OPERATION: &str = "oa::FnFlow::linearMatch";
74 validate_f32_same_runtime(OPERATION, &[clean, noise, time])?;
75 if clean.shape() != noise.shape() || clean.num_elements() == 0 || clean.shape().len() > 8 {
76 return Err(Error::invalid_argument(
77 "flow linear_match requires matching nonempty clean/noise shapes with rank at most eight",
78 ));
79 }
80 let (time_dims, time_strides) = broadcast_metadata(time.shape(), clean.shape(), true)?;
81 let state_strides = dense_strides(clean.shape())?;
82 let element_count = shader_u32(clean.num_elements(), "element count", OPERATION)?;
83 let rank = shader_u32(clean.shape().len(), "rank", OPERATION)?;
84 let state = Matrix::allocate(
85 clean.runtime(),
86 clean.shape().to_vec(),
87 clean.num_elements(),
88 DType::F32,
89 )?;
90 let velocity = Matrix::allocate(
91 clean.runtime(),
92 clean.shape().to_vec(),
93 clean.num_elements(),
94 DType::F32,
95 )?;
96 let buffers = [
97 BufferBinding::read(clean.storage()),
98 BufferBinding::read(noise.storage()),
99 BufferBinding::read(time.storage()),
100 BufferBinding::write(state.storage()),
101 BufferBinding::write(velocity.storage()),
102 ];
103 let mut push_constants = Vec::with_capacity(26);
104 push_constants.push(PushConstant::U32(element_count));
105 push_constants.push(PushConstant::U32(rank));
106 extend_u32(&mut push_constants, state_strides);
107 extend_u32(&mut push_constants, time_dims);
108 extend_u32(&mut push_constants, time_strides);
109 {
110 let inputs: &[&Matrix] = &[clean, noise, time];
111 let outputs: &[&Matrix] = &[&state, &velocity];
112 let attributes: &[OpAttribute] = &[];
113 let dispatch = ComputeDispatch {
114 kernel: KernelId::MlFlowLinearMatchF32,
115 buffers: &buffers,
116 push_constants: &push_constants,
117 workgroups: KernelId::MlFlowLinearMatchF32.linear_workgroups(element_count),
118 indirect: None,
119 };
120 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
121 Error::internal(format!(
122 "lowering-only kernel {} cannot own one semantic ML operation",
123 dispatch.kernel.report_name()
124 ))
125 })?;
126 let runtime = inputs
127 .first()
128 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
129 .runtime();
130 runtime.record_semantic(
131 dispatch,
132 SemanticDispatch {
133 contract,
134 inputs,
135 outputs,
136 attributes,
137 },
138 )
139 }?;
140 Ok((state, velocity))
141}
142
143fn euler_step_dispatch(state: &Matrix, velocity: &Matrix, delta_time: f32) -> Result<Matrix> {
144 const OPERATION: &str = "oa::FnFlow::eulerStep";
145 validate_f32_same_runtime(OPERATION, &[state, velocity])?;
146 if state.shape() != velocity.shape() || state.num_elements() == 0 || !delta_time.is_finite() {
147 return Err(Error::invalid_argument(
148 "flow euler_step requires matching nonempty F32 state/velocity and finite delta_time",
149 ));
150 }
151 let element_count = shader_u32(state.num_elements(), "element count", OPERATION)?;
152 let output = Matrix::allocate(
153 state.runtime(),
154 state.shape().to_vec(),
155 state.num_elements(),
156 DType::F32,
157 )?;
158 let buffers = [
159 BufferBinding::read(state.storage()),
160 BufferBinding::read(velocity.storage()),
161 BufferBinding::write(output.storage()),
162 ];
163 let push_constants = [
164 PushConstant::U32(element_count),
165 PushConstant::F32(delta_time),
166 ];
167 let attributes = [OpAttribute::Float {
168 name: "deltaTime".to_owned(),
169 value: f64::from(delta_time),
170 }];
171 {
172 let inputs: &[&Matrix] = &[state, velocity];
173 let outputs: &[&Matrix] = &[&output];
174 let attributes: &[OpAttribute] = &attributes;
175 let dispatch = ComputeDispatch {
176 kernel: KernelId::MlFlowEulerStepF32,
177 buffers: &buffers,
178 push_constants: &push_constants,
179 workgroups: KernelId::MlFlowEulerStepF32.linear_workgroups(element_count),
180 indirect: None,
181 };
182 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
183 Error::internal(format!(
184 "lowering-only kernel {} cannot own one semantic ML operation",
185 dispatch.kernel.report_name()
186 ))
187 })?;
188 let runtime = inputs
189 .first()
190 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
191 .runtime();
192 runtime.record_semantic(
193 dispatch,
194 SemanticDispatch {
195 contract,
196 inputs,
197 outputs,
198 attributes,
199 },
200 )
201 }?;
202 Ok(output)
203}
204
205fn masked_mse_dispatch(
206 prediction: &Matrix,
207 target: &Matrix,
208 mask: &Matrix,
209) -> Result<(Matrix, Matrix)> {
210 const OPERATION: &str = "oa::FnFlow::maskedMse";
211 validate_f32_same_runtime(OPERATION, &[prediction, target, mask])?;
212 if prediction.shape() != target.shape()
213 || prediction.num_elements() == 0
214 || prediction.shape().len() > 8
215 {
216 return Err(Error::invalid_argument(
217 "flow masked_mse requires matching nonempty prediction/target shapes with rank at most eight",
218 ));
219 }
220 let (mask_dims, mask_strides) = broadcast_metadata(mask.shape(), prediction.shape(), false)?;
221 let prediction_strides = dense_strides(prediction.shape())?;
222 let element_count = shader_u32(prediction.num_elements(), "element count", OPERATION)?;
223 let rank = shader_u32(prediction.shape().len(), "rank", OPERATION)?;
224 let loss = Matrix::allocate(prediction.runtime(), Vec::new(), 1, DType::F32)?;
225 let denominator = Matrix::allocate(prediction.runtime(), Vec::new(), 1, DType::F32)?;
226 let buffers = [
227 BufferBinding::read(prediction.storage()),
228 BufferBinding::read(target.storage()),
229 BufferBinding::read(mask.storage()),
230 BufferBinding::write(loss.storage()),
231 BufferBinding::write(denominator.storage()),
232 ];
233 let push_constants = shape_push_constants(
234 element_count,
235 rank,
236 prediction_strides,
237 mask_dims,
238 mask_strides,
239 );
240 {
241 let inputs: &[&Matrix] = &[prediction, target, mask];
242 let outputs: &[&Matrix] = &[&loss];
243 let attributes: &[OpAttribute] = &[];
244 let dispatch = ComputeDispatch {
245 kernel: KernelId::MlFlowMaskedMseF32,
246 buffers: &buffers,
247 push_constants: &push_constants,
248 workgroups: [1, 1, 1],
249 indirect: None,
250 };
251 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
252 Error::internal(format!(
253 "lowering-only kernel {} cannot own one semantic ML operation",
254 dispatch.kernel.report_name()
255 ))
256 })?;
257 let runtime = inputs
258 .first()
259 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
260 .runtime();
261 runtime.record_semantic(
262 dispatch,
263 SemanticDispatch {
264 contract,
265 inputs,
266 outputs,
267 attributes,
268 },
269 )
270 }?;
271 Ok((loss, denominator))
272}
273
274pub(in crate::ml) fn masked_mse_backward(
275 prediction: &Matrix,
276 target: &Matrix,
277 mask: &Matrix,
278 denominator: &Matrix,
279 upstream: &Matrix,
280) -> Result<Matrix> {
281 const OPERATION: &str = "oa::ml::flow::masked_mse_backward";
282 validate_f32_same_runtime(
283 OPERATION,
284 &[prediction, target, mask, denominator, upstream],
285 )?;
286 if prediction.shape() != target.shape()
287 || prediction.num_elements() == 0
288 || prediction.shape().len() > 8
289 || !denominator.shape().is_empty()
290 || !upstream.shape().is_empty()
291 {
292 return Err(Error::invalid_argument(
293 "flow masked_mse backward received invalid saved values or scalar upstream",
294 ));
295 }
296 let (mask_dims, mask_strides) = broadcast_metadata(mask.shape(), prediction.shape(), false)?;
297 let prediction_strides = dense_strides(prediction.shape())?;
298 let element_count = shader_u32(prediction.num_elements(), "element count", OPERATION)?;
299 let rank = shader_u32(prediction.shape().len(), "rank", OPERATION)?;
300 let gradient = Matrix::allocate(
301 prediction.runtime(),
302 prediction.shape().to_vec(),
303 prediction.num_elements(),
304 DType::F32,
305 )?;
306 let buffers = [
307 BufferBinding::read(prediction.storage()),
308 BufferBinding::read(target.storage()),
309 BufferBinding::read(mask.storage()),
310 BufferBinding::read(denominator.storage()),
311 BufferBinding::read(upstream.storage()),
312 BufferBinding::write(gradient.storage()),
313 ];
314 let push_constants = shape_push_constants(
315 element_count,
316 rank,
317 prediction_strides,
318 mask_dims,
319 mask_strides,
320 );
321 {
322 let inputs: &[&Matrix] = &[prediction, target, mask, denominator, upstream];
323 let outputs: &[&Matrix] = &[&gradient];
324 let attributes: &[OpAttribute] = &[];
325 let dispatch = ComputeDispatch {
326 kernel: KernelId::MlFlowMaskedMseBackwardF32,
327 buffers: &buffers,
328 push_constants: &push_constants,
329 workgroups: KernelId::MlFlowMaskedMseBackwardF32.linear_workgroups(element_count),
330 indirect: None,
331 };
332 let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
333 Error::internal(format!(
334 "lowering-only kernel {} cannot own one semantic ML operation",
335 dispatch.kernel.report_name()
336 ))
337 })?;
338 let runtime = inputs
339 .first()
340 .ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
341 .runtime();
342 runtime.record_semantic(
343 dispatch,
344 SemanticDispatch {
345 contract,
346 inputs,
347 outputs,
348 attributes,
349 },
350 )
351 }?;
352 Ok(gradient)
353}
354
355fn shape_push_constants(
360 element_count: u32,
361 rank: u32,
362 first_strides: [u32; 8],
363 second_dims: [u32; 8],
364 second_strides: [u32; 8],
365) -> Vec<PushConstant> {
366 let mut push_constants = Vec::with_capacity(26);
367 push_constants.push(PushConstant::U32(element_count));
368 push_constants.push(PushConstant::U32(rank));
369 extend_u32(&mut push_constants, first_strides);
370 extend_u32(&mut push_constants, second_dims);
371 extend_u32(&mut push_constants, second_strides);
372 push_constants
373}
374
375fn extend_u32(output: &mut Vec<PushConstant>, values: [u32; 8]) {
376 output.extend(values.into_iter().map(PushConstant::U32));
377}
378
379fn dense_strides(shape: &[usize]) -> Result<[u32; 8]> {
380 let mut output = [1_u32; 8];
381 let mut stride = 1_usize;
382 for axis in (0..shape.len()).rev() {
383 output[axis] = u32::try_from(stride)
384 .map_err(|_| Error::invalid_argument("flow stride exceeds shader u32 ABI"))?;
385 stride = stride
386 .checked_mul(shape[axis])
387 .ok_or_else(|| Error::invalid_argument("flow shape stride overflows usize"))?;
388 }
389 Ok(output)
390}
391
392fn broadcast_metadata(
393 input_shape: &[usize],
394 output_shape: &[usize],
395 batch_vector_special_case: bool,
396) -> Result<([u32; 8], [u32; 8])> {
397 if input_shape.len() > output_shape.len() || output_shape.len() > 8 {
398 return Err(Error::invalid_argument(
399 "flow input is not broadcastable to the output shape",
400 ));
401 }
402 let mut expanded = [1_usize; 8];
403 if batch_vector_special_case
404 && input_shape.len() == 1
405 && output_shape.len() > 1
406 && (input_shape[0] == 1 || input_shape[0] == output_shape[0])
407 {
408 expanded[0] = input_shape[0];
409 } else {
410 let offset = output_shape.len() - input_shape.len();
411 for (axis, extent) in input_shape.iter().copied().enumerate() {
412 expanded[offset + axis] = extent;
413 }
414 }
415 for axis in 0..output_shape.len() {
416 if expanded[axis] != 1 && expanded[axis] != output_shape[axis] {
417 return Err(Error::invalid_argument(
418 "flow input is not broadcastable to the output shape",
419 ));
420 }
421 }
422 let strides = dense_strides(&expanded[..output_shape.len()])?;
423 let mut dims = [1_u32; 8];
424 for axis in 0..output_shape.len() {
425 dims[axis] = shader_u32(expanded[axis], "broadcast extent", "flow broadcast")?;
426 }
427 Ok((dims, strides))
428}