Skip to main content

oa/ml/training/
scheduler.rs

1//! Donor-backed learning-rate schedules.
2//!
3//! Port provenance: `oa/ml/lrScheduler.h` and
4//! `oa/ml/callback/lrScheduler.cpp`.
5
6use std::f32::consts::PI;
7
8use crate::{Error, Result};
9
10/// Stateless step-to-learning-rate policy.
11pub trait LrScheduler {
12	/// Return the learning rate for `step`.
13	fn learning_rate(&self, step: u64) -> f32;
14}
15
16/// Cosine annealing from a maximum rate to a minimum rate.
17pub struct CosineScheduler {
18	max_learning_rate: f32,
19	min_learning_rate: f32,
20	total_steps: u64,
21}
22
23impl CosineScheduler {
24	/// Construct a cosine schedule.
25	///
26	/// # Errors
27	///
28	/// Returns an error for non-finite or negative rates, an inverted range, or
29	/// a zero step span.
30	pub fn new(max_learning_rate: f32, min_learning_rate: f32, total_steps: u64) -> Result<Self> {
31		validate_rate(max_learning_rate, "maximum")?;
32		validate_rate(min_learning_rate, "minimum")?;
33		if min_learning_rate > max_learning_rate {
34			return Err(Error::invalid_argument(
35				"cosine minimum learning rate exceeds its maximum",
36			));
37		}
38		if total_steps == 0 {
39			return Err(Error::invalid_argument(
40				"cosine schedule requires at least one step",
41			));
42		}
43		Ok(Self {
44			max_learning_rate,
45			min_learning_rate,
46			total_steps,
47		})
48	}
49}
50
51impl LrScheduler for CosineScheduler {
52	fn learning_rate(&self, step: u64) -> f32 {
53		if step >= self.total_steps {
54			return self.min_learning_rate;
55		}
56		let progress = step as f32 / self.total_steps as f32;
57		self.min_learning_rate
58			+ 0.5 * (self.max_learning_rate - self.min_learning_rate) * (1.0 + (progress * PI).cos())
59	}
60}
61
62/// Linear warmup followed by an optional delegated schedule.
63pub struct WarmupScheduler {
64	target_learning_rate: f32,
65	warmup_steps: u64,
66	after: Option<Box<dyn LrScheduler>>,
67}
68
69impl WarmupScheduler {
70	/// Construct a warmup that remains at its target after the warmup span.
71	///
72	/// # Errors
73	///
74	/// Returns an error when the target rate is non-finite or negative.
75	pub fn new(target_learning_rate: f32, warmup_steps: u64) -> Result<Self> {
76		Self::new_with_optional_after(target_learning_rate, warmup_steps, None)
77	}
78
79	/// Construct a warmup followed by `after` with a step origin of zero.
80	///
81	/// # Errors
82	///
83	/// Returns an error when the target rate is non-finite or negative.
84	pub fn new_with_after(
85		target_learning_rate: f32,
86		warmup_steps: u64,
87		after: Box<dyn LrScheduler>,
88	) -> Result<Self> {
89		Self::new_with_optional_after(target_learning_rate, warmup_steps, Some(after))
90	}
91
92	fn new_with_optional_after(
93		target_learning_rate: f32,
94		warmup_steps: u64,
95		after: Option<Box<dyn LrScheduler>>,
96	) -> Result<Self> {
97		validate_rate(target_learning_rate, "warmup target")?;
98		Ok(Self {
99			target_learning_rate,
100			warmup_steps,
101			after,
102		})
103	}
104}
105
106impl LrScheduler for WarmupScheduler {
107	fn learning_rate(&self, step: u64) -> f32 {
108		if step < self.warmup_steps {
109			return self.target_learning_rate * (step + 1) as f32 / self.warmup_steps as f32;
110		}
111		self
112			.after
113			.as_ref()
114			.map_or(self.target_learning_rate, |after| {
115				after.learning_rate(step - self.warmup_steps)
116			})
117	}
118}
119
120/// Smith one-cycle ramp and cosine decay policy.
121pub struct OneCycleScheduler {
122	max_learning_rate: f32,
123	total_steps: u64,
124	percent_start: f32,
125	division_factor: f32,
126	final_division_factor: f32,
127}
128
129impl OneCycleScheduler {
130	/// Construct a one-cycle schedule with OA's 0.3/25/10,000 defaults.
131	///
132	/// # Errors
133	///
134	/// Returns an error for an invalid maximum rate or empty span.
135	pub fn new_with_defaults(max_learning_rate: f32, total_steps: u64) -> Result<Self> {
136		Self::new(max_learning_rate, total_steps, 0.3, 25.0, 10_000.0)
137	}
138
139	/// Construct the donor-compatible one-cycle schedule.
140	///
141	/// # Errors
142	///
143	/// Returns an error for an invalid rate, empty span, percentage outside
144	/// `[0, 1]`, or non-positive division factor.
145	pub fn new(
146		max_learning_rate: f32,
147		total_steps: u64,
148		percent_start: f32,
149		division_factor: f32,
150		final_division_factor: f32,
151	) -> Result<Self> {
152		validate_rate(max_learning_rate, "one-cycle maximum")?;
153		if total_steps == 0 {
154			return Err(Error::invalid_argument(
155				"one-cycle schedule requires at least one step",
156			));
157		}
158		if !percent_start.is_finite() || !(0.0..=1.0).contains(&percent_start) {
159			return Err(Error::invalid_argument(
160				"one-cycle start percentage must be finite and in [0, 1]",
161			));
162		}
163		for (name, value) in [
164			("division", division_factor),
165			("final division", final_division_factor),
166		] {
167			if !value.is_finite() || value <= 0.0 {
168				return Err(Error::invalid_argument(format!(
169					"one-cycle {name} factor must be finite and positive"
170				)));
171			}
172		}
173		Ok(Self {
174			max_learning_rate,
175			total_steps,
176			percent_start,
177			division_factor,
178			final_division_factor,
179		})
180	}
181}
182
183impl LrScheduler for OneCycleScheduler {
184	fn learning_rate(&self, step: u64) -> f32 {
185		let initial = self.max_learning_rate / self.division_factor;
186		let final_rate = initial / self.final_division_factor;
187		let step = step as f32;
188		let total = self.total_steps as f32;
189		let up_steps = self.percent_start * total;
190		let down_steps = total - up_steps;
191		if step <= up_steps && up_steps > 0.0 {
192			let progress = step / up_steps;
193			return final_rate
194				+ 0.5 * (self.max_learning_rate - final_rate) * (1.0 - (PI * progress).cos());
195		}
196		if down_steps > 0.0 {
197			let progress = ((step - up_steps) / down_steps).min(1.0);
198			return final_rate
199				+ 0.5 * (self.max_learning_rate - final_rate) * (1.0 + (PI * progress).cos());
200		}
201		final_rate
202	}
203}
204
205/// Amplitude policy for [`CyclicScheduler`].
206#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
207pub enum CyclicMode {
208	/// Constant triangular amplitude.
209	#[default]
210	Triangular,
211	/// Halve amplitude after each cycle.
212	Triangular2,
213	/// Multiply amplitude by `gamma.powf(step)`.
214	ExpRange,
215}
216
217/// Triangular cyclic learning-rate policy.
218pub struct CyclicScheduler {
219	base_learning_rate: f32,
220	max_learning_rate: f32,
221	step_size_up: u64,
222	mode: CyclicMode,
223	gamma: f32,
224}
225
226impl CyclicScheduler {
227	/// Construct OA's constant-amplitude triangular schedule.
228	///
229	/// # Errors
230	///
231	/// Returns an error for invalid rates, an inverted range, or a zero
232	/// half-cycle span.
233	pub fn triangular(
234		base_learning_rate: f32,
235		max_learning_rate: f32,
236		step_size_up: u64,
237	) -> Result<Self> {
238		Self::new(
239			base_learning_rate,
240			max_learning_rate,
241			step_size_up,
242			CyclicMode::Triangular,
243			1.0,
244		)
245	}
246
247	/// Construct a cyclic schedule.
248	///
249	/// # Errors
250	///
251	/// Returns an error for invalid rates, an inverted range, a zero half-cycle,
252	/// or a non-finite/non-positive exponential factor.
253	pub fn new(
254		base_learning_rate: f32,
255		max_learning_rate: f32,
256		step_size_up: u64,
257		mode: CyclicMode,
258		gamma: f32,
259	) -> Result<Self> {
260		validate_rate(base_learning_rate, "cyclic base")?;
261		validate_rate(max_learning_rate, "cyclic maximum")?;
262		if base_learning_rate > max_learning_rate {
263			return Err(Error::invalid_argument(
264				"cyclic base learning rate exceeds its maximum",
265			));
266		}
267		if step_size_up == 0 {
268			return Err(Error::invalid_argument(
269				"cyclic schedule requires a nonzero rising span",
270			));
271		}
272		if !gamma.is_finite() || gamma <= 0.0 {
273			return Err(Error::invalid_argument(
274				"cyclic gamma must be finite and positive",
275			));
276		}
277		Ok(Self {
278			base_learning_rate,
279			max_learning_rate,
280			step_size_up,
281			mode,
282			gamma,
283		})
284	}
285}
286
287impl LrScheduler for CyclicScheduler {
288	fn learning_rate(&self, step: u64) -> f32 {
289		let step = step as f32;
290		let size = self.step_size_up as f32;
291		let cycle = (step / (2.0 * size)).floor();
292		let x = (step / size - 2.0 * cycle - 1.0).abs();
293		let scale = match self.mode {
294			CyclicMode::Triangular => 1.0,
295			CyclicMode::Triangular2 => 1.0 / 2.0_f32.powf(cycle),
296			CyclicMode::ExpRange => self.gamma.powf(step),
297		};
298		let ramp = (1.0 - x).max(0.0);
299		self.base_learning_rate + (self.max_learning_rate - self.base_learning_rate) * ramp * scale
300	}
301}
302
303/// Cosine annealing with periodic warm restarts.
304pub struct CosineWarmRestartsScheduler {
305	max_learning_rate: f32,
306	initial_period: u64,
307	period_multiplier: u64,
308	min_learning_rate: f32,
309}
310
311impl CosineWarmRestartsScheduler {
312	/// Construct fixed-period warm restarts with a zero minimum rate.
313	///
314	/// # Errors
315	///
316	/// Returns an error for an invalid maximum rate or zero period.
317	pub fn fixed(max_learning_rate: f32, initial_period: u64) -> Result<Self> {
318		Self::new(max_learning_rate, initial_period, 1, 0.0)
319	}
320
321	/// Construct a cosine-warm-restarts schedule.
322	///
323	/// # Errors
324	///
325	/// Returns an error for invalid rates, an inverted range, or zero period and
326	/// multiplier values.
327	pub fn new(
328		max_learning_rate: f32,
329		initial_period: u64,
330		period_multiplier: u64,
331		min_learning_rate: f32,
332	) -> Result<Self> {
333		validate_rate(max_learning_rate, "restart maximum")?;
334		validate_rate(min_learning_rate, "restart minimum")?;
335		if min_learning_rate > max_learning_rate {
336			return Err(Error::invalid_argument(
337				"restart minimum learning rate exceeds its maximum",
338			));
339		}
340		if initial_period == 0 || period_multiplier == 0 {
341			return Err(Error::invalid_argument(
342				"restart period and multiplier must be nonzero",
343			));
344		}
345		Ok(Self {
346			max_learning_rate,
347			initial_period,
348			period_multiplier,
349			min_learning_rate,
350		})
351	}
352}
353
354impl LrScheduler for CosineWarmRestartsScheduler {
355	fn learning_rate(&self, step: u64) -> f32 {
356		let (current, period) = if self.period_multiplier == 1 {
357			(step % self.initial_period, self.initial_period)
358		} else {
359			let mut start = 0_u64;
360			let mut period = self.initial_period;
361			loop {
362				let Some(end) = start.checked_add(period) else {
363					break (step - start, period);
364				};
365				if step < end {
366					break (step - start, period);
367				}
368				start = end;
369				let Some(next) = period.checked_mul(self.period_multiplier) else {
370					break (step - start, u64::MAX);
371				};
372				period = next;
373			}
374		};
375		let progress = current as f32 / period as f32;
376		self.min_learning_rate
377			+ 0.5 * (self.max_learning_rate - self.min_learning_rate) * (1.0 + (PI * progress).cos())
378	}
379}
380
381/// Improvement direction for [`ReduceOnPlateauScheduler`].
382#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
383pub enum PlateauMode {
384	/// A lower monitored value is better.
385	#[default]
386	Min,
387	/// A higher monitored value is better.
388	Max,
389}
390
391/// Stateful schedule that lowers its rate after a monitored plateau.
392pub struct ReduceOnPlateauScheduler {
393	current_learning_rate: f32,
394	factor: f32,
395	patience: u64,
396	threshold: f32,
397	min_learning_rate: f32,
398	mode: PlateauMode,
399	best: f32,
400	bad_epochs: u64,
401}
402
403impl ReduceOnPlateauScheduler {
404	/// Construct OA's default minimize-mode plateau policy.
405	///
406	/// This uses factor `0.1`, patience `10`, threshold `1e-4`, and a zero
407	/// minimum rate.
408	///
409	/// # Errors
410	///
411	/// Returns an error when the initial rate is invalid.
412	pub fn new_with_defaults(initial_learning_rate: f32) -> Result<Self> {
413		Self::new(
414			initial_learning_rate,
415			0.1,
416			10,
417			1.0e-4,
418			0.0,
419			PlateauMode::Min,
420		)
421	}
422
423	/// Construct a reduce-on-plateau schedule.
424	///
425	/// # Errors
426	///
427	/// Returns an error for invalid rates, a factor outside `(0, 1]`, or a
428	/// non-finite/negative threshold.
429	pub fn new(
430		initial_learning_rate: f32,
431		factor: f32,
432		patience: u64,
433		threshold: f32,
434		min_learning_rate: f32,
435		mode: PlateauMode,
436	) -> Result<Self> {
437		validate_rate(initial_learning_rate, "plateau initial")?;
438		validate_rate(min_learning_rate, "plateau minimum")?;
439		if min_learning_rate > initial_learning_rate {
440			return Err(Error::invalid_argument(
441				"plateau minimum learning rate exceeds its initial rate",
442			));
443		}
444		if !factor.is_finite() || factor <= 0.0 || factor > 1.0 {
445			return Err(Error::invalid_argument(
446				"plateau factor must be finite and in (0, 1]",
447			));
448		}
449		if !threshold.is_finite() || threshold < 0.0 {
450			return Err(Error::invalid_argument(
451				"plateau threshold must be finite and non-negative",
452			));
453		}
454		Ok(Self {
455			current_learning_rate: initial_learning_rate,
456			factor,
457			patience,
458			threshold,
459			min_learning_rate,
460			mode,
461			best: match mode {
462				PlateauMode::Min => f32::INFINITY,
463				PlateauMode::Max => f32::NEG_INFINITY,
464			},
465			bad_epochs: 0,
466		})
467	}
468
469	/// Observe one completed metric value and update the schedule state.
470	///
471	/// # Errors
472	///
473	/// Returns an error when `metric` is not finite.
474	pub fn step(&mut self, metric: f32) -> Result<()> {
475		if !metric.is_finite() {
476			return Err(Error::invalid_argument("plateau metric must be finite"));
477		}
478		let improved = match self.mode {
479			PlateauMode::Min => metric < self.best - self.threshold,
480			PlateauMode::Max => metric > self.best + self.threshold,
481		};
482		if improved {
483			self.best = metric;
484			self.bad_epochs = 0;
485		} else {
486			self.bad_epochs = self.bad_epochs.saturating_add(1);
487			if self.bad_epochs > self.patience {
488				self.current_learning_rate =
489					(self.current_learning_rate * self.factor).max(self.min_learning_rate);
490				self.bad_epochs = 0;
491			}
492		}
493		Ok(())
494	}
495}
496
497impl LrScheduler for ReduceOnPlateauScheduler {
498	fn learning_rate(&self, _step: u64) -> f32 {
499		self.current_learning_rate
500	}
501}
502
503/// Consecutive schedules selected by absolute step milestones.
504pub struct SequentialScheduler {
505	schedulers: Vec<Box<dyn LrScheduler>>,
506	milestones: Vec<u64>,
507}
508
509impl SequentialScheduler {
510	/// Construct a sequence whose `i`th milestone starts scheduler `i + 1`.
511	///
512	/// # Errors
513	///
514	/// Returns an error for an empty schedule list, a milestone count other than
515	/// `schedulers.len() - 1`, a zero first milestone, or non-increasing values.
516	pub fn new(schedulers: Vec<Box<dyn LrScheduler>>, milestones: Vec<u64>) -> Result<Self> {
517		if schedulers.is_empty() || milestones.len() + 1 != schedulers.len() {
518			return Err(Error::invalid_argument(
519				"sequential schedule requires one fewer milestone than schedulers",
520			));
521		}
522		if milestones.first().is_some_and(|first| *first == 0)
523			|| milestones.windows(2).any(|pair| pair[0] >= pair[1])
524		{
525			return Err(Error::invalid_argument(
526				"sequential schedule milestones must be positive and strictly increasing",
527			));
528		}
529		Ok(Self {
530			schedulers,
531			milestones,
532		})
533	}
534}
535
536impl LrScheduler for SequentialScheduler {
537	fn learning_rate(&self, step: u64) -> f32 {
538		let index = self
539			.milestones
540			.partition_point(|milestone| *milestone <= step);
541		let origin = if index == 0 {
542			0
543		} else {
544			self.milestones[index - 1]
545		};
546		self.schedulers[index].learning_rate(step - origin)
547	}
548}
549
550/// Linear warmup followed by cosine annealing.
551pub struct LinearWarmupCosineScheduler {
552	inner: WarmupScheduler,
553}
554
555impl LinearWarmupCosineScheduler {
556	/// Construct the donor-compatible composed schedule.
557	///
558	/// # Errors
559	///
560	/// Returns an error for invalid rates, an inverted range, or a total span not
561	/// greater than the warmup span.
562	pub fn new(
563		warmup_steps: u64,
564		total_steps: u64,
565		max_learning_rate: f32,
566		min_learning_rate: f32,
567	) -> Result<Self> {
568		if total_steps <= warmup_steps {
569			return Err(Error::invalid_argument(
570				"warmup-cosine total steps must exceed warmup steps",
571			));
572		}
573		let cosine = CosineScheduler::new(
574			max_learning_rate,
575			min_learning_rate,
576			total_steps - warmup_steps,
577		)?;
578		Ok(Self {
579			inner: WarmupScheduler::new_with_after(max_learning_rate, warmup_steps, Box::new(cosine))?,
580		})
581	}
582}
583
584impl LrScheduler for LinearWarmupCosineScheduler {
585	fn learning_rate(&self, step: u64) -> f32 {
586		self.inner.learning_rate(step.saturating_sub(1))
587	}
588}
589
590/// Step-decay schedule: `base * gamma^floor(step / step_size)`.
591pub struct StepScheduler {
592	base_learning_rate: f32,
593	gamma: f32,
594	step_size: u64,
595}
596
597impl StepScheduler {
598	/// Construct a step-decay schedule.
599	///
600	/// # Errors
601	///
602	/// Returns an error for an invalid rate, a non-finite or negative `gamma`,
603	/// or a zero `step_size`.
604	pub fn new(base_learning_rate: f32, gamma: f32, step_size: u64) -> Result<Self> {
605		validate_rate(base_learning_rate, "base")?;
606		if !gamma.is_finite() || gamma < 0.0 {
607			return Err(Error::invalid_argument(
608				"step schedule gamma must be finite and non-negative",
609			));
610		}
611		if step_size == 0 {
612			return Err(Error::invalid_argument(
613				"step schedule requires a nonzero step size",
614			));
615		}
616		Ok(Self {
617			base_learning_rate,
618			gamma,
619			step_size,
620		})
621	}
622}
623
624impl LrScheduler for StepScheduler {
625	fn learning_rate(&self, step: u64) -> f32 {
626		self.base_learning_rate * self.gamma.powi((step / self.step_size) as i32)
627	}
628}
629
630/// Milestone-decay schedule: `base * gamma^count(milestones <= step)`.
631pub struct MultiStepScheduler {
632	base_learning_rate: f32,
633	gamma: f32,
634	milestones: Vec<u64>,
635}
636
637impl MultiStepScheduler {
638	/// Construct a milestone-decay schedule over sorted `milestones`.
639	///
640	/// # Errors
641	///
642	/// Returns an error for an invalid rate, a non-finite or negative `gamma`,
643	/// or empty or unsorted `milestones`.
644	pub fn new(base_learning_rate: f32, gamma: f32, milestones: Vec<u64>) -> Result<Self> {
645		validate_rate(base_learning_rate, "base")?;
646		if !gamma.is_finite() || gamma < 0.0 {
647			return Err(Error::invalid_argument(
648				"multi-step schedule gamma must be finite and non-negative",
649			));
650		}
651		if milestones.is_empty() || !milestones.windows(2).all(|pair| pair[0] < pair[1]) {
652			return Err(Error::invalid_argument(
653				"multi-step schedule milestones must be nonempty and strictly increasing",
654			));
655		}
656		Ok(Self {
657			base_learning_rate,
658			gamma,
659			milestones,
660		})
661	}
662}
663
664impl LrScheduler for MultiStepScheduler {
665	fn learning_rate(&self, step: u64) -> f32 {
666		let decays = self
667			.milestones
668			.partition_point(|milestone| *milestone <= step);
669		self.base_learning_rate * self.gamma.powi(decays as i32)
670	}
671}
672
673/// Exponential-decay schedule: `base * gamma^step`.
674pub struct ExponentialScheduler {
675	base_learning_rate: f32,
676	gamma: f32,
677}
678
679impl ExponentialScheduler {
680	/// Construct an exponential-decay schedule.
681	///
682	/// # Errors
683	///
684	/// Returns an error for an invalid rate or a non-finite or negative `gamma`.
685	pub fn new(base_learning_rate: f32, gamma: f32) -> Result<Self> {
686		validate_rate(base_learning_rate, "base")?;
687		if !gamma.is_finite() || gamma < 0.0 {
688			return Err(Error::invalid_argument(
689				"exponential schedule gamma must be finite and non-negative",
690			));
691		}
692		Ok(Self {
693			base_learning_rate,
694			gamma,
695		})
696	}
697}
698
699impl LrScheduler for ExponentialScheduler {
700	fn learning_rate(&self, step: u64) -> f32 {
701		self.base_learning_rate * self.gamma.powi(step.min(i32::MAX as u64) as i32)
702	}
703}
704
705fn validate_rate(rate: f32, name: &str) -> Result<()> {
706	if !rate.is_finite() || rate < 0.0 {
707		return Err(Error::invalid_argument(format!(
708			"{name} learning rate must be finite and non-negative"
709		)));
710	}
711	Ok(())
712}