Skip to main content

oa/ml/autograd/
tape.rs

1use std::{
2	cell::{Cell, RefCell},
3	rc::{Rc, Weak},
4};
5
6use crate::ml::Parameter;
7use crate::{Error, Result, matrix::autograd as matrix_autograd};
8
9use super::node::GradNode;
10use crate::audio::autograd as audio_autograd;
11
12#[path = "backward.rs"]
13pub(in crate::ml::autograd) mod backward;
14
15thread_local! {
16	static ACTIVE_TAPES: RefCell<Vec<Weak<RecordingState>>> = const { RefCell::new(Vec::new()) };
17	static NEXT_SEQUENCE: Cell<u64> = const { Cell::new(0) };
18}
19
20struct TapeEntry {
21	sequence: u64,
22	node: GradNode,
23}
24
25// One shared recording allocation, weakly observed by thread-local callbacks.
26// This is recording lifetime state, not a second public tape or execution owner.
27struct RecordingState {
28	nodes: RefCell<Vec<TapeEntry>>,
29	watched_parameters: RefCell<Vec<WatchedParameter>>,
30	consumed: Cell<bool>,
31}
32
33struct WatchedParameter {
34	parameter: Parameter,
35	data_id: u64,
36	version: u64,
37}
38
39/// Thread-affine reverse-mode recording scope.
40///
41/// Constructing a tape selects it for operations on the current thread.
42/// [`GradientTape::backward`] closes the recording scope and records the
43/// corresponding backward operations into the originating runtime's eager batch.
44#[must_use]
45pub struct GradientTape {
46	recording: Rc<RecordingState>,
47	active: Cell<bool>,
48	matrix_recording: RefCell<Option<matrix_autograd::RecordingSelection>>,
49	audio_recording: RefCell<Option<audio_autograd::RecordingSelection>>,
50}
51
52impl GradientTape {
53	/// Begin a reverse-mode recording scope on the current thread.
54	pub fn new() -> Self {
55		let recording = Rc::new(RecordingState {
56			nodes: RefCell::new(Vec::new()),
57			watched_parameters: RefCell::new(Vec::new()),
58			consumed: Cell::new(false),
59		});
60		ACTIVE_TAPES.with(|tapes| tapes.borrow_mut().push(Rc::downgrade(&recording)));
61		let weak = Rc::downgrade(&recording);
62		let matrix_recording = matrix_autograd::select(move |node| {
63			let Some(tape) = weak.upgrade() else {
64				return Ok(());
65			};
66			let node = GradNode::from(node);
67			record_node_for(&tape, node)
68		});
69		let audio_weak = Rc::downgrade(&recording);
70		let audio_recording = audio_autograd::select(move |node| {
71			let Some(tape) = audio_weak.upgrade() else {
72				return Ok(());
73			};
74			let node = GradNode::from(node);
75			record_node_for(&tape, node)
76		});
77		Self {
78			recording,
79			active: Cell::new(true),
80			matrix_recording: RefCell::new(Some(matrix_recording)),
81			audio_recording: RefCell::new(Some(audio_recording)),
82		}
83	}
84
85	/// Watch a parameter so backward accumulates its adjoint into the leaf.
86	///
87	/// Module forwards register their parameters automatically; raw matrix-or
88	/// audio-operation compositions that use `parameter.data()` directly must
89	/// watch the parameter explicitly or its gradient is silently dropped.
90	/// Watching is deduplicated by parameter identity and validates the
91	/// parameter version at backward time, so a parameter mutated in place
92	/// after recording still fails loudly.
93	pub fn watch(&self, parameter: &crate::ml::Parameter) -> crate::Result<()> {
94		let (data, version, requires_grad) = parameter.snapshot();
95		if !requires_grad {
96			return Ok(());
97		}
98		let mut watched = self.recording.watched_parameters.borrow_mut();
99		if !watched
100			.iter()
101			.any(|candidate| candidate.parameter.same_as(parameter))
102		{
103			watched.push(WatchedParameter {
104				parameter: parameter.clone(),
105				data_id: data.value_id(),
106				version,
107			});
108		}
109		Ok(())
110	}
111
112	/// Close recording without constructing a backward pass.
113	pub fn close(&self) {
114		if !self.active.replace(false) {
115			return;
116		}
117		self.matrix_recording.borrow_mut().take();
118		self.audio_recording.borrow_mut().take();
119		ACTIVE_TAPES.with(|tapes| {
120			tapes.borrow_mut().retain(|candidate| {
121				candidate.strong_count() != 0 && !candidate.ptr_eq(&Rc::downgrade(&self.recording))
122			});
123		});
124	}
125}
126
127impl Default for GradientTape {
128	fn default() -> Self {
129		Self::new()
130	}
131}
132
133impl Drop for GradientTape {
134	fn drop(&mut self) {
135		self.close();
136	}
137}
138
139pub(super) fn record_node(node: GradNode) -> Result<()> {
140	ACTIVE_TAPES.with(|tapes| {
141		let active = tapes.borrow().last().and_then(Weak::upgrade);
142		if let Some(active) = active {
143			record_node_for(&active, node)?;
144		}
145		Ok(())
146	})
147}
148
149pub(in crate::ml) fn record_parameter_leaf(parameter: &Parameter) -> Result<()> {
150	let (data, version, requires_grad) = parameter.snapshot();
151	if !requires_grad {
152		return Ok(());
153	}
154	ACTIVE_TAPES.with(|tapes| {
155		let active = tapes.borrow().last().and_then(Weak::upgrade);
156		if let Some(active) = active {
157			let mut watched = active.watched_parameters.borrow_mut();
158			if !watched
159				.iter()
160				.any(|candidate| candidate.parameter.same_as(parameter))
161			{
162				watched.push(WatchedParameter {
163					parameter: parameter.clone(),
164					data_id: data.value_id(),
165					version,
166				});
167			}
168		}
169		Ok(())
170	})
171}
172
173pub(in crate::ml) fn recording_active() -> bool {
174	ACTIVE_TAPES.with(|tapes| {
175		tapes
176			.borrow()
177			.last()
178			.is_some_and(|candidate| candidate.strong_count() != 0)
179	})
180}
181
182fn record_node_for(tape: &RecordingState, node: GradNode) -> Result<()> {
183	let sequence = NEXT_SEQUENCE.with(|next| {
184		let sequence = next
185			.get()
186			.checked_add(1)
187			.ok_or_else(|| Error::resource_exhausted("autograd sequence exhausted"))?;
188		next.set(sequence);
189		Ok::<_, Error>(sequence)
190	})?;
191	tape.nodes.borrow_mut().push(TapeEntry { sequence, node });
192	Ok(())
193}
194
195#[cfg(test)]
196#[path = "../../../../../test/rs/ml/tape_unit.rs"]
197mod tests;