Skip to main content

oa/ml/nn/
sequential.gen.rs

1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_sequential.json
3// generator_version=8; schema_sha256=899022008ec9abc9c77f29f334054dd77e6e342db85a610af08f487f070fed11
4
5use std::rc::Rc;
6
7use crate::{Matrix, Result};
8
9use super::super::{Module, ModuleRegistry};
10
11// OA donor: oacpp/source/cpp/lib/oa/ml/nn/sequential/sequential.cpp
12// Adaptation: Preserved ordered Rc-owned children, layer_N names, checked registration and recursive mode propagation through the existing ModuleRegistry
13/// Apply registered child modules in insertion order.
14pub struct Sequential {
15	registry: ModuleRegistry,
16}
17
18impl Sequential {
19	/// Construct an empty sequence.
20	pub const fn new() -> Self {
21		Self {
22			registry: ModuleRegistry::new(),
23		}
24	}
25
26	/// Append one child under the deterministic `layer_N` name.
27	///
28	/// # Errors
29	///
30	/// Returns an error if the child handle is already registered.
31	pub fn add(&mut self, module: Rc<dyn Module>) -> Result<&mut Self> {
32		let name = format!("layer_{}", self.len());
33		self.add_named(name, module)
34	}
35
36	/// Append one child under an explicit registration name.
37	///
38	/// # Errors
39	///
40	/// Returns an error for an invalid/duplicate name or child handle.
41	pub fn add_named(
42		&mut self,
43		name: impl Into<String>,
44		module: Rc<dyn Module>,
45	) -> Result<&mut Self> {
46		self.registry.register_module(name, module)?;
47		Ok(self)
48	}
49
50	/// Return the number of registered children.
51	pub fn len(&self) -> usize {
52		self.registry.child_modules().len()
53	}
54
55	/// Return whether the sequence contains no children.
56	pub fn is_empty(&self) -> bool {
57		self.len() == 0
58	}
59
60	/// Apply every child in registration order.
61	///
62	/// # Errors
63	///
64	/// Returns the first child operation or validation failure.
65	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
66		let mut output = input.clone();
67		for child in self.registry.child_modules() {
68			output = child.forward(&output)?;
69		}
70		Ok(output)
71	}
72}
73
74impl Default for Sequential {
75	fn default() -> Self {
76		Self::new()
77	}
78}
79
80impl Module for Sequential {
81	fn forward(&self, input: &Matrix) -> Result<Matrix> {
82		Sequential::forward(self, input)
83	}
84
85	fn registry(&self) -> &ModuleRegistry {
86		&self.registry
87	}
88}