oarust 0.20.1

GPU-first semantic computing runtime written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
use std::{
	cell::{Cell, RefCell},
	rc::Rc,
};

use crate::{Error, Matrix, Result};

use super::Parameter;

/// Owned dotted path and stable trainable parameter handle.
pub struct NamedParameter {
	path: String,
	parameter: Parameter,
}

impl NamedParameter {
	/// Return the registration-derived dotted path.
	pub fn path(&self) -> &str {
		&self.path
	}

	/// Return the stable parameter handle.
	pub fn parameter(&self) -> Parameter {
		self.parameter.clone()
	}
}

/// Owned dotted path and non-trainable Matrix buffer.
pub struct NamedBuffer {
	path: String,
	data: Rc<RefCell<Matrix>>,
	persistent: bool,
}

/// Owned dotted path and host scalar that participates in module persistence.
///
/// Scalar state is intended for small algorithmic counters and flags whose
/// value affects the next device operation but does not belong in a Matrix
/// buffer. It is traversed and checkpointed with the same deterministic module
/// tree as parameters and buffers.
pub struct NamedStateU32 {
	path: String,
	value: Rc<Cell<u32>>,
}

impl NamedStateU32 {
	/// Return the registration-derived dotted path.
	pub fn path(&self) -> &str {
		&self.path
	}

	/// Return the current scalar value.
	pub fn value(&self) -> u32 {
		self.value.get()
	}

	pub(crate) fn replace_value(&self, value: u32) {
		self.value.set(value);
	}
}

struct CapturedCounterPair {
	forward: Matrix,
	backward: Matrix,
}

struct CapturedRngSlots {
	last_capture_generation: u64,
	slot_cursor: usize,
	slots: Vec<CapturedCounterPair>,
}

struct RngStreamState {
	draw: Cell<u64>,
	captured: RefCell<Option<CapturedRngSlots>>,
}

/// Owned dotted path and stochastic draw counter that participates in exact
/// training-run resume (`.runstate`), without polluting deployable `.oam`
/// model files.
#[derive(Clone)]
pub struct NamedRngState {
	path: String,
	state: Rc<RngStreamState>,
}

impl NamedRngState {
	/// Return the registration-derived dotted path.
	pub fn path(&self) -> &str {
		&self.path
	}

	/// Return the current draw position, reading the device-resident replay
	/// counter when the stream has been captured.
	///
	/// # Errors
	///
	/// Returns an error when called during active capture or when device
	/// readback fails.
	pub fn draw(&self) -> Result<u64> {
		if let Some(captured) = self.state.captured.borrow().as_ref()
			&& let Some(first) = captured.slots.first()
		{
			if first.forward.runtime().capture_active() {
				return Err(Error::failed_precondition(
					"cannot observe captured RNG stream state during active capture",
				));
			}
			let value = first
				.forward
				.read::<u32>()?
				.first()
				.copied()
				.ok_or_else(|| Error::internal("captured RNG counter matrix is empty"))?;
			return Ok(u64::from(value));
		}
		Ok(self.state.draw.get())
	}

	pub(crate) fn next_eager_draw(&self) -> Result<u64> {
		if let Some(captured) = self.state.captured.borrow_mut().take()
			&& let Some(first) = captured.slots.first()
		{
			let value = first
				.forward
				.read::<u32>()?
				.first()
				.copied()
				.ok_or_else(|| Error::internal("captured RNG counter matrix is empty"))?;
			self.state.draw.set(u64::from(value));
		}
		let draw = self.state.draw.get();
		self.state.draw.set(draw.wrapping_add(1));
		Ok(draw)
	}

	pub(crate) fn captured_slot(
		&self,
		runtime: &crate::runtime::RuntimeHandle,
		generation: u64,
	) -> Result<(usize, Matrix, Matrix)> {
		let mut captured = self.state.captured.borrow_mut();
		if let Some(existing) = captured.as_ref()
			&& let Some(first) = existing.slots.first()
			&& !first.forward.runtime().same_as(runtime)
		{
			return Err(Error::invalid_argument(
				"module RNG stream was previously captured on another Runtime",
			));
		}
		let slots = captured.get_or_insert_with(|| CapturedRngSlots {
			last_capture_generation: generation,
			slot_cursor: 0,
			slots: Vec::new(),
		});
		if slots.last_capture_generation != generation {
			slots.last_capture_generation = generation;
			slots.slot_cursor = 0;
		}
		let slot_index = slots.slot_cursor;
		if slot_index == slots.slots.len() {
			let initial = u32::try_from(self.state.draw.get()).map_err(|_| {
				Error::resource_exhausted("RNG stream draw counter exceeds u32 replay range")
			})?;
			let forward = Matrix::new_from_slice_handle(runtime, vec![1], &[initial])?;
			let backward = Matrix::new_from_slice_handle(runtime, vec![1], &[initial])?;
			slots.slots.push(CapturedCounterPair { forward, backward });
		}
		slots.slot_cursor += 1;
		let pair = &slots.slots[slot_index];
		Ok((slot_index, pair.forward.clone(), pair.backward.clone()))
	}

