Skip to main content

oa/ml/rl/
collector.rs

1//! Same-device rollout collection sessions.
2
3use crate::{Error, Event, Result, matrix};
4
5use super::{
6	ActorCritic, EnvironmentSpaceKind,
7	environment::Environment,
8	policy,
9	rollout::{RolloutBuffer, RolloutTransition},
10};
11pub use crate::ml::types::RolloutCollectorConfig;
12
13/// Accepted rollout and transition counts.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
15pub struct RolloutCollectorMetrics {
16	/// Successfully submitted complete rollouts.
17	pub collections: u64,
18	/// Vector-environment steps recorded across accepted rollouts.
19	pub environment_steps: u64,
20	/// Individual lane transitions across accepted rollouts.
21	pub transitions: u64,
22}
23
24/// Environment-neutral categorical collector over borrowed owners.
25///
26/// Collection records one complete transaction and returns its exact Event
27/// without waiting. It owns no environment, model, rollout storage, Runtime, or
28/// queue.
29#[must_use]
30pub struct RolloutCollector<'environment, 'model> {
31	environment: &'environment mut dyn Environment,
32	model: &'model dyn ActorCritic,
33	config: RolloutCollectorConfig,
34	metrics: RolloutCollectorMetrics,
35	action_index: u64,
36}
37
38impl<'environment, 'model> RolloutCollector<'environment, 'model> {
39	/// Construct a checked same-device categorical collector.
40	///
41	/// # Errors
42	///
43	/// Returns an error for zero horizon/lanes, invalid environment metadata, a
44	/// non-discrete action space, or model parameters owned by another Runtime.
45	pub fn new(
46		environment: &'environment mut dyn Environment,
47		model: &'model dyn ActorCritic,
48		config: RolloutCollectorConfig,
49	) -> Result<Self> {
50		if config.horizon == 0 || environment.environments() == 0 {
51			return Err(Error::invalid_argument(
52				"rollout collector requires a nonempty horizon and vector environment",
53			));
54		}
55		if environment.spec().action().kind() != EnvironmentSpaceKind::Discrete {
56			return Err(Error::invalid_argument(
57				"rollout collector requires a discrete action space",
58			));
59		}
60		for parameter in model.all_parameters()? {
61			if !environment.runtime().owns_matrix(&parameter.data()) {
62				return Err(Error::invalid_argument(
63					"rollout collector model must belong to the environment Runtime",
64				));
65			}
66		}
67		Ok(Self {
68			environment,
69			model,
70			config,
71			metrics: RolloutCollectorMetrics::default(),
72			action_index: 0,
73		})
74	}
75
76	/// Record and submit one complete categorical rollout without waiting.
77	///
78	/// # Errors
79	///
80	/// Returns an error for rollout mismatch, seed/counter overflow, environment,
81	/// model, policy, GAE, capture, or queue submission failure. Recording errors
82	/// cancel the complete transaction and rewind rollout/action host state.
83	pub fn collect(&mut self, rollout: &mut RolloutBuffer) -> Result<Event> {
84		let environments = self.environment.environments();
85		let rollout_config = rollout.config();
86		if rollout_config.time != self.config.horizon
87			|| rollout_config.environments != environments as usize
88			|| rollout_config.observation_shape != self.environment.spec().observation().shape()
89		{
90			return Err(Error::invalid_argument(
91				"rollout collector storage does not match environment/horizon schema",
92			));
93		}
94		let observation_elements = self
95			.environment
96			.spec()
97			.observation()
98			.elements_per_environment();
99		let starting_action_index = self.action_index;
100		let recorded = self.record(rollout, environments as usize, observation_elements);
101		if let Err(error) = recorded {
102			let _ = self.environment.cancel();
103			rollout.abort_unsubmitted();
104			self.action_index = starting_action_index;
105			return Err(error);
106		}
107		let event = self.environment.submit()?;
108		self.metrics.collections = self
109			.metrics
110			.collections
111			.checked_add(1)
112			.ok_or_else(|| Error::resource_exhausted("rollout collection count exhausted"))?;
113		self.metrics.environment_steps = self
114			.metrics
115			.environment_steps
116			.checked_add(self.config.horizon as u64)
117			.ok_or_else(|| Error::resource_exhausted("environment step count exhausted"))?;
118		let transitions = (self.config.horizon as u64)
119			.checked_mul(u64::from(environments))
120			.ok_or_else(|| Error::resource_exhausted("rollout transition count overflows"))?;
121		self.metrics.transitions = self
122			.metrics
123			.transitions
124			.checked_add(transitions)
125			.ok_or_else(|| Error::resource_exhausted("rollout transition count exhausted"))?;
126		Ok(event)
127	}
128
129	fn record(
130		&mut self,
131		rollout: &mut RolloutBuffer,
132		environments: usize,
133		observation_elements: usize,
134	) -> Result<()> {
135		if self.metrics.collections == 0 {
136			self.environment.reset(self.config.seed)?;
137		} else {
138			self.environment.begin()?;
139		}
140		rollout.reset()?;
141		for _ in 0..self.config.horizon {
142			let observation = self.environment.observation().clone();
143			let flat = matrix::reshape(&observation, [environments, observation_elements])?;
144			let network = self.model.evaluate(&flat)?;
145			self.action_index = self
146				.action_index
147				.checked_add(1)
148				.ok_or_else(|| Error::resource_exhausted("collector action index exhausted"))?;
149			let seed = self
150				.config
151				.seed
152				.checked_add(self.action_index)
153				.ok_or_else(|| Error::resource_exhausted("collector action seed exhausted"))?;
154			let selected = policy::sample_categorical(&network.logits, &network.value, seed)?;
155			let transition = self.environment.step(&selected.action)?;
156			let next_flat = matrix::reshape(
157				transition.next_observation(),
158				[environments, observation_elements],
159			)?;
160			let next = self.model.evaluate(&next_flat)?;
161			rollout.append(&RolloutTransition::new(
162				transition.observation().clone(),
163				selected.action,
164				transition.reward().clone(),
165				selected.value,
166				next.value,
167				selected.log_probability,
168				transition.terminated().clone(),
169				transition.truncated().clone(),
170			))?;
171			self.environment.reset_completed()?;
172		}
173		rollout.finalize(self.config.gae)
174	}
175
176	/// Return accepted collection counters.
177	pub const fn metrics(&self) -> RolloutCollectorMetrics {
178		self.metrics
179	}
180}