Skip to main content

oa/ml/optim/
grad_scaler.rs

1//! Dynamic gradient scaling for mixed-precision training.
2//!
3//! `GradScaler` mirrors the `torch.cuda.amp.GradScaler` contract: scale the
4//! loss before backward, unscale parameter gradients in place on-device, skip
5//! the optimizer step when any unscaled gradient is non-finite, and adapt the
6//! scale between steps. Scale growth and backoff follow PyTorch defaults.
7//!
8//! Unscaling and the finite check are GPU operations; the only host boundary
9//! is one scalar readback inside `step_optimizer`, where torch performs the
10//! equivalent CPU-side gate. Combined with `OA_FORCE_PRECISION=FP16`
11//! FP16-storage lowering, this is the admitted AMP route.
12
13use crate::ml::matrix::detach;
14use crate::ml::{Optimizer, Parameter};
15use crate::runtime::{BufferBinding, ComputeDispatch, KernelId, PushConstant, SemanticDispatch};
16use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime};
17
18const DEFAULT_INIT_SCALE: f32 = 65_536.0;
19const DEFAULT_GROWTH_FACTOR: f32 = 2.0;
20const DEFAULT_BACKOFF_FACTOR: f32 = 0.5;
21const DEFAULT_GROWTH_INTERVAL: u64 = 2000;
22
23/// Dynamic loss scaler for mixed-precision training steps.
24///
25/// The scale multiplies the loss so F16-storage gradients stay in
26/// representable range; `step_optimizer` skips parameter updates on the
27/// first non-finite unscaled gradient and `update` then halves the scale.
28/// After `growth_interval` consecutive finite steps the scale doubles.
29/// Device-resident scaler state replayed inside captured programs.
30///
31/// `scale` and `counter` drive scale/backoff bookkeeping on the device;
32/// `flag` is the finite gate consumed by gated captured optimizer kernels.
33/// All three are single-element F32 scalars so `record_semantic` broadcasts
34/// them against loss and gradient shapes without a view.
35#[derive(Clone)]
36struct ScalerDeviceState {
37	scale: Matrix,
38	counter: Matrix,
39	flag: Matrix,
40}
41
42/// Resume-relevant GradScaler state: the dynamic scale and the growth
43/// counter tracking consecutive finite steps. Configuration factors are
44/// construction-time constants and do not participate.
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub struct GradScalerState {
47	/// Current loss scale.
48	pub scale: f32,
49	/// Consecutive finite steps toward the next growth doubling.
50	pub growth_tracker: u64,
51}
52
53#[derive(Clone)]
54pub struct GradScaler {
55	scale: f32,
56	growth_factor: f32,
57	backoff_factor: f32,
58	growth_interval: u64,
59	growth_tracker: u64,
60	found_inf: bool,
61	device_state: Option<ScalerDeviceState>,
62}
63
64impl GradScaler {
65	/// Create a scaler with the PyTorch default configuration
66	/// (`init_scale=65536`, growth `2.0`, backoff `0.5`, interval `2000`).
67	#[must_use]
68	pub fn new() -> Self {
69		Self {
70			scale: DEFAULT_INIT_SCALE,
71			growth_factor: DEFAULT_GROWTH_FACTOR,
72			backoff_factor: DEFAULT_BACKOFF_FACTOR,
73			growth_interval: DEFAULT_GROWTH_INTERVAL,
74			growth_tracker: 0,
75			found_inf: false,
76			device_state: None,
77		}
78	}
79
80	/// Create a scaler with an explicit dynamic-scaling configuration.
81	///
82	/// # Errors
83	///
84	/// Returns an error when `init_scale`, `growth_factor`, or
85	/// `backoff_factor` is not positive and finite, or `growth_interval` is
86	/// zero.
87	pub fn with_config(
88		init_scale: f32,
89		growth_factor: f32,
90		backoff_factor: f32,
91		growth_interval: u64,
92	) -> Result<Self> {
93		if !init_scale.is_finite()
94			|| init_scale <= 0.0
95			|| !growth_factor.is_finite()
96			|| growth_factor <= 0.0
97			|| !backoff_factor.is_finite()
98			|| backoff_factor <= 0.0
99			|| growth_interval == 0
100		{
101			return Err(Error::invalid_argument(
102				"GradScaler requires positive finite scale/growth/backoff and a nonzero growth interval",
103			));
104		}
105		Ok(Self {
106			scale: init_scale,
107			growth_factor,
108			backoff_factor,
109			growth_interval,
110			growth_tracker: 0,
111			found_inf: false,
112			device_state: None,
113		})
114	}
115
116	/// Return the current scale.
117	#[must_use]
118	pub fn scale(&self) -> f32 {
119		self.scale
120	}
121
122	/// Capture the resume-relevant scaler state.
123	///
124	/// In host mode this reads the struct fields; after `prepare_captured`
125	/// the device owns scale bookkeeping, so capture reads the device scale
126	/// and counter back (one scalar synchronization each — checkpoints are
127	/// infrequent). `found_inf` is transient within a step and deliberately
128	/// absent: a checkpoint commits at completed updates.
129	///
130	/// # Errors
131	///
132	/// Returns an error when device readback fails.
133	pub fn capture_state(&self) -> Result<GradScalerState> {
134		if let Some(state) = &self.device_state {
135			let scale = state
136				.scale
137				.read_f32()?
138				.first()
139				.copied()
140				.ok_or_else(|| Error::internal("GradScaler device scale is empty"))?;
141			let counter = state
142				.counter
143				.read_f32()?
144				.first()
145				.copied()
146				.ok_or_else(|| Error::internal("GradScaler device counter is empty"))?;
147			#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
148			return Ok(GradScalerState {
149				scale,
150				growth_tracker: counter as u64,
151			});
152		}
153		Ok(GradScalerState {
154			scale: self.scale,
155			growth_tracker: self.growth_tracker,
156		})
157	}
158
159	/// Restore scaler state captured by [`GradScaler::capture_state`].
160	///
161	/// Host fields always update; when device state exists the scale and
162	/// counter upload into the live device matrices rather than replacing
163	/// them, because the optimizer's finite-gate binding references those
164	/// exact buffers.
165	///
166	/// # Errors
167	///
168	/// Returns an error when the scale is not positive and finite or the
169	/// device upload fails.
170	pub fn restore_state(&mut self, state: GradScalerState) -> Result<()> {
171		if !state.scale.is_finite() || state.scale <= 0.0 {
172			return Err(Error::invalid_argument(
173				"GradScaler restore requires a positive finite scale",
174			));
175		}
176		self.scale = state.scale;
177		self.growth_tracker = state.growth_tracker;
178		self.found_inf = false;
179		if let Some(device) = &self.device_state {
180			device.scale.write_values(&[state.scale])?;
181			#[allow(clippy::cast_precision_loss)]
182			device
183				.counter
184				.write_values(&[state.growth_tracker as f32])?;
185		}
186		Ok(())
187	}
188
189	/// Allocate device-resident scaler state on `runtime` for captured replay.
190	///
191	/// After this call, `scale_loss`, `unscale_gradients`, and
192	/// `record_finite_gate` all reference the device buffers instead of the
193	/// host scale, so a captured program replays scale adaptation and the
194	/// optimizer gate without a mid-step host decision. Bind
195	/// [`GradScaler::finite_flag`] to the optimizer once through
196	/// `Optimizer::set_finite_gate`.
197	///
198	/// # Errors
199	///
200	/// Returns an error when buffer allocation or upload fails.
201	pub fn prepare_captured(&mut self, runtime: &Runtime) -> Result<()> {
202		self.prepare_captured_with_tracker(runtime, 0.0)
203	}
204
205	fn prepare_captured_with_tracker(
206		&mut self,
207		runtime: &Runtime,
208		growth_tracker: f32,
209	) -> Result<()> {
210		let device_state = ScalerDeviceState {
211			scale: Matrix::new_from_slice_on(runtime, vec![], &[self.scale])?,
212			counter: Matrix::new_from_slice_on(runtime, vec![], &[growth_tracker])?,
213			flag: Matrix::new_from_slice_on(runtime, vec![], &[1.0])?,
214		};
215		self.device_state = Some(device_state);
216		Ok(())
217	}
218
219	pub(crate) fn ensure_captured(&mut self, runtime: &Runtime) -> Result<()> {
220		if let Some(state) = &self.device_state {
221			if !runtime.owns_matrix(&state.scale) {
222				return Err(Error::invalid_argument(
223					"GradScaler is already prepared on another Runtime",
224				));
225			}
226			return Ok(());
227		}
228		#[allow(clippy::cast_precision_loss)]
229		let growth_tracker = self.growth_tracker as f32;
230		self.prepare_captured_with_tracker(runtime, growth_tracker)
231	}
232
233	/// Return the device-resident finite flag for optimizer binding.
234	///
235	/// The flag is a single-element F32 matrix written by
236	/// [`GradScaler::record_finite_gate`]; bind it once with
237	/// `Optimizer::set_finite_gate` before the first captured step.
238	///
239	/// # Errors
240	///
241	/// Returns an error when `prepare_captured` has not run.
242	pub fn finite_flag(&self) -> Result<Matrix> {
243		self
244			.device_state
245			.as_ref()
246			.map(|state| state.flag.clone())
247			.ok_or_else(|| Error::failed_precondition("GradScaler finite flag requires prepare_captured"))
248	}
249
250	/// Record the device-side finite gate update for the current step.
251	///
252	/// Dispatches `MlGradScalerAdvanceF32`: `check` decides the flag (finite
253	/// iff every unscaled gradient element is finite), the scale backs off on
254	/// overflow or grows after `growth_interval` finite steps, and the growth
255	/// counter advances — all in device buffers, so the record replays the
256	/// full dynamic-scaling contract inside a captured training program.
257	/// Must follow `unscale_gradients` in record order.
258	///
259	/// # Errors
260	///
261	/// Returns an error when `prepare_captured` has not run, `check` is not a
262	/// same-runtime single-element F32 matrix, or recording fails.
263	pub fn record_finite_gate(&mut self, check: &Matrix) -> Result<()> {
264		const OPERATION: &str = crate::core::operation::ml::GRAD_SCALER_ADVANCE.name();
265		let Some(state) = &self.device_state else {
266			return Err(Error::failed_precondition(format!(
267				"{OPERATION} requires prepare_captured"
268			)));
269		};
270		if check.dtype() != DType::F32 || check.num_elements() != 1 {
271			return Err(Error::invalid_argument(format!(
272				"{OPERATION} requires a single-element F32 check"
273			)));
274		}
275		if !check.runtime().same_as(state.scale.runtime()) {
276			return Err(Error::invalid_argument(format!(
277				"{OPERATION} requires the check on the scaler runtime"
278			)));
279		}
280		let buffers = [
281			BufferBinding::read(check.storage()),
282			BufferBinding::read_write(state.scale.storage()),
283			BufferBinding::read_write(state.counter.storage()),
284			BufferBinding::read_write(state.flag.storage()),
285		];
286		let growth_interval = u32::try_from(self.growth_interval)
287			.map_err(|_| Error::invalid_argument(format!("{OPERATION} growth interval exceeds u32")))?;
288		let push_constants = [
289			PushConstant::F32(self.growth_factor),
290			PushConstant::F32(self.backoff_factor),
291			PushConstant::U32(growth_interval),
292		];
293		let inputs: &[&Matrix] = &[check, &state.scale, &state.counter, &state.flag];
294		let outputs: &[&Matrix] = &[&state.scale, &state.counter, &state.flag];
295		let attributes: &[OpAttribute] = &[];
296		let dispatch = ComputeDispatch {
297			kernel: KernelId::MlGradScalerAdvanceF32,
298			buffers: &buffers,
299			push_constants: &push_constants,
300			workgroups: [1, 1, 1],
301			indirect: None,
302		};
303		let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
304			Error::internal(format!(
305				"lowering-only kernel {} cannot own one semantic ML operation",
306				dispatch.kernel.report_name()
307			))
308		})?;
309		check.runtime().record_semantic(
310			dispatch,
311			SemanticDispatch {
312				contract,
313				inputs,
314				outputs,
315				attributes,
316			},
317		)
318	}
319
320	/// Multiply `loss` by the current scale as a recorded device operation.
321	///
322	/// Under `prepare_captured` the multiplier is the device scale buffer, so
323	/// replayed steps apply the scale the device-side advance produced for
324	/// that step rather than the value baked at capture time.
325	///
326	/// # Errors
327	///
328	/// Returns an error when runtime recording fails.
329	pub fn scale_loss(&self, loss: &Matrix) -> Result<Matrix> {
330		match &self.device_state {
331			Some(state) => loss.mul(&state.scale),
332			None => loss.scale(self.scale),
333		}
334	}
335
336	/// Divide every nonempty parameter gradient by the scale in place and
337	/// return a `[1]` accumulator that is finite iff every unscaled gradient
338	/// element is finite.
339	///
340	/// The unscale and the check are device-resident: each gradient is
341	/// rescaled into detached replacement storage and its full sum is folded
342	/// into the accumulator, so NaN or Inf propagates into the check value.
343	///
344	/// # Errors
345	///
346	/// Returns an error when runtime recording or allocation fails.
347	pub fn unscale_gradients(&self, parameters: &[Parameter]) -> Result<Matrix> {
348		let mut inverse_scale = match &self.device_state {
349			Some(state) => Some(detach(&state.scale.reciprocal()?)?),
350			None => None,
351		};
352		let mut check: Option<Matrix> = None;
353		for parameter in parameters {
354			let Some(gradient) = parameter.gradient() else {
355				continue;
356			};
357			let inverse_scale = match &inverse_scale {
358				Some(scale) => scale,
359				None => inverse_scale.insert(Matrix::new_from_slice_handle(
360					gradient.runtime(),
361					vec![],
362					&[1.0 / self.scale],
363				)?),
364			};
365			let unscaled = detach(&gradient.mul(inverse_scale)?)?;
366			let gradient_sum = detach(&unscaled.sum(-1)?)?;
367			parameter.set_gradient(unscaled);
368			check = Some(match check {
369				Some(acc) => acc.add(&gradient_sum)?,
370				None => gradient_sum,
371			});
372		}
373		check.ok_or_else(|| Error::invalid_argument("GradScaler found no nonempty parameter gradients"))
374	}
375
376	/// Apply `optimizer.step()` when `check` is finite; skip the update and
377	/// flag the scale for backoff when it is not.
378	///
379	/// This is the one host boundary of the scaler contract: the check value
380	/// is read back once per step, matching the CPU-side gate in torch.
381	///
382	/// # Errors
383	///
384	/// Returns an error when the check matrix is empty, readback fails, or
385	/// `optimizer.step()` fails.
386	pub fn step_optimizer(&mut self, optimizer: &mut dyn Optimizer, check: &Matrix) -> Result<bool> {
387		let value = check
388			.read_f32()?
389			.first()
390			.copied()
391			.ok_or_else(|| Error::invalid_argument("GradScaler check matrix is empty"))?;
392		if !value.is_finite() {
393			self.found_inf = true;
394			return Ok(false);
395		}
396		optimizer.step()?;
397		Ok(true)
398	}
399
400	/// Adjust the scale after `step_optimizer`: halve it on a skipped step,
401	/// otherwise double it after `growth_interval` consecutive finite steps.
402	///
403	/// This is the eager-path companion. Under `prepare_captured` the
404	/// device-side advance owns scale bookkeeping during replay and this is a
405	/// no-op; `device_scale` reads the current value back when needed.
406	pub fn update(&mut self) {
407		if self.device_state.is_some() {
408			return;
409		}
410		if self.found_inf {
411			self.scale *= self.backoff_factor;
412			self.growth_tracker = 0;
413			self.found_inf = false;
414		} else {
415			self.growth_tracker += 1;
416			if self.growth_tracker >= self.growth_interval {
417				self.scale *= self.growth_factor;
418				self.growth_tracker = 0;
419			}
420		}
421	}
422
423	/// Read the current device-resident scale back to the host.
424	///
425	/// Costs one scalar synchronization; intended for diagnostics and
426	/// logging, not per-step control flow.
427	///
428	/// # Errors
429	///
430	/// Returns an error when `prepare_captured` has not run or the readback
431	/// fails.
432	pub fn device_scale(&self) -> Result<f32> {
433		let Some(state) = &self.device_state else {
434			return Err(Error::failed_precondition(
435				"GradScaler device scale requires prepare_captured",
436			));
437		};
438		state
439			.scale
440			.read_f32()?
441			.first()
442			.copied()
443			.ok_or_else(|| Error::internal("GradScaler device scale is empty"))
444	}
445}
446
447impl Default for GradScaler {
448	fn default() -> Self {
449		Self::new()
450	}
451}