	pub(crate) fn restore_draw(&self, draw: u64) {
		self.state.draw.set(draw);
		*self.state.captured.borrow_mut() = None;
	}
}

impl NamedBuffer {
	/// Return the registration-derived dotted path.
	pub fn path(&self) -> &str {
		&self.path
	}

	/// Return a cheap handle to the registered value.
	pub fn data(&self) -> Matrix {
		self.data.borrow().clone()
	}

	/// Return whether persistence must include this buffer.
	pub const fn persistent(&self) -> bool {
		self.persistent
	}

	pub(crate) fn replace_data(&self, data: Matrix) -> Result<()> {
		let current = self.data.borrow();
		if current.shape() != data.shape()
			|| current.dtype() != data.dtype()
			|| !current.runtime().same_as(data.runtime())
		{
			return Err(Error::invalid_argument(format!(
				"replacement data does not match module buffer {}",
				self.path
			)));
		}
		drop(current);
		*self.data.borrow_mut() = data;
		Ok(())
	}
}

struct ParameterEntry {
	name: String,
	parameter: Parameter,
}

struct BufferEntry {
	name: String,
	data: Rc<RefCell<Matrix>>,
	persistent: bool,
}

struct StateU32Entry {
	name: String,
	value: Rc<Cell<u32>>,
}

struct RngStateEntry {
	name: String,
	state: Rc<RngStreamState>,
}

struct ChildEntry {
	name: String,
	module: Rc<dyn Module>,
}

/// Constructor-owned structural registry for one [`Module`].
///
/// Registration requires `&mut self`, so a module's parameter/buffer/child tree
/// is fixed before the module is shared through `Rc`.
pub struct ModuleRegistry {
	parameters: Vec<ParameterEntry>,
	buffers: Vec<BufferEntry>,
	state_u32: Vec<StateU32Entry>,
	rng_states: Vec<RngStateEntry>,
	children: Vec<ChildEntry>,
	training: Cell<bool>,
}

impl ModuleRegistry {
	/// Construct an empty registry in training mode.
	pub const fn new() -> Self {
		Self {
			parameters: Vec::new(),
			buffers: Vec::new(),
			state_u32: Vec::new(),
			rng_states: Vec::new(),
			children: Vec::new(),
			training: Cell::new(true),
		}
	}

	/// Register one direct parameter.
	///
	/// # Errors
	///
	/// Returns an error for an invalid/duplicate local name or when the same
	/// parameter handle is already registered directly.
	pub fn register_parameter(
		&mut self,
		name: impl Into<String>,
		parameter: Parameter,
	) -> Result<()> {
		let name = self.validate_new_name(name.into())?;
		if self
			.parameters
			.iter()
			.any(|entry| entry.parameter.same_as(&parameter))
		{
			return Err(Error::invalid_argument(
				"module parameter handle is already registered",
			));
		}
		self.parameters.push(ParameterEntry { name, parameter });
		Ok(())
	}

	/// Register one direct non-trainable buffer.
	///
	/// # Errors
	///
	/// Returns an error for an invalid/duplicate local name or duplicate semantic
	/// Matrix value.
	pub fn register_buffer(
		&mut self,
		name: impl Into<String>,
		data: Matrix,
		persistent: bool,
	) -> Result<()> {
		let name = self.validate_new_name(name.into())?;
		if self
			.buffers
			.iter()
			.any(|entry| entry.data.borrow().same_value_as(&data))
		{
			return Err(Error::invalid_argument(
				"module buffer value is already registered",
			));
		}
		self.buffers.push(BufferEntry {
			name,
			data: Rc::new(RefCell::new(data)),
			persistent,
		});
		Ok(())
	}

