BattleCarsLearn

Docs

BattleCarsLearn trains Rocket League bots with PPO, in Rust:

Requirements

to...you need
build, train and export a botRust (1.95+), an NVIDIA GPU with CUDA, and the collision meshes dumped from your Rocket League install
play an exported botonly RLBot v5 and the bot

A bot is a Game

Your bot is one type implementing bcl_sim::Game: what it sees, what it can do, and what it gets rewarded for.

use bcl_sim::prelude::*;

pub struct MyBot;

impl Game for MyBot {
    fn obs_builder(&self) -> Box<dyn ObsBuilder> { Box::new(DefaultObs::new(GameMode::Soccar)) }
    fn action_parser(&self) -> Arc<dyn ActionParser> { Arc::new(LookupTableAction::new()) }
    fn reward(&self) -> CombinedReward { CombinedReward::new(vec![(Box::new(TouchReward), 1.0)]) }
    fn terminals(&self) -> Vec<Box<dyn TerminalCondition>> { vec![Box::new(GoalScored)] }
    fn state_setter(&self) -> Box<dyn StateSetter> { Box::new(KickoffSetter) }
    // optional: name, env_config (tick skip, team sizes), arena_config, other_modes, metrics,
    // teacher_view, rating_terminals
}

You also need two one-line programs: the trainer, bcl::cli::run(MyBot), and the RLBot bot, bcl_rlbot::main(MyBot). Put the game and the bot in a package that does not depend on bcl, and the trainer in one that does (see example/ and example/train/). That keeps the bot a ~1 MB program with no GPU or training code.

Custom observations, rewards, setters and terminals are types implementing ObsBuilder, Reward, StateSetter and TerminalCondition. example/src/game.rs has a custom reward you can copy from.

Running

cargo dist

This builds the bot and its trainer, then puts everything they need into a run folder, dist/ (set by the dist line in example/Cargo.toml). A bot is any package whose Cargo.toml has a [package.metadata.bcl] section; its trainer goes in a package named <bot>-train. If the workspace has one bot, cargo dist builds it. If it has several, pick one with cargo dist --bot <package>, or build them all with cargo dist --all.

dist/
  example-bot-train.exe    the trainer
  example-bot.exe          the RLBot bot
  example.toml             training settings
  collision_meshes/        paste the meshes dumped from your Rocket League install here
  checkpoints/
  bots/

Then:

# train (resumes the newest checkpoint automatically)
dist/example-bot-train dist/example.toml

# make an RLBot bot from the newest checkpoint (dist/bots/ExampleBot)
dist/example-bot-train export dist/checkpoints/example

# check the exported bot offline
dist/example-bot-train bot-test

Running cargo dist again after a code change only replaces the two programs. Your config, checkpoints and generated rlbot bots stay. Relative paths in a config are relative to the config file's folder.

Every config field has a default (see crates/bcl/src/config.rs), so the TOML file only needs the fields you change. checkpoint_load = "latest" (the default) resumes the newest checkpoint in checkpoints_folder, and "" starts fresh.

Keys while training: p pauses, c saves a checkpoint, and q saves a checkpoint and quits once the current iteration ends.

Example config

n_threads = 16
arenas_per_thread = 96
ts_per_iteration = 200000
ppo_batch_size = 200000
ppo_minibatch_size = 50000
ppo_epochs = 1
policy_lr = 2e-4
critic_lr = 2e-4
shared_layer_sizes = [1024, 512]
policy_layer_sizes = [1024, 512, 512]
critic_layer_sizes = [1024, 512, 512]
activation = "leaky_relu"
mirror = true                   # left/right mirror augmentation
fp16 = true                     # fp16 matmuls + dynamic loss scaling: ~2x faster PPO updates
checkpoints_folder = "checkpoints/run10"
checkpoint_load = "latest"      # "" = fresh start
save_every_ts = 5000000

[skill]                         # policy version pool + Elo
enabled = true
ts_per_version = 25000000
update_interval = 16

