Train a 2D Lunar Lander with PPO in Rust
Train a Gymnasium-style 2D Lunar Lander PPO policy on GPU and fly it live in Vulkan.
Start the walkthrough · Jump to complete source
This tutorial uses the SDK's LunarLander2d environment and a categorical
actor-critic network. The lander and its terrain are rendered in a 2D
SDL3/Vulkan viewer. The default run trains a fresh neural policy with PPO and shows lane 0
of the training environment. The viewer-only demo uses a scripted landing
controller.
Run in Rust
From the SDK repository root, choose the mode you want.
# Train with the viewer and play back the resulting neural policy (default).cargo run --release --example tu_rl_lunar_lander_ppo# Train headlessly and write the tutorial figures.cargo run --release --example tu_rl_lunar_lander_ppo -- --train# Open the scripted flight demo immediately.cargo run --release --example tu_rl_lunar_lander_ppo -- --viewer-only
With no flags, the example behaves as --train --viewer. The window opens
after the initial evaluation, before the first PPO rollout. The right panel
shows collection progress, PPO loss, entropy, and the latest held-out return.
Each live collection batch contains eight steps. Scheduled evaluations can
pause the display while they run on the viewer thread.
After training, the window stays open for playback of the learned policy.
Close it to verify the checkpoint and generate figures, or to stop an
unfinished run. Use --rollouts N to change the training budget,
--output DIR to choose a figure directory, and --skip-plots to skip
figure generation, and --device-index N to select an enumerated Vulkan
device explicitly. Combine these options with --train --viewer for live
training.
Environment and PPO
Each GPU lane observes horizontal and vertical position and velocity, tilt, angular rate, and two landing-leg contact flags. The four discrete actions are coast, left orientation engine, main engine, and right orientation engine. The environment uses seeded terrain with a flat landing pad, applies a 600-step time limit, and tracks landing, crash, and out-of-bounds outcomes. The view covers the upper arena boundary at 15.5 m. The reward adds 200 for a settled landing on the pad and 50 off the pad. It subtracts 250 for leaving the arena and 100 for crashing or timing out, in addition to the step shaping and fuel cost. The observation and action layout follows the Gymnasium task, with OA's own dynamics and reward implementation. Gymnasium Lunar Lander
The actor and critic each use two 64-wide hidden layers. During training, the actor samples actions for 64 parallel lanes over 128 steps per rollout. Finished lanes reset in place. The trainer computes generalized advantage estimates from the retained transitions and applies four PPO update epochs with AdamW and a reward discount of 0.995. The default 300 rollouts collect 2,457,600 transitions. The tutorial evaluates a greedy policy at initialization, every 20 rollouts, and at the end, using a fixed evaluation seed and a 600-step horizon.
The tutorial saves model parameters and AdamW state to a temporary .oam
checkpoint, reloads them into a fresh model and optimizer, and checks that
the mean completed return agrees within 1e-4 and that the optimizer step
count matches. It then removes the temporary file. The optional viewer
borrows the trained model from the same run.
Verification
The earlier 100-rollout configuration could learn to climb out of the arena. The current recipe penalizes escapes more heavily, rewards a settled pad landing more strongly, and gives later rewards more weight in the PPO targets.
A 60-rollout software Vulkan run improved mean completed return from −434.80 to −374.38 over 491,520 transitions. Checkpoint reload reproduced −374.38 and AdamW step 240. The filmstrip episode still climbed to the ceiling and terminated out of bounds. A separate dense ascent-penalty experiment also escaped and scored worse at rollout 60. The 300-rollout verification run ended after the rollout-80 evaluation, so reliable landing performance remains unverified.
Viewer controls
Manual flight and terrain reset apply during playback.
| Key | Action |
|---|---|
Space | Pause or resume training or playback |
N | Advance a training batch while paused, or advance one step during playback |
R | Restart the episode with the next terrain seed |
M | Toggle manual control and the active controller |
W / Up | Take manual control and fire the main engine |
A / Left | Take manual control and fire the left orientation engine |
D / Right | Take manual control and fire the right orientation engine |
Q / Esc | Close the viewer |
Figures generated
The default output directory is var/tutorials/rl_lunar_lander_ppo/rust/.
The checked-in 2D figures come from the 60-rollout run above.
| File | Contents |
|---|---|
01_untrained_filmstrip.jpg | Greedy flight with the freshly initialized actor |
02_training_history.jpg | Held-out return, PPO loss, and policy entropy |
03_before_after_eval.jpg | Baseline, trained, and restored returns with descent telemetry and action counts |
04_trained_filmstrip.jpg | A greedy episode selected from eight deterministic demo seeds, preferring a landing when available |
Example
Tu_rl_lunar_lander_ppo.rs
1use std::path::PathBuf;2use std::time::Instant;34use oa::ml::{5 AdamW, CategoricalActorCritic, CategoricalActorCriticConfig, Module,6 environment::Environment,7 evaluation::{PolicyEvaluationConfig, PolicyEvaluationMetrics, evaluate_categorical},8 training::{PpoTrainer, PpoTrainerConfig, RolloutTrainingPhase},9};10use oa::runtime::SdlWindow;11use oa::{12 DeviceSelection, Matrix, Result, Runtime, RuntimeRequirements, Viewer, ViewerConfig, ViewerMode,13};14use oasdk::ml::rl::{15 LUNAR_LANDER_2D_ACTION_COUNT, LUNAR_LANDER_2D_OBSERVATION_SIZE, LunarLander2d,16 LunarLander2dConfig, LunarLander2dFrameState, LunarLander2dLiveSource, LunarLander2dOutcome,17 read_lane0_frame,18};1920mod plots;2122const ENVIRONMENTS: u32 = 64;23const HORIZON: usize = 128;24const LIVE_COLLECTION_STEPS: usize = 8;25const DEFAULT_ROLLOUTS: u64 = 300;26const UPDATE_EPOCHS: u64 = 4;27const EVALUATION_INTERVAL: u64 = 20;28const HIDDEN_SIZE: usize = 64;29const TRAINING_SEED: u64 = 0x1a2b_3c4d;30const EVALUATION_SEED: u64 = 0x0e7a_2d01;31const DEMO_SEED: u64 = 104;32const LEARNING_RATE: f32 = 3.0e-4;33const EVALUATION_HORIZON: usize = 600;3435struct CliOptions {36 train: bool,37 rollouts: u64,38 output: PathBuf,39 viewer: bool,40 skip_plots: bool,41 device: DeviceSelection,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_lunar_lander_ppo/rust"),51 viewer: default_live_training,52 skip_plots: false,53 device: DeviceSelection::Automatic,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_lunar_lander_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 · Lunar Lander 2D", 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}127128fn evaluate(129 runtime: &Runtime,130 model: &CategoricalActorCritic,131 seed: u64,132) -> Result<PolicyEvaluationMetrics> {133 let mut environment = LunarLander2d::new(134 runtime,135 LunarLander2dConfig {136 environments: ENVIRONMENTS,137 max_episode_steps: EVALUATION_HORIZON as u32,138 seed,139 ..LunarLander2dConfig::default()140 },141 )?;142 let initialized = environment.submit()?;143 environment.wait(&initialized)?;144 let result = evaluate_categorical(145 &mut environment,146 model,147 PolicyEvaluationConfig {148 horizon: EVALUATION_HORIZON,149 seed,150 },151 )?;152 environment.close()?;153 Ok(result)154}155156fn argmax_action(logits: &[f32]) -> i32 {157 logits158 .iter()159 .take(LUNAR_LANDER_2D_ACTION_COUNT)160 .enumerate()161 .max_by(|(_, a), (_, b)| a.total_cmp(b))162 .map(|(idx, _)| idx as i32)163 .unwrap_or(0)164}165166/// Record one greedy 1-lane GPU episode for 2D Vulkan filmstrips and telemetry plots.167fn record_episode(168 runtime: &Runtime,169 model: &CategoricalActorCritic,170 seed: u64,171) -> Result<(Vec<LunarLander2dFrameState>, [f32; 4])> {172 let mut env = LunarLander2d::new(173 runtime,174 LunarLander2dConfig {175 environments: 1,176 max_episode_steps: EVALUATION_HORIZON as u32,177 seed,178 ..LunarLander2dConfig::default()179 },180 )?;181 let init = env.submit()?;182 env.wait(&init)?;183 let first = read_lane0_frame(&env, seed, 0, 0, 0, false, false, Vec::new())?;184 let mut frames = vec![first];185 let mut trail = Vec::new();186 let mut action_counts = [0.0_f32; 4];187188 for step in 1..=(EVALUATION_HORIZON as u32) {189 let logits = model.forward(env.observation())?.read_f32()?;190 let action = argmax_action(&logits);191 action_counts[action as usize] += 1.0;192193 if let Some(prev) = frames.last()194 && step.is_multiple_of(3)195 {196 trail.push([prev.x, prev.y]);197 }198199 let action_matrix = Matrix::new_from_slice_on(runtime, [1], &[action])?;200 let transition = env.step(&action_matrix)?;201 let event = env.submit()?;202 env.wait(&event)?;203 let terminated = transition.terminated().read::<u8>()?[0] != 0;204 let truncated = transition.truncated().read::<u8>()?[0] != 0;205 let frame = read_lane0_frame(206 &env,207 seed,208 0,209 action,210 step,211 terminated,212 truncated,213 trail.clone(),214 )?;215 frames.push(frame);216 if terminated || truncated {217 break;218 }219 }220 env.close()?;221 Ok((frames, action_counts))222}223224fn pick_filmstrip_frames(225 frames: &[LunarLander2dFrameState],226 stage_titles: [&str; 4],227) -> Vec<(String, LunarLander2dFrameState)> {228 let last = frames.len().saturating_sub(1);229 let indices = [0, last / 3, (last * 2) / 3, last];230 stage_titles231 .into_iter()232 .zip(indices)233 .map(|(title, idx)| {234 let f = frames[idx].clone();235 let caption = format!(236 "{title} (step {}, alt {:.1}m, {})",237 f.step,238 (f.y - 0.70).max(0.0),239 f.outcome.label()240 );241 (caption, f)242 })243 .collect()244}245246fn run_viewer(runtime: &Runtime, source: &mut LunarLander2dLiveSource<'_>) -> Result<()> {247 let mut viewer = Viewer::new(ViewerConfig {248 mode: ViewerMode::Live,249 title: "OA · Lunar Lander 2D PPO".to_owned(),250 width: 1280,251 height: 720,252 show_help: false,253 show_stats: false,254 show_timeline: false,255 ..ViewerConfig::default()256 });257 viewer.set_live_source(source);258 viewer.run(runtime)259}260261fn main() -> Result<()> {262 let options = parse_args()?;263 let open_viewer = !options.train || options.viewer;264 let (runtime, _presentation_probe) = create_runtime(open_viewer, options.device)?;265 Runtime::set_default(runtime.clone());266267 if !options.train {268 let mut source = LunarLander2dLiveSource::new(&runtime, None, DEMO_SEED)?;269 return run_viewer(&runtime, &mut source);270 }271272 let model = CategoricalActorCritic::new(CategoricalActorCriticConfig {273 observation_size: LUNAR_LANDER_2D_OBSERVATION_SIZE,274 action_count: LUNAR_LANDER_2D_ACTION_COUNT,275 hidden_size: HIDDEN_SIZE,276 seed: TRAINING_SEED,277 })?;278 let mut optimizer = AdamW::new_with_hyperparameters(279 model.all_parameters()?,280 LEARNING_RATE,281 0.9,282 0.999,283 1.0e-8,284 0.0,285 )?;286287 println!("\nOA reinforcement learning — LunarLander-2D PPO");288 println!(289 " actor-critic: {} -> {} -> {} · {} discrete actions · {} GPU envs x {} horizon x {} rollouts",290 LUNAR_LANDER_2D_OBSERVATION_SIZE,291 HIDDEN_SIZE,292 HIDDEN_SIZE,293 LUNAR_LANDER_2D_ACTION_COUNT,294 ENVIRONMENTS,295 HORIZON,296 options.rollouts,297 );298299 let before = evaluate(&runtime, &model, EVALUATION_SEED)?;300 println!(301 " untrained: mean return {:+.2} ({} completed episodes)",302 before.mean_completed_return, before.completed_episodes,303 );304305 let untrained_frames = if options.skip_plots {306 Vec::new()307 } else {308 record_episode(&runtime, &model, DEMO_SEED)?.0309 };310311 let mut environment = LunarLander2d::new(312 &runtime,313 LunarLander2dConfig {314 environments: ENVIRONMENTS,315 max_episode_steps: EVALUATION_HORIZON as u32,316 seed: TRAINING_SEED,317 ..LunarLander2dConfig::default()318 },319 )?;320321 if options.viewer {322 // Commit the initial reset before creating the viewer's playback environment.323 let initialized = environment.submit()?;324 environment.wait(&initialized)?;325 }326 let mut eval_rollouts = vec![0.0_f32];327 let mut eval_returns = vec![before.mean_completed_return];328 let mut total_losses = Vec::with_capacity(options.rollouts as usize);329 let mut entropies = Vec::with_capacity(options.rollouts as usize);330 let mut final_eval: Option<PolicyEvaluationMetrics> = None;331332 let started = Instant::now();333 let mut wall = started.elapsed();334 let snapshot = {335 let mut trainer = PpoTrainer::new(336 &runtime,337 &model,338 &mut optimizer,339 PpoTrainerConfig {340 rollouts: options.rollouts,341 horizon: HORIZON,342 environments: ENVIRONMENTS as usize,343 update_epochs: UPDATE_EPOCHS,344 observation_shape: vec![LUNAR_LANDER_2D_OBSERVATION_SIZE],345 seed: TRAINING_SEED,346 enable_gpu_timing: true,347 gae: oa::ml::advantage::GaeConfig {348 gamma: 0.995,349 ..oa::ml::advantage::GaeConfig::default()350 },351 ..PpoTrainerConfig::default()352 },353 )?;354 let mut last_recorded = 0_u64;355 let mut collected = 0;356 let mut first_frame = options.viewer;357 let collection_steps = if options.viewer {358 LIVE_COLLECTION_STEPS359 } else {360 HORIZON361 };362 let mut advance = || -> Result<Option<(Option<LunarLander2dFrameState>, [String; 4])>> {363 if trainer.is_done() {364 return Ok(None);365 }366 if std::mem::take(&mut first_frame) {367 return Ok(Some((368 None,369 [370 format!("Rollout: 0/{}", options.rollouts),371 "Starting PPO".into(),372 "Loss: —".into(),373 format!("Eval: {:.1}", before.mean_completed_return),374 ],375 )));376 }377 let mut frame = None;378 if trainer.needs_collection() || collected != 0 {379 if environment.execution().submission_count() == 0380 && !environment.execution().has_active_recording()381 && !environment.holds_committed_state()382 {383 environment.reset(TRAINING_SEED)?;384 }385 environment.begin()?;386 if collected == 0 {387 trainer.begin_collection()?;388 }389 let end = (collected + collection_steps).min(HORIZON);390 let mut preview_action = None;391 for step in collected..end {392 let selected = trainer.act(environment.observation())?;393 let transition = environment.step(&selected.action)?;394 trainer.observe(395 transition.observation(),396 transition.next_observation(),397 transition.reward(),398 transition.terminated(),399 transition.truncated(),400 &selected,401 )?;402 environment.reset_completed()?;403 if options.viewer && step + 1 == end {404 preview_action = Some(selected.action);405 }406 }407 if end == HORIZON {408 trainer.end_collection()?;409 }410 // Release the recorder and retire this batch before drawing the preview.411 let event = environment.submit()?;412 environment.wait(&event)?;413 if let Some(action) = preview_action {414 frame = Some(read_lane0_frame(415 &environment,416 TRAINING_SEED,417 environment.episode_index().read::<u32>()?[0],418 action.read::<i32>()?[0],419 environment.episode_steps().read::<u32>()?[0],420 false,421 false,422 Vec::new(),423 )?);424 }425 if end < HORIZON {426 collected = end;427 let metrics = trainer.metrics();428 return Ok(Some((429 frame,430 [431 format!("Rollout: {}/{}", metrics.rollout, options.rollouts),432 format!("Collect: {end}/{HORIZON}"),433 format!("Loss: {:.3}", metrics.total_loss),434 format!(435 "Eval: {:.1}",436 eval_returns.last().copied().unwrap_or_default()437 ),438 ],439 )));440 }441 collected = 0;442 }443 trainer.update()?;444 let metrics = trainer.metrics();445 if trainer.phase() != RolloutTrainingPhase::Update && metrics.rollout != last_recorded {446 last_recorded = metrics.rollout;447 total_losses.push(metrics.total_loss);448 entropies.push(metrics.entropy);449 let is_final = metrics.rollout == options.rollouts;450 let should_eval = is_final || metrics.rollout.is_multiple_of(EVALUATION_INTERVAL);451 if should_eval {452 println!(453 " evaluating rollout {}/{}",454 metrics.rollout, options.rollouts455 );456 let eval = evaluate(&runtime, &model, EVALUATION_SEED)?;457 eval_rollouts.push(metrics.rollout as f32);458 eval_returns.push(eval.mean_completed_return as f32);459 println!(460 " rollout {}/{} · loss {:.5} · eval return {:.2}",461 metrics.rollout, options.rollouts, metrics.total_loss, eval.mean_completed_return,462 );463 if is_final {464 final_eval = Some(eval);465 }466 }467 }468 wall = started.elapsed();469 Ok(Some((470 frame,471 [472 format!("Rollout: {}/{}", metrics.rollout, options.rollouts),473 format!("Loss: {:.3}", metrics.total_loss),474 format!("Entropy: {:.3}", metrics.entropy),475 format!(476 "Eval: {:.1}",477 eval_returns.last().copied().unwrap_or_default()478 ),479 ],480 )))481 };482 if options.viewer {483 let mut source = LunarLander2dLiveSource::new(&runtime, Some(&model), DEMO_SEED)?;484 source.set_training_tick(advance);485 run_viewer(&runtime, &mut source)?;486 } else {487 while advance()?.is_some() {}488 }489 if !trainer.is_done() {490 environment.close()?;491 println!(" training stopped when the viewer closed");492 return Ok(());493 }494 trainer.finish()?495 };496 environment.close()?;497498 let after = match final_eval {499 Some(eval) => eval,500 None => evaluate(&runtime, &model, EVALUATION_SEED)?,501 };502 println!(503 " trained: mean return {:+.2} ({} completed episodes)",504 after.mean_completed_return, after.completed_episodes,505 );506 println!(507 " improvement: {:+.2}",508 after.mean_completed_return - before.mean_completed_return,509 );510511 // Checkpoint save + reload parity verification.512 let checkpoint = std::env::temp_dir().join("oars_lunar_lander_2d_ppo.oam");513 oa::ml::save_checkpoint(&checkpoint, &model, &optimizer)?;514 let restored_model = CategoricalActorCritic::new(CategoricalActorCriticConfig {515 observation_size: LUNAR_LANDER_2D_OBSERVATION_SIZE,516 action_count: LUNAR_LANDER_2D_ACTION_COUNT,517 hidden_size: HIDDEN_SIZE,518 seed: TRAINING_SEED,519 })?;520 let mut restored_optimizer = AdamW::new_with_hyperparameters(521 restored_model.all_parameters()?,522 LEARNING_RATE,523 0.9,524 0.999,525 1.0e-8,526 0.0,527 )?;528 oa::ml::load_checkpoint(&checkpoint, &restored_model, &mut restored_optimizer)?;529 let restored = evaluate(&runtime, &restored_model, EVALUATION_SEED)?;530 std::fs::remove_file(&checkpoint).expect("remove LunarLander2d checkpoint");531532 println!(533 " training: {:.2}s wall · {:.2} ms/update wall · {:.2} ms/update GPU · {} transitions",534 wall.as_secs_f64(),535 snapshot.wall_ms_per_step(),536 snapshot.gpu_timing_stats().mean_ms,537 u64::from(ENVIRONMENTS) * HORIZON as u64 * options.rollouts,538 );539 println!(540 " checkpoint: restored return {:+.2} · AdamW step {}",541 restored.mean_completed_return,542 restored_optimizer.step_count(),543 );544 assert!((restored.mean_completed_return - after.mean_completed_return).abs() < 1e-4);545 assert_eq!(restored_optimizer.step_count(), optimizer.step_count());546547 if !options.skip_plots {548 std::fs::create_dir_all(&options.output)549 .map_err(|error| oa::Error::io("create tutorial output directory", error))?;550551 // Pick a visually clean seed from a small deterministic pool for the trained demo filmstrip.552 let mut best_frames = Vec::new();553 let mut best_counts = [0.0_f32; 4];554 let mut best_return = f32::NEG_INFINITY;555 for offset in 0..8_u64 {556 let (frames, counts) = record_episode(&runtime, &model, DEMO_SEED + offset)?;557 let ret = frames558 .last()559 .map(|f| f.episode_return)560 .unwrap_or(f32::NEG_INFINITY);561 let landed = frames562 .last()563 .is_some_and(|f| f.outcome == LunarLander2dOutcome::Landed);564 let best_landed = best_frames565 .last()566 .is_some_and(|f: &LunarLander2dFrameState| f.outcome == LunarLander2dOutcome::Landed);567 if (landed && !best_landed) || (ret > best_return && (landed || !best_landed)) {568 best_return = ret;569 best_frames = frames;570 best_counts = counts;571 }572 }573574 let untrained_picks = pick_filmstrip_frames(575 &untrained_frames,576 [577 "1. Spawn",578 "2. Early flight",579 "3. Late flight",580 "4. Final state",581 ],582 );583 let untrained_refs: Vec<(&str, LunarLander2dFrameState)> = untrained_picks584 .iter()585 .map(|(s, f)| (s.as_str(), f.clone()))586 .collect();587 let fig_untrained = plots::filmstrip_figure(588 &runtime,589 "LunarLander-2D untrained policy (random actor-critic)",590 &untrained_refs,591 )?;592593 let fig_training =594 plots::training_history_figure(&eval_rollouts, &eval_returns, &total_losses, &entropies);595596 let trained_alts: Vec<f32> = best_frames.iter().map(|f| (f.y - 0.70).max(0.0)).collect();597 let trained_vy: Vec<f32> = best_frames.iter().map(|f| f.vy).collect();598 let fig_eval = plots::before_after_figure(599 before.mean_completed_return,600 after.mean_completed_return,601 restored.mean_completed_return,602 &trained_alts,603 &trained_vy,604 &best_counts,605 );606607 let trained_picks = pick_filmstrip_frames(608 &best_frames,609 [610 "1. Spawn",611 "2. Early flight",612 "3. Late flight",613 "4. Final state",614 ],615 );616 let trained_refs: Vec<(&str, LunarLander2dFrameState)> = trained_picks617 .iter()618 .map(|(s, f)| (s.as_str(), f.clone()))619 .collect();620 let fig_trained = plots::filmstrip_figure(621 &runtime,622 "LunarLander-2D trained PPO policy flight",623 &trained_refs,624 )?;625626 for (name, fig) in [627 ("01_untrained_filmstrip.jpg", &fig_untrained),628 ("02_training_history.jpg", &fig_training),629 ("03_before_after_eval.jpg", &fig_eval),630 ("04_trained_filmstrip.jpg", &fig_trained),631 ] {632 let path = options.output.join(name);633 let path_str = path634 .to_str()635 .ok_or_else(|| oa::Error::invalid_argument("output path must be UTF-8"))?;636 fig.save_to_on(&runtime, path_str)?;637 }638 if let Some(last) = best_frames.last() {639 println!(640 " demo ep: {} steps · outcome '{}' · return {:+.1}",641 last.step,642 last.outcome.label(),643 last.episode_return,644 );645 }646 println!(647 " figures: wrote 4 dark-theme 2D Vulkan/plot JPEGs to {}",648 options.output.display()649 );650 }651652 Ok(())653}654
plots.rs
1use oa::plot::{BarStyle, Figure, FigureConfig, LineStyle, Theme};2use oa::ui::UiStyle;3use oa::{Result, Runtime};4use oasdk::ml::rl::{LunarLander2dFrameState, render_lunar_lander_2d_texture};56const ACTION_LABELS: [&str; 4] = ["Nothing", "Left eng", "Main eng", "Right eng"];78fn figure(title: &str, rows: i32, cols: i32, width: u32, height: u32) -> Figure {9 Figure::new(FigureConfig {10 title: title.into(),11 rows,12 cols,13 width,14 height,15 theme: Theme::Dark,16 ..FigureConfig::default()17 })18}1920/// Render four 2D Lunar Lander episode frames on the GPU into a 2x2 labeled filmstrip.21pub(super) fn filmstrip_figure(22 runtime: &Runtime,23 title: &str,24 frames: &[(&str, LunarLander2dFrameState)],25) -> Result<Figure> {26 let mut fig = figure(title, 2, 2, 1280, 780);27 for (idx, (caption, frame)) in frames.iter().take(4).enumerate() {28 let row = (idx / 2) as i32;29 let col = (idx % 2) as i32;30 let tex = render_lunar_lander_2d_texture(runtime, 600, 340, frame, caption)?;31 let ax = fig.ax(row, col);32 ax.imshow(tex);33 ax.grid(false);34 ax.legend(false);35 }36 Ok(fig)37}3839/// Dark-theme training history: held-out evaluation return + PPO loss & entropy.40pub(super) fn training_history_figure(41 eval_rollouts: &[f32],42 eval_returns: &[f32],43 total_loss: &[f32],44 entropies: &[f32],45) -> Figure {46 let pal = UiStyle::default().data_palette;47 let blue = pal[0];48 let green = pal[2];49 let purple = pal[3];50 let mut fig = figure("LunarLander-2D PPO training history", 1, 2, 1280, 460);5152 {53 let ax = fig.ax(0, 0);54 ax.title("Held-out evaluation return (64 envs)");55 ax.x_label("PPO rollout");56 ax.y_label("Mean completed return");57 ax.plot_xy(58 eval_rollouts,59 eval_returns,60 LineStyle {61 color: green,62 label: "PPO mean return".into(),63 width: 2.5,64 ..LineStyle::default()65 },66 );67 ax.grid(true);68 ax.legend(true);69 }7071 {72 let rollouts: Vec<f32> = (1..=total_loss.len()).map(|i| i as f32).collect();73 let ax = fig.ax(0, 1);74 ax.title("PPO policy entropy (max ln 4 = 1.39) & loss");75 ax.x_label("PPO rollout");76 ax.y_label("Entropy (nats) / scaled loss");77 ax.plot_xy(78 &rollouts,79 entropies,80 LineStyle {81 color: purple,82 label: "Policy entropy".into(),83 width: 2.4,84 ..LineStyle::default()85 },86 );87 // Normalize total loss into a comparable visual scale if very large.88 let max_loss = total_loss89 .iter()90 .copied()91 .fold(1.0_f32, |acc, v| acc.max(v.abs()));92 let scaled_loss: Vec<f32> = total_loss.iter().map(|v| v / max_loss).collect();93 ax.plot_xy(94 &rollouts,95 &scaled_loss,96 LineStyle {97 color: blue,98 label: "Normalized total loss".into(),99 width: 2.0,100 ..LineStyle::default()101 },102 );103 ax.grid(true);104 ax.legend(true);105 }106107 fig108}109110/// Dark-theme before/after comparison: held-out mean returns + episode action usage.111pub(super) fn before_after_figure(112 before_return: f32,113 after_return: f32,114 restored_return: f32,115 trained_altitudes: &[f32],116 trained_vy: &[f32],117 action_counts: &[f32; 4],118) -> Figure {119 let pal = UiStyle::default().data_palette;120 let blue = pal[0];121 let coral = pal[1];122 let green = pal[2];123 let amber = pal[4];124 let mut fig = figure(125 "Before vs. after PPO evaluation and flight telemetry",126 1,127 3,128 1440,129 460,130 );131132 {133 let ax = fig.ax(0, 0);134 ax.title("Held-out mean return (64 envs)");135 ax.y_label("Mean completed return");136 ax.bar(137 &[before_return, f32::NAN, f32::NAN],138 BarStyle {139 color: coral,140 label: "Untrained".into(),141 ..BarStyle::default()142 },143 );144 ax.bar(145 &[f32::NAN, after_return, f32::NAN],146 BarStyle {147 color: blue,148 label: "Trained PPO".into(),149 ..BarStyle::default()150 },151 );152 ax.bar(153 &[f32::NAN, f32::NAN, restored_return],154 BarStyle {155 color: green,156 label: "Restored .oam".into(),157 ..BarStyle::default()158 },159 );160 ax.categories(&["Untrained", "Trained PPO", "Restored .oam"]);161 let min_y = before_return162 .min(after_return)163 .min(restored_return)164 .min(-20.0)165 * 1.15;166 let max_y = before_return167 .max(after_return)168 .max(restored_return)169 .max(50.0)170 * 1.15;171 ax.limits(-0.5, 2.5, min_y, max_y);172 ax.grid(true);173 ax.legend(true);174 }175176 {177 let ax = fig.ax(0, 1);178 ax.title("Trained episode altitude & vertical speed");179 ax.x_label("Step (50 Hz)");180 ax.y_label("Meters / m/s");181 let steps: Vec<f32> = (0..trained_altitudes.len()).map(|i| i as f32).collect();182 ax.plot_xy(183 &steps,184 trained_altitudes,185 LineStyle {186 color: blue,187 label: "Altitude (m)".into(),188 width: 2.4,189 ..LineStyle::default()190 },191 );192 ax.plot_xy(193 &steps,194 trained_vy,195 LineStyle {196 color: amber,197 label: "Vertical vel (m/s)".into(),198 width: 2.0,199 ..LineStyle::default()200 },201 );202 ax.grid(true);203 ax.legend(true);204 }205206 {207 let ax = fig.ax(0, 2);208 ax.title("Trained policy action mix");209 ax.y_label("Step count");210 ax.bar(211 action_counts,212 BarStyle {213 color: green,214 label: "Actions".into(),215 ..BarStyle::default()216 },217 );218 ax.categories(&ACTION_LABELS);219 let max_c = action_counts.iter().copied().fold(10.0_f32, f32::max);220 ax.limits(-0.5, 3.5, 0.0, max_c * 1.18);221 ax.grid(true);222 ax.legend(false);223 }224225 fig226}227
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.