use crate::ml::Parameter;
use crate::ml::validation::{shader_u32, validate_f32_same_runtime};
use crate::runtime::ComputeDispatch;
use crate::runtime::SemanticDispatch;
use crate::runtime::{BufferBinding, KernelId, PushConstant};
use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime};
use super::optimizer::{
Optimizer, OptimizerCheckpoint, OptimizerRestore, SgdParameterState, checkpoint_capability,
};
#[derive(Clone, Copy)]
pub(super) struct SgdScalars {
pub(super) learning_rate: f32,
pub(super) momentum: f32,
pub(super) weight_decay: f32,
}
fn sgd(parameter: &Matrix, gradient: &Matrix, scalars: SgdScalars) -> Result<()> {
const OPERATION: &str = crate::core::operation::ml::SGD.name();
validate_f32_same_runtime(OPERATION, &[parameter, gradient])?;
if gradient.shape() != parameter.shape() {
return Err(Error::invalid_argument(format!(
"{OPERATION} requires identical parameter and gradient shapes"
)));
}
let element_count = shader_u32(parameter.num_elements(), "element count", OPERATION)?;
if element_count == 0 {
return Ok(());
}
let buffers = [
BufferBinding::read_write(parameter.storage()),
BufferBinding::read(gradient.storage()),
];
let push_constants = [
PushConstant::U32(element_count),
PushConstant::F32(scalars.learning_rate),
PushConstant::F32(scalars.weight_decay),
];
let attributes = [
OpAttribute::Float {
name: "learning_rate".into(),
value: f64::from(scalars.learning_rate),
},
OpAttribute::Float {
name: "weight_decay".into(),
value: f64::from(scalars.weight_decay),
},
];
let kernel = KernelId::MlSgdF32;
{
let inputs: &[&Matrix] = &[parameter, gradient];
let outputs: &[&Matrix] = &[parameter];
let attributes: &[OpAttribute] = &attributes;
let dispatch = ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: kernel.linear_workgroups(element_count),
indirect: None,
};
let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
Error::internal(format!(
"lowering-only kernel {} cannot own one semantic ML operation",
dispatch.kernel.report_name()
))
})?;
let runtime = inputs
.first()
.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
.runtime();
runtime.record_semantic(
dispatch,
SemanticDispatch {
contract,
inputs,
outputs,
attributes,
},
)
}
}
fn sgd_momentum(
parameter: &Matrix,
gradient: &Matrix,
momentum: &Matrix,
scalars: SgdScalars,
) -> Result<()> {
const OPERATION: &str = crate::core::operation::ml::SGD_MOMENTUM.name();
validate_f32_same_runtime(OPERATION, &[parameter, gradient, momentum])?;
for candidate in [gradient, momentum] {
if candidate.shape() != parameter.shape() {
return Err(Error::invalid_argument(format!(
"{OPERATION} requires identical parameter, gradient, and momentum shapes"
)));
}
}
let element_count = shader_u32(parameter.num_elements(), "element count", OPERATION)?;
if element_count == 0 {
return Ok(());
}
let buffers = [
BufferBinding::read_write(parameter.storage()),
BufferBinding::read(gradient.storage()),
BufferBinding::read_write(momentum.storage()),
];
let push_constants = [
PushConstant::U32(element_count),
PushConstant::F32(scalars.learning_rate),
PushConstant::F32(scalars.momentum),
PushConstant::F32(scalars.weight_decay),
];
let attributes = [
OpAttribute::Float {
name: "learning_rate".into(),
value: f64::from(scalars.learning_rate),
},
OpAttribute::Float {
name: "momentum".into(),
value: f64::from(scalars.momentum),
},
OpAttribute::Float {
name: "weight_decay".into(),
value: f64::from(scalars.weight_decay),
},
];
let kernel = KernelId::MlSgdMomentumF32;
{
let inputs: &[&Matrix] = &[parameter, gradient, momentum];
let outputs: &[&Matrix] = &[parameter, momentum];
let attributes: &[OpAttribute] = &attributes;
let dispatch = ComputeDispatch {
kernel,
buffers: &buffers,
push_constants: &push_constants,
workgroups: kernel.linear_workgroups(element_count),
indirect: None,
};
let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
Error::internal(format!(
"lowering-only kernel {} cannot own one semantic ML operation",
dispatch.kernel.report_name()
))
})?;
let runtime = inputs
.first()
.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
.runtime();
runtime.record_semantic(
dispatch,
SemanticDispatch {
contract,
inputs,
outputs,
attributes,
},
)
}
}
pub struct Sgd {
pub(super) parameters: Vec<SgdParameterState>,
pub(super) learning_rate: f32,
pub(super) momentum: f32,
pub(super) weight_decay: f32,
pub(super) step: u64,
pub(super) param_group: Vec<usize>,
pub(super) groups: Vec<SgdGroupMeta>,
}
pub(super) struct SgdGroupMeta {
pub(super) lr_scale: f32,
pub(super) weight_decay: Option<f32>,
pub(super) frozen: bool,
}
impl Sgd {
pub fn new(
parameters: impl IntoIterator<Item = Parameter>,
learning_rate: f32,
momentum: f32,
weight_decay: f32,
) -> Result<Self> {
if !learning_rate.is_finite() || learning_rate < 0.0 {
return Err(Error::invalid_argument(
"SGD learning rate must be finite and non-negative",
));
}
if !momentum.is_finite() || momentum < 0.0 {
return Err(Error::invalid_argument(
"SGD momentum must be finite and non-negative",
));
}
if !weight_decay.is_finite() || weight_decay < 0.0 {
return Err(Error::invalid_argument(
"SGD weight decay must be finite and non-negative",
));
}
let parameters = parameters.into_iter().collect::<Vec<_>>();
if parameters.is_empty() {
return Err(Error::invalid_argument(
"SGD requires at least one parameter",
));
}
for (index, parameter) in parameters.iter().enumerate() {
if parameters[..index]
.iter()
.any(|existing| existing.same_as(parameter))
{
return Err(Error::invalid_argument(
"SGD parameter handle appears more than once",
));
}
}
let runtime = parameters[0].data().runtime().clone();
if parameters
.iter()
.any(|parameter| !runtime.same_as(parameter.data().runtime()))
{
return Err(Error::invalid_argument(
"SGD parameters must belong to one runtime",
));
}
let mut states = Vec::with_capacity(parameters.len());
for parameter in parameters {
let data = parameter.data();
let momentum_buf = (momentum > 0.0)
.then(|| {
Matrix::allocate(
data.runtime(),
data.shape().to_vec(),
data.num_elements(),
DType::F32,
)
})
.transpose()?;
states.push(SgdParameterState {
parameter,
momentum: momentum_buf,
});
}
Ok(Self {
parameters: states,
learning_rate,
momentum,
weight_decay,
step: 0,
param_group: Vec::new(),
groups: Vec::new(),
})
}
pub fn new_with_groups(
groups: Vec<crate::ml::optim::ParameterGroup>,
learning_rate: f32,
momentum: f32,
weight_decay: f32,
) -> Result<Self> {
if groups.is_empty() {
return Err(Error::invalid_argument(
"SGD requires at least one parameter group",
));
}
let mut parameters = Vec::new();
let mut param_group = Vec::new();
let mut metas = Vec::new();
for (group_index, group) in groups.into_iter().enumerate() {
if group.parameters.is_empty() {
return Err(Error::invalid_argument(format!(
"SGD group '{}' must not be empty",
group.name
)));
}
if !group.lr_scale.is_finite() || group.lr_scale < 0.0 {
return Err(Error::invalid_argument(format!(
"SGD group '{}' learning-rate scale must be finite and non-negative",
group.name
)));
}
if let Some(decay) = group.weight_decay
&& (!decay.is_finite() || decay < 0.0)
{
return Err(Error::invalid_argument(format!(
"SGD group '{}' weight decay must be finite and non-negative",
group.name
)));
}
for parameter in group.parameters {
parameters.push(parameter);
param_group.push(group_index);
}
metas.push(SgdGroupMeta {
lr_scale: group.lr_scale,
weight_decay: group.weight_decay,
frozen: group.frozen,
});
}
let mut optimizer = Self::new(parameters, learning_rate, momentum, weight_decay)?;
optimizer.param_group = param_group;
optimizer.groups = metas;
Ok(optimizer)
}
pub fn zero_grad(&self) {
for state in &self.parameters {
state.parameter.clear_gradient();
}
}
pub fn step(&mut self) -> Result<()> {
let next_step = self
.step
.checked_add(1)
.ok_or_else(|| Error::resource_exhausted("SGD step counter exhausted"))?;
let scalars = SgdScalars {
learning_rate: self.learning_rate,
momentum: self.momentum,
weight_decay: self.weight_decay,
};
let updates = self
.parameters
.iter()
.enumerate()
.filter(|(index, _state)| {
!self
.param_group
.get(*index)
.is_some_and(|group| self.groups[*group].frozen)
})
.filter_map(|(index, state)| {
state
.parameter
.gradient()
.map(|gradient| (index, state, state.parameter.data(), gradient))
})
.collect::<Vec<_>>();
for (_, state, _, _) in &updates {
state.parameter.validate_can_update()?;
}
for (index, state, parameter, gradient) in &updates {
let scalars = match self.param_group.get(*index) {
Some(group) => {
let meta = &self.groups[*group];
SgdScalars {
learning_rate: self.learning_rate * meta.lr_scale,
momentum: self.momentum,
weight_decay: meta.weight_decay.unwrap_or(self.weight_decay),
}
}
None => scalars,
};
match &state.momentum {
Some(momentum) => sgd_momentum(parameter, gradient, momentum, scalars)?,
None => sgd(parameter, gradient, scalars)?,
}
}
for (_, state, _, _) in &updates {
state.parameter.mark_updated()?;
}
self.step = next_step;
Ok(())
}
pub const fn learning_rate(&self) -> f32 {
self.learning_rate
}
pub fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()> {
if !learning_rate.is_finite() || learning_rate < 0.0 {
return Err(Error::invalid_argument(
"SGD learning rate must be finite and non-negative",
));
}
self.learning_rate = learning_rate;
Ok(())
}
pub const fn step_count(&self) -> u64 {
self.step
}
pub(super) fn belongs_to_runtime(&self, runtime: &Runtime) -> bool {
runtime.same_as_handle(self.parameters[0].parameter.data().runtime())
}
pub(super) fn checkpoint(&self) -> Result<OptimizerCheckpoint> {
let momentum_state = self.momentum > 0.0;
let mut first_state = Vec::new();
let mut second_state = Vec::new();
if momentum_state {
for state in &self.parameters {
let momentum = state.momentum.as_ref().ok_or_else(|| {
Error::failed_precondition("SGD momentum state missing for a parameter")
})?;
first_state.push(momentum.clone());
let data = state.parameter.data();
second_state.push(Matrix::allocate(
data.runtime(),
data.shape().to_vec(),
data.num_elements(),
DType::F32,
)?);
}
}
Ok(OptimizerCheckpoint {
kind: "SGD",
step: self.step,
applied_step: None,
learning_rate: self.learning_rate,
beta1: self.momentum,
beta2: 0.0,
epsilon: 0.0,
weight_decay: self.weight_decay,
parameters: self
.parameters
.iter()
.map(|state| state.parameter.clone())
.collect(),
first_state,
second_state,
})
}
pub(super) fn validate_checkpoint(&self, state: &OptimizerRestore) -> Result<()> {
if state.kind != "SGD"
|| !state.learning_rate.is_finite()
|| state.learning_rate < 0.0
|| !state.beta1.is_finite()
|| state.beta1 < 0.0
|| state.beta1 != self.momentum
|| state.beta2 != 0.0
|| state.epsilon != 0.0
|| !state.weight_decay.is_finite()
|| state.weight_decay < 0.0
{
return Err(Error::invalid_argument("invalid SGD checkpoint state"));
}
if self.momentum > 0.0 {
if state.first_state.len() != self.parameters.len()
|| state.second_state.len() != self.parameters.len()
{
return Err(Error::invalid_argument(
"SGD momentum checkpoint state does not cover the parameter set",
));
}
for (parameter_state, momentum) in self.parameters.iter().zip(&state.first_state) {
let data = parameter_state.parameter.data();
if momentum.shape() != data.shape()
|| momentum.dtype() != DType::F32
|| !momentum.runtime().same_as(data.runtime())
{
return Err(Error::invalid_argument(
"SGD checkpoint momentum contract mismatch",
));
}
}
} else if !state.first_state.is_empty() || !state.second_state.is_empty() {
return Err(Error::invalid_argument(
"zero-momentum SGD checkpoint carries momentum state",
));
}
Ok(())
}
pub(super) fn restore_checkpoint(&mut self, state: OptimizerRestore) -> Result<()> {
self.validate_checkpoint(&state)?;
if self.momentum > 0.0 {
for (parameter_state, momentum) in self.parameters.iter_mut().zip(state.first_state) {
parameter_state.momentum = Some(momentum);
}
}
self.step = state.step;
self.learning_rate = state.learning_rate;
self.weight_decay = state.weight_decay;
Ok(())
}
}
impl Optimizer for Sgd {
fn zero_grad(&self) {
Self::zero_grad(self);
}
fn step(&mut self) -> Result<()> {
Self::step(self)
}
fn learning_rate(&self) -> f32 {
Self::learning_rate(self)
}
fn set_learning_rate(&mut self, learning_rate: f32) -> Result<()> {
Self::set_learning_rate(self, learning_rate)
}
fn step_count(&self) -> u64 {
Self::step_count(self)
}
fn belongs_to(&self, runtime: &Runtime) -> bool {
self.belongs_to_runtime(runtime)
}
}
impl checkpoint_capability::Persistence for Sgd {
fn checkpoint_state(&self) -> Result<OptimizerCheckpoint> {
Self::checkpoint(self)
}
fn validate_checkpoint_state(&self, state: &OptimizerRestore) -> Result<()> {
Self::validate_checkpoint(self, state)
}
fn restore_checkpoint_state(&mut self, state: OptimizerRestore) -> Result<()> {
Self::restore_checkpoint(self, state)
}
}