oarust 0.20.0

GPU-first semantic computing runtime written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Fixed-temperature Soft Actor-Critic update coordinator.
//!
//! Port provenance: OA C++ `oa/ml/sacTrainer.{h,cpp}`. Actor and twin-critic
//! optimizer units remain separate [`Training`] lifecycles while sharing the
//! caller's one Runtime and replay owner.

use crate::{DType, Error, Matrix, Result, Runtime, matrix};

use super::{Optimizer, Training, TrainingConfig, target};
pub use crate::ml::types::SacTrainerConfig;
use crate::ml::{GradientTape, Module, ReplayBuffer, loss, policy};

impl Default for SacTrainerConfig {
	fn default() -> Self {
		Self {
			updates: 0,
			batch_size: 0,
			action_dimensions: 0,
			target_update_interval: 1,
			observation_shape: Vec::new(),
			action_minimum: -1.0,
			action_maximum: 1.0,
			seed: 0,
			loss: loss::SacLossConfig::default(),
		}
	}
}

/// Last completed SAC actor/critic update pair.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SacTrainerMetrics {
	/// One-based completed update-pair count.
	pub update: u64,
	/// Last synchronized actor loss.
	pub actor_loss: f32,
	/// Last synchronized twin-critic loss.
	pub critic_loss: f32,
	/// The fixed temperature of this run — constant within a run since the
	/// admitted SAC path is fixed-temperature; surfaced so learning curves
	/// record it beside the losses. Learned-temperature SAC is qualified
	/// separately in the roadmap.
	pub temperature: f32,
}

impl SacTrainerMetrics {
	/// Construct metrics for zero completed updates.
	#[inline]
	#[must_use]
	pub fn new() -> Self {
		Self::default()
	}
}

/// Stateful fixed-temperature SAC coordinator over caller-owned components.
#[must_use]
pub struct SacTrainer<'runtime, 'hooks> {
	runtime: &'runtime Runtime,
	actor: &'runtime dyn Module,
	critic1: &'runtime dyn Module,
	critic2: &'runtime dyn Module,
	target_critic1: &'runtime dyn Module,
	target_critic2: &'runtime dyn Module,
	replay: &'runtime ReplayBuffer,
	config: SacTrainerConfig,
	observation_elements: usize,
	critic_training: Training<'runtime, 'hooks>,
	actor_training: Training<'runtime, 'hooks>,
	metrics: SacTrainerMetrics,
}

