Skip to main content

oa/ml/
module.rs

1use std::{
2	cell::{Cell, RefCell},
3	rc::Rc,
4};
5
6use crate::{Error, Matrix, Result};
7
8use super::Parameter;
9
10/// Owned dotted path and stable trainable parameter handle.
11pub struct NamedParameter {
12	path: String,
13	parameter: Parameter,
14}
15
16impl NamedParameter {
17	/// Return the registration-derived dotted path.
18	pub fn path(&self) -> &str {
19		&self.path
20	}
21
22	/// Return the stable parameter handle.
23	pub fn parameter(&self) -> Parameter {
24		self.parameter.clone()
25	}
26}
27
28/// Owned dotted path and non-trainable Matrix buffer.
29pub struct NamedBuffer {
30	path: String,
31	data: Rc<RefCell<Matrix>>,
32	persistent: bool,
33}
34
35/// Owned dotted path and host scalar that participates in module persistence.
36///
37/// Scalar state is intended for small algorithmic counters and flags whose
38/// value affects the next device operation but does not belong in a Matrix
39/// buffer. It is traversed and checkpointed with the same deterministic module
40/// tree as parameters and buffers.
41pub struct NamedStateU32 {
42	path: String,
43	value: Rc<Cell<u32>>,
44}
45
46impl NamedStateU32 {
47	/// Return the registration-derived dotted path.
48	pub fn path(&self) -> &str {
49		&self.path
50	}
51
52	/// Return the current scalar value.
53	pub fn value(&self) -> u32 {
54		self.value.get()
55	}
56
57	pub(crate) fn replace_value(&self, value: u32) {
58		self.value.set(value);
59	}
60}
61
62struct CapturedCounterPair {
63	forward: Matrix,
64	backward: Matrix,
65}
66
67struct CapturedRngSlots {
68	last_capture_generation: u64,
69	slot_cursor: usize,
70	slots: Vec<CapturedCounterPair>,
71}
72
73struct RngStreamState {
74	draw: Cell<u64>,
75	captured: RefCell<Option<CapturedRngSlots>>,
76}
77
78/// Owned dotted path and stochastic draw counter that participates in exact
79/// training-run resume (`.runstate`), without polluting deployable `.oam`
80/// model files.
81#[derive(Clone)]
82pub struct NamedRngState {
83	path: String,
84	state: Rc<RngStreamState>,
85}
86
87impl NamedRngState {
88	/// Return the registration-derived dotted path.
89	pub fn path(&self) -> &str {
90		&self.path
91	}
92
93	/// Return the current draw position, reading the device-resident replay
94	/// counter when the stream has been captured.
95	///
96	/// # Errors
97	///
98	/// Returns an error when called during active capture or when device
99	/// readback fails.
100	pub fn draw(&self) -> Result<u64> {
101		if let Some(captured) = self.state.captured.borrow().as_ref()
102			&& let Some(first) = captured.slots.first()
103		{
104			if first.forward.runtime().capture_active() {
105				return Err(Error::failed_precondition(
106					"cannot observe captured RNG stream state during active capture",
107				));
108			}
109			let value = first
110				.forward
111				.read::<u32>()?
112				.first()
113				.copied()
114				.ok_or_else(|| Error::internal("captured RNG counter matrix is empty"))?;
115			return Ok(u64::from(value));
116		}
117		Ok(self.state.draw.get())
118	}
119
120	pub(crate) fn next_eager_draw(&self) -> Result<u64> {
121		if let Some(captured) = self.state.captured.borrow_mut().take()
122			&& let Some(first) = captured.slots.first()
123		{
124			let value = first
125				.forward
126				.read::<u32>()?
127				.first()
128				.copied()
129				.ok_or_else(|| Error::internal("captured RNG counter matrix is empty"))?;
130			self.state.draw.set(u64::from(value));
131		}
132		let draw = self.state.draw.get();
133		self.state.draw.set(draw.wrapping_add(1));
134		Ok(draw)
135	}
136
137	pub(crate) fn captured_slot(
138		&self,
139		runtime: &crate::runtime::RuntimeHandle,
140		generation: u64,
141	) -> Result<(usize, Matrix, Matrix)> {
142		let mut captured = self.state.captured.borrow_mut();
143		if let Some(existing) = captured.as_ref()
144			&& let Some(first) = existing.slots.first()
145			&& !first.forward.runtime().same_as(runtime)
146		{
147			return Err(Error::invalid_argument(
148				"module RNG stream was previously captured on another Runtime",
149			));
150		}
151		let slots = captured.get_or_insert_with(|| CapturedRngSlots {
152			last_capture_generation: generation,
153			slot_cursor: 0,
154			slots: Vec::new(),
155		});
156		if slots.last_capture_generation != generation {
157			slots.last_capture_generation = generation;
158			slots.slot_cursor = 0;
159		}
160		let slot_index = slots.slot_cursor;
161		if slot_index == slots.slots.len() {
162			let initial = u32::try_from(self.state.draw.get()).map_err(|_| {
163				Error::resource_exhausted("RNG stream draw counter exceeds u32 replay range")
164			})?;
165			let forward = Matrix::new_from_slice_handle(runtime, vec![1], &[initial])?;
166			let backward = Matrix::new_from_slice_handle(runtime, vec![1], &[initial])?;
167			slots.slots.push(CapturedCounterPair { forward, backward });
168		}
169		slots.slot_cursor += 1;
170		let pair = &slots.slots[slot_index];
171		Ok((slot_index, pair.forward.clone(), pair.backward.clone()))
172	}
173
174	pub(crate) fn restore_draw(&self, draw: u64) {
175		self.state.draw.set(draw);
176		*self.state.captured.borrow_mut() = None;
177	}
178}
179
180impl NamedBuffer {
181	/// Return the registration-derived dotted path.
182	pub fn path(&self) -> &str {
183		&self.path
184	}
185
186	/// Return a cheap handle to the registered value.
187	pub fn data(&self) -> Matrix {
188		self.data.borrow().clone()
189	}
190
191	/// Return whether persistence must include this buffer.
192	pub const fn persistent(&self) -> bool {
193		self.persistent
194	}
195
196	pub(crate) fn replace_data(&self, data: Matrix) -> Result<()> {
197		let current = self.data.borrow();
198		if current.shape() != data.shape()
199			|| current.dtype() != data.dtype()
200			|| !current.runtime().same_as(data.runtime())
201		{
202			return Err(Error::invalid_argument(format!(
203				"replacement data does not match module buffer {}",
204				self.path
205			)));
206		}
207		drop(current);
208		*self.data.borrow_mut() = data;
209		Ok(())
210	}
211}
212
213struct ParameterEntry {
214	name: String,
215	parameter: Parameter,
216}
217
218struct BufferEntry {
219	name: String,
220	data: Rc<RefCell<Matrix>>,
221	persistent: bool,
222}
223
224struct StateU32Entry {
225	name: String,
226	value: Rc<Cell<u32>>,
227}
228
229struct RngStateEntry {
230	name: String,
231	state: Rc<RngStreamState>,
232}
233
234struct ChildEntry {
235	name: String,
236	module: Rc<dyn Module>,
237}
238
239/// Constructor-owned structural registry for one [`Module`].
240///
241/// Registration requires `&mut self`, so a module's parameter/buffer/child tree
242/// is fixed before the module is shared through `Rc`.
243pub struct ModuleRegistry {
244	parameters: Vec<ParameterEntry>,
245	buffers: Vec<BufferEntry>,
246	state_u32: Vec<StateU32Entry>,
247	rng_states: Vec<RngStateEntry>,
248	children: Vec<ChildEntry>,
249	training: Cell<bool>,
250}
251
252impl ModuleRegistry {
253	/// Construct an empty registry in training mode.
254	pub const fn new() -> Self {
255		Self {
256			parameters: Vec::new(),
257			buffers: Vec::new(),
258			state_u32: Vec::new(),
259			rng_states: Vec::new(),
260			children: Vec::new(),
261			training: Cell::new(true),
262		}
263	}
264
265	/// Register one direct parameter.
266	///
267	/// # Errors
268	///
269	/// Returns an error for an invalid/duplicate local name or when the same
270	/// parameter handle is already registered directly.
271	pub fn register_parameter(
272		&mut self,
273		name: impl Into<String>,
274		parameter: Parameter,
275	) -> Result<()> {
276		let name = self.validate_new_name(name.into())?;
277		if self
278			.parameters
279			.iter()
280			.any(|entry| entry.parameter.same_as(&parameter))
281		{
282			return Err(Error::invalid_argument(
283				"module parameter handle is already registered",
284			));
285		}
286		self.parameters.push(ParameterEntry { name, parameter });
287		Ok(())
288	}
289
290	/// Register one direct non-trainable buffer.
291	///
292	/// # Errors
293	///
294	/// Returns an error for an invalid/duplicate local name or duplicate semantic
295	/// Matrix value.
296	pub fn register_buffer(
297		&mut self,
298		name: impl Into<String>,
299		data: Matrix,
300		persistent: bool,
301	) -> Result<()> {
302		let name = self.validate_new_name(name.into())?;
303		if self
304			.buffers
305			.iter()
306			.any(|entry| entry.data.borrow().same_value_as(&data))
307		{
308			return Err(Error::invalid_argument(
309				"module buffer value is already registered",
310			));
311		}
312		self.buffers.push(BufferEntry {
313			name,
314			data: Rc::new(RefCell::new(data)),
315			persistent,
316		});
317		Ok(())
318	}
319
320	/// Register one direct persistent `u32` scalar state value.
321	///
322	/// This is for compact host metadata whose value changes the next operation,
323	/// such as an EMA transition counter. Bulk numerical state remains a Matrix
324	/// buffer.
325	///
326	/// # Errors
327	///
328	/// Returns an error for an invalid or duplicate local name.
329	pub fn register_state_u32(
330		&mut self,
331		name: impl Into<String>,
332		value: u32,
333	) -> Result<NamedStateU32> {
334		let name = self.validate_new_name(name.into())?;
335		let value = Rc::new(Cell::new(value));
336		self.state_u32.push(StateU32Entry {
337			name: name.clone(),
338			value: value.clone(),
339		});
340		Ok(NamedStateU32 { path: name, value })
341	}
342
343	/// Register one direct stochastic RNG draw stream for exact run-state resume.
344	///
345	/// Unlike [`Self::register_state_u32`], RNG streams are excluded from `.oam`
346	/// model artifacts and persisted only in `.runstate` companion files.
347	///
348	/// # Errors
349	///
350	/// Returns an error for an invalid or duplicate local name.
351	pub fn register_rng_state(
352		&mut self,
353		name: impl Into<String>,
354		initial_draw: u64,
355	) -> Result<NamedRngState> {
356		let name = self.validate_new_name(name.into())?;
357		let state = Rc::new(RngStreamState {
358			draw: Cell::new(initial_draw),
359			captured: RefCell::new(None),
360		});
361		self.rng_states.push(RngStateEntry {
362			name: name.clone(),
363			state: state.clone(),
364		});
365		Ok(NamedRngState { path: name, state })
366	}
367
368	/// Attach an existing [`Parameter`] under a local or dotted path.
369	///
370	/// Intended for dynamic composition adapters (such as the Python `Module`
371	/// bridge) that flatten a validated module tree into one registry while
372	/// preserving each entry's dotted path.
373	///
374	/// # Errors
375	///
376	/// Returns an error for an invalid dotted path, duplicate name, or duplicate
377	/// parameter identity.
378	pub fn attach_parameter(&mut self, path: impl Into<String>, parameter: Parameter) -> Result<()> {
379		let path = self.validate_dotted_path(path.into(), "parameter")?;
380		if self
381			.parameters
382			.iter()
383			.any(|entry| entry.parameter.same_as(&parameter))
384		{
385			return Err(Error::failed_precondition(format!(
386				"parameter attached through multiple module paths, including {path}"
387			)));
388		}
389		self.parameters.push(ParameterEntry {
390			name: path,
391			parameter,
392		});
393		Ok(())
394	}
395
396	/// Attach an existing live [`NamedBuffer`] under a local or dotted path.
397	///
398	/// Mutations applied through checkpoint loading update the original buffer's
399	/// `Rc<RefCell<Matrix>>` in place.
400	///
401	/// # Errors
402	///
403	/// Returns an error for an invalid dotted path, duplicate name, or duplicate
404	/// semantic Matrix buffer.
405	pub fn attach_buffer(&mut self, path: impl Into<String>, buffer: NamedBuffer) -> Result<()> {
406		let path = self.validate_dotted_path(path.into(), "buffer")?;
407		let incoming = buffer.data.borrow();
408		if self
409			.buffers
410			.iter()
411			.any(|entry| entry.data.borrow().same_value_as(&incoming))
412		{
413			return Err(Error::failed_precondition(format!(
414				"buffer attached through multiple module paths, including {path}"
415			)));
416		}
417		drop(incoming);
418		self.buffers.push(BufferEntry {
419			name: path,
420			data: buffer.data,
421			persistent: buffer.persistent,
422		});
423		Ok(())
424	}
425
426	/// Attach a Matrix buffer under a local or dotted path and return its live
427	/// [`NamedBuffer`] handle so callers can observe replacements after load.
428	///
429	/// # Errors
430	///
431	/// Returns an error for an invalid dotted path, duplicate name, or duplicate
432	/// semantic Matrix buffer.
433	pub fn attach_buffer_matrix(
434		&mut self,
435		path: impl Into<String>,
436		data: Matrix,
437		persistent: bool,
438	) -> Result<NamedBuffer> {
439		let path = self.validate_dotted_path(path.into(), "buffer")?;
440		if self
441			.buffers
442			.iter()
443			.any(|entry| entry.data.borrow().same_value_as(&data))
444		{
445			return Err(Error::failed_precondition(format!(
446				"buffer attached through multiple module paths, including {path}"
447			)));
448		}
449		let cell = Rc::new(RefCell::new(data));
450		self.buffers.push(BufferEntry {
451			name: path.clone(),
452			data: cell.clone(),
453			persistent,
454		});
455		Ok(NamedBuffer {
456			path,
457			data: cell,
458			persistent,
459		})
460	}
461
462	/// Attach an existing [`NamedRngState`] under a local or dotted path.
463	///
464	/// Intended for dynamic composition adapters (such as the Python `Module`
465	/// bridge) that assemble live RNG handles from child modules into one flat
466	/// registry while keeping each stream's dotted path intact.
467	///
468	/// # Errors
469	///
470	/// Returns an error when `path` is empty, contains empty or non-ASCII
471	/// segments, collides with an existing entry name, or attaches the same
472	/// live RNG stream more than once.
473	pub fn attach_rng_state(&mut self, path: impl Into<String>, state: NamedRngState) -> Result<()> {
474		let path = self.validate_dotted_path(path.into(), "RNG stream")?;
475		if self
476			.rng_states
477			.iter()
478			.any(|entry| Rc::ptr_eq(&entry.state, &state.state))
479		{
480			return Err(Error::failed_precondition(format!(
481				"RNG stream attached through multiple module paths, including {path}"
482			)));
483		}
484		self.rng_states.push(RngStateEntry {
485			name: path,
486			state: state.state,
487		});
488		Ok(())
489	}
490
491	/// Register one owned child handle.
492	///
493	/// The child immediately inherits this registry's train/eval mode.
494	///
495	/// # Errors
496	///
497	/// Returns an error for an invalid/duplicate local name or when the same child
498	/// handle is already registered directly.
499	pub fn register_module(&mut self, name: impl Into<String>, module: Rc<dyn Module>) -> Result<()> {
500		let name = self.validate_new_name(name.into())?;
501		if self
502			.children
503			.iter()
504			.any(|entry| Rc::ptr_eq(&entry.module, &module))
505		{
506			return Err(Error::invalid_argument(
507				"module child handle is already registered",
508			));
509		}
510		module.train(self.training.get());
511		self.children.push(ChildEntry { name, module });
512		Ok(())
513	}
514
515	fn validate_dotted_path(&self, path: String, label: &str) -> Result<String> {
516		if path.is_empty()
517			|| path.split('.').any(|segment| {
518				segment.is_empty()
519					|| !segment
520						.bytes()
521						.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
522			}) {
523			return Err(Error::invalid_argument(format!(
524				"module {label} path {path:?} must contain nonempty ASCII segments separated by '.'"
525			)));
526		}
527		if self.parameters.iter().any(|entry| entry.name == path)
528			|| self.buffers.iter().any(|entry| entry.name == path)
529			|| self.state_u32.iter().any(|entry| entry.name == path)
530			|| self.rng_states.iter().any(|entry| entry.name == path)
531			|| self.children.iter().any(|entry| entry.name == path)
532		{
533			return Err(Error::invalid_argument(format!(
534				"module registration name {path:?} is already used"
535			)));
536		}
537		Ok(path)
538	}
539
540	fn validate_new_name(&self, name: String) -> Result<String> {
541		let mut bytes = name.bytes();
542		let first = bytes.next();
543		let valid = first.is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
544			&& bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_');
545		if !valid {
546			return Err(Error::invalid_argument(format!(
547				"module registration name {name:?} must be a nonempty ASCII identifier without dots"
548			)));
549		}
550		if self.parameters.iter().any(|entry| entry.name == name)
551			|| self.buffers.iter().any(|entry| entry.name == name)
552			|| self.state_u32.iter().any(|entry| entry.name == name)
553			|| self.rng_states.iter().any(|entry| entry.name == name)
554			|| self.children.iter().any(|entry| entry.name == name)
555		{
556			return Err(Error::invalid_argument(format!(
557				"module registration name {name:?} is already used"
558			)));
559		}
560		Ok(name)
561	}
562
563	pub(crate) fn child_modules(&self) -> impl ExactSizeIterator<Item = &Rc<dyn Module>> {
564		self.children.iter().map(|entry| &entry.module)
565	}
566
567	pub fn buffer_handle(&self, name: &str) -> Option<NamedBuffer> {
568		self
569			.buffers
570			.iter()
571			.find(|entry| entry.name == name)
572			.map(|entry| NamedBuffer {
573				path: entry.name.clone(),
574				data: entry.data.clone(),
575				persistent: entry.persistent,
576			})
577	}
578}
579
580impl Default for ModuleRegistry {
581	fn default() -> Self {
582		Self::new()
583	}
584}
585
586/// Stateful neural-network component with one registered ownership tree.
587pub trait Module {
588	/// Evaluate one Matrix input without submitting or waiting.
589	fn forward(&self, input: &Matrix) -> Result<Matrix>;
590
591	/// Return this module's structural registry.
592	fn registry(&self) -> &ModuleRegistry;
593
594	/// Return direct parameters only.
595	fn parameters(&self) -> Vec<Parameter> {
596		self
597			.registry()
598			.parameters
599			.iter()
600			.map(|entry| entry.parameter.clone())
601			.collect()
602	}
603
604	/// Return direct parameters with local registration names.
605	fn named_parameters(&self) -> Vec<NamedParameter> {
606		self
607			.registry()
608			.parameters
609			.iter()
610			.map(|entry| NamedParameter {
611				path: entry.name.clone(),
612				parameter: entry.parameter.clone(),
613			})
614			.collect()
615	}
616
617	/// Return direct non-trainable buffers only.
618	fn buffers(&self) -> Vec<Matrix> {
619		self
620			.registry()
621			.buffers
622			.iter()
623			.map(|entry| entry.data.borrow().clone())
624			.collect()
625	}
626
627	/// Return direct buffers with local registration names and persistence flags.
628	fn named_buffers(&self) -> Vec<NamedBuffer> {
629		self
630			.registry()
631			.buffers
632			.iter()
633			.map(|entry| NamedBuffer {
634				path: entry.name.clone(),
635				data: entry.data.clone(),
636				persistent: entry.persistent,
637			})
638			.collect()
639	}
640
641	/// Return every parameter exactly once in deterministic depth-first order.
642	///
643	/// # Errors
644	///
645	/// Returns `FailedPrecondition` if independently constructed registries expose
646	/// one shared parameter through multiple tree paths.
647	fn all_parameters(&self) -> Result<Vec<Parameter>> {
648		Ok(
649			collect_named_parameters(self.registry())?
650				.into_iter()
651				.map(|entry| entry.parameter)
652				.collect(),
653		)
654	}
655
656	/// Return every parameter with its registration-derived dotted path.
657	///
658	/// # Errors
659	///
660	/// Returns `FailedPrecondition` for duplicate parameter identity.
661	fn all_named_parameters(&self) -> Result<Vec<NamedParameter>> {
662		collect_named_parameters(self.registry())
663	}
664
665	/// Return all direct and recursive buffers in deterministic depth-first order.
666	///
667	/// # Errors
668	///
669	/// Returns `FailedPrecondition` for duplicate child or buffer identity.
670	fn all_named_buffers(&self) -> Result<Vec<NamedBuffer>> {
671		let mut output = Vec::new();
672		let mut modules = Vec::new();
673		collect_named_buffers(self.registry(), "", &mut modules, &mut output)?;
674		Ok(output)
675	}
676
677	/// Return all direct and recursive persistent `u32` scalar state in
678	/// deterministic depth-first order.
679	///
680	/// # Errors
681	///
682	/// Returns `FailedPrecondition` for duplicate child ownership.
683	fn all_named_state_u32(&self) -> Result<Vec<NamedStateU32>> {
684		let mut output = Vec::new();
685		let mut modules = Vec::new();
686		collect_named_state_u32(self.registry(), "", &mut modules, &mut output)?;
687		Ok(output)
688	}
689
690	/// Return all direct and recursive stochastic RNG streams in deterministic
691	/// depth-first order.
692	///
693	/// # Errors
694	///
695	/// Returns `FailedPrecondition` for duplicate child ownership.
696	fn all_named_rng_states(&self) -> Result<Vec<NamedRngState>> {
697		let mut output = Vec::new();
698		let mut modules = Vec::new();
699		collect_named_rng_states(self.registry(), "", &mut modules, &mut output)?;
700		Ok(output)
701	}
702
703	/// Return the total number of trainable scalar values.
704	///
705	/// # Errors
706	///
707	/// Returns an error for duplicate parameter identity or count overflow.
708	fn num_parameters(&self) -> Result<usize> {
709		self
710			.all_parameters()?
711			.into_iter()
712			.try_fold(0_usize, |total, parameter| {
713				total
714					.checked_add(parameter.data().num_elements())
715					.ok_or_else(|| Error::resource_exhausted("module parameter count overflows usize"))
716			})
717	}
718
719	/// Set train/eval mode recursively.
720	fn train(&self, training: bool) {
721		self.registry().training.set(training);
722		for child in &self.registry().children {
723			child.module.train(training);
724		}
725	}
726
727	/// Enter evaluation mode recursively.
728	fn eval(&self) {
729		self.train(false);
730	}
731
732	/// Return this module's current train/eval mode.
733	fn is_training(&self) -> bool {
734		self.registry().training.get()
735	}
736
737	/// Enter evaluation mode until the returned guard is dropped.
738	fn scoped_eval(&self) -> ScopedEval<'_> {
739		ScopedEval::new(self.registry())
740	}
741}
742
743/// Bounded evaluation mode that restores the complete module tree on drop.
744#[must_use]
745pub struct ScopedEval<'a> {
746	modes: Vec<(&'a Cell<bool>, bool)>,
747}
748
749impl<'a> ScopedEval<'a> {
750	fn new(registry: &'a ModuleRegistry) -> Self {
751		let mut modes = Vec::new();
752		save_eval_modes(registry, &mut modes);
753		Self { modes }
754	}
755}
756
757impl Drop for ScopedEval<'_> {
758	fn drop(&mut self) {
759		for (mode, previous) in self.modes.iter().rev() {
760			mode.set(*previous);
761		}
762	}
763}
764
765fn save_eval_modes<'a>(registry: &'a ModuleRegistry, modes: &mut Vec<(&'a Cell<bool>, bool)>) {
766	modes.push((&registry.training, registry.training.replace(false)));
767	for child in &registry.children {
768		save_eval_modes(child.module.registry(), modes);
769	}
770}
771
772fn collect_named_parameters(registry: &ModuleRegistry) -> Result<Vec<NamedParameter>> {
773	let mut output = Vec::new();
774	let mut modules = Vec::new();
775	collect_parameters(registry, "", &mut modules, &mut output)?;
776	Ok(output)
777}
778
779fn collect_parameters(
780	registry: &ModuleRegistry,
781	prefix: &str,
782	modules: &mut Vec<*const ModuleRegistry>,
783	output: &mut Vec<NamedParameter>,
784) -> Result<()> {
785	register_tree_node(registry, prefix, modules)?;
786	for entry in &registry.parameters {
787		if output
788			.iter()
789			.any(|existing| existing.parameter.same_as(&entry.parameter))
790		{
791			return Err(Error::failed_precondition(format!(
792				"parameter registered through multiple module paths, including {}",
793				join_path(prefix, &entry.name)
794			)));
795		}
796		output.push(NamedParameter {
797			path: join_path(prefix, &entry.name),
798			parameter: entry.parameter.clone(),
799		});
800	}
801	for child in &registry.children {
802		collect_parameters(
803			child.module.registry(),
804			&join_path(prefix, &child.name),
805			modules,
806			output,
807		)?;
808	}
809	Ok(())
810}
811
812fn collect_named_buffers(
813	registry: &ModuleRegistry,
814	prefix: &str,
815	modules: &mut Vec<*const ModuleRegistry>,
816	output: &mut Vec<NamedBuffer>,
817) -> Result<()> {
818	register_tree_node(registry, prefix, modules)?;
819	for entry in &registry.buffers {
820		if output
821			.iter()
822			.any(|existing| existing.data.borrow().same_value_as(&entry.data.borrow()))
823		{
824			return Err(Error::failed_precondition(format!(
825				"buffer registered through multiple module paths, including {}",
826				join_path(prefix, &entry.name)
827			)));
828		}
829		output.push(NamedBuffer {
830			path: join_path(prefix, &entry.name),
831			data: entry.data.clone(),
832			persistent: entry.persistent,
833		});
834	}
835	for child in &registry.children {
836		collect_named_buffers(
837			child.module.registry(),
838			&join_path(prefix, &child.name),
839			modules,
840			output,
841		)?;
842	}
843	Ok(())
844}
845
846fn collect_named_state_u32(
847	registry: &ModuleRegistry,
848	prefix: &str,
849	modules: &mut Vec<*const ModuleRegistry>,
850	output: &mut Vec<NamedStateU32>,
851) -> Result<()> {
852	register_tree_node(registry, prefix, modules)?;
853	for entry in &registry.state_u32 {
854		output.push(NamedStateU32 {
855			path: join_path(prefix, &entry.name),
856			value: entry.value.clone(),
857		});
858	}
859	for child in &registry.children {
860		collect_named_state_u32(
861			child.module.registry(),
862			&join_path(prefix, &child.name),
863			modules,
864			output,
865		)?;
866	}
867	Ok(())
868}
869
870fn collect_named_rng_states(
871	registry: &ModuleRegistry,
872	prefix: &str,
873	modules: &mut Vec<*const ModuleRegistry>,
874	output: &mut Vec<NamedRngState>,
875) -> Result<()> {
876	register_tree_node(registry, prefix, modules)?;
877	for entry in &registry.rng_states {
878		output.push(NamedRngState {
879			path: join_path(prefix, &entry.name),
880			state: entry.state.clone(),
881		});
882	}
883	for child in &registry.children {
884		collect_named_rng_states(
885			child.module.registry(),
886			&join_path(prefix, &child.name),
887			modules,
888			output,
889		)?;
890	}
891	Ok(())
892}
893
894fn register_tree_node(
895	registry: &ModuleRegistry,
896	path: &str,
897	modules: &mut Vec<*const ModuleRegistry>,
898) -> Result<()> {
899	let identity = std::ptr::from_ref(registry);
900	if modules.contains(&identity) {
901		let path = if path.is_empty() { "<root>" } else { path };
902		return Err(Error::failed_precondition(format!(
903			"module registered through multiple tree paths, including {path}"
904		)));
905	}
906	modules.push(identity);
907	Ok(())
908}
909
910fn join_path(prefix: &str, name: &str) -> String {
911	if prefix.is_empty() {
912		name.to_owned()
913	} else {
914		format!("{prefix}.{name}")
915	}
916}