Skip to main content

oa/ml/
optim.rs

1//! Stateless optimizer-adjacent transformations and stateful optimizer implementations.
2
3mod adam;
4mod adamw;
5mod grad_scaler;
6mod muon;
7mod optimizer;
8mod sgd;
9
10pub use adam::Adam;
11pub use adamw::{AdamW, AdamWProgramSignature};
12pub use grad_scaler::{GradScaler, GradScalerState};
13pub use muon::Muon;
14pub use optimizer::{
15	CheckpointOptimizer, NoOpOptimizer, Optimizer, OptimizerCheckpoint, OptimizerRestore,
16};
17pub use sgd::Sgd;
18
19/// A named parameter group for differential optimizer treatment.
20///
21/// Groups are construction-time configuration: `lr_scale` multiplies the
22/// optimizer's base learning rate for member parameters, `weight_decay`
23/// replaces the optimizer-level decay when present (`Some(0.0)` is the decay
24/// exclusion), and `frozen` parameters keep both their values and their
25/// optimizer moments untouched across updates. The name is diagnostic; it
26/// participates in validation errors. Group membership must be disjoint and
27/// cover the optimizer's whole parameter set.
28#[derive(Clone)]
29pub struct ParameterGroup {
30	/// Diagnostic group name.
31	pub name: String,
32	/// Member parameters; disjoint across groups.
33	pub parameters: Vec<Parameter>,
34	/// Multiplier on the base learning rate.
35	pub lr_scale: f32,
36	/// Per-group weight decay replacing the optimizer default.
37	pub weight_decay: Option<f32>,
38	/// Frozen members skip value and moment updates entirely.
39	pub frozen: bool,
40}
41
42impl ParameterGroup {
43	/// Construct a group with default treatment — unit learning-rate scale,
44	/// optimizer-level weight decay, unfrozen.
45	#[must_use]
46	pub fn new(name: impl Into<String>, parameters: Vec<Parameter>) -> Self {
47		Self {
48			name: name.into(),
49			parameters,
50			lr_scale: 1.0,
51			weight_decay: None,
52			frozen: false,
53		}
54	}
55
56	/// Multiplier on the base learning rate for member parameters.
57	#[must_use]
58	pub fn with_lr_scale(mut self, lr_scale: f32) -> Self {
59		self.lr_scale = lr_scale;
60		self
61	}
62
63	/// Per-group weight decay; zero excludes members from decay.
64	#[must_use]
65	pub fn with_weight_decay(mut self, weight_decay: f32) -> Self {
66		self.weight_decay = Some(weight_decay);
67		self
68	}
69
70	/// Freeze member parameters and their optimizer moments.
71	#[must_use]
72	pub fn frozen(mut self) -> Self {
73		self.frozen = true;
74		self
75	}
76}
77
78use crate::ml::Parameter;
79use crate::ml::matrix::detach;
80use crate::ml::validation::{shader_u32, validate_f32_same_runtime};
81use crate::runtime::{BufferBinding, ComputeDispatch, KernelId, SemanticDispatch};
82use crate::{Error, Matrix, OpAttribute, Result};
83
84/// Clip the combined L2 norm of nonempty FP32 gradients in place.
85///
86/// The operation records one GPU reduction followed by one GPU scaling pass.
87/// It does not read gradients back to the CPU or wait for completion. Empty
88/// matrices are ignored; at most sixteen nonempty gradients are admitted.
89///
90/// # Errors
91///
92/// Returns an error when `max_norm` is negative or non-finite, more than
93/// sixteen nonempty gradients are supplied, gradients do not share one runtime,
94/// a gradient is not FP32, storage is duplicated, a size exceeds the shader
95/// ABI, or allocation and runtime recording fail.
96pub fn clip_grad_norm(gradients: &[Matrix], max_norm: f32) -> Result<()> {
97	const OPERATION: &str = crate::core::operation::ml::CLIP_GRAD_NORM.name();
98	if !max_norm.is_finite() || max_norm < 0.0 {
99		return Err(Error::invalid_argument(format!(
100			"{OPERATION} max_norm must be finite and non-negative"
101		)));
102	}
103	let gradients = gradients
104		.iter()
105		.filter(|gradient| gradient.num_elements() != 0)
106		.collect::<Vec<_>>();
107	if gradients.is_empty() {
108		return Ok(());
109	}
110	if gradients.len() > 16 {
111		return Err(Error::invalid_argument(format!(
112			"{OPERATION} supports at most 16 nonempty gradients"
113		)));
114	}
115	validate_f32_same_runtime(OPERATION, &gradients)?;
116	for (index, gradient) in gradients.iter().enumerate() {
117		if gradients[..index]
118			.iter()
119			.any(|previous| previous.storage().same_as(gradient.storage()))
120		{
121			return Err(Error::invalid_argument(format!(
122				"{OPERATION} gradients must not share storage"
123			)));
124		}
125	}
126	let mut params = [0_u32; 18];
127	let gradient_count = u32::try_from(gradients.len())
128		.map_err(|_| Error::invalid_argument(format!("{OPERATION} gradient count exceeds u32")))?;
129	params[0] = gradient_count;
130	for (index, gradient) in gradients.iter().enumerate() {
131		params[index + 1] = shader_u32(gradient.num_elements(), "element count", OPERATION)?;
132	}
133	params[17] = max_norm.to_bits();
134	let runtime = gradients[0].runtime();
135	let params = Matrix::new_from_slice_handle(runtime, vec![18], &params)?;
136	let partials = Matrix::allocate(runtime, vec![16], 16, crate::DType::F32)?;
137	let mut reduce_buffers = Vec::with_capacity(18);
138	reduce_buffers.push(BufferBinding::read(params.storage()));
139	reduce_buffers.push(BufferBinding::write(partials.storage()));
140	for index in 0..16 {
141		reduce_buffers.push(BufferBinding::read(
142			gradients
143				.get(index)
144				.copied()
145				.unwrap_or(gradients[0])
146				.storage(),
147		));
148	}
149	let mut scale_buffers = Vec::with_capacity(18);
150	scale_buffers.push(BufferBinding::read(params.storage()));
151	scale_buffers.push(BufferBinding::read(partials.storage()));
152	for index in 0..16 {
153		let binding = gradients.get(index).copied().map_or_else(
154			|| BufferBinding::read(gradients[0].storage()),
155			|gradient| BufferBinding::read_write(gradient.storage()),
156		);
157		scale_buffers.push(binding);
158	}
159	let reduce = KernelId::MlClipGradNormReduceF32;
160	let scale = KernelId::MlClipGradNormScaleF32;
161	let dispatches = [
162		ComputeDispatch {
163			kernel: reduce,
164			buffers: &reduce_buffers,
165			push_constants: &[],
166			workgroups: [gradient_count, 1, 1],
167			indirect: None,
168		},
169		ComputeDispatch {
170			kernel: scale,
171			buffers: &scale_buffers,
172			push_constants: &[],
173			workgroups: [gradient_count, 1, 1],
174			indirect: None,
175		},
176	];
177	let attributes = [OpAttribute::Float {
178		name: "max_norm".into(),
179		value: f64::from(max_norm),
180	}];
181	runtime.record_split_semantic(
182		&dispatches,
183		SemanticDispatch {
184			contract: crate::core::operation::ml::CLIP_GRAD_NORM,
185			inputs: &gradients,
186			outputs: &gradients,
187			attributes: &attributes,
188		},
189	)
190}
191
192/// Clip the combined L2 norm of accumulated [`Parameter`] gradients.
193///
194/// This is the parameter-level form of [`clip_grad_norm`]: each parameter's
195/// live gradient handle is collected, parameters without a gradient are
196/// skipped, and gradient values are rescaled so a following
197/// [`Optimizer::step`] observes clipped values. Up to sixteen nonempty
198/// gradients scale in place through the fused two-pass kernel; larger models
199/// take an equivalent device-resident reduction and broadcast-rescale path
200/// that stores a detached replacement gradient.
201///
202/// Call between backward and the optimizer step. Inside
203/// [`crate::ml::Training::step`] the call belongs in the `record` closure so
204/// the rescale is captured into the training program; in eager steps it
205/// belongs before [`crate::ml::Training::complete_step`].
206///
207/// # Errors
208///
209/// Returns an error when `max_norm` is negative or non-finite, gradients do
210/// not share one runtime or are not FP32, storages are duplicated on the fused
211/// path, a size exceeds the shader ABI, or allocation and runtime recording
212/// fail.
213pub fn clip_parameter_grad_norm(parameters: &[Parameter], max_norm: f32) -> Result<()> {
214	const OPERATION: &str = "clip_parameter_grad_norm";
215	if !max_norm.is_finite() || max_norm < 0.0 {
216		return Err(Error::invalid_argument(format!(
217			"{OPERATION} max_norm must be finite and non-negative"
218		)));
219	}
220	let pairs = parameters
221		.iter()
222		.filter_map(|parameter| parameter.gradient().map(|gradient| (parameter, gradient)))
223		.collect::<Vec<_>>();
224	if pairs.is_empty() {
225		return Ok(());
226	}
227	if pairs.len() <= 16 {
228		let gradients = pairs
229			.iter()
230			.map(|(_, gradient)| gradient.clone())
231			.collect::<Vec<_>>();
232		return clip_grad_norm(&gradients, max_norm);
233	}
234	// The fused kernel admits at most sixteen gradient storages. Larger models
235	// take the equivalent device-resident route: one full reduction over every
236	// squared norm, then a broadcast rescale into detached replacement storage.
237	let mut total_sq: Option<Matrix> = None;
238	for (_, gradient) in &pairs {
239		let sq = gradient.mul(gradient)?.sum(-1)?;
240		total_sq = Some(match total_sq {
241			Some(acc) => acc.add(&sq)?,
242			None => sq,
243		});
244	}
245	let Some(total_sq) = total_sq else {
246		return Ok(());
247	};
248	let scale = total_sq
249		.sqrt()?
250		.add_scalar(1.0e-6)?
251		.reciprocal()?
252		.scale(max_norm)?
253		.clamp_max(1.0)?;
254	for (parameter, gradient) in &pairs {
255		parameter.set_gradient(detach(&gradient.mul(&scale)?)?);
256	}
257	Ok(())
258}