1use crate::{Error, Result, matrix};
4
5use super::{
6 ActorCritic, EnvironmentSpaceKind,
7 environment::Environment,
8 policy,
9 rollout::{RolloutBuffer, RolloutConfig, RolloutTransition},
10};
11pub use crate::ml::types::PolicyEvaluationConfig;
12
13impl Default for PolicyEvaluationConfig {
14 fn default() -> Self {
15 Self {
16 horizon: 1000,
17 seed: 1,
18 }
19 }
20}
21
22#[derive(Clone, Copy, Debug, Default, PartialEq)]
24pub struct PolicyEvaluationMetrics {
25 pub environment_steps: u64,
27 pub transitions: u64,
29 pub completed_episodes: u64,
31 pub mean_completed_return: f32,
33 pub minimum_completed_return: f32,
35 pub maximum_completed_return: f32,
37 pub terminated_episodes: u64,
39 pub truncated_episodes: u64,
41 pub mean_completed_length: f32,
44 pub maximum_completed_length: u64,
47}
48
49pub fn evaluate_categorical(
61 environment: &mut dyn Environment,
62 model: &dyn ActorCritic,
63 config: PolicyEvaluationConfig,
64) -> Result<PolicyEvaluationMetrics> {
65 if config.horizon == 0 || environment.environments() == 0 {
66 return Err(Error::invalid_argument(
67 "categorical evaluation requires a nonempty horizon and vector environment",
68 ));
69 }
70 if environment.spec().action().kind() != EnvironmentSpaceKind::Discrete {
71 return Err(Error::invalid_argument(
72 "categorical evaluation requires a discrete action space",
73 ));
74 }
75 for parameter in model.all_parameters()? {
76 if !environment.runtime().owns_matrix(¶meter.data()) {
77 return Err(Error::invalid_argument(
78 "evaluation model must belong to the environment Runtime",
79 ));
80 }
81 }
82 let environments = environment.environments() as usize;
83 let observation_shape = environment.spec().observation().shape().to_vec();
84 let observation_elements = environment.spec().observation().elements_per_environment();
85 let mut rollout = RolloutBuffer::new(
86 environment.runtime(),
87 RolloutConfig {
88 time: config.horizon,
89 environments,
90 observation_shape,
91 },
92 )?;
93
94 const RECORDING_STEPS: usize = 32;
97 for start in (0..config.horizon).step_by(RECORDING_STEPS) {
98 let steps = (config.horizon - start).min(RECORDING_STEPS);
99 let recorded = (|| {
100 if start == 0 {
101 environment.reset(config.seed)?;
102 rollout.reset()?;
103 } else {
104 environment.begin()?;
105 }
106 record_categorical_evaluation(
107 environment,
108 model,
109 steps,
110 config.seed,
111 environments,
112 observation_elements,
113 &mut rollout,
114 )
115 })();
116 if let Err(error) = recorded {
117 let _ = environment.cancel();
118 rollout.abort_unsubmitted();
119 return Err(error);
120 }
121 let event = environment.submit()?;
122 environment.wait(&event)?;
123 }
124 let reward = rollout.batch().reward().read_f32()?;
125 let terminated = rollout.batch().terminated().read::<u8>()?;
126 let truncated = rollout.batch().truncated().read::<u8>()?;
127 summarize(
128 config.horizon,
129 environments,
130 &reward,
131 &terminated,
132 &truncated,
133 )
134}
135
136fn record_categorical_evaluation(
137 environment: &mut dyn Environment,
138 model: &dyn ActorCritic,
139 steps: usize,
140 seed: u64,
141 environments: usize,
142 observation_elements: usize,
143 rollout: &mut RolloutBuffer,
144) -> Result<()> {
145 for _ in 0..steps {
146 let observation = environment.observation().clone();
147 let flat = matrix::reshape(&observation, [environments, observation_elements])?;
148 let network = model.evaluate(&flat)?;
149 let action = matrix::sample_logits(&network.logits, 0.0, 0, 1.0, seed)?;
150 let selected = policy::evaluate_categorical(&network.logits, &action, &network.value)?;
151 let transition = environment.step(&action)?;
152 rollout.append(&RolloutTransition::new(
153 transition.observation().clone(),
154 action,
155 transition.reward().clone(),
156 network.value.clone(),
157 network.value,
158 selected.log_probability,
159 transition.terminated().clone(),
160 transition.truncated().clone(),
161 ))?;
162 environment.reset_completed()?;
163 }
164 Ok(())
165}
166
167fn summarize(
168 horizon: usize,
169 environments: usize,
170 reward: &[f32],
171 terminated: &[u8],
172 truncated: &[u8],
173) -> Result<PolicyEvaluationMetrics> {
174 let transitions = horizon
175 .checked_mul(environments)
176 .ok_or_else(|| Error::resource_exhausted("evaluation transition count overflows"))?;
177 if reward.len() != transitions
178 || terminated.len() != transitions
179 || truncated.len() != transitions
180 {
181 return Err(Error::failed_precondition(
182 "evaluation rollout readback length is inconsistent",
183 ));
184 }
185 let mut episode_return = vec![0.0_f32; environments];
186 let mut episode_length = vec![0_u64; environments];
187 let mut sum = 0.0_f64;
188 let mut minimum = f32::INFINITY;
189 let mut maximum = f32::NEG_INFINITY;
190 let mut completed = 0_u64;
191 let mut terminated_episodes = 0_u64;
192 let mut truncated_episodes = 0_u64;
193 let mut length_sum = 0_u64;
194 let mut maximum_length = 0_u64;
195 for step in 0..horizon {
196 for (lane, lane_return) in episode_return.iter_mut().enumerate() {
197 let index = step * environments + lane;
198 *lane_return += reward[index];
199 episode_length[lane] += 1;
200 if terminated[index] != 0 || truncated[index] != 0 {
201 sum += f64::from(*lane_return);
202 minimum = minimum.min(*lane_return);
203 maximum = maximum.max(*lane_return);
204 *lane_return = 0.0;
205 length_sum = length_sum
206 .checked_add(episode_length[lane])
207 .ok_or_else(|| Error::resource_exhausted("episode length sum exhausted"))?;
208 maximum_length = maximum_length.max(episode_length[lane]);
209 episode_length[lane] = 0;
210 if terminated[index] != 0 {
211 terminated_episodes += 1;
212 }
213 if truncated[index] != 0 {
214 truncated_episodes += 1;
215 }
216 completed = completed
217 .checked_add(1)
218 .ok_or_else(|| Error::resource_exhausted("completed episode count exhausted"))?;
219 }
220 }
221 }
222 Ok(PolicyEvaluationMetrics {
223 environment_steps: u64::try_from(horizon)
224 .map_err(|_| Error::resource_exhausted("evaluation horizon exceeds u64"))?,
225 transitions: u64::try_from(transitions)
226 .map_err(|_| Error::resource_exhausted("evaluation transitions exceed u64"))?,
227 completed_episodes: completed,
228 mean_completed_return: if completed == 0 {
229 0.0
230 } else {
231 (sum / completed as f64) as f32
232 },
233 minimum_completed_return: if completed == 0 { 0.0 } else { minimum },
234 maximum_completed_return: if completed == 0 { 0.0 } else { maximum },
235 terminated_episodes,
236 truncated_episodes,
237 mean_completed_length: if completed == 0 {
238 0.0
239 } else {
240 (length_sum as f64 / completed as f64) as f32
241 },
242 maximum_completed_length: if completed == 0 { 0 } else { maximum_length },
243 })
244}