Skip to main content

oa/ml/rl/
actor_critic.rs

1//! Environment-neutral actor/critic module contracts.
2
3use std::rc::Rc;
4
5use crate::{DType, Error, Matrix, Result, Runtime, matrix as core_matrix};
6
7pub use crate::ml::types::CategoricalActorCriticConfig;
8use crate::ml::{Module, ModuleRegistry, matrix, nn::Linear};
9
10/// Policy logits and scalar critic value produced from one observation batch.
11pub struct ActorCriticOutput {
12	/// FP32 categorical policy logits shaped `[batch, actions]`.
13	pub logits: Matrix,
14	/// FP32 critic estimates shaped `[batch]`.
15	pub value: Matrix,
16}
17
18/// Environment-neutral discrete actor/critic behavior.
19///
20/// PPO depends on this contract rather than a concrete network architecture.
21pub trait ActorCritic: Module {
22	/// Evaluate policy logits and critic values without submitting or waiting.
23	///
24	/// # Errors
25	///
26	/// Returns an error when the observation contract or a child operation fails.
27	fn evaluate(&self, observation: &Matrix) -> Result<ActorCriticOutput>;
28
29	/// Add model-owned regularization to the task loss under its active tape.
30	/// The default retains the task loss; sparse models may add routing losses.
31	///
32	/// # Errors
33	/// Returns a model loss-composition or ownership failure.
34	fn auxiliary_loss(&self, task: &Matrix) -> Result<Matrix> {
35		Ok(task.clone())
36	}
37
38	/// Whether [`Self::evaluate`] computes each observation row independently
39	/// of the other rows in its batch and leaves model state unchanged.
40	///
41	/// Trainers may then coalesce evaluations recorded under unchanged
42	/// parameters into one larger batch. The default `false` keeps one
43	/// evaluation per caller-supplied batch; return `true` only when batch
44	/// composition and evaluation count cannot change any row's logits or value.
45	fn evaluates_rows_independently(&self) -> bool {
46		false
47	}
48}
49
50/// Default two-tower categorical actor/critic MLP.
51///
52/// Policy and value paths are independent
53/// `Linear -> ReLU -> Linear -> ReLU -> Linear` towers, matching OA C++.
54pub struct CategoricalActorCritic {
55	config: CategoricalActorCriticConfig,
56	policy_0: Rc<Linear>,
57	policy_1: Rc<Linear>,
58	policy: Rc<Linear>,
59	value_0: Rc<Linear>,
60	value_1: Rc<Linear>,
61	value: Rc<Linear>,
62	registry: ModuleRegistry,
63}
64
65impl CategoricalActorCritic {
66	pub fn new(config: CategoricalActorCriticConfig) -> Result<Self> {
67		Self::new_on(&Runtime::current()?, config)
68	}
69
70	/// Construct the checked default categorical actor/critic.
71	///
72	/// # Errors
73	///
74	/// Returns an error for zero observation/hidden width, fewer than two
75	/// actions, initializer overflow, allocation failure, or invalid child
76	/// registration.
77	pub fn new_on(runtime: &Runtime, config: CategoricalActorCriticConfig) -> Result<Self> {
78		if config.observation_size == 0 || config.action_count < 2 || config.hidden_size == 0 {
79			return Err(Error::invalid_argument(
80				"categorical actor-critic requires positive observation/hidden sizes and at least two actions",
81			));
82		}
83		let policy_0 = Rc::new(Linear::new_with_seed_on(
84			runtime,
85			config.observation_size,
86			config.hidden_size,
87			config.seed,
88		)?);
89		let policy_1 = Rc::new(Linear::new_with_seed_on(
90			runtime,
91			config.hidden_size,
92			config.hidden_size,
93			config.seed.wrapping_add(1),
94		)?);
95		let policy = Rc::new(Linear::new_with_seed_on(
96			runtime,
97			config.hidden_size,
98			config.action_count,
99			config.seed.wrapping_add(2),
100		)?);
101		let value_0 = Rc::new(Linear::new_with_seed_on(
102			runtime,
103			config.observation_size,
104			config.hidden_size,
105			config.seed.wrapping_add(3),
106		)?);
107		let value_1 = Rc::new(Linear::new_with_seed_on(
108			runtime,
109			config.hidden_size,
110			config.hidden_size,
111			config.seed.wrapping_add(4),
112		)?);
113		let value = Rc::new(Linear::new_with_seed_on(
114			runtime,
115			config.hidden_size,
116			1,
117			config.seed.wrapping_add(5),
118		)?);
119		let mut registry = ModuleRegistry::new();
120		registry.register_module("policy_0", policy_0.clone())?;
121		registry.register_module("policy_1", policy_1.clone())?;
122		registry.register_module("policy", policy.clone())?;
123		registry.register_module("value_0", value_0.clone())?;
124		registry.register_module("value_1", value_1.clone())?;
125		registry.register_module("value", value.clone())?;
126		Ok(Self {
127			config,
128			policy_0,
129			policy_1,
130			policy,
131			value_0,
132			value_1,
133			value,
134			registry,
135		})
136	}
137
138	/// Evaluate the independent policy and value towers.
139	///
140	/// # Errors
141	///
142	/// Returns an error unless observations are nonempty FP32 `[batch, O]`,
143	/// or when a child Matrix operation fails.
144	pub fn evaluate(&self, observation: &Matrix) -> Result<ActorCriticOutput> {
145		let [batch, features] = observation.shape() else {
146			return Err(Error::invalid_argument(
147				"categorical actor-critic observations must have rank two",
148			));
149		};
150		if *batch == 0 || *features != self.config.observation_size || observation.dtype() != DType::F32
151		{
152			return Err(Error::invalid_argument(format!(
153				"categorical actor-critic requires nonempty FP32 observations [batch, {}]",
154				self.config.observation_size
155			)));
156		}
157		let policy_hidden = matrix::relu(&self.policy_0.forward(observation)?)?;
158		let policy_hidden = matrix::relu(&self.policy_1.forward(&policy_hidden)?)?;
159		let value_hidden = matrix::relu(&self.value_0.forward(observation)?)?;
160		let value_hidden = matrix::relu(&self.value_1.forward(&value_hidden)?)?;
161		let value = self.value.forward(&value_hidden)?;
162		Ok(ActorCriticOutput {
163			logits: self.policy.forward(&policy_hidden)?,
164			value: core_matrix::reshape(&value, [*batch])?,
165		})
166	}
167
168	/// Return the immutable architecture and seed.
169	pub const fn config(&self) -> CategoricalActorCriticConfig {
170		self.config
171	}
172}
173
174impl Module for CategoricalActorCritic {
175	fn forward(&self, input: &Matrix) -> Result<Matrix> {
176		Ok(self.evaluate(input)?.logits)
177	}
178
179	fn registry(&self) -> &ModuleRegistry {
180		&self.registry
181	}
182}
183
184impl ActorCritic for CategoricalActorCritic {
185	fn evaluate(&self, observation: &Matrix) -> Result<ActorCriticOutput> {
186		CategoricalActorCritic::evaluate(self, observation)
187	}
188
189	// Both towers are stateless row-wise Linear/ReLU chains.
190	fn evaluates_rows_independently(&self) -> bool {
191		true
192	}
193}