[wandb]                         # wandb config
enabled = true
project = "ExampleBot"
group = "selfplay-1v1"
run_name = "run10"

Weights & Biases

dist/example-bot-train wandb-login

This asks for your API key once (get it from wandb.ai/authorize; it isn't shown while you paste it). It checks the key with W&B and saves it in ~/_netrc (~/.netrc on Linux and macOS), the same entry wandb login writes, so you don't need Python. After that, a run only needs [wandb] enabled = true in its config. You can set the WANDB_API_KEY environment variable instead, and it takes priority. When a run resumes from a checkpoint, it continues the same W&B run, and its charts pick up where they stopped.

Iterations and speed

An iteration keeps collecting until ts_per_iteration steps are in finished episodes, the same way rlgym_ppo does it. Episodes still running carry over to the next iteration, so an iteration's size depends on when episodes end. Arenas that start together end together, so with many arenas an iteration can be several times ts_per_iteration. The PPO update costs about the same per row at any iteration size, but each new iteration size needs a one-time GPU kernel compile. That takes 15-25 s and happens a handful of times in the first ~10 iterations of a run. The first iteration of every run also spends ~75 s compiling everything.

Measure speed with Rows Trained per Second (rows the update trained on, divided by iteration time) over a few dozen iterations. Overall Steps per Second divides collected steps by iteration time, so it reads too high when an iteration collects fewer steps than it trains on.

The update uploads its training data to the GPU as whole tensors, up to ppo_resident_limit_mb (default 1024). Above that, it uploads each minibatch's rows as they're needed, so no iteration size can ask for one huge buffer.

Every iteration's report has a PPO/* breakdown of the update and Time/* timings for the work around it. With profile_update = true, the GPU is synced after each stage, so the timings include GPU work, and the minibatch time is split further into forward, loss, backward and grad accumulation. Syncing costs ~5%, so turn it off once you've found where the time goes.

Extra charts

Game::metrics() can return a GameMetrics. It writes one value per name every step, and its optional report turns an iteration's totals (sum, min, max and count of each value, over all arenas) into the charted numbers: averages by default, or ratios, rates and extremes. example/src/game.rs charts the average ball height, the top car speed and touches per goal. Charts appear under Metrics/.

Raycasts in rewards

A reward can query the arena once per step in Reward::query_arena, called after pre_step with the arena at the observed state. Cast rays there with Arena::cast_rays (any number per call, traced four at a time) or test shapes with Arena::test_collision, and keep the results for get_reward:

fn query_arena(&mut self, arena: &Arena, state: &GameState) {
    let pos = state.players[0].phys.pos;
    let [hit] = arena.cast_rays([RaycastQuery { from: pos, to: pos - Vec3A::Z * 5000.0, include_dynamics: false }]);
    self.floor_dist = hit.map(|h| pos.z - h.hit_point.z);
}

This works in rewards only. Observations have no arena hook, because the RLBot bot has no arena to cast rays in.

Watching training live

render = true
render_speed = 1.0            # 1 = real time, 2 = double speed, 0 = as fast as possible
# render_ip = "127.0.0.1"     # where the frames go (UDP)
# render_port = 9273

One extra arena runs on its own thread, separate from the training arenas. It plays the newest policy (swapped in after every iteration) on a CPU copy of the network and sends every step as a JSON frame over UDP. You can open any viewer listening on that port, such as RocketSimVis (port 9273), and close it whenever you like, because nothing waits for it. It doesn't affect training speed, and training never uses the rendered games.

Training against past versions

With [past_self], a fraction of arenas play against a frozen version of the policy instead of the current one. The versions come from the Elo version pool, so [skill] must be enabled. Arenas are assigned at episode boundaries, the learner plays a random side, and only the learner's cars produce training data. Results are reported as PastSelf/*.

[past_self]
enabled = true
fraction = 0.2       # share of episodes against a past version
n_opponents = 4      # versions in use at once; one at a time is rotated out for a fresh pick
recent_bias = 1.0    # 0 = uniform over the pool; higher favours recent versions
prioritize_losses = false # lean toward versions the bot loses to (losses_share of the picks)
losses_share = 0.5   # share of the choice made by loss priority
losses_power = 2.0   # priority = (1 - learner's score against the version)^power

prioritize_losses is prioritised fictitious self-play, the AlphaStar league idea. Every version keeps a running score of how the learner does against it, and losses_share of the picks go to the versions where that score is lowest. The scores are saved with the checkpoint. This matters most when the learner still loses to some old versions, for example because it forgot a skill or because strategies beat each other in a circle.

Exploration bonus

[explore] helps the policy try actions, or sequences of actions, that it almost never picks. The learner's cars sample from p' = (p + b) / (1 + sum b), and the update scores the chosen action under the same p', so the PPO ratio stays exact. Past-self opponents, rating games, the live view and exported bots all play the plain policy.

[explore]
enabled = true
mode = "repeat"
channel = "roll"             # "" = repeat the exact action
exclude = ["jump"]
air_only = true
min_height = 300.0
max_ball_distance = 500.0
bonus = 0.5
half_life_ts = 500000000     # 0 = constant
min_bonus = 0.01
obs_has_previous_action = true

The bonus doesn't make the policy learn the target actions faster. It makes the policy reach the states that follow them. The policy comes to rely on it, so fade it out slowly, and compare Explore/Own Target Prob (the plain policy) with Explore/Behaviour Target Prob (what was actually sampled).

Teachers

Kickstarting

[teacher] mode = "kickstart" runs PPO as usual and adds kickstart_weight * KL(teacher || student) on the student's own states. The weight falls linearly to 0 over kickstart_decay_steps; after that the teacher is dropped and costs nothing.

Transfer learning

mode = "transfer" is pure imitation of the teacher, with no rewards and no critic. It uses KL or GigaLearn's L1 loss. teacher_rollout_fraction sets who drives: 1.0 is the teacher only, and lower values mix in the student DAgger-style. Checkpoints are normal ones, so you can switch the mode off and PPO continues from the result.

[teacher]
policy = "checkpoints/other_run/123456789"
mode = "kickstart"                           # or "transfer"
kickstart_weight = 1.0
kickstart_decay_steps = 300000000
use_teacher_view = false
[teacher.transfer]
batch_size = 50000
epochs = 5
use_kl_div = false
loss_scale = 500.0
teacher_rollout_fraction = 1.0
timestep_limit = 50000000

If the teacher uses a different format (another obs builder or action table), describe it in Game::teacher_view(). Without an action_map, BCL builds one: each student action maps to the teacher action with the same controls, comparing only what acts on the ground (throttle, steer, jump, boost, handbrake) or in the air (pitch, yaw, roll, jump, boost). Where nothing matches exactly it takes the nearest action with the same buttons and prints the worst matches at startup. If a student action has no teacher action with the same buttons, training won't start. For tables that differ a lot, write your own action_map; it's checked every step.

Timing

Physics always runs at 120 Hz, the same as the game. EnvConfig::tick_skip sets the number of ticks per step, and EnvConfig::action_delay sets how many of those ticks run after the observation. The default is tick_skip - 1, the rlgym_sim and GigaLearn timing.

Game modes and mutators

Game::arena_config() sets the RocketSim arena: game mode, mutators (gravity, boost, ball settings, ...) and memory mode. The default is soccar with standard rules.

fn arena_config(&self) -> ArenaConfig {
    let mut m = MutatorConfig::new(GameMode::Soccar);
    m.gravity.z = -325.0;
    ArenaConfig::new(GameMode::Soccar).with_mutators(m)
}

The built-in obs builders have one input per boost pad, so give them the same mode: DefaultObs::new(GameMode::Hoops). Mirror augmentation, the shot and save tracker and the RLBot bot follow the mode on their own.

mode
soccartrained and tested
hoopssupported. Shots are predicted from the ball's flight, so bank shots off the backboard don't count as shots
snowday, heatseekersupported, on the soccar field
dropshotwip

More than one mode

A bot for several modes returns a Game per extra mode from Game::other_modes(), each with its own arena_config and whatever else differs (rewards, setters, ...).

fn other_modes(&self) -> Vec<Arc<dyn Game>> { vec![Arc::new(MyHoopsBot)] }

Training splits the arenas evenly over the modes and checks at startup that they all build the same observation width and action count. DefaultObs is as wide as the mode's boost pads (34 in soccar, 20 in hoops), so mixed modes need an obs builder with one width for all of them. The exported bot plays the game for the mode RLBot reports for the match, and the first one (with a warning) for a mode it doesn't have. Each mode needs its folder in collision_meshes.

Team sizes

EnvConfig::team_size plays the same nvn in every episode. EnvConfig::team_sizes picks a mode for each episode instead, as (blue, orange) cars. Uneven modes are allowed, and listing a mode twice doubles its share:

fn env_config(&self) -> EnvConfig {
    EnvConfig { team_sizes: vec![(1, 1), (2, 2), (3, 3), (2, 1), (3, 2)], ..Default::default() }
}

Self-play controls both teams, so in a 2v1 the bot practises being outnumbered and outnumbering at the same time. Observations get padded to the biggest teams in the list. Missing cars are zeros, and one presence flag per slot says which slots hold a car. The obs builder needs player_layout(); both built-in ones have it. Set player_encoder_layer_sizes too, so that empty slots are left out of the encoder's pooling. A teacher view (use_teacher_view) can't be combined with team_sizes yet.

Elo games use only the even modes in the list. An exported bot plays any match up to the biggest teams it was trained for, against the closest cars.

Long runs

All of these are off by default.

[lr_schedule]
kind = "cosine"           # constant | linear | cosine | exponential
end_scale = 0.3           # learning rate multiplier reached at end_steps
end_steps = 5000000000    # then it stays there

regen_strength = 1e-4     # pulls weights back toward their initial values after every step
regen_noise = 0.0         # gaussian noise added after every step
adv_percentile_scaling = true
adv_scale_ema = 0.99
gae_finite_horizon = true

Categorical critic

value_bins = 101
value_range = 5.0   # in standardized return units (default 10.0)
value_coef = 1.0    # critic loss weight

With value_bins > 1, the critic predicts a distribution over that many bins on [-value_range, value_range] instead of one number. It's trained with the HL-Gauss cross entropy (Imani & White 2018, Farebrother et al. 2024), and the value it reports is that distribution's mean. 0 (the default) keeps the plain MSE critic. It changes the critic's shape, so a checkpoint only resumes with the same setting. Only the critic changes, so exported bots are unaffected.

Lookahead

The policy looks ahead in the real simulator. For a fraction of the learner's steps:

  1. The policy's top candidates actions are drawn without replacement from one Gumbel draw (Gumbel top-k).
  2. On a copy of the arena, each candidate is held for segments steps while the other cars keep their actions.
  3. Each candidate is scored with its reward on those steps, plus the critic's discounted value where it ends up.
  4. The scores define a target pi * exp(A / eta) over the candidates. eta is set each iteration so that the mean KL(target || pi) is kl_target, as in SPO (Macfarlane et al., NeurIPS 2024), and weight * KL(target || policy) on the searched rows is added to the PPO loss.

The car still plays its own sample, so PPO stays on-policy. This is policy improvement by search, like AlphaZero's, but one level deep and with the exact simulator as the model. The worker threads play the searches while the next step is being inferred.

[lookahead]
enabled = true
fraction = 0.15     # share of learner steps searched
candidates = 2
segments = 2        # steps each candidate is held
weight = 1.0        # weight of the KL(target || policy) term
kl_target = 0.2

Expect around three quarters of the plain throughput with the defaults. It's meant to be used with the categorical critic. Charts: Lookahead/* (searched rows, target shift KL, eta, mean absolute advantage) and Time/Lookahead Targets.

Rewards on the copies are evaluated with CombinedReward::peek. A stateful reward (one that keeps something between steps) should implement Reward::fork, so that the copies step a copy of it through pre_step like a real game. Parts without a fork are only read on the copies, so a reward that compares with its previous step sees the real previous step. EventReward, ZeroSumReward and ConditionalReward already fork.

Exported bots can run the same search to pick their actions. At every decision the bot rebuilds the arena from the RLBot packet, runs it forward by the action delay, holds each of the policy's top candidates actions for segments steps while the other cars keep their last input, and plays the one with the best reward plus critic value.

[play_search]
candidates = 2   # < 2 = off (the default)
segments = 2
rewards = true   # false = critic only

Training ignores this section; export reads it from the checkpoint's config.toml, or from export --config <toml> to turn it on for a checkpoint trained without it. The bot folder then also holds the critic (critic.bcl) and a copy of the collision meshes. The rewards come from the bot's Game, so build the bot from the same game the checkpoint trained with, or score with the critic alone (rewards = false). A decision with search costs about 5 ms on the CPU.

<trainer> bot-test <bot folder> [seconds] vs-plain [k=N] [segs=N]

This plays the bot with search against itself without, one game per CPU thread from kickoffs, with 2% random actions on both sides. k and segs override the folder's settings.

Overlapped collection

overlap_collect = true

This collects the next batch while the update trains on the current one, so the policy that collects is one update behind. In our tests it took plain training from about 91k to 103k steps/s, and lookahead from 50k to 57k, at a small cost per step: at equal steps, it scored 45% of the goals in matches against the same run without it. Off by default.

Playing in RLBot v5

<trainer> export <checkpoint or run folder> [--out DIR] [--name NAME] [--developer WHO] [--sample] [--bot-exe PATH] [--config TOML]
file
bot.tomlRLBot's agent config: name, agent id, run command
<bot>.exethe bot program (~1 MB)
policy.bclthe policy weights (~7 MB for a 1024-512 network)
bot.jsontick skip, action delay, team sizes, action selection, observation normalization, play-time search settings
critic.bcl, collision_meshes/only with [play_search]

In RLBot v5, add the folder (RLBot finds bot.toml) and put the bot in a match. The bot doesn't need a GPU or Python, and it needs collision meshes only with [play_search], which export copies into the folder.

<trainer> bot-test <bot folder> [seconds] checks it offline. It plays the exported bot in RocketSim through RLBot packets at 120 Hz, then plays the same policy the way training runs it:

600 s self-play, 58M-step checkpointtouches/mincar speeddistance to ball
through the bot (packets, 120 Hz)8.03981022
directly (training's path)8.03971046

Car fields the packet doesn't carry (smoothed handbrake, jump and air timers, the boost latch, the last flip's direction and timer) are rebuilt by replaying RocketSim's per-tick rules, and tests check them against the simulator on every tick. Another test runs the play-time search on an arena rebuilt from packets next to the arena they came from: same best candidate on 300 of 300 states. One known approximation remains: the packet has no body contact info, so "turtled" is estimated from the car's hitbox touching the floor.

Tests

cargo test --release --workspace

The tests cover GAE, the action table and masks, the mirror map, the game event tracker, config parsing, metrics, lookahead's arena copies and reward forks, multi-mode games, and the RLBot side (including the play-time search on rebuilt arenas), where sim states turned into packets and back must give the bot the same observations training saw. Tests that need the simulator look for collision meshes in BCL_COLLISION_MESHES, then in dist/collision_meshes, and are skipped if neither has them. Checks that need a GPU or take longer are examples in bcl-ppo and bcl-sim.

Speed

Ryzen 7 3700X + RTX 2080 Ti, 16 threads x 96 arenas, a 1024-512 shared trunk with 1024-512-512 heads, mirror on:

fp32fp16
environment only (random actions)~1.05M steps/s
collection (policy acting)~340k steps/s~340k steps/s
overall (collection + PPO update)~55k steps/s~109k steps/s

The fused LayerNorm (fused_layer_norm = true, the default) replaces Burn's LayerNorm with a few CubeCL kernels and roughly halves its backward pass. Set it to false to use Burn's own LayerNorm.

Credits