Behavior World Model (BWM) expands selected nuPlan scenes into behaviorally varied scenarios for SimEngine. The public BWM module is inference-only: users load the provided checkpoint, generate validated scenario candidates, and explicitly publish them in the SimEngine scenario format.
Run all commands below from the WorldEngine repository root.
- Prerequisites
- Configuration Model
- Validate Before Generation
- Generate Scenarios
- Publish for SimEngine
- Output Contract
- Scene Quality Filtering
- Troubleshooting
Create the bwm environment by following the
Installation Guide.
Then activate it:
conda activate bwmDownload the BWM checkpoint
to data/alg_engine/ckpts/nuplan.ckpt under the repository root.
If you downloaded the WorldEngine dataset before this checkpoint was added,
fetch this file separately; you do not need to download the full dataset again.
BWM uses data shared with the other WorldEngine modules. The default configuration expects:
data/
├── alg_engine/
│ └── ckpts/
│ └── nuplan.ckpt
├── raw/
│ ├── nuplan/
│ │ └── dataset/
│ │ ├── maps/
│ │ └── nuplan-v1.1/
│ │ ├── trainval/
│ │ └── sensor_blobs/
│ └── openscene-v1.1/
│ └── meta_datas/
│ ├── trainval/
│ └── test/
└── sim_engine/
└── assets/
└── navtrain/
└── assets/
└── <log-name>-<lidar-token>/
└── video_scene_dict.pkl
See Data Organization for the complete repository layout. If your data lives elsewhere, override the corresponding paths in your BWM scenario YAML. Relative paths are resolved against the WorldEngine repository root.
BWM uses two configuration layers:
projects/BWM/configs/default.yamlowns model, runtime, data, staging, and publication defaults.- A file under
projects/BWM/configs/scenarios/identifies one generation job and references an AlgEngine SceneFilter YAML.
The SceneFilter remains the single source of truth for scene membership. It
provides log_names and/or tokens; do not duplicate those lists in the BWM
scenario YAML.
Base-scene selection applies these rules:
| SceneFilter selection | Eligible scenes |
|---|---|
Both log_names and tokens |
The log and token must each belong to their respective list. |
Only log_names |
Scenes belonging to those logs. |
Only tokens |
Scenes with those tokens. |
Either list explicitly set to [] |
No scenes. |
Both fields omitted or null |
Configuration error. |
An omitted or null field imposes no restriction on that field. The lists
are independent allowlists, not pairs matched by list position. A selected
scene must have <log-name>-<lidar-token>/video_scene_dict.pkl under
digitaltwin_data_root; scenes without this asset are skipped. Existing
canonical staging outputs are also skipped during generation.
The included scenario config is:
# projects/BWM/configs/scenarios/navtrain_50pct_ep_1pct.yaml
scenario_name: navtrain_50pct_ep_1pct
data_type: navtrain_ep_per1
scene_filter_path: projects/AlgEngine/configs/navsim_splits/navtrain_split/e2e_vadv2_50pct_rare/navtrain_50pct_ep_1pct.yamlTo create a new generation job, add a similarly small file:
# projects/BWM/configs/scenarios/my_scenario.yaml
scenario_name: my_scenario
data_type: navtrain
scene_filter_path: projects/AlgEngine/configs/path/to/my_scene_filter.yamlUse a safe, unique scenario_name. It becomes both the staging directory
name and the published SimEngine scenario directory name.
The default config runs two tasks for each selected base scene, in this order:
| Task | Maximum attempts | Maximum accepted scenarios |
|---|---|---|
goal_conditional_copy_with_noise |
30 | 7 |
intent_attack_with_goal_selection |
20 | 3 |
Each task stops when it reaches either limit. An attempt includes candidates that cannot be generated, fail quality checks, or encounter a recoverable error; accepted scenarios have passed motion validation and NC/DAC checks. Defaults therefore allow up to 50 attempts and 10 accepted scenarios per base scene, but do not guarantee 10 successes. The budgets reset for each base scene.
For a normal run, inherit these defaults without adding any fields. To change a budget, add only the desired overrides to your BWM scenario YAML. For example, append:
generation:
tasks:
goal_conditional_copy_with_noise:
max_attempts: 10
max_success: 2This changes the first task to 10 attempts and 2 accepted scenarios. The
second task still inherits 20 and 3. Task execution order is fixed regardless
of YAML key order. Both limits must be non-negative integers; setting either
limit to 0 skips that task. Omitted values inherit from the default config.
These settings control repeated candidate generation. model.diffuser.steps
controls the diffusion steps inside one inference call and remains 32 by
default. Generation processes scenes and tasks sequentially with one loaded
model; this entry point does not provide a worker-pool setting.
save_scenario_description defaults to true, so accepted scenarios are
saved to the canonical staging PKL for publication and rollout. For a
diagnostic run, append this to your BWM scenario YAML:
save_scenario_description: falseGeneration, metric checks, logs, and visualizations still run, but the final
scene PKL is not written. This option does not reduce inference work or
delete existing files. A fresh run with saving disabled produces no scene
PKLs to publish. Use a new scenario_name for diagnostics or changed budgets:
existing canonical staging outputs are skipped even when saving is disabled.
Common paths that may be overridden are:
checkpoint: data/alg_engine/ckpts/nuplan.ckpt
digitaltwin_data_root: data/sim_engine/assets/navtrain/assets
openscene_data_root: data/raw/openscene-v1.1
scenario_builder:
data_root: data/raw/nuplan/dataset/nuplan-v1.1/trainval
map_root: data/raw/nuplan/dataset/maps
sensor_root: data/raw/nuplan/dataset/nuplan-v1.1/sensor_blobsAlways validate a new config first:
scripts/run_bwm.sh validate \
--config projects/BWM/configs/scenarios/my_scenario.yamlValidation composes both configuration layers, loads the referenced SceneFilter, checks generation controls and required runtime inputs, anchors repository-relative paths, and reports the selected log/token counts. Inspect the effective budgets and saving flag before generation. With defaults, the summary includes:
generation_execution: sequential
generation.tasks.goal_conditional_copy_with_noise: max_attempts=30, max_success=7
generation.tasks.intent_attack_with_goal_selection: max_attempts=20, max_success=3
save_scenario_description: true
runtime_unset: none
Validation does not load the model or generate files. Invalid budget values, unknown task names, and non-boolean saving flags are rejected before model loading. The same effective settings are printed when generation starts.
Start generation with the same config:
scripts/run_bwm.sh generate \
--config projects/BWM/configs/scenarios/my_scenario.yamlThe default staging layout is:
projects/BWM/outputs/
└── my_scenario/
└── <source>/
├── <source>.pkl
└── generated visualizations
Each canonical source file must use the exact
<source>/<source>.pkl layout. Visualizations and other files in the source
directory are not publication inputs.
Generation applies several quality gates before accepting a candidate, including agent temporal validity, dynamic-vehicle movement and proximity, trajectory validity, no-collision (NC), and drivable-area compliance (DAC). Only accepted scenarios are written to the canonical source pickle. See Scene Quality Filtering for the detailed stage-by-stage rules and current thresholds.
Generation and publication are separate operations. Publish only after reviewing the staging output:
scripts/run_bwm.sh publish \
--config projects/BWM/configs/scenarios/my_scenario.yamlThe publisher discovers immediate canonical source files, validates their pickle mappings and required SimEngine fields, rejects duplicate scenario IDs, and writes:
data/sim_engine/scenarios/augmented/
└── my_scenario/
└── all_scenarios.pkl
Publication is atomic and refuses to replace an existing
all_scenarios.pkl by default. To intentionally replace it:
scripts/run_bwm.sh publish \
--config projects/BWM/configs/scenarios/my_scenario.yaml \
--overwriteThe destination pickle is a mapping from scenario ID to scenario description. It can be loaded with standard Python:
import pickle
from pathlib import Path
path = Path(
"data/sim_engine/scenarios/augmented/"
"my_scenario/all_scenarios.pkl"
)
with path.open("rb") as stream:
scenarios = pickle.load(stream)
print(f"Loaded {len(scenarios)} BWM scenarios")Next, follow Rollouts from BWM Scenarios
to select the published augmented input and run NR rollout with the base
scene assets. After automatic rollout export, follow
AlgEngine dataset verification
and fine-tuning configuration
to train on the generated observations and rewards.
Every published scenario contains the fields required by SimEngine:
id, name, token, dataset, map, log_length, sample_rate, base_timestamp,
metadata, cameras, lidar, object_track, sdc_id, map_features,
dynamic_map_states
The top-level mapping key must match the scenario's id and name. BWM
outputs use the dataset identifier bwm.nuplan.
The 2 Hz OpenScene sequence is exported with sample_rate: 10: SimEngine
interprets this field as a stride relative to nuPlan's 20 Hz, so each step
advances by 10 * 0.05 = 0.5 seconds.
BWM ego features use the nuPlan rear-axle position. On export, ego positions
are converted to vehicle centers, matching SimEngine's object_track
convention. Ego, other agents, and map features share one local origin;
subtract metadata.old_origin_in_current_coordinate to recover global
positions. SimEngine converts ego centers back to rear-axle poses before
rendering. NC/DAC evaluation uses the exported vehicle centers directly.
BWM model inputs use lane and lane-connector centerlines, matching the
training feature builder. Stop lines and crosswalks use polygon outlines.
The exported scenario retains lane topology in map_features. DAC uses the
complete nuPlan DRIVABLE_AREA stored as GeoJSON in
metadata.drivable_area, including road segments, intersections, generic
drivable areas, and car parks. The geometry retains polygon holes and uses
global coordinates; the metric converter applies
metadata.old_origin_in_current_coordinate to align it with local tracks.
Use a new scenario_name when changing generation settings or updating BWM,
then generate and publish the new output. Generation skips existing canonical
source files; republishing alone does not recompute trajectories or metadata.
The SceneFilter selects the base scenes for a generation job. The following checks filter agents before inference and validate generated candidates before they are written to staging.
Feature extraction
→ Agent temporal validity
→ Dynamic vehicle selection
→ Spatial proximity (skip inference if no candidates remain)
→ Direction-compatible lane goal selection (attack task)
→ Diffusion inference and successful dynamics optimization
→ Motion continuity and velocity consistency
→ Trajectory valid point check
→ No collision (NC) and drivable-area compliance (DAC)
→ Final acceptance gate
→ Write accepted scenarios to staging
During feature extraction, vehicles, pedestrians, and cyclists with fewer than 5 valid frames are excluded from the scene tensor.
Implementation: compute_features() in
feature_processor.py.
A vehicle is eligible for behavior modification when its cumulative displacement across valid positions is greater than 3.0 m. Displacement is the sum of Euclidean distances between successive valid positions; vehicles with fewer than two valid positions are excluded.
If no vehicle passes this check, the task sets scenario_valid=False and
skips inference.
Implementation: is_vehicle_moving() in
nuplan_utils.py.
Dynamic candidates must be valid at the fifth frame and satisfy both distance limits in the ego vehicle's coordinate frame at that frame:
| Distance from ego | Maximum absolute distance |
|---|---|
| Lateral | 5.0 m |
| Longitudinal | 15.0 m |
If no candidate remains, the task sets scenario_valid=False and skips
inference.
Implementation: filter_nearby_vehicles() in
scene_generator_v2.py.
For attack generation, candidates must additionally have all five historical frames present and finite. The attacker is sampled from the four closest filtered candidates, ranked at the fifth (current) frame. Other vehicles stay in log replay. Attack generation may extend an incomplete future track; it does not manufacture missing history.
Attack goals use valid, non-degenerate LANE / LANE_CONNECTOR centerline
segments. Stop-line and crosswalk outlines are not driving goals. A goal must:
- Lie within 15 degrees of the current heading, using wrapped angle differences.
- Be at a distance between
speed * (horizon - 1)andspeed * (horizon + 1), with the lower duration clamped to zero. Speed is the current velocity magnitude; horizon is the number of future steps times 0.5 seconds (8 seconds by default). - Have a lane heading within 60 degrees of both the current heading and the displacement toward the goal. Terminal velocity follows that heading.
The optional ego-endpoint target must pass the same geometric checks and be within 5 m of an eligible lane point with a compatible heading. If no goal passes, the attempt is rejected before inference; the last observed state is not reused as a fallback goal. These are conservative geometric screens, not a guarantee of route connectivity or dynamic feasibility.
The sampler retains hard terminal conditions. Every invoked dynamics or collision optimization must report success and return finite states. Failure rejects the entire attempt and logs the optimization stage and solver status; an unoptimized trajectory is no longer accepted as a fallback. Fully replayed tracks skip optimization. Collision optimization is invoked only when its collision detector identifies a conflict. These stricter rules may reduce yield within the same attempt budget.
Both generation tasks screen ego and modified vehicles in native BWM coordinates before export. Controlled tracks must have complete, finite states and positive dimensions. Checks cover all transitions involving a generated state, including history-to-future and penultimate-to-fixed-goal boundaries. Fully replayed tracks and wholly historical transitions are excluded from the motion limits.
The provisional defaults are:
Setting under motion_validation |
Default | Measurement |
|---|---|---|
max_speed_mps |
45.0 | Stored speed and displacement divided by 0.5 s |
max_acceleration_mps2 |
10.0 | Vector acceleration from position differences and stored velocities |
max_velocity_error_mps |
5.0 | Displacement-derived velocity minus the mean of the two endpoint velocities |
Override individual limits in the scenario YAML, for example:
motion_validation:
max_velocity_error_mps: 3.0Limits must be finite positive numbers. They are initial rejection
thresholds, not calibrated guarantees of physical realism. Review rejection
rates and retained trajectories on real generation runs before release.
Use a new scenario_name: existing staging files are skipped and are not
revalidated by publishing them again.
Implementation: motion_validation.py.
Before computing metrics for an agent, the pipeline counts its valid trajectory points:
| Valid points | Handling |
|---|---|
| 0 | Set NC and DAC to 0.0; skip metric computation. |
| 1–2 | Set NC and DAC to 0.1, emit a warning, and skip metric computation. |
| 3 or more | Compute NC and DAC over continuous valid segments. |
Zero valid points cause rejection at the final gate. The 0.1 fallback
for 1–2 points satisfies the current > 0 acceptance threshold, so these
short trajectories can pass this metric gate in isolation. Newly generated
controlled tracks must first pass the complete-track motion validation above.
Implementation: calculate_metrics_for_agent_from_sd() in
example_usage.py.
For trajectories with at least three valid points, metric computation uses
continuous valid segments of at least 3 points. If no such segment
exists, NC and DAC are both 0.0.
Within each segment, collision detection tests intersections between the agent's oriented bounding box and other objects at each valid timestep. Fault is assigned relative to the agent being evaluated:
| Collision type | Condition | At fault |
|---|---|---|
| Stopped track | Other object's speed is below 0.005 m/s | Yes |
| Active front | Moving object is ahead of the evaluated agent | Yes |
| Active lateral | Moving object is to the side or rear | No |
The stopped-track condition is checked first. NC uses the lowest score across collisions and segments:
| Outcome | NC score |
|---|---|
| At-fault collision with a vehicle, cyclist, or motorcyclist | 0.0 |
| At-fault collision with another object type | 0.5 |
| No at-fault collision | 1.0 |
Implementation: StandaloneMetricsCalculator in
standalone_metrics.py.
At each valid timestep, DAC measures the fraction of the agent's bounding box area overlapping the union of drivable-area polygons:
| Overlap fraction | DAC score at that timestep |
|---|---|
| 0 (completely off-road) | 0.0 |
| Greater than 0 and below 0.8 | The overlap fraction |
| 0.8 or greater | 1.0 (no penalty) |
The final score is the minimum across timesteps and valid segments. BWM exports include the complete native drivable geometry for polygons intersecting the 500 m query window around the scene origin. Empty or invalid native geometry raises an error during export or evaluation.
For supplied files without metadata.drivable_area, the metric converter
falls back to map_features. This can omit valid areas such as parts of
intersections; regenerate those files with BWM to include complete geometry.
In this fallback path, absent drivable-area map data defaults to 1.0.
The no-valid-segment rejection described above still applies.
Implementation: StandaloneMetricsCalculator in
standalone_metrics.py.
The pipeline checks ego and the controlled agents returned by the
generation task after the motion gate. Each checked agent must satisfy
NC > 0 and DAC > 0.
Checks stop at the first failure, and the entire candidate is discarded.
Passing agents receive metric_check_passed=True in their metadata.
Requested agents absent from object_track are skipped with a warning.
The threshold permits positive partial scores, including NC 0.5, DAC
below 0.8, and the short-trajectory fallback of 0.1. These are the
current acceptance rules; passing does not require NC and DAC to equal
1.0.
Accepted candidates are saved in the canonical staging layout described
under Generate Scenarios. Use
Publish for SimEngine to assemble the final
all_scenarios.pkl.
Implementation: metric_check() in
pipeline_w_opt.py.
Run validate and inspect every reported path. The default checkpoint,
NuPlan, OpenScene, and DigitalTwin inputs must exist before generation.
Confirm that generation produced:
projects/BWM/outputs/<scenario_name>/<source>/<source>.pkl
The publisher intentionally ignores arbitrary nested or differently named pickle files.
The publisher does not silently overwrite SimEngine inputs. Review the
existing file, then pass --overwrite only if replacement is intentional.
Two staging source files own the same scenario ID. Fix the generation output or scenario naming; the publisher will not choose one silently.
Generation catches CUDA OOM per task and stops that task early. Free GPU memory and retry; do not publish a partial staging directory until its contents have been reviewed.