Skip to main content

oa/ml/training/
sac.rs

1//! Fixed-temperature Soft Actor-Critic update coordinator.
2//!
3//! Port provenance: OA C++ `oa/ml/sacTrainer.{h,cpp}`. Actor and twin-critic
4//! optimizer units remain separate [`Training`] lifecycles while sharing the
5//! caller's one Runtime and replay owner.
6
7use crate::{DType, Error, Matrix, Result, Runtime, matrix};
8
9use super::{Optimizer, Training, TrainingConfig, target};
10pub use crate::ml::types::SacTrainerConfig;
11use crate::ml::{GradientTape, Module, ReplayBuffer, loss, policy};
12
13impl Default for SacTrainerConfig {
14	fn default() -> Self {
15		Self {
16			updates: 0,
17			batch_size: 0,
18			action_dimensions: 0,
19			target_update_interval: 1,
20			observation_shape: Vec::new(),
21			action_minimum: -1.0,
22			action_maximum: 1.0,
23			seed: 0,
24			loss: loss::SacLossConfig::default(),
25		}
26	}
27}
28
29/// Last completed SAC actor/critic update pair.
30#[derive(Clone, Copy, Debug, Default, PartialEq)]
31pub struct SacTrainerMetrics {
32	/// One-based completed update-pair count.
33	pub update: u64,
34	/// Last synchronized actor loss.
35	pub actor_loss: f32,
36	/// Last synchronized twin-critic loss.
37	pub critic_loss: f32,
38	/// The fixed temperature of this run — constant within a run since the
39	/// admitted SAC path is fixed-temperature; surfaced so learning curves
40	/// record it beside the losses. Learned-temperature SAC is qualified
41	/// separately in the roadmap.
42	pub temperature: f32,
43}
44
45impl SacTrainerMetrics {
46	/// Construct metrics for zero completed updates.
47	#[inline]
48	#[must_use]
49	pub fn new() -> Self {
50		Self::default()
51	}
52}
53
54/// Stateful fixed-temperature SAC coordinator over caller-owned components.
55#[must_use]
56pub struct SacTrainer<'runtime, 'hooks> {
57	runtime: &'runtime Runtime,
58	actor: &'runtime dyn Module,
59	critic1: &'runtime dyn Module,
60	critic2: &'runtime dyn Module,
61	target_critic1: &'runtime dyn Module,
62	target_critic2: &'runtime dyn Module,
63	replay: &'runtime ReplayBuffer,
64	config: SacTrainerConfig,
65	observation_elements: usize,
66	critic_training: Training<'runtime, 'hooks>,
67	actor_training: Training<'runtime, 'hooks>,
68	metrics: SacTrainerMetrics,
69}
70
71impl<'runtime, 'hooks> SacTrainer<'runtime, 'hooks> {
72	/// Validate all owners, construct two training lifecycles, and synchronize targets.
73	///
74	/// # Errors
75	///
76	/// Returns an error for invalid shape/range/update policy, incompatible
77	/// critic schemas, optimizer ownership, overflow, or target-copy failure.
78	#[allow(
79		clippy::too_many_arguments,
80		reason = "the SAC owner contract keeps actor, twin critics, twin targets, and optimizers explicit"
81	)]
82	pub fn new(
83		runtime: &'runtime Runtime,
84		actor: &'runtime dyn Module,
85		critic1: &'runtime dyn Module,
86		critic2: &'runtime dyn Module,
87		target_critic1: &'runtime dyn Module,
88		target_critic2: &'runtime dyn Module,
89		actor_optimizer: &'runtime mut dyn Optimizer,
90		critic_optimizer: &'runtime mut dyn Optimizer,
91		replay: &'runtime ReplayBuffer,
92		config: SacTrainerConfig,
93	) -> Result<Self> {
94		Self::build(
95			runtime,
96			actor,
97			critic1,
98			critic2,
99			target_critic1,
100			target_critic2,
101			actor_optimizer,
102			critic_optimizer,
103			replay,
104			config,
105			0,
106			true,
107		)
108	}
109
110	/// Construct a resumed SAC trainer at `completed_updates` without
111	/// overwriting restored target-critic weights.
112	///
113	/// Validates both target-critic schemas and runtime ownership, ensures
114	/// target parameters do not require gradients, and sets replay/policy seeds
115	/// and target-sync cadence to continue from `completed_updates`.
116	///
117	/// # Errors
118	///
119	/// Returns an error when `completed_updates > config.updates` or any
120	/// precondition checked by [`SacTrainer::new`] fails.
121	#[allow(
122		clippy::too_many_arguments,
123		reason = "the SAC owner contract keeps actor, twin critics, twin targets, optimizers, and resume state explicit"
124	)]
125	pub fn new_resumed(
126		runtime: &'runtime Runtime,
127		actor: &'runtime dyn Module,
128		critic1: &'runtime dyn Module,
129		critic2: &'runtime dyn Module,
130		target_critic1: &'runtime dyn Module,
131		target_critic2: &'runtime dyn Module,
132		actor_optimizer: &'runtime mut dyn Optimizer,
133		critic_optimizer: &'runtime mut dyn Optimizer,
134		replay: &'runtime ReplayBuffer,
135		config: SacTrainerConfig,
136		completed_updates: u64,
137	) -> Result<Self> {
138		Self::build(
139			runtime,
140			actor,
141			critic1,
142			critic2,
143			target_critic1,
144			target_critic2,
145			actor_optimizer,
146			critic_optimizer,
147			replay,
148			config,
149			completed_updates,
150			false,
151		)
152	}
153
154	#[allow(
155		clippy::too_many_arguments,
156		reason = "shared SAC constructor keeps all owners and resume parameters explicit"
157	)]
158	fn build(
159		runtime: &'runtime Runtime,
160		actor: &'runtime dyn Module,
161		critic1: &'runtime dyn Module,
162		critic2: &'runtime dyn Module,
163		target_critic1: &'runtime dyn Module,
164		target_critic2: &'runtime dyn Module,
165		actor_optimizer: &'runtime mut dyn Optimizer,
166		critic_optimizer: &'runtime mut dyn Optimizer,
167		replay: &'runtime ReplayBuffer,
168		config: SacTrainerConfig,
169		completed_updates: u64,
170		sync_targets_initially: bool,
171	) -> Result<Self> {
172		validate_config(replay, &config)?;
173		if completed_updates > config.updates {
174			return Err(Error::invalid_argument(
175				"SAC completed_updates exceeds configured update budget",
176			));
177		}
178		let observation_elements = shape_elements(&config.observation_shape, "observation")?;
179		let pairs = [(critic1, target_critic1), (critic2, target_critic2)];
180		if sync_targets_initially {
181			target::sync_exact(runtime, &pairs, "SAC critic")?;
182		} else {
183			target::validate_exact_schema(runtime, &pairs, "SAC critic")?;
184		}
185		let batch_size = u64::try_from(config.batch_size)
186			.map_err(|_| Error::resource_exhausted("SAC batch size exceeds u64"))?;
187		let critic_training = Training::new_eager(
188			runtime,
189			critic_optimizer,
190			TrainingConfig {
191				total_steps: config.updates,
192				initial_step: completed_updates,
193				batch_size,
194				timer_name: "sac_critic_update".into(),
195				..TrainingConfig::default()
196			},
197		)?;
198		let actor_training = Training::new_eager(
199			runtime,
200			actor_optimizer,
201			TrainingConfig {
202				total_steps: config.updates,
203				initial_step: completed_updates,
204				batch_size,
205				timer_name: "sac_actor_update".into(),
206				..TrainingConfig::default()
207			},
208		)?;
209		let temperature = config.loss.entropy_coefficient;
210		Ok(Self {
211			runtime,
212			actor,
213			critic1,
214			critic2,
215			target_critic1,
216			target_critic2,
217			replay,
218			config,
219			observation_elements,
220			critic_training,
221			actor_training,
222			metrics: SacTrainerMetrics {
223				update: completed_updates,
224				temperature,
225				..SacTrainerMetrics::default()
226			},
227		})
228	}
229
230	/// Return the cumulative number of completed update pairs (including any resumed offset).
231	pub fn completed_updates(&self) -> u64 {
232		self.critic_training.snapshot().step_count()
233	}
234
235	/// Complete one critic update followed by one actor update.
236	///
237	/// Returns `false` when either coordinated loop has stopped or exhausted its
238	/// budget. Next-state policy and target-critic work is recorded before either
239	/// tape, preserving the donor's detached Bellman target.
240	///
241	/// # Errors
242	///
243	/// Returns an error for insufficient replay, module output drift, loss,
244	/// reverse-mode, optimizer, callback, synchronization, or runtime failure.
245	pub fn update(&mut self) -> Result<bool> {
246		if self.is_done() {
247			return Ok(false);
248		}
249		if self.replay.len() < self.config.batch_size {
250			return Err(Error::failed_precondition(
251				"SAC replay does not contain one complete batch",
252			));
253		}
254		// The two coordinated lifecycles must never overlap: each eager training
255		// opens a stable-resource frame at begin_step, and frames cannot nest.
256		// The critic step therefore completes in full before the actor step
257		// begins. Budgets are identical by construction, so the lifecycles
258		// cannot drift.
259		if !self.critic_training.begin_step()? {
260			self.actor_training.request_stop();
261			return Ok(false);
262		}
263		if let Err(error) = self.record_critic_update() {
264			self.runtime.abort_pending_work();
265			return self.critic_training.fail_composed_step(error);
266		}
267		if !self.actor_training.begin_step()? {
268			self.critic_training.request_stop();
269			return Ok(false);
270		}
271		if let Err(error) = self.record_actor_update() {
272			self.runtime.abort_pending_work();
273			return self.actor_training.fail_composed_step(error);
274		}
275		let update = self.critic_training.snapshot().step_count();
276		self.metrics.update = update;
277		if update.is_multiple_of(self.config.target_update_interval) {
278			self.sync_targets()?;
279		}
280		Ok(true)
281	}
282
283	fn record_critic_update(&mut self) -> Result<()> {
284		let update = self.metrics.update;
285		let sample_seed = checked_seed(self.config.seed, update + 1, "replay")?;
286		let sampled = self.replay.sample(self.config.batch_size, sample_seed)?;
287		let shape = vec![self.config.batch_size, self.observation_elements];
288		let observation = matrix::reshape(sampled.observation(), shape.clone())?;
289		let next_observation = matrix::reshape(sampled.next_observation(), shape)?;
290
291		let next_policy = self.actor_policy(
292			&next_observation,
293			checked_seed(self.config.seed, 0x1_0000_0001 + update, "next policy")?,
294		)?;
295		let next_input = critic_input(&next_observation, &next_policy.action)?;
296		let next_q1 = vector_q(
297			self.target_critic1.forward(&next_input)?,
298			self.config.batch_size,
299		)?;
300		let next_q2 = vector_q(
301			self.target_critic2.forward(&next_input)?,
302			self.config.batch_size,
303		)?;
304
305		self.critic_training.zero_grad();
306		let critic_tape = GradientTape::new();
307		let stored_input = critic_input(&observation, sampled.action())?;
308		let q1 = vector_q(self.critic1.forward(&stored_input)?, self.config.batch_size)?;
309		let q2 = vector_q(self.critic2.forward(&stored_input)?, self.config.batch_size)?;
310		let critic = loss::sac_critic(
311			&q1,
312			&q2,
313			sampled.reward(),
314			&next_q1,
315			&next_q2,
316			&next_policy.log_probability,
317			sampled.terminated(),
318			sampled.truncated(),
319			self.config.loss,
320		)?;
321		critic_tape.backward(&critic.total_loss)?;
322		self.critic_training.complete_step(&critic.total_loss)?;
323		self.metrics.critic_loss = self.critic_training.snapshot().last_loss().unwrap_or(0.0);
324		Ok(())
325	}
326
327	fn record_actor_update(&mut self) -> Result<()> {
328		// Re-sample with the critic half's identical seed: replay sampling is
329		// a deterministic function of the seed and neither half mutates the
330		// buffer, so the actor update composes over the bitwise same batch.
331		let update = self.metrics.update;
332		let sample_seed = checked_seed(self.config.seed, update + 1, "replay")?;
333		let sampled = self.replay.sample(self.config.batch_size, sample_seed)?;
334		let shape = vec![self.config.batch_size, self.observation_elements];
335		let observation = matrix::reshape(sampled.observation(), shape)?;
336
337		self.actor_training.zero_grad();
338		self.critic_training.zero_grad();
339		let actor_tape = GradientTape::new();
340		let actor_policy = self.actor_policy(
341			&observation,
342			checked_seed(self.config.seed, 0x2_0000_0001 + update, "actor policy")?,
343		)?;
344		let policy_input = critic_input(&observation, &actor_policy.action)?;
345		let actor_q1 = vector_q(self.critic1.forward(&policy_input)?, self.config.batch_size)?;
346		let actor_q2 = vector_q(self.critic2.forward(&policy_input)?, self.config.batch_size)?;
347		let actor_loss = loss::sac_actor(
348			&actor_q1,
349			&actor_q2,
350			&actor_policy.log_probability,
351			self.config.loss.entropy_coefficient,
352		)?;
353		actor_tape.backward(&actor_loss)?;
354		self.actor_training.complete_step(&actor_loss)?;
355		self.metrics.actor_loss = self.actor_training.snapshot().last_loss().unwrap_or(0.0);
356		Ok(())
357	}
358
359	fn actor_policy(
360		&self,
361		observation: &Matrix,
362		seed: u64,
363	) -> Result<policy::ContinuousPolicyResult> {
364		let output = self.actor.forward(observation)?;
365		let expected_width = self
366			.config
367			.action_dimensions
368			.checked_mul(2)
369			.ok_or_else(|| Error::resource_exhausted("SAC actor width overflows usize"))?;
370		if output.shape() != [self.config.batch_size, expected_width] || output.dtype() != DType::F32 {
371			return Err(Error::invalid_argument(
372				"SAC actor must return F32 [batch, 2 * action_dimensions]",
373			));
374		}
375		let split = i64::try_from(self.config.action_dimensions)
376			.map_err(|_| Error::resource_exhausted("SAC action width exceeds i64"))?;
377		let end = i64::try_from(expected_width)
378			.map_err(|_| Error::resource_exhausted("SAC actor width exceeds i64"))?;
379		let mean = matrix::slice(&output, 1, 0, split)?;
380		let log_stddev = matrix::slice(&output, 1, split, end)?;
381		let value = matrix::full_on(self.runtime, [self.config.batch_size], 0.0)?;
382		policy::sample_tanh_normal(
383			&mean,
384			&log_stddev,
385			&value,
386			self.config.action_minimum,
387			self.config.action_maximum,
388			seed,
389			1.0e-6,
390		)
391	}
392
393	/// Exactly synchronize both online critics into their target peers.
394	pub fn sync_targets(&self) -> Result<()> {
395		target::sync_exact(
396			self.runtime,
397			&[
398				(self.critic1, self.target_critic1),
399				(self.critic2, self.target_critic2),
400			],
401			"SAC critic",
402		)
403	}
404
405	/// Return whether either coordinated loop has stopped or reached its budget.
406	pub fn is_done(&self) -> bool {
407		let critic = self.critic_training.snapshot().step_count();
408		let actor = self.actor_training.snapshot().step_count();
409		self.critic_training.stop_requested()
410			|| self.actor_training.stop_requested()
411			|| critic >= self.config.updates
412			|| actor >= self.config.updates
413	}
414
415	/// Return the last completed update-pair metrics.
416	pub const fn metrics(&self) -> SacTrainerMetrics {
417		self.metrics
418	}
419
420	/// Borrow the primary critic update lifecycle.
421	pub const fn training_loop(&self) -> &Training<'runtime, 'hooks> {
422		&self.critic_training
423	}
424
425	/// Mutably borrow the primary critic update lifecycle.
426	pub fn training_loop_mut(&mut self) -> &mut Training<'runtime, 'hooks> {
427		&mut self.critic_training
428	}
429
430	/// Borrow the independently observable actor update lifecycle.
431	pub const fn actor_training_loop(&self) -> &Training<'runtime, 'hooks> {
432		&self.actor_training
433	}
434
435	/// Mutably borrow the actor update lifecycle.
436	pub fn actor_training_loop_mut(&mut self) -> &mut Training<'runtime, 'hooks> {
437		&mut self.actor_training
438	}
439
440	/// Fire both explicit terminal boundaries and return critic then actor snapshots.
441	///
442	/// # Errors
443	///
444	/// Returns an error for incomplete steps or terminal callback failure.
445	pub fn finish(self) -> Result<(super::TrainingSnapshot, super::TrainingSnapshot)> {
446		let critic = self.critic_training.finish()?;
447		let actor = self.actor_training.finish()?;
448		Ok((critic, actor))
449	}
450}
451
452fn validate_config(replay: &ReplayBuffer, config: &SacTrainerConfig) -> Result<()> {
453	let replay_config = replay.config();
454	if config.updates == 0
455		|| config.batch_size == 0
456		|| config.action_dimensions == 0
457		|| config.target_update_interval == 0
458		|| config.observation_shape != replay_config.observation_shape
459		|| replay_config.action_dtype != DType::F32
460		|| replay_config.action_shape != [config.action_dimensions]
461		|| !config.action_minimum.is_finite()
462		|| !config.action_maximum.is_finite()
463		|| config.action_minimum >= config.action_maximum
464	{
465		return Err(Error::invalid_argument(
466			"SAC trainer configuration does not match continuous replay storage",
467		));
468	}
469	shape_elements(&config.observation_shape, "observation")?;
470	Ok(())
471}
472
473fn shape_elements(shape: &[usize], label: &'static str) -> Result<usize> {
474	shape.iter().try_fold(1_usize, |count, extent| {
475		count
476			.checked_mul(*extent)
477			.ok_or_else(|| Error::resource_exhausted(format!("SAC {label} size overflows usize")))
478	})
479}
480
481fn checked_seed(base: u64, offset: u64, label: &'static str) -> Result<u64> {
482	base
483		.checked_add(offset)
484		.ok_or_else(|| Error::resource_exhausted(format!("SAC {label} seed exhausted")))
485}
486
487fn critic_input(observation: &Matrix, action: &Matrix) -> Result<Matrix> {
488	matrix::concat(&[observation.clone(), action.clone()], 1)
489}
490
491fn vector_q(input: Matrix, batch_size: usize) -> Result<Matrix> {
492	if input.dtype() != DType::F32 {
493		return Err(Error::invalid_argument("SAC critic output must be F32"));
494	}
495	if input.shape() == [batch_size] {
496		return Ok(input);
497	}
498	if input.shape() == [batch_size, 1] {
499		return matrix::reshape(&input, [batch_size]);
500	}
501	Err(Error::invalid_argument(
502		"SAC critics must return [batch] or [batch, 1]",
503	))
504}