Skip to main content

oa/ml/
parameter.rs

1use std::{cell::RefCell, rc::Rc};
2
3use crate::{DType, Error, Matrix, Result, matrix};
4
5/// Named trainable FP32 matrix with one live accumulated gradient.
6#[derive(Clone)]
7pub struct Parameter {
8	inner: Rc<RefCell<ParameterState>>,
9}
10
11struct ParameterState {
12	name: String,
13	data: Matrix,
14	gradient: Option<Matrix>,
15	requires_grad: bool,
16	version: u64,
17}
18
19impl Parameter {
20	/// Create a trainable parameter from an existing FP32 matrix.
21	///
22	/// # Errors
23	///
24	/// Returns an error when `data` is not FP32.
25	pub fn new(name: impl Into<String>, data: Matrix) -> Result<Self> {
26		if data.dtype() != DType::F32 {
27			return Err(Error::invalid_argument(format!(
28				"parameter data must be F32; found {}",
29				data.dtype().token()
30			)));
31		}
32		Ok(Self {
33			inner: Rc::new(RefCell::new(ParameterState {
34				name: name.into(),
35				data,
36				gradient: None,
37				requires_grad: true,
38				version: 0,
39			})),
40		})
41	}
42
43	/// Return this parameter's local name.
44	pub fn name(&self) -> String {
45		self.inner.borrow().name.clone()
46	}
47
48	/// Return a cheap handle to the current parameter storage.
49	///
50	/// AdamW updates this stable storage in place. Existing handles therefore
51	/// observe later optimizer steps after the corresponding execution completes.
52	pub fn data(&self) -> Matrix {
53		self.inner.borrow().data.clone()
54	}
55
56	/// Return a cheap handle to the accumulated gradient, when present.
57	pub fn gradient(&self) -> Option<Matrix> {
58		self.inner.borrow().gradient.clone()
59	}
60
61	/// Enable or disable gradient accumulation for this parameter.
62	pub fn set_requires_grad(&self, requires_grad: bool) {
63		let mut state = self.inner.borrow_mut();
64		state.requires_grad = requires_grad;
65		if !requires_grad {
66			state.gradient = None;
67		}
68	}
69
70	/// Return whether reverse-mode differentiation accumulates this parameter.
71	pub fn requires_grad(&self) -> bool {
72		self.inner.borrow().requires_grad
73	}
74
75	/// Return whether both handles refer to the same live parameter cell.
76	pub fn same_as(&self, other: &Self) -> bool {
77		Rc::ptr_eq(&self.inner, &other.inner)
78	}
79
80	pub(crate) fn snapshot(&self) -> (Matrix, u64, bool) {
81		let state = self.inner.borrow();
82		(state.data.clone(), state.version, state.requires_grad)
83	}
84
85	pub(crate) fn validate_version(&self, expected: u64) -> Result<()> {
86		let state = self.inner.borrow();
87		if state.version != expected {
88			return Err(Error::failed_precondition(format!(
89				"parameter {} changed after its value was saved for backward",
90				state.name
91			)));
92		}
93		Ok(())
94	}
95
96	pub(crate) fn accumulate_gradient(&self, gradient: Matrix) -> Result<()> {
97		let previous = {
98			let state = self.inner.borrow();
99			if !state.requires_grad {
100				return Ok(());
101			}
102			state.gradient.clone()
103		};
104		let gradient = match previous {
105			Some(previous) => matrix::add(&previous, &gradient)?,
106			None => gradient,
107		};
108		self.inner.borrow_mut().gradient = Some(gradient);
109		Ok(())
110	}
111
112	/// Replace the accumulated gradient outright.
113	///
114	/// Gradient-policy helpers such as `clip_parameter_grad_norm` own this write:
115	/// callers store an already-rescaled value and the requires-grad flag is
116	/// unchanged.
117	pub(crate) fn set_gradient(&self, gradient: Matrix) {
118		self.inner.borrow_mut().gradient = Some(gradient);
119	}
120
121	pub(crate) fn replace_data(&self, data: Matrix) -> Result<()> {
122		let mut state = self.inner.borrow_mut();
123		if state.data.shape() != data.shape()
124			|| state.data.dtype() != data.dtype()
125			|| !state.data.runtime().same_as(data.runtime())
126		{
127			return Err(Error::invalid_argument(format!(
128				"replacement data does not match parameter {}",
129				state.name
130			)));
131		}
132		state.data = data;
133		state.version = state
134			.version
135			.checked_add(1)
136			.ok_or_else(|| Error::resource_exhausted("parameter mutation version exhausted"))?;
137		Ok(())
138	}
139
140	pub(crate) fn mark_updated(&self) -> Result<()> {
141		let mut state = self.inner.borrow_mut();
142		state.version = state
143			.version
144			.checked_add(1)
145			.ok_or_else(|| Error::resource_exhausted("parameter mutation version exhausted"))?;
146		Ok(())
147	}
148
149	pub(crate) fn validate_can_update(&self) -> Result<()> {
150		if self.inner.borrow().version == u64::MAX {
151			return Err(Error::resource_exhausted(
152				"parameter mutation version exhausted",
153			));
154		}
155		Ok(())
156	}
157
158	pub(crate) fn restore_gradient(&self, gradient: Matrix) {
159		// Only compiled training owns this route; shapes/Runtime are fixed by capture.
160		self.inner.borrow_mut().gradient = Some(gradient);
161	}
162
163	/// Clear any accumulated gradient without changing `requires_grad`.
164	pub fn clear_gradient(&self) {
165		self.inner.borrow_mut().gradient = None;
166	}
167}