impl<'runtime, 'hooks> SacTrainer<'runtime, 'hooks> {
	/// Validate all owners, construct two training lifecycles, and synchronize targets.
	///
	/// # Errors
	///
	/// Returns an error for invalid shape/range/update policy, incompatible
	/// critic schemas, optimizer ownership, overflow, or target-copy failure.
	#[allow(
		clippy::too_many_arguments,
		reason = "the SAC owner contract keeps actor, twin critics, twin targets, and optimizers explicit"
	)]
	pub fn new(
		runtime: &'runtime Runtime,
		actor: &'runtime dyn Module,
		critic1: &'runtime dyn Module,
		critic2: &'runtime dyn Module,
		target_critic1: &'runtime dyn Module,
		target_critic2: &'runtime dyn Module,
		actor_optimizer: &'runtime mut dyn Optimizer,
		critic_optimizer: &'runtime mut dyn Optimizer,
		replay: &'runtime ReplayBuffer,
		config: SacTrainerConfig,
	) -> Result<Self> {
		Self::build(
			runtime,
			actor,
			critic1,
			critic2,
			target_critic1,
			target_critic2,
			actor_optimizer,
			critic_optimizer,
			replay,
			config,
			0,
			true,
		)
	}

	/// Construct a resumed SAC trainer at `completed_updates` without
	/// overwriting restored target-critic weights.
	///
	/// Validates both target-critic schemas and runtime ownership, ensures
	/// target parameters do not require gradients, and sets replay/policy seeds
	/// and target-sync cadence to continue from `completed_updates`.
	///
	/// # Errors
	///
	/// Returns an error when `completed_updates > config.updates` or any
	/// precondition checked by [`SacTrainer::new`] fails.
	#[allow(
		clippy::too_many_arguments,
		reason = "the SAC owner contract keeps actor, twin critics, twin targets, optimizers, and resume state explicit"
	)]
	pub fn new_resumed(
		runtime: &'runtime Runtime,
		actor: &'runtime dyn Module,
		critic1: &'runtime dyn Module,
		critic2: &'runtime dyn Module,
		target_critic1: &'runtime dyn Module,
		target_critic2: &'runtime dyn Module,
		actor_optimizer: &'runtime mut dyn Optimizer,
		critic_optimizer: &'runtime mut dyn Optimizer,
		replay: &'runtime ReplayBuffer,
		config: SacTrainerConfig,
		completed_updates: u64,
	) -> Result<Self> {
		Self::build(
			runtime,
			actor,
			critic1,
			critic2,
			target_critic1,
			target_critic2,
			actor_optimizer,
			critic_optimizer,
			replay,
			config,
			completed_updates,
			false,
		)
	}

	#[allow(
		clippy::too_many_arguments,
		reason = "shared SAC constructor keeps all owners and resume parameters explicit"
	)]
	fn build(
		runtime: &'runtime Runtime,
		actor: &'runtime dyn Module,
		critic1: &'runtime dyn Module,
		critic2: &'runtime dyn Module,
		target_critic1: &'runtime dyn Module,
		target_critic2: &'runtime dyn Module,
		actor_optimizer: &'runtime mut dyn Optimizer,
		critic_optimizer: &'runtime mut dyn Optimizer,
		replay: &'runtime ReplayBuffer,
		config: SacTrainerConfig,
		completed_updates: u64,
		sync_targets_initially: bool,
	) -> Result<Self> {
		validate_config(replay, &config)?;
		if completed_updates > config.updates {
			return Err(Error::invalid_argument(
				"SAC completed_updates exceeds configured update budget",
			));
		}
		let observation_elements = shape_elements(&config.observation_shape, "observation")?;
		let pairs = [(critic1, target_critic1), (critic2, target_critic2)];
		if sync_targets_initially {
			target::sync_exact(runtime, &pairs, "SAC critic")?;
		} else {
			target::validate_exact_schema(runtime, &pairs, "SAC critic")?;
		}
		let batch_size = u64::try_from(config.batch_size)
			.map_err(|_| Error::resource_exhausted("SAC batch size exceeds u64"))?;
		let critic_training = Training::new_eager(
			runtime,
			critic_optimizer,
			TrainingConfig {
				total_steps: config.updates,
				initial_step: completed_updates,
				batch_size,
				timer_name: "sac_critic_update".into(),
				..TrainingConfig::default()
			},
		)?;
		let actor_training = Training::new_eager(
			runtime,
			actor_optimizer,
			TrainingConfig {
				total_steps: config.updates,
				initial_step: completed_updates,
				batch_size,
				timer_name: "sac_actor_update".into(),
				..TrainingConfig::default()
			},
		)?;
		let temperature = config.loss.entropy_coefficient;
		Ok(Self {
			runtime,
			actor,
			critic1,
			critic2,
			target_critic1,
			target_critic2,
			replay,
			config,
			observation_elements,
			critic_training,
			actor_training,
			metrics: SacTrainerMetrics {
				update: completed_updates,
				temperature,
				..SacTrainerMetrics::default()
			},
		})
	}

	/// Return the cumulative number of completed update pairs (including any resumed offset).
	pub fn completed_updates(&self) -> u64 {
		self.critic_training.snapshot().step_count()
	}

	/// Complete one critic update followed by one actor update.
	///
	/// Returns `false` when either coordinated loop has stopped or exhausted its
	/// budget. Next-state policy and target-critic work is recorded before either
	/// tape, preserving the donor's detached Bellman target.
	///
	/// # Errors
	///
	/// Returns an error for insufficient replay, module output drift, loss,
	/// reverse-mode, optimizer, callback, synchronization, or runtime failure.
	pub fn update(&mut self) -> Result<bool> {
		if self.is_done() {
			return Ok(false);
		}
		if self.replay.len() < self.config.batch_size {
			return Err(Error::failed_precondition(
				"SAC replay does not contain one complete batch",
			));
		}
		// The two coordinated lifecycles must never overlap: each eager training
		// opens a stable-resource frame at begin_step, and frames cannot nest.
		// The critic step therefore completes in full before the actor step
		// begins. Budgets are identical by construction, so the lifecycles
		// cannot drift.
		if !self.critic_training.begin_step()? {
			self.actor_training.request_stop();
			return Ok(false);
		}
		if let Err(error) = self.record_critic_update() {
			self.runtime.abort_pending_work();
			return self.critic_training.fail_composed_step(error);
		}
		if !self.actor_training.begin_step()? {
			self.critic_training.request_stop();
			return Ok(false);
		}
		if let Err(error) = self.record_actor_update() {
			self.runtime.abort_pending_work();
			return self.actor_training.fail_composed_step(error);
		}
		let update = self.critic_training.snapshot().step_count();
		self.metrics.update = update;
		if update.is_multiple_of(self.config.target_update_interval) {
			self.sync_targets()?;
		}
		Ok(true)
	}

	fn record_critic_update(&mut self) -> Result<()> {
		let update = self.metrics.update;
		let sample_seed = checked_seed(self.config.seed, update + 1, "replay")?;
		let sampled = self.replay.sample(self.config.batch_size, sample_seed)?;
		let shape = vec![self.config.batch_size, self.observation_elements];
		let observation = matrix::reshape(sampled.observation(), shape.clone())?;
		let next_observation = matrix::reshape(sampled.next_observation(), shape)?;

		let next_policy = self.actor_policy(
			&next_observation,
			checked_seed(self.config.seed, 0x1_0000_0001 + update, "next policy")?,
		)?;
		let next_input = critic_input(&next_observation, &next_policy.action)?;
		let next_q1 = vector_q(
			self.target_critic1.forward(&next_input)?,
			self.config.batch_size,
		)?;
		let next_q2 = vector_q(
			self.target_critic2.forward(&next_input)?,
			self.config.batch_size,
		)?;

		self.critic_training.zero_grad();
		let critic_tape = GradientTape::new();
		let stored_input = critic_input(&observation, sampled.action())?;
		let q1 = vector_q(self.critic1.forward(&stored_input)?, self.config.batch_size)?;
		let q2 = vector_q(self.critic2.forward(&stored_input)?, self.config.batch_size)?;
		let critic = loss::sac_critic(
			&q1,
			&q2,
			sampled.reward(),
			&next_q1,
			&next_q2,
			&next_policy.log_probability,
			sampled.terminated(),
			sampled.truncated(),
			self.config.loss,
		)?;
		critic_tape.backward(&critic.total_loss)?;
		self.critic_training.complete_step(&critic.total_loss)?;
		self.metrics.critic_loss = self.critic_training.snapshot().last_loss().unwrap_or(0.0);
		Ok(())
	}

	fn record_actor_update(&mut self) -> Result<()> {
		// Re-sample with the critic half's identical seed: replay sampling is
		// a deterministic function of the seed and neither half mutates the
		// buffer, so the actor update composes over the bitwise same batch.
		let update = self.metrics.update;
		let sample_seed = checked_seed(self.config.seed, update + 1, "replay")?;
		let sampled = self.replay.sample(self.config.batch_size, sample_seed)?;
		let shape = vec![self.config.batch_size, self.observation_elements];
		let observation = matrix::reshape(sampled.observation(), shape)?;

		self.actor_training.zero_grad();
		self.critic_training.zero_grad();
		let actor_tape = GradientTape::new();
		let actor_policy = self.actor_policy(
			&observation,
			checked_seed(self.config.seed, 0x2_0000_0001 + update, "actor policy")?,
		)?;
		let policy_input = critic_input(&observation, &actor_policy.action)?;
		let actor_q1 = vector_q(self.critic1.forward(&policy_input)?, self.config.batch_size)?;
		let actor_q2 = vector_q(self.critic2.forward(&policy_input)?, self.config.batch_size)?;
		let actor_loss = loss::sac_actor(
			&actor_q1,
			&actor_q2,
			&actor_policy.log_probability,
			self.config.loss.entropy_coefficient,
		)?;
		actor_tape.backward(&actor_loss)?;
		self.actor_training.complete_step(&actor_loss)?;
		self.metrics.actor_loss = self.actor_training.snapshot().last_loss().unwrap_or(0.0);
		Ok(())
	}

	fn actor_policy(
		&self,
		observation: &Matrix,
		seed: u64,
	) -> Result<policy::ContinuousPolicyResult> {
		let output = self.actor.forward(observation)?;
		let expected_width = self
			.config
			.action_dimensions
			.checked_mul(2)
			.ok_or_else(|| Error::resource_exhausted("SAC actor width overflows usize"))?;
		if output.shape() != [self.config.batch_size, expected_width] || output.dtype() != DType::F32 {
			return Err(Error::invalid_argument(
				"SAC actor must return F32 [batch, 2 * action_dimensions]",
			));
		}
		let split = i64::try_from(self.config.action_dimensions)
			.map_err(|_| Error::resource_exhausted("SAC action width exceeds i64"))?;
		let end = i64::try_from(expected_width)
			.map_err(|_| Error::resource_exhausted("SAC actor width exceeds i64"))?;
		let mean = matrix::slice(&output, 1, 0, split)?;
		let log_stddev = matrix::slice(&output, 1, split, end)?;
		let value = matrix::full_on(self.runtime, [self.config.batch_size], 0.0)?;
		policy::sample_tanh_normal(
			&mean,
			&log_stddev,
			&value,
			self.config.action_minimum,
			self.config.action_maximum,
			seed,
			1.0e-6,
		)
	}

	/// Exactly synchronize both online critics into their target peers.
	pub fn sync_targets(&self) -> Result<()> {
		target::sync_exact(
			self.runtime,
			&[
				(self.critic1, self.target_critic1),
				(self.critic2, self.target_critic2),
			],
			"SAC critic",
		)
	}

	/// Return whether either coordinated loop has stopped or reached its budget.
	pub fn is_done(&self) -> bool {
		let critic = self.critic_training.snapshot().step_count();
		let actor = self.actor_training.snapshot().step_count();
		self.critic_training.stop_requested()
			|| self.actor_training.stop_requested()
			|| critic >= self.config.updates
			|| actor >= self.config.updates
	}

	/// Return the last completed update-pair metrics.
	pub const fn metrics(&self) -> SacTrainerMetrics {
		self.metrics
	}

	/// Borrow the primary critic update lifecycle.
	pub const fn training_loop(&self) -> &Training<'runtime, 'hooks> {
		&self.critic_training
	}

	/// Mutably borrow the primary critic update lifecycle.
	pub fn training_loop_mut(&mut self) -> &mut Training<'runtime, 'hooks> {
		&mut self.critic_training
	}

	/// Borrow the independently observable actor update lifecycle.
	pub const fn actor_training_loop(&self) -> &Training<'runtime, 'hooks> {
		&self.actor_training
	}

	/// Mutably borrow the actor update lifecycle.
	pub fn actor_training_loop_mut(&mut self) -> &mut Training<'runtime, 'hooks> {
		&mut self.actor_training
	}

	/// Fire both explicit terminal boundaries and return critic then actor snapshots.
	///
	/// # Errors
	///
	/// Returns an error for incomplete steps or terminal callback failure.
	pub fn finish(self) -> Result<(super::TrainingSnapshot, super::TrainingSnapshot)> {
		let critic = self.critic_training.finish()?;
		let actor = self.actor_training.finish()?;
		Ok((critic, actor))
	}
}

