Skip to main content

oa/ml/nn/
utility.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_utility.json
3// generator_version=8; schema_sha256=e26e498a140eb3b89530554aa299a1fab82a06802c4645d946d2c4562d540ca7
4
5use crate::{Error, Matrix, Result};
6
7use super::super::{Module, ModuleRegistry, matrix};
8
9// OA donor: oacpp/source/cpp/lib/oa/ml/nn/identity/identity.cpp
10// Adaptation: Rust ownership, ModuleRegistry and checked error contracts; preserved operation behavior
11/// Return the input value unchanged.
12pub struct Identity {
13	registry: ModuleRegistry,
14}
15
16impl Identity {
17	/// Construct an identity module.
18	pub const fn new() -> Self {
19		Self {
20			registry: ModuleRegistry::new(),
21		}
22	}
23
24	/// Return a cheap handle to the same semantic Matrix value.
25	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
26		Ok(input.clone())
27	}
28}
29
30impl Default for Identity {
31	fn default() -> Self {
32		Self::new()
33	}
34}
35
36impl Module for Identity {
37	fn forward(&self, input: &Matrix) -> Result<Matrix> {
38		Identity::forward(self, input)
39	}
40
41	fn registry(&self) -> &ModuleRegistry {
42		&self.registry
43	}
44}
45
46// OA donor: oacpp/source/cpp/lib/oa/ml/nn/flatten/flatten.cpp
47// Adaptation: Rust ownership, ModuleRegistry and checked error contracts; preserved operation behavior
48/// Flatten an inclusive range of Matrix dimensions into one dimension.
49///
50/// Negative dimensions are resolved from the end at call time. The donor
51/// default `(1, -1)` preserves a leading batch dimension.
52pub struct Flatten {
53	start_dim: isize,
54	end_dim: isize,
55	registry: ModuleRegistry,
56}
57
58impl Flatten {
59	/// Construct a flatten module with PyTorch-style dimension indexing.
60	pub const fn new(start_dim: isize, end_dim: isize) -> Self {
61		Self {
62			start_dim,
63			end_dim,
64			registry: ModuleRegistry::new(),
65		}
66	}
67
68	/// Return the configured inclusive start dimension.
69	pub const fn start_dim(&self) -> isize {
70		self.start_dim
71	}
72
73	/// Return the configured inclusive end dimension.
74	pub const fn end_dim(&self) -> isize {
75		self.end_dim
76	}
77
78	/// Return a differentiable zero-copy flattened Matrix view.
79	///
80	/// Inputs of rank zero or one and positive start dimensions beyond the input
81	/// rank preserve the donor identity behavior.
82	///
83	/// # Errors
84	///
85	/// Returns an error when either resolved dimension is outside the input rank,
86	/// the resolved range is reversed, or the flattened extent overflows.
87	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
88		let rank = input.shape().len();
89		if rank <= 1 || self.start_dim >= 0 && self.start_dim as usize >= rank {
90			return Ok(input.clone());
91		}
92		let start = resolve_dim(self.start_dim, rank, "start")?;
93		let end = resolve_dim(self.end_dim, rank, "end")?;
94		if start > end {
95			return Err(Error::invalid_argument(format!(
96				"Flatten start dimension {start} exceeds end dimension {end}"
97			)));
98		}
99		let flattened = input.shape()[start..=end]
100			.iter()
101			.try_fold(1_usize, |extent, dimension| {
102				extent
103					.checked_mul(*dimension)
104					.ok_or_else(|| Error::resource_exhausted("Flatten extent overflows usize"))
105			})?;
106		let mut shape = Vec::with_capacity(rank - (end - start));
107		shape.extend_from_slice(&input.shape()[..start]);
108		shape.push(flattened);
109		shape.extend_from_slice(&input.shape()[end + 1..]);
110		input.reshape(shape)
111	}
112}
113
114impl Default for Flatten {
115	fn default() -> Self {
116		Self::new(1, -1)
117	}
118}
119
120impl Module for Flatten {
121	fn forward(&self, input: &Matrix) -> Result<Matrix> {
122		Flatten::forward(self, input)
123	}
124
125	fn registry(&self) -> &ModuleRegistry {
126		&self.registry
127	}
128}
129
130// OA donor: oacpp/source/cpp/lib/oa/ml/nn/unfold/unfold.cpp
131// Adaptation: Rust ownership, ModuleRegistry and checked error contracts; preserved operation behavior
132/// Extract NCHW sliding kernel windows into [N, C * kernel², L] column layout.
133pub struct Unfold {
134	kernel_size: usize,
135	stride: usize,
136	padding: usize,
137	dilation: usize,
138	registry: ModuleRegistry,
139}
140
141impl Unfold {
142	/// Construct Unfold with explicit sliding-window geometry.
143	///
144	/// # Errors
145	///
146	/// Returns an error when `kernel_size`, `stride`, or `dilation` is zero.
147	pub fn new(kernel_size: usize, stride: usize, padding: usize, dilation: usize) -> Result<Self> {
148		if kernel_size == 0 || stride == 0 || dilation == 0 {
149			return Err(crate::Error::invalid_argument(
150				"Unfold requires nonzero kernel size, stride, and dilation",
151			));
152		}
153		Ok(Self {
154			kernel_size,
155			stride,
156			padding,
157			dilation,
158			registry: ModuleRegistry::new(),
159		})
160	}
161
162	/// Extract NCHW sliding windows into column layout without submitting or waiting.
163	///
164	/// # Errors
165	///
166	/// Returns an error from the underlying Matrix operation.
167	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
168		matrix::unfold(
169			input,
170			self.kernel_size,
171			self.stride,
172			self.padding,
173			self.dilation,
174		)
175	}
176
177	/// Return the square kernel extent.
178	pub const fn kernel_size(&self) -> usize {
179		self.kernel_size
180	}
181
182	/// Return the spatial stride.
183	pub const fn stride(&self) -> usize {
184		self.stride
185	}
186
187	/// Return the symmetric zero-padding extent.
188	pub const fn padding(&self) -> usize {
189		self.padding
190	}
191
192	/// Return the kernel dilation.
193	pub const fn dilation(&self) -> usize {
194		self.dilation
195	}
196}
197
198impl Module for Unfold {
199	fn forward(&self, input: &Matrix) -> Result<Matrix> {
200		Unfold::forward(self, input)
201	}
202
203	fn registry(&self) -> &ModuleRegistry {
204		&self.registry
205	}
206}
207
208// OA donor: oacpp/source/cpp/lib/oa/ml/nn/fold/fold.cpp
209// Adaptation: Rust ownership, ModuleRegistry and checked error contracts; preserved operation behavior
210/// Combine [N, C * kernel², L] sliding columns into an overlapping NCHW image.
211pub struct Fold {
212	output_height: usize,
213	output_width: usize,
214	kernel_size: usize,
215	stride: usize,
216	padding: usize,
217	dilation: usize,
218	registry: ModuleRegistry,
219}
220
221impl Fold {
222	/// Construct Fold with explicit output extent and window geometry.
223	///
224	/// # Errors
225	///
226	/// Returns an error when any extent or `kernel_size`, `stride`, `dilation`
227	/// is zero.
228	pub fn new(
229		output_height: usize,
230		output_width: usize,
231		kernel_size: usize,
232		stride: usize,
233		padding: usize,
234		dilation: usize,
235	) -> Result<Self> {
236		if output_height == 0 || output_width == 0 || kernel_size == 0 || stride == 0 || dilation == 0 {
237			return Err(crate::Error::invalid_argument(
238				"Fold requires nonzero output extent, kernel size, stride, and dilation",
239			));
240		}
241		Ok(Self {
242			output_height,
243			output_width,
244			kernel_size,
245			stride,
246			padding,
247			dilation,
248			registry: ModuleRegistry::new(),
249		})
250	}
251
252	/// Combine sliding columns into an overlapping NCHW image without
253	/// submitting or waiting.
254	///
255	/// # Errors
256	///
257	/// Returns an error from the underlying Matrix operation.
258	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
259		matrix::fold(
260			input,
261			self.output_height,
262			self.output_width,
263			self.kernel_size,
264			self.stride,
265			self.padding,
266			self.dilation,
267		)
268	}
269
270	/// Return the reconstructed image height.
271	pub const fn output_height(&self) -> usize {
272		self.output_height
273	}
274
275	/// Return the reconstructed image width.
276	pub const fn output_width(&self) -> usize {
277		self.output_width
278	}
279
280	/// Return the square kernel extent.
281	pub const fn kernel_size(&self) -> usize {
282		self.kernel_size
283	}
284
285	/// Return the spatial stride.
286	pub const fn stride(&self) -> usize {
287		self.stride
288	}
289
290	/// Return the symmetric zero-padding extent.
291	pub const fn padding(&self) -> usize {
292		self.padding
293	}
294
295	/// Return the kernel dilation.
296	pub const fn dilation(&self) -> usize {
297		self.dilation
298	}
299}
300
301impl Module for Fold {
302	fn forward(&self, input: &Matrix) -> Result<Matrix> {
303		Fold::forward(self, input)
304	}
305
306	fn registry(&self) -> &ModuleRegistry {
307		&self.registry
308	}
309}
310
311fn resolve_dim(dimension: isize, rank: usize, label: &str) -> Result<usize> {
312	let rank =
313		isize::try_from(rank).map_err(|_| Error::resource_exhausted("Matrix rank exceeds isize"))?;
314	let resolved = if dimension < 0 {
315		rank
316			.checked_add(dimension)
317			.ok_or_else(|| Error::invalid_argument(format!("Flatten {label} dimension is invalid")))?
318	} else {
319		dimension
320	};
321	if !(0..rank).contains(&resolved) {
322		return Err(Error::invalid_argument(format!(
323			"Flatten {label} dimension {dimension} is outside rank {rank}"
324		)));
325	}
326	Ok(resolved as usize)
327}