Skip to main content

oa/ml/optim/
sgd.rs

1//! Stochastic gradient descent optimizer.
2
3use crate::ml::Parameter;
4use crate::ml::validation::{shader_u32, validate_f32_same_runtime};
5use crate::runtime::ComputeDispatch;
6use crate::runtime::SemanticDispatch;
7use crate::runtime::{BufferBinding, KernelId, PushConstant};
8use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime};
9
10use super::optimizer::{
11	Optimizer, OptimizerCheckpoint, OptimizerRestore, SgdParameterState, checkpoint_capability,
12};
13
14/// Stochastic gradient descent over stable [`Parameter`] handles.
15#[derive(Clone, Copy)]
16pub(super) struct SgdScalars {
17	pub(super) learning_rate: f32,
18	pub(super) momentum: f32,
19	pub(super) weight_decay: f32,
20}
21
22fn sgd(parameter: &Matrix, gradient: &Matrix, scalars: SgdScalars) -> Result<()> {
23	const OPERATION: &str = crate::core::operation::ml::SGD.name();
24	validate_f32_same_runtime(OPERATION, &[parameter, gradient])?;
25	if gradient.shape() != parameter.shape() {
26		return Err(Error::invalid_argument(format!(
27			"{OPERATION} requires identical parameter and gradient shapes"
28		)));
29	}
30	let element_count = shader_u32(parameter.num_elements(), "element count", OPERATION)?;
31	if element_count == 0 {
32		return Ok(());
33	}
34	let buffers = [
35		BufferBinding::read_write(parameter.storage()),
36		BufferBinding::read(gradient.storage()),
37	];
38	let push_constants = [
39		PushConstant::U32(element_count),
40		PushConstant::F32(scalars.learning_rate),
41		PushConstant::F32(scalars.weight_decay),
42	];
43	let attributes = [
44		OpAttribute::Float {
45			name: "learning_rate".into(),
46			value: f64::from(scalars.learning_rate),
47		},
48		OpAttribute::Float {
49			name: "weight_decay".into(),
50			value: f64::from(scalars.weight_decay),
51		},
52	];
53	let kernel = KernelId::MlSgdF32;
54	{
55		let inputs: &[&Matrix] = &[parameter, gradient];
56		let outputs: &[&Matrix] = &[parameter];
57		let attributes: &[OpAttribute] = &attributes;
58		let dispatch = ComputeDispatch {
59			kernel,
60			buffers: &buffers,
61			push_constants: &push_constants,
62			workgroups: kernel.linear_workgroups(element_count),
63			indirect: None,
64		};
65		let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
66			Error::internal(format!(
67				"lowering-only kernel {} cannot own one semantic ML operation",
68				dispatch.kernel.report_name()
69			))
70		})?;
71		let runtime = inputs
72			.first()
73			.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
74			.runtime();
75		runtime.record_semantic(
76			dispatch,
77			SemanticDispatch {
78				contract,
79				inputs,
80				outputs,
81				attributes,
82			},
83		)
84	}
85}
86
87fn sgd_momentum(
88	parameter: &Matrix,
89	gradient: &Matrix,
90	momentum: &Matrix,
91	scalars: SgdScalars,
92) -> Result<()> {
93	const OPERATION: &str = crate::core::operation::ml::SGD_MOMENTUM.name();
94	validate_f32_same_runtime(OPERATION, &[parameter, gradient, momentum])?;
95	for candidate in [gradient, momentum] {
96		if candidate.shape() != parameter.shape() {
97			return Err(Error::invalid_argument(format!(
98				"{OPERATION} requires identical parameter, gradient, and momentum shapes"
99			)));
100		}
101	}
102	let element_count = shader_u32(parameter.num_elements(), "element count", OPERATION)?;
103	if element_count == 0 {
104		return Ok(());
105	}
106	let buffers = [
107		BufferBinding::read_write(parameter.storage()),
108		BufferBinding::read(gradient.storage()),
109		BufferBinding::read_write(momentum.storage()),
110	];
111	let push_constants = [
112		PushConstant::U32(element_count),
113		PushConstant::F32(scalars.learning_rate),
114		PushConstant::F32(scalars.momentum),
115		PushConstant::F32(scalars.weight_decay),
116	];
117	let attributes = [
118		OpAttribute::Float {
119			name: "learning_rate".into(),
120			value: f64::from(scalars.learning_rate),
121		},
122		OpAttribute::Float {
123			name: "momentum".into(),
124			value: f64::from(scalars.momentum),
125		},
126		OpAttribute::Float {
127			name: "weight_decay".into(),
128			value: f64::from(scalars.weight_decay),
129		},
130	];
131	let kernel = KernelId::MlSgdMomentumF32;
132	{
133		let inputs: &[&Matrix] = &[parameter, gradient, momentum];
134		let outputs: &[&Matrix] = &[parameter, momentum];
135		let attributes: &[OpAttribute] = &attributes;
136		let dispatch = ComputeDispatch {
137			kernel,
138			buffers: &buffers,
139			push_constants: &push_constants,
140			workgroups: kernel.linear_workgroups(element_count),
141			indirect: None,
142		};
143		let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
144			Error::internal(format!(
145				"lowering-only kernel {} cannot own one semantic ML operation",
146				dispatch.kernel.report_name()
147			))
148		})?;
149		let runtime = inputs
150			.first()
151			.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
152			.runtime();
153		runtime.record_semantic(
154			dispatch,
155			SemanticDispatch {
156				contract,
157				inputs,
158				outputs,
159				attributes,
160			},
161		)
162	}
163}
164
165pub struct Sgd {
166	pub(super) parameters: Vec<SgdParameterState>,
167	pub(super) learning_rate: f32,
168	pub(super) momentum: f32,
169	pub(super) weight_decay: f32,
170	pub(super) step: u64,
171	/// Group index per parameter, parallel to `parameters`; empty when the
172	/// optimizer was constructed uniformly.
173	pub(super) param_group: Vec<usize>,
174	pub(super) groups: Vec<SgdGroupMeta>,
175}
176
177/// Construction-time treatment of one named parameter group.
178pub(super) struct SgdGroupMeta {
179	pub(super) lr_scale: f32,
180	pub(super) weight_decay: Option<f32>,
181	pub(super) frozen: bool,
182}
183
184impl Sgd {
185	/// Bind SGD to a nonempty FP32 parameter set.
186	///
187	/// A positive momentum coefficient allocates one zero-initialized momentum
188	/// tensor per parameter. Weight decay follows the donor kernels exactly.
189	///
190	/// # Errors
191	///
192	/// Returns an error for invalid hyperparameters, duplicate parameters,
193	/// mixed-runtime ownership, or momentum allocation/upload failure.
194	pub fn new(
195		parameters: impl IntoIterator<Item = Parameter>,
196		learning_rate: f32,
197		momentum: f32,
198		weight_decay: f32,
199	) -> Result<Self> {
200		if !learning_rate.is_finite() || learning_rate < 0.0 {
201			return Err(Error::invalid_argument(
202				"SGD learning rate must be finite and non-negative",
203			));
204		}
205		if !momentum.is_finite() || momentum < 0.0 {
206			return Err(Error::invalid_argument(
207				"SGD momentum must be finite and non-negative",
208			));
209		}
210		if !weight_decay.is_finite() || weight_decay < 0.0 {
211			return Err(Error::invalid_argument(
212				"SGD weight decay must be finite and non-negative",
213			));
214		}
215		let parameters = parameters.into_iter().collect::<Vec<_>>();
216		if parameters.is_empty() {
217			return Err(Error::invalid_argument(
218				"SGD requires at least one parameter",
219			));
220		}
221		for (index, parameter) in parameters.iter().enumerate() {
222			if parameters[..index]
223				.iter()
224				.any(|existing| existing.same_as(parameter))
225			{
226				return Err(Error::invalid_argument(
227					"SGD parameter handle appears more than once",
228				));
229			}
230		}
231		let runtime = parameters[0].data().runtime().clone();
232		if parameters
233			.iter()
234			.any(|parameter| !runtime.same_as(parameter.data().runtime()))
235		{
236			return Err(Error::invalid_argument(
237				"SGD parameters must belong to one runtime",
238			));
239		}
240		let mut states = Vec::with_capacity(parameters.len());
241		for parameter in parameters {
242			let data = parameter.data();
243			let momentum_buf = (momentum > 0.0)
244				.then(|| {
245					Matrix::allocate(
246						data.runtime(),
247						data.shape().to_vec(),
248						data.num_elements(),
249						DType::F32,
250					)
251				})
252				.transpose()?;
253			states.push(SgdParameterState {
254				parameter,
255				momentum: momentum_buf,
256			});
257		}
258		Ok(Self {
259			parameters: states,
260			learning_rate,
261			momentum,
262			weight_decay,
263			step: 0,
264			param_group: Vec::new(),
265			groups: Vec::new(),
266		})
267	}
268
269	/// Bind SGD over named parameter groups with differential treatment,
270	/// following the AdamW contract: `lr_scale` multiplies the base learning
271	/// rate, `weight_decay` replaces the optimizer default per group
272	/// (`Some(0.0)` excludes members), and frozen groups skip value and
273	/// momentum updates entirely.
274	///
275	/// # Errors
276	///
277	/// Returns the construction errors of the uniform constructor plus
278	/// overlapping membership, empty groups, and invalid group scales.
279	pub fn new_with_groups(
280		groups: Vec<crate::ml::optim::ParameterGroup>,
281		learning_rate: f32,
282		momentum: f32,
283		weight_decay: f32,
284	) -> Result<Self> {
285		if groups.is_empty() {
286			return Err(Error::invalid_argument(
287				"SGD requires at least one parameter group",
288			));
289		}
290		let mut parameters = Vec::new();
291		let mut param_group = Vec::new();
292		let mut metas = Vec::new();
293		for (group_index, group) in groups.into_iter().enumerate() {
294			if group.parameters.is_empty() {
295				return Err(Error::invalid_argument(format!(
296					"SGD group '{}' must not be empty",
297					group.name
298				)));
299			}
300			if !group.lr_scale.is_finite() || group.lr_scale < 0.0 {
301				return Err(Error::invalid_argument(format!(
302					"SGD group '{}' learning-rate scale must be finite and non-negative",
303					group.name
304				)));
305			}
306			if let Some(decay) = group.weight_decay
307				&& (!decay.is_finite() || decay < 0.0)
308			{
309				return Err(Error::invalid_argument(format!(
310					"SGD group '{}' weight decay must be finite and non-negative",
311					group.name
312				)));
313			}
314			for parameter in group.parameters {
315				parameters.push(parameter);
316				param_group.push(group_index);
317			}
318			metas.push(SgdGroupMeta {
319				lr_scale: group.lr_scale,
320				weight_decay: group.weight_decay,
321				frozen: group.frozen,
322			});
323		}
324		let mut optimizer = Self::new(parameters, learning_rate, momentum, weight_decay)?;
325		optimizer.param_group = param_group;
326		optimizer.groups = metas;
327		Ok(optimizer)
328	}
329
330	/// Discard every currently accumulated parameter gradient.
331	pub fn zero_grad(&self) {
332		for state in &self.parameters {
333			state.parameter.clear_gradient();
334		}
335	}
336
337	/// Record one SGD update for every parameter carrying a gradient.
338	///
339	/// # Errors
340	///
341	/// Returns an error when the step counter is exhausted, a parameter contract
342	/// changed, or runtime recording fails.
343	pub fn step(&mut self) -> Result<()> {
344		let next_step = self
345			.step
346			.checked_add(1)
347			.ok_or_else(|| Error::resource_exhausted("SGD step counter exhausted"))?;
348		let scalars = SgdScalars {
349			learning_rate: self.learning_rate,
350			momentum: self.momentum,
351			weight_decay: self.weight_decay,
352		};
353		let updates = self
354			.parameters
355			.iter()
356			.enumerate()
357			.filter(|(index, _state)| {
358				!self
359					.param_group
360					.get(*index)
361					.is_some_and(|group| self.groups[*group].frozen)
362			})
363			.filter_map(|(index, state)| {
364				state
365					.parameter
366					.gradient()
367					.map(|gradient| (index, state, state.parameter.data(), gradient))
368			})
369			.collect::<Vec<_>>();
370		for (_, state, _, _) in &updates {
371			state.parameter.validate_can_update()?;
372		}
373		for (index, state, parameter, gradient) in &updates {
374			let scalars = match self.param_group.get(*index) {
375				Some(group) => {
376					let meta = &self.groups[*group];
377					SgdScalars {
378						learning_rate: self.learning_rate * meta.lr_scale,
379						momentum: self.momentum,
380						weight_decay: meta.weight_decay.unwrap_or(self.weight_decay),
381					}
382				}
383				None => scalars,
384			};
385			match &state.momentum {
386				Some(momentum) => sgd_momentum(parameter, gradient, momentum, scalars)?,
387				None => sgd(parameter, gradient, scalars)?,
388			}
389		}
390		for (_, state, _, _) in &updates {
391			state.parameter.mark_updated()?;
392		}
393		self.step = next_step;
394		Ok(())
395	}
396
397	/// Return the learning rate used by the next step.
398	pub const fn learning_rate(&self) -> f32 {
399		self.learning_rate
400	}
401
402	/// Set the learning rate used by subsequent steps.
403	///
404	/// # Errors
405	///
406	/// Returns an error when the value is not finite and non-negative.
407	pub fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()> {
408		if !learning_rate.is_finite() || learning_rate < 0.0 {
409			return Err(Error::invalid_argument(
410				"SGD learning rate must be finite and non-negative",
411			));
412		}
413		self.learning_rate = learning_rate;
414		Ok(())
415	}
416
417	/// Return the number of completed logical steps.
418	pub const fn step_count(&self) -> u64 {
419		self.step
420	}
421
422	pub(super) fn belongs_to_runtime(&self, runtime: &Runtime) -> bool {
423		runtime.same_as_handle(self.parameters[0].parameter.data().runtime())
424	}
425
426	pub(super) fn checkpoint(&self) -> Result<OptimizerCheckpoint> {
427		// Momentum occupies the first state array, matching the wire codec's
428		// two-array SGD payload: the second array carries zeros of equal
429		// length because the format admits only equal-length non-Muon arrays.
430		// Zero-momentum SGD keeps the legacy empty-array form.
431		let momentum_state = self.momentum > 0.0;
432		let mut first_state = Vec::new();
433		let mut second_state = Vec::new();
434		if momentum_state {
435			for state in &self.parameters {
436				let momentum = state.momentum.as_ref().ok_or_else(|| {
437					Error::failed_precondition("SGD momentum state missing for a parameter")
438				})?;
439				first_state.push(momentum.clone());
440				let data = state.parameter.data();
441				second_state.push(Matrix::allocate(
442					data.runtime(),
443					data.shape().to_vec(),
444					data.num_elements(),
445					DType::F32,
446				)?);
447			}
448		}
449		Ok(OptimizerCheckpoint {
450			kind: "SGD",
451			step: self.step,
452			applied_step: None,
453			learning_rate: self.learning_rate,
454			beta1: self.momentum,
455			beta2: 0.0,
456			epsilon: 0.0,
457			weight_decay: self.weight_decay,
458			parameters: self
459				.parameters
460				.iter()
461				.map(|state| state.parameter.clone())
462				.collect(),
463			first_state,
464			second_state,
465		})
466	}
467
468	pub(super) fn validate_checkpoint(&self, state: &OptimizerRestore) -> Result<()> {
469		if state.kind != "SGD"
470			|| !state.learning_rate.is_finite()
471			|| state.learning_rate < 0.0
472			|| !state.beta1.is_finite()
473			|| state.beta1 < 0.0
474			|| state.beta1 != self.momentum
475			|| state.beta2 != 0.0
476			|| state.epsilon != 0.0
477			|| !state.weight_decay.is_finite()
478			|| state.weight_decay < 0.0
479		{
480			return Err(Error::invalid_argument("invalid SGD checkpoint state"));
481		}
482		if self.momentum > 0.0 {
483			if state.first_state.len() != self.parameters.len()
484				|| state.second_state.len() != self.parameters.len()
485			{
486				return Err(Error::invalid_argument(
487					"SGD momentum checkpoint state does not cover the parameter set",
488				));
489			}
490			for (parameter_state, momentum) in self.parameters.iter().zip(&state.first_state) {
491				let data = parameter_state.parameter.data();
492				if momentum.shape() != data.shape()
493					|| momentum.dtype() != DType::F32
494					|| !momentum.runtime().same_as(data.runtime())
495				{
496					return Err(Error::invalid_argument(
497						"SGD checkpoint momentum contract mismatch",
498					));
499				}
500			}
501		} else if !state.first_state.is_empty() || !state.second_state.is_empty() {
502			return Err(Error::invalid_argument(
503				"zero-momentum SGD checkpoint carries momentum state",
504			));
505		}
506		Ok(())
507	}
508
509	pub(super) fn restore_checkpoint(&mut self, state: OptimizerRestore) -> Result<()> {
510		self.validate_checkpoint(&state)?;
511		if self.momentum > 0.0 {
512			for (parameter_state, momentum) in self.parameters.iter_mut().zip(state.first_state) {
513				parameter_state.momentum = Some(momentum);
514			}
515		}
516		self.step = state.step;
517		self.learning_rate = state.learning_rate;
518		self.weight_decay = state.weight_decay;
519		Ok(())
520	}
521}
522
523impl Optimizer for Sgd {
524	fn zero_grad(&self) {
525		Self::zero_grad(self);
526	}
527
528	fn step(&mut self) -> Result<()> {
529		Self::step(self)
530	}
531
532	fn learning_rate(&self) -> f32 {
533		Self::learning_rate(self)
534	}
535
536	fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()> {
537		Self::set_learning_rate(self, learning_rate)
538	}
539
540	fn step_count(&self) -> u64 {
541		Self::step_count(self)
542	}
543
544	fn belongs_to(&self, runtime: &Runtime) -> bool {
545		self.belongs_to_runtime(runtime)
546	}
547}
548
549impl checkpoint_capability::Persistence for Sgd {
550	fn checkpoint_state(&self) -> Result<OptimizerCheckpoint> {
551		Self::checkpoint(self)
552	}
553
554	fn validate_checkpoint_state(&self, state: &OptimizerRestore) -> Result<()> {
555		Self::validate_checkpoint(self, state)
556	}
557
558	fn restore_checkpoint_state(&mut self, state: OptimizerRestore) -> Result<()> {
559		Self::restore_checkpoint(self, state)
560	}
561}