Skip to main content

oa/ml/rl/
environment.rs

1use crate::{DType, Error, Matrix, OpAttribute, Result, matrix};
2
3use crate::runtime::SemanticDispatch;
4
5mod compiled;
6mod session;
7mod trading;
8pub use crate::ml::types::TradingConfig;
9pub use compiled::CompiledEnvironment;
10pub use trading::{
11	TRADING_ACCOUNT_FEATURES, TRADING_ELEMENT_BUDGET, TRADING_LEDGER_WIDTH, TradingBook,
12	TradingEnvironment, TradingExecution, TradingMarginTier, TradingSeries, TradingState,
13};
14
15pub use session::{Environment, EnvironmentExecution};
16
17/// Structural domain of one reinforcement-learning environment field.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum EnvironmentSpaceKind {
20	/// Bounded or unbounded floating-point values.
21	Box,
22	/// One integer category per environment.
23	Discrete,
24	/// Zero-or-one values.
25	Binary,
26}
27
28/// Checked shape, dtype, and range contract for one environment field.
29///
30/// `shape` excludes the leading environment-batch dimension. An empty shape
31/// therefore represents one scalar per environment.
32#[derive(Clone, Debug)]
33pub struct EnvironmentSpace {
34	name: String,
35	kind: EnvironmentSpaceKind,
36	shape: Vec<usize>,
37	dtype: DType,
38	minimum: f64,
39	maximum: f64,
40	cardinality: usize,
41}
42
43impl EnvironmentSpace {
44	/// Construct a floating-point Box space.
45	///
46	/// # Errors
47	///
48	/// Returns an error for an empty name, unsupported dtype, zero/overflowing
49	/// dimensions, NaN bounds, or reversed bounds.
50	pub fn continuous(
51		name: impl Into<String>,
52		shape: impl Into<Vec<usize>>,
53		dtype: DType,
54		minimum: f64,
55		maximum: f64,
56	) -> Result<Self> {
57		Self::checked(
58			name.into(),
59			EnvironmentSpaceKind::Box,
60			shape.into(),
61			dtype,
62			minimum,
63			maximum,
64			0,
65		)
66	}
67
68	/// Construct a scalar integer category space over `[0, cardinality)`.
69	///
70	/// # Errors
71	///
72	/// Returns an error for an empty name, zero cardinality, unsupported dtype,
73	/// or a cardinality whose inclusive upper bound cannot be represented exactly.
74	pub fn discrete(name: impl Into<String>, cardinality: usize, dtype: DType) -> Result<Self> {
75		let maximum = cardinality
76			.checked_sub(1)
77			.ok_or_else(|| Error::invalid_argument("discrete cardinality must be positive"))?;
78		if maximum as u128 > 1_u128 << 53 {
79			return Err(Error::invalid_argument(
80				"discrete cardinality exceeds exact f64 bound representation",
81			));
82		}
83		Self::checked(
84			name.into(),
85			EnvironmentSpaceKind::Discrete,
86			Vec::new(),
87			dtype,
88			0.0,
89			maximum as f64,
90			cardinality,
91		)
92	}
93
94	/// Construct a U8 binary scalar or shaped field.
95	///
96	/// # Errors
97	///
98	/// Returns an error for an empty name or zero/overflowing dimensions.
99	pub fn binary(name: impl Into<String>, shape: impl Into<Vec<usize>>) -> Result<Self> {
100		Self::checked(
101			name.into(),
102			EnvironmentSpaceKind::Binary,
103			shape.into(),
104			DType::U8,
105			0.0,
106			1.0,
107			2,
108		)
109	}
110
111	#[allow(clippy::too_many_arguments)]
112	fn checked(
113		name: String,
114		kind: EnvironmentSpaceKind,
115		shape: Vec<usize>,
116		dtype: DType,
117		minimum: f64,
118		maximum: f64,
119		cardinality: usize,
120	) -> Result<Self> {
121		if name.is_empty() {
122			return Err(Error::invalid_argument(
123				"environment field name must not be empty",
124			));
125		}
126		if shape.contains(&0) {
127			return Err(Error::invalid_argument(format!(
128				"environment field {name:?} dimensions must be positive"
129			)));
130		}
131		shape.iter().try_fold(1_usize, |elements, dimension| {
132			elements.checked_mul(*dimension).ok_or_else(|| {
133				Error::invalid_argument(format!(
134					"environment field {name:?} shape product overflows usize"
135				))
136			})
137		})?;
138		if minimum.is_nan() || maximum.is_nan() || minimum > maximum {
139			return Err(Error::invalid_argument(format!(
140				"environment field {name:?} bounds must be ordered and not NaN"
141			)));
142		}
143		let valid_kind = match kind {
144			EnvironmentSpaceKind::Box => dtype == DType::F32 && cardinality == 0,
145			EnvironmentSpaceKind::Discrete => {
146				matches!(dtype, DType::U8 | DType::I32 | DType::U32)
147					&& shape.is_empty()
148					&& cardinality > 0
149					&& minimum == 0.0
150					&& maximum == (cardinality - 1) as f64
151			}
152			EnvironmentSpaceKind::Binary => {
153				dtype == DType::U8 && cardinality == 2 && minimum == 0.0 && maximum == 1.0
154			}
155		};
156		if !valid_kind {
157			return Err(Error::invalid_argument(format!(
158				"environment field {name:?} kind and dtype contract is invalid"
159			)));
160		}
161		Ok(Self {
162			name,
163			kind,
164			shape,
165			dtype,
166			minimum,
167			maximum,
168			cardinality,
169		})
170	}
171
172	/// Return the field name.
173	pub fn name(&self) -> &str {
174		&self.name
175	}
176
177	/// Return the structural space kind.
178	pub const fn kind(&self) -> EnvironmentSpaceKind {
179		self.kind
180	}
181
182	/// Return the per-environment shape without the batch dimension.
183	pub fn shape(&self) -> &[usize] {
184		&self.shape
185	}
186
187	/// Return the required Matrix dtype.
188	pub const fn dtype(&self) -> DType {
189		self.dtype
190	}
191
192	/// Return the inclusive lower bound.
193	pub const fn minimum(&self) -> f64 {
194		self.minimum
195	}
196
197	/// Return the inclusive upper bound.
198	pub const fn maximum(&self) -> f64 {
199		self.maximum
200	}
201
202	/// Return the category count, or zero for a Box space.
203	pub const fn cardinality(&self) -> usize {
204		self.cardinality
205	}
206
207	/// Return the number of dense values stored per environment.
208	pub fn elements_per_environment(&self) -> usize {
209		self.shape.iter().copied().product()
210	}
211
212	/// Return the exact Matrix shape for a positive environment count.
213	///
214	/// # Errors
215	///
216	/// Returns an error when `environments` is zero.
217	pub fn batched_shape(&self, environments: u32) -> Result<Vec<usize>> {
218		if environments == 0 {
219			return Err(Error::invalid_argument(format!(
220				"environment field {:?} requires a positive environment count",
221				self.name
222			)));
223		}
224		let mut shape = Vec::with_capacity(self.shape.len() + 1);
225		shape.push(environments as usize);
226		shape.extend_from_slice(&self.shape);
227		Ok(shape)
228	}
229
230	/// Validate one device Matrix against this batched field contract.
231	///
232	/// # Errors
233	///
234	/// Returns an error for zero environments or a shape/dtype mismatch.
235	pub fn validate_matrix(&self, matrix: &Matrix, environments: u32) -> Result<()> {
236		let expected = self.batched_shape(environments)?;
237		if matrix.dtype() != self.dtype || matrix.shape() != expected {
238			return Err(Error::invalid_argument(format!(
239				"environment field {:?} requires {:?} {:?}; found {:?} {:?}",
240				self.name,
241				self.dtype,
242				expected,
243				matrix.dtype(),
244				matrix.shape()
245			)));
246		}
247		Ok(())
248	}
249}
250
251/// Complete single-agent environment schema shared by native and adapter paths.
252#[derive(Clone, Debug)]
253pub struct EnvironmentSpec {
254	observation: EnvironmentSpace,
255	action: EnvironmentSpace,
256	reward: EnvironmentSpace,
257	terminated: EnvironmentSpace,
258	truncated: EnvironmentSpace,
259}
260
261impl EnvironmentSpec {
262	/// Construct the five durable Gymnasium-compatible field contracts.
263	///
264	/// # Errors
265	///
266	/// Returns an error unless reward is a scalar Box and both episode-boundary
267	/// fields are scalar Binary spaces.
268	pub fn new(
269		observation: EnvironmentSpace,
270		action: EnvironmentSpace,
271		reward: EnvironmentSpace,
272		terminated: EnvironmentSpace,
273		truncated: EnvironmentSpace,
274	) -> Result<Self> {
275		if reward.kind != EnvironmentSpaceKind::Box || !reward.shape.is_empty() {
276			return Err(Error::invalid_argument(
277				"environment reward must be one floating scalar per environment",
278			));
279		}
280		if terminated.kind != EnvironmentSpaceKind::Binary
281			|| !terminated.shape.is_empty()
282			|| truncated.kind != EnvironmentSpaceKind::Binary
283			|| !truncated.shape.is_empty()
284		{
285			return Err(Error::invalid_argument(
286				"environment termination and truncation must be binary scalars",
287			));
288		}
289		Ok(Self {
290			observation,
291			action,
292			reward,
293			terminated,
294			truncated,
295		})
296	}
297
298	/// Return the observation field contract.
299	pub const fn observation(&self) -> &EnvironmentSpace {
300		&self.observation
301	}
302
303	/// Return the action field contract.
304	pub const fn action(&self) -> &EnvironmentSpace {
305		&self.action
306	}
307
308	/// Return the scalar reward field contract.
309	pub const fn reward(&self) -> &EnvironmentSpace {
310		&self.reward
311	}
312
313	/// Return the task-terminal field contract.
314	pub const fn terminated(&self) -> &EnvironmentSpace {
315		&self.terminated
316	}
317
318	/// Return the external-truncation field contract.
319	pub const fn truncated(&self) -> &EnvironmentSpace {
320		&self.truncated
321	}
322
323	/// Validate one batched reset observation without reading it back.
324	///
325	/// # Errors
326	///
327	/// Returns an error for a zero environment count or shape/dtype mismatch.
328	pub fn validate_reset(&self, observation: &Matrix, environments: u32) -> Result<()> {
329		self.observation.validate_matrix(observation, environments)
330	}
331
332	/// Validate one batched action without reading it back.
333	///
334	/// # Errors
335	///
336	/// Returns an error for a zero environment count or shape/dtype mismatch.
337	pub fn validate_action(&self, action: &Matrix, environments: u32) -> Result<()> {
338		self.action.validate_matrix(action, environments)
339	}
340
341	/// Validate action and all five transition values without readback.
342	///
343	/// # Errors
344	///
345	/// Returns an error for a zero environment count or any shape/dtype mismatch.
346	pub fn validate_transition(
347		&self,
348		action: &Matrix,
349		transition: &EnvironmentTransition,
350		environments: u32,
351	) -> Result<()> {
352		self
353			.observation
354			.validate_matrix(&transition.observation, environments)?;
355		self.action.validate_matrix(action, environments)?;
356		self
357			.observation
358			.validate_matrix(&transition.next_observation, environments)?;
359		self
360			.reward
361			.validate_matrix(&transition.reward, environments)?;
362		self
363			.terminated
364			.validate_matrix(&transition.terminated, environments)?;
365		self
366			.truncated
367			.validate_matrix(&transition.truncated, environments)
368	}
369}
370
371/// One batched environment step result preserving termination and truncation.
372pub struct EnvironmentTransition {
373	observation: Matrix,
374	next_observation: Matrix,
375	reward: Matrix,
376	terminated: Matrix,
377	truncated: Matrix,
378}
379
380impl EnvironmentTransition {
381	/// Construct an owned transition value; [`EnvironmentSpec::validate_transition`]
382	/// proves its complete field contract together with the action.
383	pub fn new(
384		observation: Matrix,
385		next_observation: Matrix,
386		reward: Matrix,
387		terminated: Matrix,
388		truncated: Matrix,
389	) -> Self {
390		Self {
391			observation,
392			next_observation,
393			reward,
394			terminated,
395			truncated,
396		}
397	}
398
399	/// Return the observation before the action.
400	pub const fn observation(&self) -> &Matrix {
401		&self.observation
402	}
403
404	/// Return the observation after the action.
405	pub const fn next_observation(&self) -> &Matrix {
406		&self.next_observation
407	}
408
409	/// Return one reward per environment.
410	pub const fn reward(&self) -> &Matrix {
411		&self.reward
412	}
413
414	/// Return task-terminal flags, distinct from truncation.
415	pub const fn terminated(&self) -> &Matrix {
416		&self.terminated
417	}
418
419	/// Return external/time-limit flags, distinct from termination.
420	pub const fn truncated(&self) -> &Matrix {
421		&self.truncated
422	}
423}
424
425/// Normalize and symmetrically clip FP32 observations.
426///
427/// Computes `clamp((observation - mean) / (stddev + epsilon), -clip, clip)`
428/// through differentiable Core Matrix operations under one Environment
429/// semantic identity.
430///
431/// # Errors
432///
433/// Returns an error for empty/non-FP32 inputs, invalid epsilon/clip, incompatible
434/// broadcasting or ownership, or composite lowering failure.
435pub fn normalize_observation(
436	observation: &Matrix,
437	mean: &Matrix,
438	stddev: &Matrix,
439	epsilon: f32,
440	clip: f32,
441) -> Result<Matrix> {
442	const CONTRACT: crate::OperationContract = crate::core::operation::ml::NORMALIZE_OBSERVATION;
443	if [observation, mean, stddev]
444		.into_iter()
445		.any(|input| input.dtype() != DType::F32 || input.num_elements() == 0)
446		|| !epsilon.is_finite()
447		|| epsilon <= 0.0
448		|| !clip.is_finite()
449		|| clip <= 0.0
450	{
451		return Err(Error::invalid_argument(format!(
452			"{} requires nonempty FP32 inputs and positive finite epsilon/clip",
453			CONTRACT.name()
454		)));
455	}
456	let lowering = observation.runtime().begin_semantic_lowering()?;
457	let centered = matrix::sub(observation, mean)?;
458	let denominator = matrix::add_scalar(stddev, epsilon)?;
459	let normalized = matrix::div(&centered, &denominator)?;
460	let result = clamp(&normalized, -clip, clip)?;
461	let attributes = [
462		OpAttribute::Float {
463			name: "epsilon".into(),
464			value: f64::from(epsilon),
465		},
466		OpAttribute::Float {
467			name: "clip".into(),
468			value: f64::from(clip),
469		},
470	];
471	lowering.commit(SemanticDispatch {
472		contract: CONTRACT,
473		inputs: &[observation, mean, stddev],
474		outputs: &[&result],
475		attributes: &attributes,
476	})?;
477	Ok(result)
478}
479
480/// Affinely map FP32 actions between two finite ranges.
481///
482/// # Errors
483///
484/// Returns an error for an empty/non-FP32 input, unordered/non-finite bounds,
485/// or Matrix/composite lowering failure.
486pub fn scale_action(
487	action: &Matrix,
488	source_minimum: f32,
489	source_maximum: f32,
490	target_minimum: f32,
491	target_maximum: f32,
492	clamp_source: bool,
493) -> Result<Matrix> {
494	const CONTRACT: crate::OperationContract = crate::core::operation::ml::SCALE_ACTION;
495	if action.dtype() != DType::F32
496		|| action.num_elements() == 0
497		|| !source_minimum.is_finite()
498		|| !source_maximum.is_finite()
499		|| !target_minimum.is_finite()
500		|| !target_maximum.is_finite()
501		|| source_minimum >= source_maximum
502		|| target_minimum >= target_maximum
503	{
504		return Err(Error::invalid_argument(format!(
505			"{} requires nonempty FP32 actions and ordered finite bounds",
506			CONTRACT.name()
507		)));
508	}
509	let lowering = action.runtime().begin_semantic_lowering()?;
510	let source = if clamp_source {
511		clamp(action, source_minimum, source_maximum)?
512	} else {
513		action.clone()
514	};
515	let scale = (target_maximum - target_minimum) / (source_maximum - source_minimum);
516	let result = matrix::add_scalar(
517		&matrix::scale(&matrix::sub_scalar(&source, source_minimum)?, scale)?,
518		target_minimum,
519	)?;
520	let attributes = [
521		OpAttribute::Float {
522			name: "sourceMinimum".into(),
523			value: f64::from(source_minimum),
524		},
525		OpAttribute::Float {
526			name: "sourceMaximum".into(),
527			value: f64::from(source_maximum),
528		},
529		OpAttribute::Float {
530			name: "targetMinimum".into(),
531			value: f64::from(target_minimum),
532		},
533		OpAttribute::Float {
534			name: "targetMaximum".into(),
535			value: f64::from(target_maximum),
536		},
537		OpAttribute::Boolean {
538			name: "clamp".into(),
539			value: clamp_source,
540		},
541	];
542	lowering.commit(SemanticDispatch {
543		contract: CONTRACT,
544		inputs: &[action],
545		outputs: &[&result],
546		attributes: &attributes,
547	})?;
548	Ok(result)
549}
550
551/// Clip FP32 rewards to an inclusive finite range.
552///
553/// # Errors
554///
555/// Returns an error for an empty/non-FP32 input, unordered/non-finite bounds,
556/// or Matrix/composite lowering failure.
557pub fn clip_reward(reward: &Matrix, minimum: f32, maximum: f32) -> Result<Matrix> {
558	const CONTRACT: crate::OperationContract = crate::core::operation::ml::CLIP_REWARD;
559	if reward.dtype() != DType::F32
560		|| reward.num_elements() == 0
561		|| !minimum.is_finite()
562		|| !maximum.is_finite()
563		|| minimum > maximum
564	{
565		return Err(Error::invalid_argument(format!(
566			"{} requires nonempty FP32 rewards and ordered finite bounds",
567			CONTRACT.name()
568		)));
569	}
570	let lowering = reward.runtime().begin_semantic_lowering()?;
571	let result = clamp(reward, minimum, maximum)?;
572	let attributes = [
573		OpAttribute::Float {
574			name: "minimum".into(),
575			value: f64::from(minimum),
576		},
577		OpAttribute::Float {
578			name: "maximum".into(),
579			value: f64::from(maximum),
580		},
581	];
582	lowering.commit(SemanticDispatch {
583		contract: CONTRACT,
584		inputs: &[reward],
585		outputs: &[&result],
586		attributes: &attributes,
587	})?;
588	Ok(result)
589}
590
591fn clamp(input: &Matrix, minimum: f32, maximum: f32) -> Result<Matrix> {
592	matrix::clamp_max(&matrix::clamp_min(input, minimum)?, maximum)
593}