	/// Register one direct persistent `u32` scalar state value.
	///
	/// This is for compact host metadata whose value changes the next operation,
	/// such as an EMA transition counter. Bulk numerical state remains a Matrix
	/// buffer.
	///
	/// # Errors
	///
	/// Returns an error for an invalid or duplicate local name.
	pub fn register_state_u32(
		&mut self,
		name: impl Into<String>,
		value: u32,
	) -> Result<NamedStateU32> {
		let name = self.validate_new_name(name.into())?;
		let value = Rc::new(Cell::new(value));
		self.state_u32.push(StateU32Entry {
			name: name.clone(),
			value: value.clone(),
		});
		Ok(NamedStateU32 { path: name, value })
	}

	/// Register one direct stochastic RNG draw stream for exact run-state resume.
	///
	/// Unlike [`Self::register_state_u32`], RNG streams are excluded from `.oam`
	/// model artifacts and persisted only in `.runstate` companion files.
	///
	/// # Errors
	///
	/// Returns an error for an invalid or duplicate local name.
	pub fn register_rng_state(
		&mut self,
		name: impl Into<String>,
		initial_draw: u64,
	) -> Result<NamedRngState> {
		let name = self.validate_new_name(name.into())?;
		let state = Rc::new(RngStreamState {
			draw: Cell::new(initial_draw),
			captured: RefCell::new(None),
		});
		self.rng_states.push(RngStateEntry {
			name: name.clone(),
			state: state.clone(),
		});
		Ok(NamedRngState { path: name, state })
	}

	/// Attach an existing [`Parameter`] under a local or dotted path.
	///
	/// Intended for dynamic composition adapters (such as the Python `Module`
	/// bridge) that flatten a validated module tree into one registry while
	/// preserving each entry's dotted path.
	///
	/// # Errors
	///
	/// Returns an error for an invalid dotted path, duplicate name, or duplicate
	/// parameter identity.
	pub fn attach_parameter(&mut self, path: impl Into<String>, parameter: Parameter) -> Result<()> {
		let path = self.validate_dotted_path(path.into(), "parameter")?;
		if self
			.parameters
			.iter()
			.any(|entry| entry.parameter.same_as(&parameter))
		{
			return Err(Error::failed_precondition(format!(
				"parameter attached through multiple module paths, including {path}"
			)));
		}
		self.parameters.push(ParameterEntry {
			name: path,
			parameter,
		});
		Ok(())
	}

	/// Attach an existing live [`NamedBuffer`] under a local or dotted path.
	///
	/// Mutations applied through checkpoint loading update the original buffer's
	/// `Rc<RefCell<Matrix>>` in place.
	///
	/// # Errors
	///
	/// Returns an error for an invalid dotted path, duplicate name, or duplicate
	/// semantic Matrix buffer.
	pub fn attach_buffer(&mut self, path: impl Into<String>, buffer: NamedBuffer) -> Result<()> {
		let path = self.validate_dotted_path(path.into(), "buffer")?;
		let incoming = buffer.data.borrow();
		if self
			.buffers
			.iter()
			.any(|entry| entry.data.borrow().same_value_as(&incoming))
		{
			return Err(Error::failed_precondition(format!(
				"buffer attached through multiple module paths, including {path}"
			)));
		}
		drop(incoming);
		self.buffers.push(BufferEntry {
			name: path,
			data: buffer.data,
			persistent: buffer.persistent,
		});
		Ok(())
	}

	/// Attach a Matrix buffer under a local or dotted path and return its live
	/// [`NamedBuffer`] handle so callers can observe replacements after load.
	///
	/// # Errors
	///
	/// Returns an error for an invalid dotted path, duplicate name, or duplicate
	/// semantic Matrix buffer.
	pub fn attach_buffer_matrix(
		&mut self,
		path: impl Into<String>,
		data: Matrix,
		persistent: bool,
	) -> Result<NamedBuffer> {
		let path = self.validate_dotted_path(path.into(), "buffer")?;
		if self
			.buffers
			.iter()
			.any(|entry| entry.data.borrow().same_value_as(&data))
		{
			return Err(Error::failed_precondition(format!(
				"buffer attached through multiple module paths, including {path}"
			)));
		}
		let cell = Rc::new(RefCell::new(data));
		self.buffers.push(BufferEntry {
			name: path.clone(),
			data: cell.clone(),
			persistent,
		});
		Ok(NamedBuffer {
			path,
			data: cell,
			persistent,
		})
	}

