1mod 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#[derive(Clone)]
29pub struct ParameterGroup {
30 pub name: String,
32 pub parameters: Vec<Parameter>,
34 pub lr_scale: f32,
36 pub weight_decay: Option<f32>,
38 pub frozen: bool,
40}
41
42impl ParameterGroup {
43 #[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 #[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 #[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 #[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
84pub 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], ¶ms)?;
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
192pub 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 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}