fn validate_config(replay: &ReplayBuffer, config: &SacTrainerConfig) -> Result<()> {
	let replay_config = replay.config();
	if config.updates == 0
		|| config.batch_size == 0
		|| config.action_dimensions == 0
		|| config.target_update_interval == 0
		|| config.observation_shape != replay_config.observation_shape
		|| replay_config.action_dtype != DType::F32
		|| replay_config.action_shape != [config.action_dimensions]
		|| !config.action_minimum.is_finite()
		|| !config.action_maximum.is_finite()
		|| config.action_minimum >= config.action_maximum
	{
		return Err(Error::invalid_argument(
			"SAC trainer configuration does not match continuous replay storage",
		));
	}
	shape_elements(&config.observation_shape, "observation")?;
	Ok(())
}

fn shape_elements(shape: &[usize], label: &'static str) -> Result<usize> {
	shape.iter().try_fold(1_usize, |count, extent| {
		count
			.checked_mul(*extent)
			.ok_or_else(|| Error::resource_exhausted(format!("SAC {label} size overflows usize")))
	})
}

fn checked_seed(base: u64, offset: u64, label: &'static str) -> Result<u64> {
	base
		.checked_add(offset)
		.ok_or_else(|| Error::resource_exhausted(format!("SAC {label} seed exhausted")))
}

fn critic_input(observation: &Matrix, action: &Matrix) -> Result<Matrix> {
	matrix::concat(&[observation.clone(), action.clone()], 1)
}

fn vector_q(input: Matrix, batch_size: usize) -> Result<Matrix> {
	if input.dtype() != DType::F32 {
		return Err(Error::invalid_argument("SAC critic output must be F32"));
	}
	if input.shape() == [batch_size] {
		return Ok(input);
	}
	if input.shape() == [batch_size, 1] {
		return matrix::reshape(&input, [batch_size]);
	}
	Err(Error::invalid_argument(
		"SAC critics must return [batch] or [batch, 1]",
	))
}