	/// Attach an existing [`NamedRngState`] under a local or dotted path.
	///
	/// Intended for dynamic composition adapters (such as the Python `Module`
	/// bridge) that assemble live RNG handles from child modules into one flat
	/// registry while keeping each stream's dotted path intact.
	///
	/// # Errors
	///
	/// Returns an error when `path` is empty, contains empty or non-ASCII
	/// segments, collides with an existing entry name, or attaches the same
	/// live RNG stream more than once.
	pub fn attach_rng_state(&mut self, path: impl Into<String>, state: NamedRngState) -> Result<()> {
		let path = self.validate_dotted_path(path.into(), "RNG stream")?;
		if self
			.rng_states
			.iter()
			.any(|entry| Rc::ptr_eq(&entry.state, &state.state))
		{
			return Err(Error::failed_precondition(format!(
				"RNG stream attached through multiple module paths, including {path}"
			)));
		}
		self.rng_states.push(RngStateEntry {
			name: path,
			state: state.state,
		});
		Ok(())
	}

	/// Register one owned child handle.
	///
	/// The child immediately inherits this registry's train/eval mode.
	///
	/// # Errors
	///
	/// Returns an error for an invalid/duplicate local name or when the same child
	/// handle is already registered directly.
	pub fn register_module(&mut self, name: impl Into<String>, module: Rc<dyn Module>) -> Result<()> {
		let name = self.validate_new_name(name.into())?;
		if self
			.children
			.iter()
			.any(|entry| Rc::ptr_eq(&entry.module, &module))
		{
			return Err(Error::invalid_argument(
				"module child handle is already registered",
			));
		}
		module.train(self.training.get());
		self.children.push(ChildEntry { name, module });
		Ok(())
	}

	fn validate_dotted_path(&self, path: String, label: &str) -> Result<String> {
		if path.is_empty()
			|| path.split('.').any(|segment| {
				segment.is_empty()
					|| !segment
						.bytes()
						.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
			}) {
			return Err(Error::invalid_argument(format!(
				"module {label} path {path:?} must contain nonempty ASCII segments separated by '.'"
			)));
		}
		if self.parameters.iter().any(|entry| entry.name == path)
			|| self.buffers.iter().any(|entry| entry.name == path)
			|| self.state_u32.iter().any(|entry| entry.name == path)
			|| self.rng_states.iter().any(|entry| entry.name == path)
			|| self.children.iter().any(|entry| entry.name == path)
		{
			return Err(Error::invalid_argument(format!(
				"module registration name {path:?} is already used"
			)));
		}
		Ok(path)
	}

	fn validate_new_name(&self, name: String) -> Result<String> {
		let mut bytes = name.bytes();
		let first = bytes.next();
		let valid = first.is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
			&& bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_');
		if !valid {
			return Err(Error::invalid_argument(format!(
				"module registration name {name:?} must be a nonempty ASCII identifier without dots"
			)));
		}
		if self.parameters.iter().any(|entry| entry.name == name)
			|| self.buffers.iter().any(|entry| entry.name == name)
			|| self.state_u32.iter().any(|entry| entry.name == name)
			|| self.rng_states.iter().any(|entry| entry.name == name)
			|| self.children.iter().any(|entry| entry.name == name)
		{
			return Err(Error::invalid_argument(format!(
				"module registration name {name:?} is already used"
			)));
		}
		Ok(name)
	}

	pub(crate) fn child_modules(&self) -> impl ExactSizeIterator<Item = &Rc<dyn Module>> {
		self.children.iter().map(|entry| &entry.module)
	}

	pub fn buffer_handle(&self, name: &str) -> Option<NamedBuffer> {
		self
			.buffers
			.iter()
			.find(|entry| entry.name == name)
			.map(|entry| NamedBuffer {
				path: entry.name.clone(),
				data: entry.data.clone(),
				persistent: entry.persistent,
			})
	}
}

impl Default for ModuleRegistry {
	fn default() -> Self {
		Self::new()
	}
}

/// Stateful neural-network component with one registered ownership tree.
pub trait Module {
	/// Evaluate one Matrix input without submitting or waiting.
	fn forward(&self, input: &Matrix) -> Result<Matrix>;

	/// Return this module's structural registry.
	fn registry(&self) -> &ModuleRegistry;

	/// Return direct parameters only.
	fn parameters(&self) -> Vec<Parameter> {
		self
			.registry()
			.parameters
			.iter()
			.map(|entry| entry.parameter.clone())
			.collect()
	}

