Skip to main content

oa/ml/nn/
conv.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_conv.json
3// generator_version=8; schema_sha256=9391a55e95880b1f5aa8b0173e618a86b7f55fdf92d2bbe2daec4f82530fae4a
4
5use crate::{DType, Error, Matrix, Result, Runtime};
6
7use super::super::{Module, ModuleRegistry, Parameter, matrix, random};
8
9// OA donor: oacpp/source/cpp/lib/oa/ml/nn/conv1d/conv1d.cpp
10// Adaptation: Preserve existing Rust initializer, shape/ownership checks and versioned parameter adjoints; mechanical generated ownership
11/// Trainable FP32 one-dimensional convolution over NCL matrices.
12pub struct Conv1d {
13	input_channels: usize,
14	output_channels: usize,
15	kernel_size: usize,
16	stride: usize,
17	padding: usize,
18	dilation: usize,
19	weight: Parameter,
20	bias: Parameter,
21	registry: ModuleRegistry,
22}
23
24impl Conv1d {
25	/// Construct a deterministically initialized Conv1d layer.
26	///
27	/// Forward preserves OA's im2col plus tiled-GEMM route. Weight uses a
28	/// fan-in-scaled symmetric uniform initializer and bias starts at zero.
29	///
30	/// # Errors
31	///
32	/// Returns an error when dimensions, stride, or dilation are zero, shape
33	/// arithmetic overflows, or allocation/upload fails.
34	#[allow(
35		clippy::too_many_arguments,
36		reason = "the donor Conv1d contract has five geometry fields plus a seed"
37	)]
38	pub fn new_with_seed(
39		input_channels: usize,
40		output_channels: usize,
41		kernel_size: usize,
42		stride: usize,
43		padding: usize,
44		dilation: usize,
45		seed: u64,
46	) -> Result<Self> {
47		Self::new_with_seed_on(
48			&Runtime::current()?,
49			input_channels,
50			output_channels,
51			kernel_size,
52			stride,
53			padding,
54			dilation,
55			seed,
56		)
57	}
58
59	#[allow(clippy::too_many_arguments)]
60	pub fn new_with_seed_on(
61		runtime: &Runtime,
62		input_channels: usize,
63		output_channels: usize,
64		kernel_size: usize,
65		stride: usize,
66		padding: usize,
67		dilation: usize,
68		seed: u64,
69	) -> Result<Self> {
70		if input_channels == 0
71			|| output_channels == 0
72			|| kernel_size == 0
73			|| stride == 0
74			|| dilation == 0
75		{
76			return Err(Error::invalid_argument(
77				"Conv1d requires nonzero channels, kernel size, stride, and dilation",
78			));
79		}
80		let fan_in = input_channels
81			.checked_mul(kernel_size)
82			.ok_or_else(|| Error::invalid_argument("Conv1d fan-in overflows usize"))?;
83		let weight_count = output_channels
84			.checked_mul(fan_in)
85			.ok_or_else(|| Error::invalid_argument("Conv1d weight size overflows usize"))?;
86		let limit = 1.0_f32 / (fan_in as f32).sqrt();
87		let values = random::symmetric_uniform(weight_count, limit, seed);
88		let weight = Matrix::new_from_f32_on(
89			runtime,
90			[output_channels, input_channels, kernel_size],
91			&values,
92		)?;
93		let bias = Matrix::new_from_f32_on(runtime, [output_channels], &vec![0.0; output_channels])?;
94		Self::new_from_matrices(weight, bias, stride, padding, dilation)
95	}
96
97	/// Construct Conv1d from exact OIK weight and channel-bias matrices.
98	///
99	/// # Errors
100	///
101	/// Returns an error unless weight is nonempty F32 `[O, I, K]`, bias is
102	/// matching same-runtime F32 `[O]`, and stride/dilation are nonzero.
103	pub fn new_from_matrices(
104		weight: Matrix,
105		bias: Matrix,
106		stride: usize,
107		padding: usize,
108		dilation: usize,
109	) -> Result<Self> {
110		let [output_channels, input_channels, kernel_size] = weight.shape() else {
111			return Err(Error::invalid_argument(
112				"Conv1d weight must have OIK rank three",
113			));
114		};
115		if *output_channels == 0
116			|| *input_channels == 0
117			|| *kernel_size == 0
118			|| stride == 0
119			|| dilation == 0
120			|| bias.shape() != [*output_channels]
121			|| weight.dtype() != DType::F32
122			|| bias.dtype() != DType::F32
123			|| !weight.runtime().same_as(bias.runtime())
124		{
125			return Err(Error::invalid_argument(
126				"Conv1d requires nonempty same-runtime F32 OIK weight, matching bias, and nonzero stride/dilation",
127			));
128		}
129		let input_channels = *input_channels;
130		let output_channels = *output_channels;
131		let kernel_size = *kernel_size;
132		let weight = Parameter::new("weight", weight)?;
133		let bias = Parameter::new("bias", bias)?;
134		let mut registry = ModuleRegistry::new();
135		registry.register_parameter("weight", weight.clone())?;
136		registry.register_parameter("bias", bias.clone())?;
137		Ok(Self {
138			input_channels,
139			output_channels,
140			kernel_size,
141			stride,
142			padding,
143			dilation,
144			weight,
145			bias,
146			registry,
147		})
148	}
149
150	/// Apply Conv1d without submitting or waiting.
151	///
152	/// # Errors
153	///
154	/// Returns an error from the underlying Matrix operation.
155	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
156		let (weight, weight_version, _) = self.weight.snapshot();
157		let (bias, bias_version, _) = self.bias.snapshot();
158		matrix::conv_1d_parameterized(
159			input,
160			(self.weight.clone(), weight, weight_version),
161			(self.bias.clone(), bias, bias_version),
162			self.stride,
163			self.padding,
164			self.dilation,
165		)
166	}
167
168	/// Return the input channel count.
169	pub const fn input_channels(&self) -> usize {
170		self.input_channels
171	}
172
173	/// Return the output channel count.
174	pub const fn output_channels(&self) -> usize {
175		self.output_channels
176	}
177
178	/// Return the kernel extent.
179	pub const fn kernel_size(&self) -> usize {
180		self.kernel_size
181	}
182
183	/// Return the spatial stride.
184	pub const fn stride(&self) -> usize {
185		self.stride
186	}
187
188	/// Return the symmetric zero-padding extent.
189	pub const fn padding(&self) -> usize {
190		self.padding
191	}
192
193	/// Return the within-kernel dilation.
194	pub const fn dilation(&self) -> usize {
195		self.dilation
196	}
197
198	/// Return the stable OIK weight parameter.
199	pub fn weight(&self) -> Parameter {
200		self.weight.clone()
201	}
202
203	/// Return the stable channel-bias parameter.
204	pub fn bias(&self) -> Parameter {
205		self.bias.clone()
206	}
207
208	/// Return parameters in deterministic weight, bias order.
209	pub fn parameters(&self) -> [Parameter; 2] {
210		[self.weight.clone(), self.bias.clone()]
211	}
212}
213
214impl Module for Conv1d {
215	fn forward(&self, input: &Matrix) -> Result<Matrix> {
216		Conv1d::forward(self, input)
217	}
218
219	fn registry(&self) -> &ModuleRegistry {
220		&self.registry
221	}
222}
223
224// OA donor: oacpp/source/cpp/lib/oa/ml/nn/convtranspose1d/convTranspose1d.cpp
225// Adaptation: Preserve existing Rust initializer, shape/ownership checks and versioned parameter adjoints; mechanical generated ownership
226/// Trainable bias-free FP32 one-dimensional transposed convolution over NCL matrices.
227pub struct ConvTranspose1d {
228	input_channels: usize,
229	output_channels: usize,
230	kernel_size: usize,
231	stride: usize,
232	padding: usize,
233	weight: Parameter,
234	registry: ModuleRegistry,
235}
236
237impl ConvTranspose1d {
238	/// Construct a deterministically initialized ConvTranspose1d layer.
239	///
240	/// Weight uses the donor `[input_channels, output_channels, kernel]` layout,
241	/// a fan-in-scaled symmetric uniform initializer, and no bias parameter.
242	///
243	/// # Errors
244	///
245	/// Returns an error when channels, kernel size, or stride are zero, shape
246	/// arithmetic overflows, or parameter allocation/upload fails.
247	#[allow(
248		clippy::too_many_arguments,
249		reason = "the donor ConvTranspose1d contract has five geometry fields plus a seed"
250	)]
251	pub fn new_with_seed(
252		input_channels: usize,
253		output_channels: usize,
254		kernel_size: usize,
255		stride: usize,
256		padding: usize,
257		seed: u64,
258	) -> Result<Self> {
259		Self::new_with_seed_on(
260			&Runtime::current()?,
261			input_channels,
262			output_channels,
263			kernel_size,
264			stride,
265			padding,
266			seed,
267		)
268	}
269
270	#[allow(clippy::too_many_arguments)]
271	pub fn new_with_seed_on(
272		runtime: &Runtime,
273		input_channels: usize,
274		output_channels: usize,
275		kernel_size: usize,
276		stride: usize,
277		padding: usize,
278		seed: u64,
279	) -> Result<Self> {
280		if input_channels == 0 || output_channels == 0 || kernel_size == 0 || stride == 0 {
281			return Err(Error::invalid_argument(
282				"ConvTranspose1d requires nonzero channels, kernel size, and stride",
283			));
284		}
285		let fan_in = output_channels
286			.checked_mul(kernel_size)
287			.ok_or_else(|| Error::invalid_argument("ConvTranspose1d fan-in overflows usize"))?;
288		let weight_count = input_channels
289			.checked_mul(fan_in)
290			.ok_or_else(|| Error::invalid_argument("ConvTranspose1d weight size overflows usize"))?;
291		let limit = 1.0_f32 / (fan_in as f32).sqrt();
292		let values = random::symmetric_uniform(weight_count, limit, seed);
293		let weight = Matrix::new_from_f32_on(
294			runtime,
295			[input_channels, output_channels, kernel_size],
296			&values,
297		)?;
298		Self::new_from_matrix(weight, stride, padding)
299	}
300
301	/// Construct ConvTranspose1d from an exact IOK weight matrix.
302	///
303	/// # Errors
304	///
305	/// Returns an error unless weight is nonempty F32 `[I, O, K]` and stride is
306	/// nonzero.
307	pub fn new_from_matrix(weight: Matrix, stride: usize, padding: usize) -> Result<Self> {
308		let [input_channels, output_channels, kernel_size] = weight.shape() else {
309			return Err(Error::invalid_argument(
310				"ConvTranspose1d weight must have IOK rank three",
311			));
312		};
313		if *input_channels == 0
314			|| *output_channels == 0
315			|| *kernel_size == 0
316			|| stride == 0
317			|| weight.dtype() != DType::F32
318		{
319			return Err(Error::invalid_argument(
320				"ConvTranspose1d requires nonempty F32 IOK weight and nonzero stride",
321			));
322		}
323		let input_channels = *input_channels;
324		let output_channels = *output_channels;
325		let kernel_size = *kernel_size;
326		let weight = Parameter::new("weight", weight)?;
327		let mut registry = ModuleRegistry::new();
328		registry.register_parameter("weight", weight.clone())?;
329		Ok(Self {
330			input_channels,
331			output_channels,
332			kernel_size,
333			stride,
334			padding,
335			weight,
336			registry,
337		})
338	}
339
340	/// Apply ConvTranspose1d without submitting or waiting.
341	///
342	/// # Errors
343	///
344	/// Returns an error from the underlying Matrix operation.
345	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
346		let (weight, weight_version, _) = self.weight.snapshot();
347		matrix::conv_1d_transpose_parameterized(
348			input,
349			(self.weight.clone(), weight, weight_version),
350			self.stride,
351			self.padding,
352			1,
353		)
354	}
355
356	/// Return the input channel count.
357	pub const fn input_channels(&self) -> usize {
358		self.input_channels
359	}
360
361	/// Return the output channel count.
362	pub const fn output_channels(&self) -> usize {
363		self.output_channels
364	}
365
366	/// Return the kernel extent.
367	pub const fn kernel_size(&self) -> usize {
368		self.kernel_size
369	}
370
371	/// Return the spatial stride.
372	pub const fn stride(&self) -> usize {
373		self.stride
374	}
375
376	/// Return the symmetric zero-padding extent.
377	pub const fn padding(&self) -> usize {
378		self.padding
379	}
380
381	/// Return the stable IOK weight parameter.
382	pub fn weight(&self) -> Parameter {
383		self.weight.clone()
384	}
385
386	/// Return the only trainable parameter.
387	pub fn parameters(&self) -> [Parameter; 1] {
388		[self.weight.clone()]
389	}
390}
391
392impl Module for ConvTranspose1d {
393	fn forward(&self, input: &Matrix) -> Result<Matrix> {
394		ConvTranspose1d::forward(self, input)
395	}
396
397	fn registry(&self) -> &ModuleRegistry {
398		&self.registry
399	}
400}
401
402// OA donor: oacpp/source/cpp/lib/oa/ml/nn/convtranspose2d/convTranspose2d.cpp
403// Adaptation: Preserve existing Rust initializer, shape/ownership checks and versioned parameter adjoints; mechanical generated ownership
404/// Trainable FP32 two-dimensional transposed convolution over NCHW matrices.
405pub struct ConvTranspose2d {
406	input_channels: usize,
407	output_channels: usize,
408	kernel_size: usize,
409	stride: usize,
410	padding: usize,
411	weight: Parameter,
412	bias: Parameter,
413	registry: ModuleRegistry,
414}
415
416impl ConvTranspose2d {
417	/// Construct a deterministically initialized ConvTranspose2d layer.
418	///
419	/// Weight uses `[input_channels, output_channels, kernel, kernel]` layout,
420	/// a fan-in-scaled symmetric uniform initializer, and zero channel bias.
421	///
422	/// # Errors
423	///
424	/// Returns an error when channels, kernel size, or stride are zero, shape
425	/// arithmetic overflows, or parameter allocation/upload fails.
426	#[allow(
427		clippy::too_many_arguments,
428		reason = "the donor ConvTranspose2d contract has five geometry fields plus a seed"
429	)]
430	pub fn new_with_seed(
431		input_channels: usize,
432		output_channels: usize,
433		kernel_size: usize,
434		stride: usize,
435		padding: usize,
436		seed: u64,
437	) -> Result<Self> {
438		Self::new_with_seed_on(
439			&Runtime::current()?,
440			input_channels,
441			output_channels,
442			kernel_size,
443			stride,
444			padding,
445			seed,
446		)
447	}
448
449	#[allow(clippy::too_many_arguments)]
450	pub fn new_with_seed_on(
451		runtime: &Runtime,
452		input_channels: usize,
453		output_channels: usize,
454		kernel_size: usize,
455		stride: usize,
456		padding: usize,
457		seed: u64,
458	) -> Result<Self> {
459		if input_channels == 0 || output_channels == 0 || kernel_size == 0 || stride == 0 {
460			return Err(Error::invalid_argument(
461				"ConvTranspose2d requires nonzero channels, kernel size, and stride",
462			));
463		}
464		let fan_in = output_channels
465			.checked_mul(kernel_size)
466			.and_then(|count| count.checked_mul(kernel_size))
467			.ok_or_else(|| Error::invalid_argument("ConvTranspose2d fan-in overflows usize"))?;
468		let weight_count = input_channels
469			.checked_mul(fan_in)
470			.ok_or_else(|| Error::invalid_argument("ConvTranspose2d weight size overflows usize"))?;
471		let limit = 1.0_f32 / (fan_in as f32).sqrt();
472		let values = random::symmetric_uniform(weight_count, limit, seed);
473		let weight = Matrix::new_from_f32_on(
474			runtime,
475			[input_channels, output_channels, kernel_size, kernel_size],
476			&values,
477		)?;
478		let bias = Matrix::new_from_f32_on(runtime, [output_channels], &vec![0.0; output_channels])?;
479		Self::new_from_matrices(weight, bias, stride, padding)
480	}
481
482	/// Construct ConvTranspose2d from exact IOKK weight and channel-bias matrices.
483	///
484	/// # Errors
485	///
486	/// Returns an error unless weight is nonempty F32 `[I, O, K, K]`, bias is
487	/// matching same-runtime F32 `[O]`, and stride is nonzero.
488	pub fn new_from_matrices(
489		weight: Matrix,
490		bias: Matrix,
491		stride: usize,
492		padding: usize,
493	) -> Result<Self> {
494		let [input_channels, output_channels, kernel_height, kernel_width] = weight.shape() else {
495			return Err(Error::invalid_argument(
496				"ConvTranspose2d weight must have IOKK rank four",
497			));
498		};
499		if *input_channels == 0
500			|| *output_channels == 0
501			|| *kernel_height == 0
502			|| kernel_height != kernel_width
503			|| stride == 0
504			|| bias.shape() != [*output_channels]
505			|| weight.dtype() != DType::F32
506			|| bias.dtype() != DType::F32
507			|| !weight.runtime().same_as(bias.runtime())
508		{
509			return Err(Error::invalid_argument(
510				"ConvTranspose2d requires nonempty same-runtime F32 square IOKK weight, matching bias, and nonzero stride",
511			));
512		}
513		let input_channels = *input_channels;
514		let output_channels = *output_channels;
515		let kernel_size = *kernel_height;
516		let weight = Parameter::new("weight", weight)?;
517		let bias = Parameter::new("bias", bias)?;
518		let mut registry = ModuleRegistry::new();
519		registry.register_parameter("weight", weight.clone())?;
520		registry.register_parameter("bias", bias.clone())?;
521		Ok(Self {
522			input_channels,
523			output_channels,
524			kernel_size,
525			stride,
526			padding,
527			weight,
528			bias,
529			registry,
530		})
531	}
532
533	/// Apply ConvTranspose2d without submitting or waiting.
534	///
535	/// # Errors
536	///
537	/// Returns an error from the underlying Matrix operation.
538	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
539		let (weight, weight_version, _) = self.weight.snapshot();
540		let (bias, bias_version, _) = self.bias.snapshot();
541		matrix::conv_2d_transpose_parameterized(
542			input,
543			(self.weight.clone(), weight, weight_version),
544			(self.bias.clone(), bias, bias_version),
545			self.stride,
546			self.padding,
547		)
548	}
549
550	/// Return the input channel count.
551	pub const fn input_channels(&self) -> usize {
552		self.input_channels
553	}
554
555	/// Return the output channel count.
556	pub const fn output_channels(&self) -> usize {
557		self.output_channels
558	}
559
560	/// Return the square kernel extent.
561	pub const fn kernel_size(&self) -> usize {
562		self.kernel_size
563	}
564
565	/// Return the spatial stride.
566	pub const fn stride(&self) -> usize {
567		self.stride
568	}
569
570	/// Return the symmetric zero-padding extent.
571	pub const fn padding(&self) -> usize {
572		self.padding
573	}
574
575	/// Return the stable IOKK weight parameter.
576	pub fn weight(&self) -> Parameter {
577		self.weight.clone()
578	}
579
580	/// Return the stable channel-bias parameter.
581	pub fn bias(&self) -> Parameter {
582		self.bias.clone()
583	}
584
585	/// Return parameters in deterministic weight, bias order.
586	pub fn parameters(&self) -> [Parameter; 2] {
587		[self.weight.clone(), self.bias.clone()]
588	}
589}
590
591impl Module for ConvTranspose2d {
592	fn forward(&self, input: &Matrix) -> Result<Matrix> {
593		ConvTranspose2d::forward(self, input)
594	}
595
596	fn registry(&self) -> &ModuleRegistry {
597		&self.registry
598	}
599}
600
601// OA donor: oacpp/source/cpp/lib/oa/ml/nn/conv2d/conv2d.cpp
602// Adaptation: Preserve existing Rust initializer, shape/ownership checks and versioned parameter adjoints; mechanical generated ownership
603/// Trainable grouped FP32 two-dimensional convolution over NCHW matrices.
604pub struct Conv2d {
605	input_channels: usize,
606	output_channels: usize,
607	kernel_size: usize,
608	stride: usize,
609	padding: usize,
610	groups: usize,
611	weight: Parameter,
612	bias: Parameter,
613	registry: ModuleRegistry,
614}
615
616impl Conv2d {
617	/// Construct a deterministically initialized grouped Conv2d layer.
618	///
619	/// The weight initializer is symmetric uniform with bound
620	/// `1 / sqrt((input_channels / groups) * kernel_size²)`; bias starts at zero.
621	///
622	/// # Errors
623	///
624	/// Returns an error when dimensions are zero, channels are not divisible by
625	/// `groups`, shape arithmetic overflows, or allocation/upload fails.
626	#[allow(
627		clippy::too_many_arguments,
628		reason = "the donor Conv2d contract has six independent geometry fields plus a seed"
629	)]
630	pub fn new_with_seed(
631		input_channels: usize,
632		output_channels: usize,
633		kernel_size: usize,
634		stride: usize,
635		padding: usize,
636		groups: usize,
637		seed: u64,
638	) -> Result<Self> {
639		Self::new_with_seed_on(
640			&Runtime::current()?,
641			input_channels,
642			output_channels,
643			kernel_size,
644			stride,
645			padding,
646			groups,
647			seed,
648		)
649	}
650
651	#[allow(clippy::too_many_arguments)]
652	pub fn new_with_seed_on(
653		runtime: &Runtime,
654		input_channels: usize,
655		output_channels: usize,
656		kernel_size: usize,
657		stride: usize,
658		padding: usize,
659		groups: usize,
660		seed: u64,
661	) -> Result<Self> {
662		if input_channels == 0
663			|| output_channels == 0
664			|| kernel_size == 0
665			|| stride == 0
666			|| groups == 0
667			|| !input_channels.is_multiple_of(groups)
668			|| !output_channels.is_multiple_of(groups)
669		{
670			return Err(Error::invalid_argument(
671				"Conv2d requires nonzero dimensions and channels divisible by groups",
672			));
673		}
674		let input_channels_per_group = input_channels / groups;
675		let fan_in = input_channels_per_group
676			.checked_mul(kernel_size)
677			.and_then(|count| count.checked_mul(kernel_size))
678			.ok_or_else(|| Error::invalid_argument("Conv2d fan-in overflows usize"))?;
679		let weight_count = output_channels
680			.checked_mul(fan_in)
681			.ok_or_else(|| Error::invalid_argument("Conv2d weight size overflows usize"))?;
682		let limit = 1.0_f32 / (fan_in as f32).sqrt();
683		let weight_values = random::symmetric_uniform(weight_count, limit, seed);
684		let weight = Matrix::new_from_f32_on(
685			runtime,
686			[
687				output_channels,
688				input_channels_per_group,
689				kernel_size,
690				kernel_size,
691			],
692			&weight_values,
693		)?;
694		let bias = Matrix::new_from_f32_on(runtime, [output_channels], &vec![0.0; output_channels])?;
695		Self::new_from_matrices(weight, bias, stride, padding, groups)
696	}
697
698	/// Construct Conv2d from exact grouped OIHW weight and bias matrices.
699	///
700	/// # Errors
701	///
702	/// Returns an error unless weight is nonempty square-kernel F32 OIHW/group,
703	/// bias is matching same-runtime F32, stride/groups are nonzero, and output
704	/// channels are divisible by groups.
705	pub fn new_from_matrices(
706		weight: Matrix,
707		bias: Matrix,
708		stride: usize,
709		padding: usize,
710		groups: usize,
711	) -> Result<Self> {
712		let [
713			output_channels,
714			input_channels_per_group,
715			kernel_height,
716			kernel_width,
717		] = weight.shape()
718		else {
719			return Err(Error::invalid_argument(
720				"Conv2d weight must have grouped OIHW rank four",
721			));
722		};
723		let input_channels = input_channels_per_group
724			.checked_mul(groups)
725			.ok_or_else(|| Error::invalid_argument("Conv2d input channel count overflows usize"))?;
726		if *output_channels == 0
727			|| *input_channels_per_group == 0
728			|| *kernel_height == 0
729			|| kernel_height != kernel_width
730			|| stride == 0
731			|| groups == 0
732			|| !output_channels.is_multiple_of(groups)
733			|| bias.shape() != [*output_channels]
734			|| weight.dtype() != DType::F32
735			|| bias.dtype() != DType::F32
736			|| !weight.runtime().same_as(bias.runtime())
737		{
738			return Err(Error::invalid_argument(
739				"Conv2d requires nonempty same-runtime F32 square OIHW/group weight, matching bias, nonzero stride/groups, and output channels divisible by groups",
740			));
741		}
742		let output_channels = *output_channels;
743		let kernel_size = *kernel_height;
744		let weight = Parameter::new("weight", weight)?;
745		let bias = Parameter::new("bias", bias)?;
746		let mut registry = ModuleRegistry::new();
747		registry.register_parameter("weight", weight.clone())?;
748		registry.register_parameter("bias", bias.clone())?;
749		Ok(Self {
750			input_channels,
751			output_channels,
752			kernel_size,
753			stride,
754			padding,
755			groups,
756			weight,
757			bias,
758			registry,
759		})
760	}
761
762	/// Apply grouped convolution without submitting or waiting.
763	///
764	/// # Errors
765	///
766	/// Returns an error from the underlying Matrix operation.
767	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
768		let (weight, weight_version, _) = self.weight.snapshot();
769		let (bias, bias_version, _) = self.bias.snapshot();
770		matrix::conv_2d_parameterized(
771			input,
772			(self.weight.clone(), weight, weight_version),
773			(self.bias.clone(), bias, bias_version),
774			self.stride,
775			self.padding,
776			self.groups,
777		)
778	}
779
780	/// Return the input channel count.
781	pub const fn input_channels(&self) -> usize {
782		self.input_channels
783	}
784
785	/// Return the output channel count.
786	pub const fn output_channels(&self) -> usize {
787		self.output_channels
788	}
789
790	/// Return the square kernel extent.
791	pub const fn kernel_size(&self) -> usize {
792		self.kernel_size
793	}
794
795	/// Return the spatial stride.
796	pub const fn stride(&self) -> usize {
797		self.stride
798	}
799
800	/// Return the symmetric zero-padding extent.
801	pub const fn padding(&self) -> usize {
802		self.padding
803	}
804
805	/// Return the convolution group count.
806	pub const fn groups(&self) -> usize {
807		self.groups
808	}
809
810	/// Return the stable grouped OIHW weight parameter.
811	pub fn weight(&self) -> Parameter {
812		self.weight.clone()
813	}
814
815	/// Return the stable channel-bias parameter.
816	pub fn bias(&self) -> Parameter {
817		self.bias.clone()
818	}
819
820	/// Return parameters in deterministic weight, bias order.
821	pub fn parameters(&self) -> [Parameter; 2] {
822		[self.weight.clone(), self.bias.clone()]
823	}
824}
825
826impl Module for Conv2d {
827	fn forward(&self, input: &Matrix) -> Result<Matrix> {
828		Conv2d::forward(self, input)
829	}
830
831	fn registry(&self) -> &ModuleRegistry {
832		&self.registry
833	}
834}
835
836// OA donor: oacpp/source/cpp/lib/oa/ml/nn/conv3d/conv3d.cpp
837// Adaptation: Preserve existing Rust initializer, shape/ownership checks and versioned parameter adjoints; mechanical generated ownership
838/// Trainable grouped FP32 three-dimensional convolution over NCDHW matrices.
839pub struct Conv3d {
840	input_channels: usize,
841	output_channels: usize,
842	kernel_size: usize,
843	stride: usize,
844	padding: usize,
845	groups: usize,
846	weight: Parameter,
847	bias: Parameter,
848	registry: ModuleRegistry,
849}
850
851impl Conv3d {
852	/// Construct a deterministically initialized grouped Conv3d layer.
853	///
854	/// The weight initializer is symmetric uniform with bound
855	/// `1 / sqrt((input_channels / groups) * kernel_size³)`; bias starts at zero.
856	///
857	/// # Errors
858	///
859	/// Returns an error when dimensions are zero, channels are not divisible by
860	/// `groups`, shape arithmetic overflows, or allocation/upload fails.
861	#[allow(
862		clippy::too_many_arguments,
863		reason = "the donor Conv3d contract has six independent geometry fields plus a seed"
864	)]
865	pub fn new_with_seed(
866		input_channels: usize,
867		output_channels: usize,
868		kernel_size: usize,
869		stride: usize,
870		padding: usize,
871		groups: usize,
872		seed: u64,
873	) -> Result<Self> {
874		Self::new_with_seed_on(
875			&Runtime::current()?,
876			input_channels,
877			output_channels,
878			kernel_size,
879			stride,
880			padding,
881			groups,
882			seed,
883		)
884	}
885
886	#[allow(clippy::too_many_arguments)]
887	pub fn new_with_seed_on(
888		runtime: &Runtime,
889		input_channels: usize,
890		output_channels: usize,
891		kernel_size: usize,
892		stride: usize,
893		padding: usize,
894		groups: usize,
895		seed: u64,
896	) -> Result<Self> {
897		if input_channels == 0
898			|| output_channels == 0
899			|| kernel_size == 0
900			|| stride == 0
901			|| groups == 0
902			|| !input_channels.is_multiple_of(groups)
903			|| !output_channels.is_multiple_of(groups)
904		{
905			return Err(Error::invalid_argument(
906				"Conv3d requires nonzero dimensions and channels divisible by groups",
907			));
908		}
909		let input_channels_per_group = input_channels / groups;
910		let fan_in = input_channels_per_group
911			.checked_mul(kernel_size)
912			.and_then(|count| count.checked_mul(kernel_size))
913			.and_then(|count| count.checked_mul(kernel_size))
914			.ok_or_else(|| Error::invalid_argument("Conv3d fan-in overflows usize"))?;
915		let weight_count = output_channels
916			.checked_mul(fan_in)
917			.ok_or_else(|| Error::invalid_argument("Conv3d weight size overflows usize"))?;
918		let limit = 1.0_f32 / (fan_in as f32).sqrt();
919		let weight_values = random::symmetric_uniform(weight_count, limit, seed);
920		let weight = Matrix::new_from_f32_on(
921			runtime,
922			[
923				output_channels,
924				input_channels_per_group,
925				kernel_size,
926				kernel_size,
927				kernel_size,
928			],
929			&weight_values,
930		)?;
931		let bias = Matrix::new_from_f32_on(runtime, [output_channels], &vec![0.0; output_channels])?;
932		Self::new_from_matrices(weight, bias, stride, padding, groups)
933	}
934
935	/// Construct Conv3d from exact grouped OIDHW weight and bias matrices.
936	///
937	/// # Errors
938	///
939	/// Returns an error unless weight is nonempty cubic-kernel F32 OIDHW/group,
940	/// bias is matching same-runtime F32, stride/groups are nonzero, and output
941	/// channels are divisible by groups.
942	pub fn new_from_matrices(
943		weight: Matrix,
944		bias: Matrix,
945		stride: usize,
946		padding: usize,
947		groups: usize,
948	) -> Result<Self> {
949		let [
950			output_channels,
951			input_channels_per_group,
952			kernel_depth,
953			kernel_height,
954			kernel_width,
955		] = weight.shape()
956		else {
957			return Err(Error::invalid_argument(
958				"Conv3d weight must have grouped OIDHW rank five",
959			));
960		};
961		let input_channels = input_channels_per_group
962			.checked_mul(groups)
963			.ok_or_else(|| Error::invalid_argument("Conv3d input channel count overflows usize"))?;
964		if *output_channels == 0
965			|| *input_channels_per_group == 0
966			|| *kernel_depth == 0
967			|| kernel_depth != kernel_height
968			|| kernel_height != kernel_width
969			|| stride == 0
970			|| groups == 0
971			|| !output_channels.is_multiple_of(groups)
972			|| bias.shape() != [*output_channels]
973			|| weight.dtype() != DType::F32
974			|| bias.dtype() != DType::F32
975			|| !weight.runtime().same_as(bias.runtime())
976		{
977			return Err(Error::invalid_argument(
978				"Conv3d requires nonempty same-runtime F32 cubic OIDHW/group weight, matching bias, nonzero stride/groups, and output channels divisible by groups",
979			));
980		}
981		let output_channels = *output_channels;
982		let kernel_size = *kernel_depth;
983		let weight = Parameter::new("weight", weight)?;
984		let bias = Parameter::new("bias", bias)?;
985		let mut registry = ModuleRegistry::new();
986		registry.register_parameter("weight", weight.clone())?;
987		registry.register_parameter("bias", bias.clone())?;
988		Ok(Self {
989			input_channels,
990			output_channels,
991			kernel_size,
992			stride,
993			padding,
994			groups,
995			weight,
996			bias,
997			registry,
998		})
999	}
1000
1001	/// Apply grouped convolution without submitting or waiting.
1002	///
1003	/// # Errors
1004	///
1005	/// Returns an error from the underlying Matrix operation.
1006	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
1007		let (weight, weight_version, _) = self.weight.snapshot();
1008		let (bias, bias_version, _) = self.bias.snapshot();
1009		matrix::conv_3d_parameterized(
1010			input,
1011			(self.weight.clone(), weight, weight_version),
1012			(self.bias.clone(), bias, bias_version),
1013			self.stride,
1014			self.padding,
1015			self.groups,
1016		)
1017	}
1018
1019	/// Return the input channel count.
1020	pub const fn input_channels(&self) -> usize {
1021		self.input_channels
1022	}
1023
1024	/// Return the output channel count.
1025	pub const fn output_channels(&self) -> usize {
1026		self.output_channels
1027	}
1028
1029	/// Return the cubic kernel extent.
1030	pub const fn kernel_size(&self) -> usize {
1031		self.kernel_size
1032	}
1033
1034	/// Return the spatial stride.
1035	pub const fn stride(&self) -> usize {
1036		self.stride
1037	}
1038
1039	/// Return the symmetric zero-padding extent.
1040	pub const fn padding(&self) -> usize {
1041		self.padding
1042	}
1043
1044	/// Return the convolution group count.
1045	pub const fn groups(&self) -> usize {
1046		self.groups
1047	}
1048
1049	/// Return the stable grouped OIDHW weight parameter.
1050	pub fn weight(&self) -> Parameter {
1051		self.weight.clone()
1052	}
1053
1054	/// Return the stable channel-bias parameter.
1055	pub fn bias(&self) -> Parameter {
1056		self.bias.clone()
1057	}
1058
1059	/// Return parameters in deterministic weight, bias order.
1060	pub fn parameters(&self) -> [Parameter; 2] {
1061		[self.weight.clone(), self.bias.clone()]
1062	}
1063}
1064
1065impl Module for Conv3d {
1066	fn forward(&self, input: &Matrix) -> Result<Matrix> {
1067		Conv3d::forward(self, input)
1068	}
1069
1070	fn registry(&self) -> &ModuleRegistry {
1071		&self.registry
1072	}
1073}
1074
1075// OA donor: oacpp/source/cpp/lib/oa/ml/nn/convtranspose2d/convTranspose2d.cpp
1076// Adaptation: Preserve existing Rust initializer, shape/ownership checks and versioned parameter adjoints over the IOKKK NCDHW kernel; mechanical generated ownership
1077/// Trainable FP32 three-dimensional transposed convolution over NCDHW matrices.
1078pub struct ConvTranspose3d {
1079	input_channels: usize,
1080	output_channels: usize,
1081	kernel_size: usize,
1082	stride: usize,
1083	padding: usize,
1084	weight: Parameter,
1085	bias: Parameter,
1086	registry: ModuleRegistry,
1087}
1088
1089impl ConvTranspose3d {
1090	/// Construct a deterministically initialized ConvTranspose3d layer.
1091	///
1092	/// Weight uses `[input_channels, output_channels, kernel, kernel, kernel]`
1093	/// layout, a fan-in-scaled symmetric uniform initializer, and zero channel
1094	/// bias.
1095	///
1096	/// # Errors
1097	///
1098	/// Returns an error when channels, kernel size, or stride are zero, shape
1099	/// arithmetic overflows, or parameter allocation/upload fails.
1100	#[allow(
1101		clippy::too_many_arguments,
1102		reason = "the donor ConvTranspose3d contract has five geometry fields plus a seed"
1103	)]
1104	pub fn new_with_seed(
1105		input_channels: usize,
1106		output_channels: usize,
1107		kernel_size: usize,
1108		stride: usize,
1109		padding: usize,
1110		seed: u64,
1111	) -> Result<Self> {
1112		Self::new_with_seed_on(
1113			&Runtime::current()?,
1114			input_channels,
1115			output_channels,
1116			kernel_size,
1117			stride,
1118			padding,
1119			seed,
1120		)
1121	}
1122
1123	#[allow(clippy::too_many_arguments)]
1124	pub fn new_with_seed_on(
1125		runtime: &Runtime,
1126		input_channels: usize,
1127		output_channels: usize,
1128		kernel_size: usize,
1129		stride: usize,
1130		padding: usize,
1131		seed: u64,
1132	) -> Result<Self> {
1133		if input_channels == 0 || output_channels == 0 || kernel_size == 0 || stride == 0 {
1134			return Err(Error::invalid_argument(
1135				"ConvTranspose3d requires nonzero channels, kernel size, and stride",
1136			));
1137		}
1138		let fan_in = output_channels
1139			.checked_mul(kernel_size)
1140			.and_then(|count| count.checked_mul(kernel_size))
1141			.and_then(|count| count.checked_mul(kernel_size))
1142			.ok_or_else(|| Error::invalid_argument("ConvTranspose3d fan-in overflows usize"))?;
1143		let weight_count = input_channels
1144			.checked_mul(fan_in)
1145			.ok_or_else(|| Error::invalid_argument("ConvTranspose3d weight size overflows usize"))?;
1146		let limit = 1.0_f32 / (fan_in as f32).sqrt();
1147		let values = random::symmetric_uniform(weight_count, limit, seed);
1148		let weight = Matrix::new_from_f32_on(
1149			runtime,
1150			[
1151				input_channels,
1152				output_channels,
1153				kernel_size,
1154				kernel_size,
1155				kernel_size,
1156			],
1157			&values,
1158		)?;
1159		let bias = Matrix::new_from_f32_on(runtime, [output_channels], &vec![0.0; output_channels])?;
1160		Self::new_from_matrices(weight, bias, stride, padding)
1161	}
1162
1163	/// Construct ConvTranspose3d from exact IOKKK weight and channel-bias matrices.
1164	///
1165	/// # Errors
1166	///
1167	/// Returns an error unless weight is nonempty F32 `[I, O, K, K, K]`, bias
1168	/// is matching same-runtime F32 `[O]`, and stride is nonzero.
1169	pub fn new_from_matrices(
1170		weight: Matrix,
1171		bias: Matrix,
1172		stride: usize,
1173		padding: usize,
1174	) -> Result<Self> {
1175		let [
1176			input_channels,
1177			output_channels,
1178			kernel_depth,
1179			kernel_height,
1180			kernel_width,
1181		] = weight.shape()
1182		else {
1183			return Err(Error::invalid_argument(
1184				"ConvTranspose3d weight must have IOKKK rank five",
1185			));
1186		};
1187		if *input_channels == 0
1188			|| *output_channels == 0
1189			|| *kernel_depth == 0
1190			|| kernel_depth != kernel_height
1191			|| kernel_height != kernel_width
1192			|| stride == 0
1193			|| bias.shape() != [*output_channels]
1194			|| weight.dtype() != DType::F32
1195			|| bias.dtype() != DType::F32
1196			|| !weight.runtime().same_as(bias.runtime())
1197		{
1198			return Err(Error::invalid_argument(
1199				"ConvTranspose3d requires nonempty same-runtime F32 cubic IOKKK weight, matching bias, and nonzero stride",
1200			));
1201		}
1202		let input_channels = *input_channels;
1203		let output_channels = *output_channels;
1204		let kernel_size = *kernel_depth;
1205		let weight = Parameter::new("weight", weight)?;
1206		let bias = Parameter::new("bias", bias)?;
1207		let mut registry = ModuleRegistry::new();
1208		registry.register_parameter("weight", weight.clone())?;
1209		registry.register_parameter("bias", bias.clone())?;
1210		Ok(Self {
1211			input_channels,
1212			output_channels,
1213			kernel_size,
1214			stride,
1215			padding,
1216			weight,
1217			bias,
1218			registry,
1219		})
1220	}
1221
1222	/// Apply ConvTranspose3d without submitting or waiting.
1223	///
1224	/// # Errors
1225	///
1226	/// Returns an error from the underlying Matrix operation.
1227	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
1228		let (weight, weight_version, _) = self.weight.snapshot();
1229		let (bias, bias_version, _) = self.bias.snapshot();
1230		matrix::conv_3d_transpose_parameterized(
1231			input,
1232			(self.weight.clone(), weight, weight_version),
1233			(self.bias.clone(), bias, bias_version),
1234			self.stride,
1235			self.padding,
1236		)
1237	}
1238
1239	/// Return the input channel count.
1240	pub const fn input_channels(&self) -> usize {
1241		self.input_channels
1242	}
1243
1244	/// Return the output channel count.
1245	pub const fn output_channels(&self) -> usize {
1246		self.output_channels
1247	}
1248
1249	/// Return the cubic kernel extent.
1250	pub const fn kernel_size(&self) -> usize {
1251		self.kernel_size
1252	}
1253
1254	/// Return the spatial stride.
1255	pub const fn stride(&self) -> usize {
1256		self.stride
1257	}
1258
1259	/// Return the symmetric zero-padding extent.
1260	pub const fn padding(&self) -> usize {
1261		self.padding
1262	}
1263
1264	/// Return the stable IOKKK weight parameter.
1265	pub fn weight(&self) -> Parameter {
1266		self.weight.clone()
1267	}
1268
1269	/// Return the stable channel-bias parameter.
1270	pub fn bias(&self) -> Parameter {
1271		self.bias.clone()
1272	}
1273
1274	/// Return parameters in deterministic weight, bias order.
1275	pub fn parameters(&self) -> [Parameter; 2] {
1276		[self.weight.clone(), self.bias.clone()]
1277	}
1278}
1279
1280impl Module for ConvTranspose3d {
1281	fn forward(&self, input: &Matrix) -> Result<Matrix> {
1282		ConvTranspose3d::forward(self, input)
1283	}
1284
1285	fn registry(&self) -> &ModuleRegistry {
1286		&self.registry
1287	}
1288}