Skip to main content

oa/ml/rl/
advantage.rs

1pub use crate::ml::types::{GaeConfig, GaeResult};
2use crate::runtime::ComputeDispatch;
3use crate::runtime::{BufferBinding, KernelId, PushConstant, SemanticDispatch};
4use crate::{DType, Error, Matrix, OpAttribute, Result, matrix};
5
6impl Default for GaeConfig {
7	fn default() -> Self {
8		Self {
9			gamma: 0.99,
10			lambda: 0.95,
11		}
12	}
13}
14
15/// Standardize a nonempty FP32 advantage tensor over all elements.
16///
17/// The result is `(advantage - mean) / sqrt(variance + epsilon)`. The operation
18/// remains device-resident and differentiable, and records one semantic
19/// identity over its composite Matrix lowering.
20///
21/// # Errors
22///
23/// Returns an error when `advantage` is empty or not FP32, `epsilon` is not
24/// positive and finite, a size exceeds the admitted shader ABI, allocation
25/// fails, or composite lowering fails.
26pub fn normalize(advantage: &Matrix, epsilon: f32) -> Result<Matrix> {
27	const CONTRACT: crate::OperationContract = crate::core::operation::ml::NORMALIZE;
28	if advantage.dtype() != DType::F32 || advantage.num_elements() == 0 {
29		return Err(Error::invalid_argument(format!(
30			"{} requires a nonempty F32 matrix",
31			CONTRACT.name()
32		)));
33	}
34	if !epsilon.is_finite() || epsilon <= 0.0 {
35		return Err(Error::invalid_argument(format!(
36			"{} requires a positive finite epsilon",
37			CONTRACT.name()
38		)));
39	}
40	let lowering = advantage.runtime().begin_semantic_lowering()?;
41	let inverse_count = 1.0 / advantage.num_elements() as f32;
42	let mean = matrix::scale(&matrix::sum(advantage, -1)?, inverse_count)?;
43	let centered = matrix::sub(advantage, &mean)?;
44	let variance = matrix::scale(
45		&matrix::sum(&matrix::mul(&centered, &centered)?, -1)?,
46		inverse_count,
47	)?;
48	let denominator = matrix::sqrt(&matrix::add_scalar(&variance, epsilon)?)?;
49	let result = matrix::div(&centered, &denominator)?;
50	let attributes = [OpAttribute::Float {
51		name: "epsilon".into(),
52		value: f64::from(epsilon),
53	}];
54	lowering.commit(SemanticDispatch {
55		contract: CONTRACT,
56		inputs: &[advantage],
57		outputs: &[&result],
58		attributes: &attributes,
59	})?;
60	Ok(result)
61}
62
63/// Compute generalized advantage estimates over a fixed rollout.
64///
65/// Termination disables value bootstrap. Termination and truncation both stop
66/// the reverse trace, while truncation deliberately retains one-step bootstrap.
67///
68/// # Errors
69///
70/// Returns an error unless all inputs share one runtime and one nonempty
71/// `[time, environments]` shape, values are F32, boundary masks are U8, both
72/// discounts are finite in `[0, 1]`, and GPU recording succeeds.
73pub fn gae(
74	reward: &Matrix,
75	value: &Matrix,
76	next_value: &Matrix,
77	terminated: &Matrix,
78	truncated: &Matrix,
79	config: GaeConfig,
80) -> Result<GaeResult> {
81	validate_inputs(reward, value, next_value, terminated, truncated, config)?;
82	let mut advantage = Matrix::allocate(
83		reward.runtime(),
84		reward.shape().to_vec(),
85		reward.num_elements(),
86		DType::F32,
87	)?;
88	let mut returns = Matrix::allocate(
89		reward.runtime(),
90		reward.shape().to_vec(),
91		reward.num_elements(),
92		DType::F32,
93	)?;
94	gae_into(
95		reward,
96		value,
97		next_value,
98		terminated,
99		truncated,
100		&mut advantage,
101		&mut returns,
102		config,
103	)?;
104	Ok(GaeResult { advantage, returns })
105}
106
107/// Record generalized advantage estimation into caller-owned output storage.
108///
109/// This is the allocation-free form used by fixed-capacity rollout storage. It
110/// has the same semantic identity and numerical contract as [`gae`].
111///
112/// # Errors
113///
114/// Returns the errors from [`gae`], and rejects output matrices that do not
115/// match the rollout's runtime, F32 dtype, and shape or alias any input/each other.
116#[allow(
117	clippy::too_many_arguments,
118	reason = "the allocation-free API keeps every rollout field and both outputs explicit"
119)]
120pub fn gae_into(
121	reward: &Matrix,
122	value: &Matrix,
123	next_value: &Matrix,
124	terminated: &Matrix,
125	truncated: &Matrix,
126	advantage: &mut Matrix,
127	returns: &mut Matrix,
128	config: GaeConfig,
129) -> Result<()> {
130	const OPERATION: &str = "oa::FnAdvantage::gae";
131	validate_inputs(reward, value, next_value, terminated, truncated, config)?;
132	for output in [&*advantage, &*returns] {
133		if !reward.runtime().same_as(output.runtime())
134			|| output.dtype() != DType::F32
135			|| output.shape() != reward.shape()
136		{
137			return Err(Error::invalid_argument(format!(
138				"{OPERATION} outputs must be same-runtime F32 matrices matching the rollout shape"
139			)));
140		}
141	}
142	let inputs = [reward, value, next_value, terminated, truncated];
143	if advantage.storage().same_as(returns.storage())
144		|| inputs.iter().any(|input| {
145			input.storage().same_as(advantage.storage()) || input.storage().same_as(returns.storage())
146		}) {
147		return Err(Error::invalid_argument(format!(
148			"{OPERATION} outputs must not alias inputs or each other"
149		)));
150	}
151	let time = u32::try_from(reward.shape()[0])
152		.map_err(|_| Error::invalid_argument(format!("{OPERATION} time exceeds u32")))?;
153	let environments = u32::try_from(reward.shape()[1])
154		.map_err(|_| Error::invalid_argument(format!("{OPERATION} environment count exceeds u32")))?;
155	let buffers = [
156		BufferBinding::read(reward.storage()),
157		BufferBinding::read(value.storage()),
158		BufferBinding::read(next_value.storage()),
159		BufferBinding::read(terminated.storage()),
160		BufferBinding::read(truncated.storage()),
161		BufferBinding::write(advantage.storage()),
162		BufferBinding::write(returns.storage()),
163	];
164	let push_constants = [
165		PushConstant::U32(time),
166		PushConstant::U32(environments),
167		PushConstant::F32(config.gamma),
168		PushConstant::F32(config.lambda),
169	];
170	let attributes = [
171		OpAttribute::Float {
172			name: "gamma".to_owned(),
173			value: f64::from(config.gamma),
174		},
175		OpAttribute::Float {
176			name: "lambda".to_owned(),
177			value: f64::from(config.lambda),
178		},
179	];
180	let kernel = KernelId::MlGaeF32;
181	{
182		let inputs: &[&Matrix] = &inputs;
183		let outputs: &[&Matrix] = &[advantage, returns];
184		let attributes: &[OpAttribute] = &attributes;
185		let dispatch = ComputeDispatch {
186			kernel,
187			buffers: &buffers,
188			push_constants: &push_constants,
189			workgroups: kernel.linear_workgroups(environments),
190			indirect: None,
191		};
192		let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
193			Error::internal(format!(
194				"lowering-only kernel {} cannot own one semantic ML operation",
195				dispatch.kernel.report_name()
196			))
197		})?;
198		let runtime = inputs
199			.first()
200			.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
201			.runtime();
202		runtime.record_semantic(
203			dispatch,
204			SemanticDispatch {
205				contract,
206				inputs,
207				outputs,
208				attributes,
209			},
210		)
211	}
212}
213
214fn validate_inputs(
215	reward: &Matrix,
216	value: &Matrix,
217	next_value: &Matrix,
218	terminated: &Matrix,
219	truncated: &Matrix,
220	config: GaeConfig,
221) -> Result<()> {
222	const OPERATION: &str = "oa::FnAdvantage::gae";
223	for input in [reward, value, next_value, terminated, truncated] {
224		if !reward.runtime().same_as(input.runtime()) {
225			return Err(Error::invalid_argument(format!(
226				"{OPERATION} inputs must belong to the same runtime"
227			)));
228		}
229		if input.shape() != reward.shape() {
230			return Err(Error::invalid_argument(format!(
231				"{OPERATION} inputs must have one matching shape"
232			)));
233		}
234	}
235	if reward.shape().len() != 2 || reward.shape().contains(&0) {
236		return Err(Error::invalid_argument(format!(
237			"{OPERATION} requires a nonempty [time, environments] rollout"
238		)));
239	}
240	if reward.dtype() != DType::F32
241		|| value.dtype() != DType::F32
242		|| next_value.dtype() != DType::F32
243		|| terminated.dtype() != DType::U8
244		|| truncated.dtype() != DType::U8
245	{
246		return Err(Error::invalid_argument(format!(
247			"{OPERATION} requires F32 reward/value inputs and U8 boundary masks"
248		)));
249	}
250	if !config.gamma.is_finite()
251		|| !(0.0..=1.0).contains(&config.gamma)
252		|| !config.lambda.is_finite()
253		|| !(0.0..=1.0).contains(&config.lambda)
254	{
255		return Err(Error::invalid_argument(format!(
256			"{OPERATION} requires finite gamma and lambda in [0, 1]"
257		)));
258	}
259	Ok(())
260}