	/// Return direct parameters with local registration names.
	fn named_parameters(&self) -> Vec<NamedParameter> {
		self
			.registry()
			.parameters
			.iter()
			.map(|entry| NamedParameter {
				path: entry.name.clone(),
				parameter: entry.parameter.clone(),
			})
			.collect()
	}

	/// Return direct non-trainable buffers only.
	fn buffers(&self) -> Vec<Matrix> {
		self
			.registry()
			.buffers
			.iter()
			.map(|entry| entry.data.borrow().clone())
			.collect()
	}

	/// Return direct buffers with local registration names and persistence flags.
	fn named_buffers(&self) -> Vec<NamedBuffer> {
		self
			.registry()
			.buffers
			.iter()
			.map(|entry| NamedBuffer {
				path: entry.name.clone(),
				data: entry.data.clone(),
				persistent: entry.persistent,
			})
			.collect()
	}

	/// Return every parameter exactly once in deterministic depth-first order.
	///
	/// # Errors
	///
	/// Returns `FailedPrecondition` if independently constructed registries expose
	/// one shared parameter through multiple tree paths.
	fn all_parameters(&self) -> Result<Vec<Parameter>> {
		Ok(
			collect_named_parameters(self.registry())?
				.into_iter()
				.map(|entry| entry.parameter)
				.collect(),
		)
	}

	/// Return every parameter with its registration-derived dotted path.
	///
	/// # Errors
	///
	/// Returns `FailedPrecondition` for duplicate parameter identity.
	fn all_named_parameters(&self) -> Result<Vec<NamedParameter>> {
		collect_named_parameters(self.registry())
	}

	/// Return all direct and recursive buffers in deterministic depth-first order.
	///
	/// # Errors
	///
	/// Returns `FailedPrecondition` for duplicate child or buffer identity.
	fn all_named_buffers(&self) -> Result<Vec<NamedBuffer>> {
		let mut output = Vec::new();
		let mut modules = Vec::new();
		collect_named_buffers(self.registry(), "", &mut modules, &mut output)?;
		Ok(output)
	}

	/// Return all direct and recursive persistent `u32` scalar state in
	/// deterministic depth-first order.
	///
	/// # Errors
	///
	/// Returns `FailedPrecondition` for duplicate child ownership.
	fn all_named_state_u32(&self) -> Result<Vec<NamedStateU32>> {
		let mut output = Vec::new();
		let mut modules = Vec::new();
		collect_named_state_u32(self.registry(), "", &mut modules, &mut output)?;
		Ok(output)
	}

	/// Return all direct and recursive stochastic RNG streams in deterministic
	/// depth-first order.
	///
	/// # Errors
	///
	/// Returns `FailedPrecondition` for duplicate child ownership.
	fn all_named_rng_states(&self) -> Result<Vec<NamedRngState>> {
		let mut output = Vec::new();
		let mut modules = Vec::new();
		collect_named_rng_states(self.registry(), "", &mut modules, &mut output)?;
		Ok(output)
	}

	/// Return the total number of trainable scalar values.
	///
	/// # Errors
	///
	/// Returns an error for duplicate parameter identity or count overflow.
	fn num_parameters(&self) -> Result<usize> {
		self
			.all_parameters()?
			.into_iter()
			.try_fold(0_usize, |total, parameter| {
				total
					.checked_add(parameter.data().num_elements())
					.ok_or_else(|| Error::resource_exhausted("module parameter count overflows usize"))
			})
	}

	/// Set train/eval mode recursively.
	fn train(&self, training: bool) {
		self.registry().training.set(training);
		for child in &self.registry().children {
			child.module.train(training);
		}
	}

	/// Enter evaluation mode recursively.
	fn eval(&self) {
		self.train(false);
	}

	/// Return this module's current train/eval mode.
	fn is_training(&self) -> bool {
		self.registry().training.get()
	}

	/// Enter evaluation mode until the returned guard is dropped.
	fn scoped_eval(&self) -> ScopedEval<'_> {
		ScopedEval::new(self.registry())
	}
}

/// Bounded evaluation mode that restores the complete module tree on drop.
#[must_use]
pub struct ScopedEval<'a> {
	modes: Vec<(&'a Cell<bool>, bool)>,
}

impl<'a> ScopedEval<'a> {
	fn new(registry: &'a ModuleRegistry) -> Self {
		let mut modes = Vec::new();
		save_eval_modes(registry, &mut modes);
		Self { modes }
	}
}

