Balance CartPole-v1 with PPO in Rust
Collect GPU-resident rollouts, train a CartPole-v1 PPO policy, and inspect it in Vulkan.
Start the walkthrough · Jump to complete source
Train a discrete actor-critic policy to balance an inverted pendulum using
Proximal Policy Optimization (PPO) across 64 parallel Vulkan environments.
This OA walkthrough implements the classic control problem formalized in
Gymnasium's CartPole-v1 environment,
ported to vectorized Slang compute shaders in oasdk::ml::rl::CartPole.
Rollout collection, advantage estimation, PPO updates, checkpoint verification,
and 2D Vulkan scene rendering all run on the same oa::Runtime. The figures
and measurements below were captured with OA 0.19.0 on Intel Iris Xe (ADL GT2)
with Mesa 26.3.1.
Run in Rust
From the OASDK root, with oa-dev and oads-dev as sibling checkouts:
# Train PPO with the Vulkan viewer (default):cargo run --release --example tu_rl_cart_pole_ppo# Run headless GPU PPO training (40 rollouts) and generate four figures:cargo run --release --example tu_rl_cart_pole_ppo -- --train# Watch PPO training, then play back the resulting neural policy:cargo run --release --example tu_rl_cart_pole_ppo -- --train --viewer --skip-plots
With -- --train, the example writes four dark-theme Vulkan/plot JPEGs to
var/tutorials/rl_cart_pole_ppo/rust/. Combine with -- --viewer to open the
interactive window during PPO training, -- --rollouts N
for a shorter or longer training budget, -- --output DIR to choose a figure
directory, or -- --skip-plots to skip headless rendering.
Use -- --device-index N to select an enumerated Vulkan device explicitly.
1. The CartPole-v1 environment on the GPU
A frictionless cart moves along a one-dimensional track while supporting a
hinged pole. At every 50 Hz Euler step (dt = 0.02 s), the policy observes a
4-element floating-point state vector and chooses one of two discrete forces
(-10 N left or +10 N right):
| Index | Observation | Termination bound |
|---|---|---|
| 0 | Cart position $x$ (m) | $ |
| 1 | Cart velocity $\dot{x}$ (m/s) | Unbounded |
| 2 | Pole angle $\theta$ (rad) | $ |
| 3 | Pole angular velocity $\dot{\theta}$ (rad/s) | Unbounded |
Every surviving step awards +1.0 reward, and an episode truncates after 500
steps (maximum return 500.0). In OA, CartPole stores all environment lanes
in device-resident matrices and advances every lane in parallel with Slang
compute kernels (ml_cart_pole_reset_f32, ml_cart_pole_step_f32, and
ml_cart_pole_reset_cursor_f32).
Before any training, a randomly initialized policy applies biased pushes and quickly tips past the $\pm 12^\circ$ limit. In the recorded baseline episode below (rendered headlessly with OA's Vulkan 2D pipeline), the pole falls at step 29:
2. Zero-host-readback rollouts and GAE
Before launching the full PPO trainer, the tutorial runs a 32-environment
rollout primer that exposes the exact mechanics underneath PpoTrainer.
During collection, observations, sampled actions, log-probabilities, rewards,
and termination flags stay on the GPU without a single host readback. Calling
environment.reset_completed() resets only finished lanes in place, and
rollout.finalize(GaeConfig::default()) computes Generalized Advantage
Estimation (GAE) and bootstrapped returns on the device before one final
submit() / wait() synchronization barrier:
1rollout.reset()?;2for step in 0..ROLLOUT_PRIMER_HORIZON {3 let logits = oa::matrix::matmul(environment.observation(), &policy_weight)?;4 let selected =5 policy::sample_categorical(&logits, &value, ROLLOUT_PRIMER_SEED + step as u64 + 1)?;6 let transition = environment.step(&selected.action)?;7 rollout.append(&RolloutTransition::new(8 transition.observation().clone(),9 selected.action,10 transition.reward().clone(),11 selected.value,12 value.clone(),13 selected.log_probability,14 transition.terminated().clone(),15 transition.truncated().clone(),16 ))?;17 environment.reset_completed()?;18}19rollout.finalize(advantage::GaeConfig::default())?;20let completion = environment.submit()?;21environment.wait(&completion)?;22
Across 32 lanes and 64 steps (2,048 transitions), the linear heuristic policy
collects 2,048 total reward with 1 completed episode and verifies that
every valid mask is 1 and every computed GAE advantage is finite.
3. Separate actor-critic network
CategoricalActorCritic constructs independent actor and critic multi-layer
perceptrons so value-function gradients do not distort policy representations:
| Tower | Layers | Output |
|---|---|---|
| Actor (policy) | 4 -> 64 -> 64 -> 2 | Unnormalized action logits (Left, Right) |
| Critic (value) | 4 -> 64 -> 64 -> 1 | Scalar state-value estimate $V(s)$ |
1let model = CategoricalActorCritic::new(CategoricalActorCriticConfig {2 observation_size: 4,3 action_count: 2,4 hidden_size: 64,5 seed: TRAINING_SEED,6})?;7let mut optimizer = AdamW::new_with_hyperparameters(8 model.all_parameters()?,9 2.5e-4,10 0.9,11 0.999,12 1.0e-8,13 0.0,14)?;15
AdamW uses zero weight decay with learning rate 2.5e-4, matching standard
on-policy PPO practice.
4. Train 64 parallel environments with PPO
PpoTrainer alternates between device-side rollout collection (64 lanes ×
128 steps = 8,192 transitions per rollout) and 4 clipped-surrogate PPO
update epochs over the collected batch. Over 40 rollouts, the policy trains
on 327,680 environment transitions and 160 optimizer updates while
evaluating periodically on a held-out 64-lane environment with a 500-step
horizon. The headless loop submits a full rollout at once. The live path
submits eight collection steps per viewer update and uses the same 128-step
rollout for GAE and PPO. This excerpt shows the headless loop.
1while !trainer.is_done() {2 if trainer.needs_collection() {3 environment.begin()?;4 trainer.begin_collection()?;5 for _ in 0..HORIZON {6 let selected = trainer.act(environment.observation())?;7 let transition = environment.step(&selected.action)?;8 trainer.observe(9 transition.observation(),10 transition.next_observation(),11 transition.reward(),12 transition.terminated(),13 transition.truncated(),14 &selected,15 )?;16 environment.reset_completed()?;17 }18 trainer.end_collection()?;19 let event = environment.submit()?;20 environment.wait(&event)?;21 }22 trainer.update()?;23}24
The checked-in figures and the following output come from a 40-rollout headless run on llvmpipe software Vulkan.
1OA reinforcement learning — CartPole-v1 PPO2 primer: 32 envs x 64 steps (2048 transitions) · 2048 reward · 1 episodes · 0 host reads during collection3 separate actor/critic: each 4 -> 64 -> 64 (ReLU/Tanh)4 heads: categorical policy 2 · scalar value 15 rollout: 64 env x 128 steps · 4 PPO epochs · 40 rollouts6 before: 33.35 mean completed return (904 episodes)7 evaluating rollout 5/408 rollout 5/40 · loss 42.16689 · eval return 323.209 evaluating rollout 10/4010 rollout 10/40 · loss 47.93501 · eval return 268.0611 evaluating rollout 20/4012 rollout 20/40 · loss 64.53754 · eval return 279.0413 evaluating rollout 30/4014 rollout 30/40 · loss 79.72110 · eval return 436.5215 evaluating rollout 40/4016 rollout 40/40 · loss 89.61024 · eval return 448.7717 after: 448.77 mean completed return (64 episodes)18 improvement: +415.4119 checkpoint: 448.77 restored return · AdamW step 16020 training: 148.85s wall · 918.80 ms/update wall · 415.04 ms/update GPU · 327680 transitions21
Notice that the PPO composite loss rises as the policy improves: because episodes survive more than 13× longer, discounted return targets grow in magnitude and dominate the squared value-error term while the clipped policy surrogate stays bounded. Held-out episode return is therefore the primary measure of progress.
5. Evaluate and verify .oam checkpoint reload
After training, the example saves both the actor-critic parameters and AdamW
moment buffers into a native .oam checkpoint, loads them into a freshly
initialized model and optimizer, and re-runs the deterministic 64-lane
evaluation:
1oa::ml::save_checkpoint(&checkpoint, &model, &optimizer)?;2oa::ml::load_checkpoint(&checkpoint, &restored_model, &mut restored_optimizer)?;3let restored = evaluate(&runtime, &restored_model, EVALUATION_SEED)?;4assert_eq!(restored.mean_completed_return, after.mean_completed_return);5assert_eq!(restored_optimizer.step_count(), optimizer.step_count());6
Mean completed return improved from 33.35 to 448.77 in the figure run.
The reloaded checkpoint reproduced the final return and AdamW step 160.
6. Interactive Vulkan viewer
Running tu_rl_cart_pole_ppo with no arguments is equivalent to
-- --train --viewer. Use -- --viewer-only for the scripted PD balance
demo. During training, the viewer shows lane 0 of the training environment
between PPO updates. The window opens after the primer and initial evaluation,
before the first PPO rollout. The right panel shows rollout and collection progress,
loss, entropy, and the latest held-out return. Scheduled evaluations run
synchronously on the viewer thread, so the display can pause during evaluation.
The viewer stays open and plays back the neural policy learned in that run
after training completes. Close it to run the checkpoint check and write
figures, or to stop an unfinished run.
cargo run --release --example tu_rl_cart_pole_ppo -- --viewer-onlycargo run --release --example tu_rl_cart_pole_ppo -- --train --viewer
| Key | Action |
|---|---|
Space | Pause or resume the preview and live training |
Right | Advance one training batch while training is paused, or one preview step during playback |
R | Reset the episode during playback |
M | Toggle between the active controller and manual input during playback |
A | Take manual control and push left during playback |
D | Take manual control and push right during playback |
The complete interactive training run on a physical Vulkan device remains unverified after the latest viewer and evaluation changes.
Figures generated
| File | Contents |
|---|---|
01_untrained_filmstrip.jpg | Four headless Vulkan frames from an untrained baseline episode |
02_training_history.jpg | Held-out evaluation return and PPO composite loss over 40 rollouts |
03_before_after_eval.jpg | Untrained, trained, and .oam-restored returns plus pole-angle traces |
04_trained_filmstrip.jpg | Four headless Vulkan frames from one trained-policy episode |
Attribution
CartPole dynamics and episode limits follow Barto, Sutton, and Anderson (1983) and the Farama Gymnasium CartPole-v1 specification.
Source
Example
Tu_rl_cart_pole_ppo.rs
1use std::path::PathBuf;2use std::time::Instant;34use oa::ml::{5 AdamW, CategoricalActorCritic, CategoricalActorCriticConfig, Module, RolloutBuffer,6 RolloutConfig, RolloutTransition, advantage,7 environment::Environment,8 evaluation::{PolicyEvaluationConfig, PolicyEvaluationMetrics, evaluate_categorical},9 policy,10 training::{PpoTrainer, PpoTrainerConfig, RolloutTrainingPhase},11};12use oa::runtime::SdlWindow;13use oa::{14 DeviceSelection, Matrix, Result, Runtime, RuntimeRequirements, Viewer, ViewerConfig, ViewerMode,15};16use oasdk::ml::rl::{CartPole, CartPoleConfig, CartPoleFrameState, CartPoleLiveSource};1718mod plots;1920const ROLLOUT_PRIMER_ENVS: usize = 32;21const ROLLOUT_PRIMER_HORIZON: usize = 64;22const ROLLOUT_PRIMER_SEED: u64 = 20_260_716;2324const ENVIRONMENTS: u32 = 64;25const HORIZON: usize = 128;26const LIVE_COLLECTION_STEPS: usize = 8;27const DEFAULT_ROLLOUTS: u64 = 40;28const UPDATE_EPOCHS: u64 = 4;29const EVALUATION_INTERVAL: u64 = 10;30const TRAINING_SEED: u64 = 0x0a11_ce55;31const EVALUATION_SEED: u64 = 0x0e7a1;32const LEARNING_RATE: f32 = 2.5e-4;33const EVALUATION_HORIZON: usize = 500;3435struct CliOptions {36 train: bool,37 rollouts: u64,38 output: PathBuf,39 viewer: bool,40 device: DeviceSelection,41 skip_plots: bool,42}4344fn parse_args() -> Result<CliOptions> {45 let mut args = std::env::args().skip(1).peekable();46 let default_live_training = args.peek().is_none();47 let mut options = CliOptions {48 train: default_live_training,49 rollouts: DEFAULT_ROLLOUTS,50 output: PathBuf::from("var/tutorials/rl_cart_pole_ppo/rust"),51 viewer: default_live_training,52 device: DeviceSelection::Automatic,53 skip_plots: false,54 };55 while let Some(arg) = args.next() {56 match arg.as_str() {57 "--train" => options.train = true,58 "--rollouts" => {59 let value = args60 .next()61 .ok_or_else(|| oa::Error::invalid_argument("--rollouts requires a value"))?;62 options.rollouts = value63 .parse::<u64>()64 .map_err(|_| oa::Error::invalid_argument("invalid --rollouts integer"))?;65 options.train = true;66 }67 "--output" => {68 let value = args69 .next()70 .ok_or_else(|| oa::Error::invalid_argument("--output requires a path"))?;71 options.output = PathBuf::from(value);72 options.train = true;73 }74 "--device-index" => {75 let value = args76 .next()77 .ok_or_else(|| oa::Error::invalid_argument("--device-index requires a value"))?;78 options.device = DeviceSelection::Index(79 value80 .parse()81 .map_err(|_| oa::Error::invalid_argument("invalid --device-index integer"))?,82 );83 }84 "--viewer" => options.viewer = true,85 "--viewer-only" => {86 options.train = false;87 options.viewer = true;88 }89 "--skip-plots" => {90 options.skip_plots = true;91 options.train = true;92 }93 "-h" | "--help" => {94 println!(95 "Usage: tu_rl_cart_pole_ppo [--train] [--rollouts N] [--output DIR] [--viewer] [--viewer-only] [--skip-plots] [--device-index N]\n default (no flags): train PPO with the Vulkan viewer"96 );97 std::process::exit(0);98 }99 other => {100 return Err(oa::Error::invalid_argument(format!(101 "unknown argument: {other}"102 )));103 }104 }105 }106 Ok(options)107}108109fn create_runtime(110 presentation: bool,111 device: DeviceSelection,112) -> Result<(Runtime, Option<SdlWindow>)> {113 if presentation {114 let probe = SdlWindow::new_hidden("OA · CartPole-v1 PPO", 64, 64)?;115 let extensions = probe.required_instance_extensions()?;116 let runtime = Runtime::builder()117 .devices(device)118 .requirements(RuntimeRequirements::default().presentation())119 .instance_extensions(extensions)120 .build()?;121 // Keep SDL video initialized until the viewer closes.122 Ok((runtime, Some(probe)))123 } else {124 Ok((Runtime::builder().devices(device).build()?, None))125 }126}127128/// Section 1: demonstrate a zero-host-readback vectorized GPU rollout and GAE pass.129fn run_rollout_primer(runtime: &Runtime) -> Result<()> {130 let mut environment = CartPole::new(131 runtime,132 CartPoleConfig {133 environments: ROLLOUT_PRIMER_ENVS as u32,134 max_episode_steps: 500,135 seed: ROLLOUT_PRIMER_SEED,136 ..CartPoleConfig::default()137 },138 )?;139 let mut rollout = RolloutBuffer::new(140 runtime,141 RolloutConfig {142 time: ROLLOUT_PRIMER_HORIZON,143 environments: ROLLOUT_PRIMER_ENVS,144 observation_shape: vec![4],145 },146 )?;147 let policy_weight = Matrix::new_from_f32_on(148 runtime,149 [2, 4],150 &[0.0, -0.1, -4.0, -1.0, 0.0, 0.1, 4.0, 1.0],151 )?;152 let value = Matrix::new_from_f32_on(runtime, [ROLLOUT_PRIMER_ENVS], &[0.0; ROLLOUT_PRIMER_ENVS])?;153154 rollout.reset()?;155 for step in 0..ROLLOUT_PRIMER_HORIZON {156 let logits = oa::matrix::matmul(environment.observation(), &policy_weight)?;157 let selected =158 policy::sample_categorical(&logits, &value, ROLLOUT_PRIMER_SEED + step as u64 + 1)?;159 let transition = environment.step(&selected.action)?;160 rollout.append(&RolloutTransition::new(161 transition.observation().clone(),162 selected.action,163 transition.reward().clone(),164 selected.value,165 value.clone(),166 selected.log_probability,167 transition.terminated().clone(),168 transition.truncated().clone(),169 ))?;170 environment.reset_completed()?;171 }172 rollout.finalize(advantage::GaeConfig::default())?;173 let completion = environment.submit()?;174 environment.wait(&completion)?;175176 let reward = rollout.batch().reward().read_f32()?;177 let terminated = rollout.batch().terminated().read::<u8>()?;178 let truncated = rollout.batch().truncated().read::<u8>()?;179 let valid = rollout.batch().valid().read::<u8>()?;180 let adv = rollout.batch().advantage().read_f32()?;181 let reward_sum = reward.iter().copied().map(f64::from).sum::<f64>();182 let episodes = terminated183 .iter()184 .zip(&truncated)185 .filter(|(t, tr)| **t != 0 || **tr != 0)186 .count();187 assert!(valid.iter().all(|v| *v == 1));188 assert!(adv.iter().all(|v| v.is_finite()));189 assert_eq!(rollout.len(), ROLLOUT_PRIMER_HORIZON);190 assert!(reward_sum > 0.0);191 environment.close()?;192193 println!(194 " primer: {ROLLOUT_PRIMER_ENVS} envs x {ROLLOUT_PRIMER_HORIZON} steps ({} transitions) · {reward_sum:.0} reward · {episodes} episodes · 0 host reads during collection",195 ROLLOUT_PRIMER_ENVS * ROLLOUT_PRIMER_HORIZON196 );197 Ok(())198}199200fn evaluate(201 runtime: &Runtime,202 model: &CategoricalActorCritic,203 seed: u64,204) -> Result<PolicyEvaluationMetrics> {205 let mut environment = CartPole::new(206 runtime,207 CartPoleConfig {208 environments: ENVIRONMENTS,209 max_episode_steps: 500,210 seed,211 ..CartPoleConfig::default()212 },213 )?;214 let initialized = environment.submit()?;215 environment.wait(&initialized)?;216 let result = evaluate_categorical(217 &mut environment,218 model,219 PolicyEvaluationConfig {220 horizon: EVALUATION_HORIZON,221 seed,222 },223 )?;224 environment.close()?;225 Ok(result)226}227228/// Record one greedy 1-lane GPU episode for plotting and Vulkan filmstrip rendering.229fn record_episode(230 runtime: &Runtime,231 model: &CategoricalActorCritic,232 seed: u64,233) -> Result<Vec<CartPoleFrameState>> {234 let mut env = CartPole::new(235 runtime,236 CartPoleConfig {237 environments: 1,238 max_episode_steps: 500,239 seed,240 ..CartPoleConfig::default()241 },242 )?;243 let init = env.submit()?;244 env.wait(&init)?;245 let initial_obs = env.observation().read_f32()?;246 let mut frames = vec![CartPoleFrameState {247 cart_position: initial_obs[0],248 cart_velocity: initial_obs[1],249 pole_angle: initial_obs[2],250 pole_angular_velocity: initial_obs[3],251 action: 1,252 step: 0,253 max_steps: 500,254 terminated: false,255 truncated: false,256 }];257 for step in 1..=500_u32 {258 let logits = model.forward(env.observation())?.read_f32()?;259 let action = if logits[1] >= logits[0] { 1_i32 } else { 0_i32 };260 let action_matrix = Matrix::new_from_slice_on(runtime, [1], &[action])?;261 let transition = env.step(&action_matrix)?;262 let event = env.submit()?;263 env.wait(&event)?;264 let obs = transition.observation().read_f32()?;265 let terminated = transition.terminated().read::<u8>()?[0] != 0;266 let truncated = transition.truncated().read::<u8>()?[0] != 0;267 frames.push(CartPoleFrameState {268 cart_position: obs[0],269 cart_velocity: obs[1],270 pole_angle: obs[2],271 pole_angular_velocity: obs[3],272 action,273 step,274 max_steps: 500,275 terminated,276 truncated,277 });278 if terminated || truncated {279 break;280 }281 }282 env.close()?;283 Ok(frames)284}285286fn select_key_frames(frames: &[CartPoleFrameState]) -> Vec<(&'static str, CartPoleFrameState)> {287 let last = frames.len().saturating_sub(1);288 let i1 = last / 3;289 let i2 = (last * 2) / 3;290 vec![291 ("1. Episode start", frames[0]),292 ("2. Early control", frames[i1]),293 ("3. Mid-episode", frames[i2]),294 ("4. Episode end", frames[last]),295 ]296}297298fn run_viewer(runtime: &Runtime, source: &mut CartPoleLiveSource<'_>) -> Result<()> {299 let mut viewer = Viewer::new(ViewerConfig {300 mode: ViewerMode::Live,301 title: "OA · CartPole-v1 PPO".to_owned(),302 width: 1280,303 height: 720,304 show_help: false,305 show_stats: false,306 show_timeline: false,307 ..ViewerConfig::default()308 });309 viewer.set_live_source(source);310 viewer.run(runtime)311}312313fn main() -> Result<()> {314 let options = parse_args()?;315 let open_viewer = !options.train || options.viewer;316 let (runtime, _presentation_probe) = create_runtime(open_viewer, options.device)?;317 Runtime::set_default(runtime.clone());318319 if !options.train {320 let mut source = CartPoleLiveSource::new(&runtime, None, EVALUATION_SEED)?;321 return run_viewer(&runtime, &mut source);322 }323324 println!("\nOA reinforcement learning — CartPole-v1 PPO");325 run_rollout_primer(&runtime)?;326327 let model = CategoricalActorCritic::new(CategoricalActorCriticConfig {328 observation_size: 4,329 action_count: 2,330 hidden_size: 64,331 seed: TRAINING_SEED,332 })?;333 let mut optimizer = AdamW::new_with_hyperparameters(334 model.all_parameters()?,335 LEARNING_RATE,336 0.9,337 0.999,338 1.0e-8,339 0.0,340 )?;341342 println!(" separate actor/critic: each 4 -> 64 -> 64 (ReLU/Tanh)");343 println!(" heads: categorical policy 2 · scalar value 1");344 println!(345 " rollout: {ENVIRONMENTS} env x {HORIZON} steps · {UPDATE_EPOCHS} PPO epochs · {} rollouts",346 options.rollouts347 );348349 let before = evaluate(&runtime, &model, EVALUATION_SEED)?;350 println!(351 " before: {:.2} mean completed return ({} episodes)",352 before.mean_completed_return, before.completed_episodes353 );354 let untrained_episode = if options.skip_plots {355 Vec::new()356 } else {357 record_episode(&runtime, &model, EVALUATION_SEED)?358 };359360 let mut environment = CartPole::new(361 &runtime,362 CartPoleConfig {363 environments: ENVIRONMENTS,364 max_episode_steps: 500,365 seed: TRAINING_SEED,366 ..CartPoleConfig::default()367 },368 )?;369 if options.viewer {370 // CartPole::new records the initial reset. Commit it before the371 // preview environment opens its own transaction on the same Runtime.372 let initialized = environment.submit()?;373 environment.wait(&initialized)?;374 }375 let mut rollout_losses = Vec::with_capacity(options.rollouts as usize);376 let mut eval_x = vec![0.0_f32];377 let mut eval_y = vec![before.mean_completed_return as f32];378 let mut final_eval: Option<PolicyEvaluationMetrics> = None;379380 let started = Instant::now();381 let mut wall = started.elapsed();382 let snapshot = {383 let mut trainer = PpoTrainer::new(384 &runtime,385 &model,386 &mut optimizer,387 PpoTrainerConfig {388 rollouts: options.rollouts,389 horizon: HORIZON,390 environments: ENVIRONMENTS as usize,391 update_epochs: UPDATE_EPOCHS,392 observation_shape: vec![4],393 seed: TRAINING_SEED,394 enable_gpu_timing: true,395 ..PpoTrainerConfig::default()396 },397 )?;398 let mut last_recorded = 0_u64;399 let mut collected = 0;400 let mut first_frame = options.viewer;401 let collection_steps = if options.viewer {402 LIVE_COLLECTION_STEPS403 } else {404 HORIZON405 };406 let mut advance = || -> Result<Option<(Option<CartPoleFrameState>, [String; 4])>> {407 if trainer.is_done() {408 return Ok(None);409 }410 if std::mem::take(&mut first_frame) {411 return Ok(Some((412 None,413 [414 format!("Rollout: 0/{}", options.rollouts),415 "Starting PPO".into(),416 "Loss: —".into(),417 format!("Eval: {:.1}", before.mean_completed_return),418 ],419 )));420 }421 let mut frame = None;422 if trainer.needs_collection() || collected != 0 {423 if environment.execution().submission_count() == 0424 && !environment.execution().has_active_recording()425 && !environment.holds_committed_state()426 {427 environment.reset(TRAINING_SEED)?;428 }429 environment.begin()?;430 if collected == 0 {431 trainer.begin_collection()?;432 }433 let end = (collected + collection_steps).min(HORIZON);434 let mut preview_action = None;435 for step in collected..end {436 let selected = trainer.act(environment.observation())?;437 let transition = environment.step(&selected.action)?;438 trainer.observe(439 transition.observation(),440 transition.next_observation(),441 transition.reward(),442 transition.terminated(),443 transition.truncated(),444 &selected,445 )?;446 environment.reset_completed()?;447 if options.viewer && step + 1 == end {448 preview_action = Some(selected.action);449 }450 }451 if end == HORIZON {452 trainer.end_collection()?;453 }454 // Release the recorder and retire this batch before drawing the preview.455 let event = environment.submit()?;456 environment.wait(&event)?;457 if let Some(action) = preview_action {458 let obs = environment.observation().read_f32()?;459 frame = Some(CartPoleFrameState {460 cart_position: obs[0],461 cart_velocity: obs[1],462 pole_angle: obs[2],463 pole_angular_velocity: obs[3],464 action: action.read::<i32>()?[0],465 step: environment.episode_steps().read::<u32>()?[0],466 max_steps: 500,467 ..CartPoleFrameState::default()468 });469 }470 if end < HORIZON {471 collected = end;472 let metrics = trainer.metrics();473 return Ok(Some((474 frame,475 [476 format!("Rollout: {}/{}", metrics.rollout, options.rollouts),477 format!("Collect: {end}/{HORIZON}"),478 format!("Loss: {:.3}", metrics.total_loss),479 format!("Eval: {:.1}", eval_y.last().copied().unwrap_or_default()),480 ],481 )));482 }483 collected = 0;484 }485 trainer.update()?;486 let metrics = trainer.metrics();487 if trainer.phase() != RolloutTrainingPhase::Update && metrics.rollout != last_recorded {488 last_recorded = metrics.rollout;489 rollout_losses.push(metrics.total_loss);490 let is_final = metrics.rollout == options.rollouts;491 let should_eval =492 is_final || metrics.rollout == 5 || metrics.rollout.is_multiple_of(EVALUATION_INTERVAL);493 if should_eval {494 println!(495 " evaluating rollout {}/{}",496 metrics.rollout, options.rollouts497 );498 let eval = evaluate(&runtime, &model, EVALUATION_SEED)?;499 eval_x.push(metrics.rollout as f32);500 eval_y.push(eval.mean_completed_return as f32);501 println!(502 " rollout {}/{} · loss {:.5} · eval return {:.2}",503 metrics.rollout, options.rollouts, metrics.total_loss, eval.mean_completed_return,504 );505 if is_final {506 final_eval = Some(eval);507 }508 }509 }510 wall = started.elapsed();511 Ok(Some((512 frame,513 [514 format!("Rollout: {}/{}", metrics.rollout, options.rollouts),515 format!("Loss: {:.3}", metrics.total_loss),516 format!("Entropy: {:.3}", metrics.entropy),517 format!("Eval: {:.1}", eval_y.last().copied().unwrap_or_default()),518 ],519 )))520 };521 if options.viewer {522 let mut source = CartPoleLiveSource::new(&runtime, Some(&model), EVALUATION_SEED)?;523 source.set_training_tick(advance);524 run_viewer(&runtime, &mut source)?;525 } else {526 while advance()?.is_some() {}527 }528 if !trainer.is_done() {529 environment.close()?;530 println!(" training stopped when the viewer closed");531 return Ok(());532 }533 trainer.finish()?534 };535 environment.close()?;536537 let after = match final_eval {538 Some(eval) => eval,539 None => evaluate(&runtime, &model, EVALUATION_SEED)?,540 };541 let checkpoint = std::env::temp_dir().join("oars_cart_pole_ppo.oam");542 oa::ml::save_checkpoint(&checkpoint, &model, &optimizer)?;543 let restored_model = CategoricalActorCritic::new(CategoricalActorCriticConfig {544 observation_size: 4,545 action_count: 2,546 hidden_size: 64,547 seed: TRAINING_SEED,548 })?;549 let mut restored_optimizer = AdamW::new_with_hyperparameters(550 restored_model.all_parameters()?,551 LEARNING_RATE,552 0.9,553 0.999,554 1.0e-8,555 0.0,556 )?;557 oa::ml::load_checkpoint(&checkpoint, &restored_model, &mut restored_optimizer)?;558 let restored = evaluate(&runtime, &restored_model, EVALUATION_SEED)?;559 std::fs::remove_file(&checkpoint).expect("remove completed CartPole checkpoint");560561 println!(562 " after: {:.2} mean completed return ({} episodes)",563 after.mean_completed_return, after.completed_episodes564 );565 println!(566 " improvement: {:+.2}",567 after.mean_completed_return - before.mean_completed_return568 );569 println!(570 " checkpoint: {:.2} restored return · AdamW step {}",571 restored.mean_completed_return,572 restored_optimizer.step_count()573 );574 println!(575 " training: {:.2}s wall · {:.2} ms/update wall · {:.2} ms/update GPU · {} transitions",576 wall.as_secs_f64(),577 snapshot.wall_ms_per_step(),578 snapshot.gpu_timing_stats().mean_ms,579 u64::from(ENVIRONMENTS) * HORIZON as u64 * options.rollouts580 );581582 if options.rollouts >= DEFAULT_ROLLOUTS {583 assert!(after.mean_completed_return >= before.mean_completed_return + 25.0);584 assert!(after.mean_completed_return >= 75.0);585 }586 assert_eq!(restored.mean_completed_return, after.mean_completed_return);587 assert_eq!(restored.completed_episodes, after.completed_episodes);588 assert_eq!(restored_optimizer.step_count(), optimizer.step_count());589590 if !options.skip_plots {591 std::fs::create_dir_all(&options.output)592 .map_err(|error| oa::Error::io("create tutorial output directory", error))?;593 let trained_episode = record_episode(&runtime, &model, EVALUATION_SEED)?;594595 let untrained_angles: Vec<f32> = untrained_episode596 .iter()597 .map(|f| f.pole_angle.to_degrees())598 .collect();599 let trained_angles: Vec<f32> = trained_episode600 .iter()601 .map(|f| f.pole_angle.to_degrees())602 .collect();603604 let f1 = plots::filmstrip_figure(605 &runtime,606 "Untrained CartPole-v1 episode (Vulkan headless)",607 &select_key_frames(&untrained_episode),608 )?;609 let f2 = plots::training_history_figure(&eval_x, &eval_y, &rollout_losses);610 let f3 = plots::before_after_figure(611 before.mean_completed_return as f32,612 after.mean_completed_return as f32,613 restored.mean_completed_return as f32,614 &untrained_angles,615 &trained_angles,616 );617 let f4 = plots::filmstrip_figure(618 &runtime,619 "Trained CartPole-v1 PPO episode (Vulkan headless)",620 &select_key_frames(&trained_episode),621 )?;622623 for (name, fig) in [624 ("01_untrained_filmstrip.jpg", &f1),625 ("02_training_history.jpg", &f2),626 ("03_before_after_eval.jpg", &f3),627 ("04_trained_filmstrip.jpg", &f4),628 ] {629 let path = options.output.join(name);630 let path_str = path631 .to_str()632 .ok_or_else(|| oa::Error::invalid_argument("output path must be UTF-8"))?;633 fig.save_to_on(&runtime, path_str)?;634 }635 println!(636 " figures: wrote 4 dark-theme Vulkan/plot JPEGs to {}",637 options.output.display()638 );639 }640641 Ok(())642}643
plots.rs
1use oa::plot::{BarStyle, Figure, FigureConfig, LineStyle, Theme};2use oa::ui::UiStyle;3use oa::{Result, Runtime};4use oasdk::ml::rl::{CartPoleFrameState, render_cart_pole_texture};56fn figure(title: &str, rows: i32, cols: i32, width: u32, height: u32) -> Figure {7 Figure::new(FigureConfig {8 title: title.into(),9 rows,10 cols,11 width,12 height,13 theme: Theme::Dark,14 ..FigureConfig::default()15 })16}1718/// Render four CartPole episode frames on the GPU into a 2x2 labeled filmstrip.19pub(super) fn filmstrip_figure(20 runtime: &Runtime,21 title: &str,22 frames: &[(&str, CartPoleFrameState)],23) -> Result<Figure> {24 let mut fig = figure(title, 2, 2, 1280, 780);25 for (idx, (caption, frame)) in frames.iter().take(4).enumerate() {26 let row = (idx / 2) as i32;27 let col = (idx % 2) as i32;28 let tex = render_cart_pole_texture(runtime, 600, 340, frame, caption)?;29 let ax = fig.ax(row, col);30 ax.imshow(tex);31 ax.grid(false);32 ax.legend(false);33 }34 Ok(fig)35}3637/// Dark-theme training history: held-out return progression + PPO loss curve.38pub(super) fn training_history_figure(39 eval_rollouts: &[f32],40 eval_returns: &[f32],41 rollout_losses: &[f32],42) -> Figure {43 let pal = UiStyle::default().data_palette;44 let blue = pal[0];45 let green = pal[2];46 let mut fig = figure("CartPole-v1 PPO training history", 1, 2, 1280, 460);4748 {49 let ax = fig.ax(0, 0);50 ax.title("Held-out evaluation return");51 ax.x_label("PPO rollout");52 ax.y_label("Mean completed return");53 ax.plot_xy(54 eval_rollouts,55 eval_returns,56 LineStyle {57 color: green,58 label: "Mean return".into(),59 width: 2.5,60 ..LineStyle::default()61 },62 );63 ax.grid(true);64 ax.legend(true);65 }6667 {68 let rollouts: Vec<f32> = (1..=rollout_losses.len()).map(|i| i as f32).collect();69 let ax = fig.ax(0, 1);70 ax.title("PPO composite loss");71 ax.x_label("PPO rollout");72 ax.y_label("Loss");73 ax.plot_xy(74 &rollouts,75 rollout_losses,76 LineStyle {77 color: blue,78 label: "Total loss".into(),79 width: 2.5,80 ..LineStyle::default()81 },82 );83 ax.grid(true);84 ax.legend(true);85 }8687 fig88}8990/// Dark-theme before/after comparison: mean returns bar chart + pole-angle trace.91pub(super) fn before_after_figure(92 before_return: f32,93 after_return: f32,94 restored_return: f32,95 untrained_angles_deg: &[f32],96 trained_angles_deg: &[f32],97) -> Figure {98 let pal = UiStyle::default().data_palette;99 let blue = pal[0];100 let coral = pal[1];101 let green = pal[2];102 let amber = pal[4];103 let mut fig = figure(104 "Before vs. after PPO evaluation and pole stability",105 1,106 2,107 1280,108 460,109 );110111 {112 let ax = fig.ax(0, 0);113 ax.title("Held-out mean return (64 envs, 500-step horizon)");114 ax.y_label("Mean completed return");115 ax.bar(116 &[before_return, f32::NAN, f32::NAN],117 BarStyle {118 color: coral,119 label: "Untrained".into(),120 ..BarStyle::default()121 },122 );123 ax.bar(124 &[f32::NAN, after_return, f32::NAN],125 BarStyle {126 color: blue,127 label: "Trained PPO".into(),128 ..BarStyle::default()129 },130 );131 ax.bar(132 &[f32::NAN, f32::NAN, restored_return],133 BarStyle {134 color: green,135 label: "Restored .oam".into(),136 ..BarStyle::default()137 },138 );139 ax.categories(&["Untrained", "Trained PPO", "Restored .oam"]);140 let max_y = before_return.max(after_return).max(restored_return) * 1.15;141 ax.limits(-0.5, 2.5, 0.0, max_y.max(100.0));142 ax.grid(true);143 ax.legend(true);144 }145146 {147 let ax = fig.ax(0, 1);148 ax.title("Episode pole angle trajectory (degrees)");149 ax.x_label("Environment step");150 ax.y_label("Pole angle (deg)");151 let x_untrained: Vec<f32> = (0..untrained_angles_deg.len()).map(|i| i as f32).collect();152 let x_trained: Vec<f32> = (0..trained_angles_deg.len()).map(|i| i as f32).collect();153 let horizon = x_trained.len().max(x_untrained.len()).max(2) as f32;154 ax.plot_xy(155 &[0.0, horizon],156 &[12.0, 12.0],157 LineStyle {158 color: amber,159 label: "+/- 12 deg limit".into(),160 width: 1.5,161 ..LineStyle::default()162 },163 );164 ax.plot_xy(165 &[0.0, horizon],166 &[-12.0, -12.0],167 LineStyle {168 color: amber,169 width: 1.5,170 ..LineStyle::default()171 },172 );173 ax.plot_xy(174 &x_untrained,175 untrained_angles_deg,176 LineStyle {177 color: coral,178 label: "Untrained".into(),179 width: 2.2,180 ..LineStyle::default()181 },182 );183 ax.plot_xy(184 &x_trained,185 trained_angles_deg,186 LineStyle {187 color: green,188 label: "Trained PPO".into(),189 width: 2.2,190 ..LineStyle::default()191 },192 );193 ax.limits(0.0, horizon, -15.0, 15.0);194 ax.grid(true);195 ax.legend(true);196 }197198 fig199}200
Run Rust tutorials from the OA SDK checkout with cargo run --release --example <name>. Run Python with the environment containing the OA native extension. Consult each program's arguments and capability checks before running it.