impl Drop for ScopedEval<'_> {
	fn drop(&mut self) {
		for (mode, previous) in self.modes.iter().rev() {
			mode.set(*previous);
		}
	}
}

fn save_eval_modes<'a>(registry: &'a ModuleRegistry, modes: &mut Vec<(&'a Cell<bool>, bool)>) {
	modes.push((&registry.training, registry.training.replace(false)));
	for child in &registry.children {
		save_eval_modes(child.module.registry(), modes);
	}
}

fn collect_named_parameters(registry: &ModuleRegistry) -> Result<Vec<NamedParameter>> {
	let mut output = Vec::new();
	let mut modules = Vec::new();
	collect_parameters(registry, "", &mut modules, &mut output)?;
	Ok(output)
}

fn collect_parameters(
	registry: &ModuleRegistry,
	prefix: &str,
	modules: &mut Vec<*const ModuleRegistry>,
	output: &mut Vec<NamedParameter>,
) -> Result<()> {
	register_tree_node(registry, prefix, modules)?;
	for entry in &registry.parameters {
		if output
			.iter()
			.any(|existing| existing.parameter.same_as(&entry.parameter))
		{
			return Err(Error::failed_precondition(format!(
				"parameter registered through multiple module paths, including {}",
				join_path(prefix, &entry.name)
			)));
		}
		output.push(NamedParameter {
			path: join_path(prefix, &entry.name),
			parameter: entry.parameter.clone(),
		});
	}
	for child in &registry.children {
		collect_parameters(
			child.module.registry(),
			&join_path(prefix, &child.name),
			modules,
			output,
		)?;
	}
	Ok(())
}

fn collect_named_buffers(
	registry: &ModuleRegistry,
	prefix: &str,
	modules: &mut Vec<*const ModuleRegistry>,
	output: &mut Vec<NamedBuffer>,
) -> Result<()> {
	register_tree_node(registry, prefix, modules)?;
	for entry in &registry.buffers {
		if output
			.iter()
			.any(|existing| existing.data.borrow().same_value_as(&entry.data.borrow()))
		{
			return Err(Error::failed_precondition(format!(
				"buffer registered through multiple module paths, including {}",
				join_path(prefix, &entry.name)
			)));
		}
		output.push(NamedBuffer {
			path: join_path(prefix, &entry.name),
			data: entry.data.clone(),
			persistent: entry.persistent,
		});
	}
	for child in &registry.children {
		collect_named_buffers(
			child.module.registry(),
			&join_path(prefix, &child.name),
			modules,
			output,
		)?;
	}
	Ok(())
}

fn collect_named_state_u32(
	registry: &ModuleRegistry,
	prefix: &str,
	modules: &mut Vec<*const ModuleRegistry>,
	output: &mut Vec<NamedStateU32>,
) -> Result<()> {
	register_tree_node(registry, prefix, modules)?;
	for entry in &registry.state_u32 {
		output.push(NamedStateU32 {
			path: join_path(prefix, &entry.name),
			value: entry.value.clone(),
		});
	}
	for child in &registry.children {
		collect_named_state_u32(
			child.module.registry(),
			&join_path(prefix, &child.name),
			modules,
			output,
		)?;
	}
	Ok(())
}

fn collect_named_rng_states(
	registry: &ModuleRegistry,
	prefix: &str,
	modules: &mut Vec<*const ModuleRegistry>,
	output: &mut Vec<NamedRngState>,
) -> Result<()> {
	register_tree_node(registry, prefix, modules)?;
	for entry in &registry.rng_states {
		output.push(NamedRngState {
			path: join_path(prefix, &entry.name),
			state: entry.state.clone(),
		});
	}
	for child in &registry.children {
		collect_named_rng_states(
			child.module.registry(),
			&join_path(prefix, &child.name),
			modules,
			output,
		)?;
	}
	Ok(())
}

fn register_tree_node(
	registry: &ModuleRegistry,
	path: &str,
	modules: &mut Vec<*const ModuleRegistry>,
) -> Result<()> {
	let identity = std::ptr::from_ref(registry);
	if modules.contains(&identity) {
		let path = if path.is_empty() { "<root>" } else { path };
		return Err(Error::failed_precondition(format!(
			"module registered through multiple tree paths, including {path}"
		)));
	}
	modules.push(identity);
	Ok(())
}

fn join_path(prefix: &str, name: &str) -> String {
	if prefix.is_empty() {
		name.to_owned()
	} else {
		format!("{prefix}.{name}")
	}
}