Conversation
Evaluation tooling for the token-count and imbalance investigation (docs/token_imbalance_analysis.md): - scripts/token_occupancy_scan.py: token-slot occupancy statistics over an npz dataset (mask_p-equivalent validity) - scripts/token_importance.py: permutation-importance analog via raw-input ablation (class drop / nearest-K / distance cutoff sweeps). Supports PyTorch checkpoints and ONNX (forward-only; normalization applied externally from args.json, CUDA EP when available) - scripts/attention_analysis.py: fusion attention share by token class (selectivity vs count share, value-norm weighting, distance bins, turning-vs-straight route share) Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Isamu Yamashita <isamu.yamashita@tier4.jp>
- latest_ckpt: accept a directory that directly contains best_model.pth (e.g. best_models/<date>/best_model with args.json alongside) - attention_analysis: move raw distance tensors to the eval device so --device cuda works Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Isamu Yamashita <isamu.yamashita@tier4.jp>
Checkpoints saved from DDP-wrapped models (e.g. multi-GPU training clusters) prefix every key with "module.", which made load_state_dict fail with all-keys-missing. Strip the prefix on load. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Isamu Yamashita <isamu.yamashita@tier4.jp>
- attention_analysis.py: add --out_json to dump aggregated results (class shares per layer, selectivity inputs, distance bins, turning-vs-straight route share) for downstream visualization - notebook/token_analysis.ipynb: visualize token_importance TSV and attention JSON — class-removal importance, nearest-K sweep curves, attention selectivity vs count share, per-layer shares, scenario split — with an interpretation guide for full-data verification Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Isamu Yamashita <isamu.yamashita@tier4.jp>
The moving-scene selection loaded every npz in the dataset even for skipped indices, which is prohibitive on large datasets. Build the strided candidate list first and load only those files. Co-Authored-By: Claude <noreply@anthropic.com> Signed-off-by: Isamu Yamashita <isamu.yamashita@tier4.jp>
| for li, block in enumerate(fusion.blocks): | ||
|
|
||
| def make_fwd(blk, layer_idx): | ||
| def fwd(x, mask): |
There was a problem hiding this comment.
Actually, we should consider to modify FusionEncoder instead of making patching here
There was a problem hiding this comment.
That's a good idea. Since this would require modifying the core Diffusion Planner code, We'd like to discuss it with the team first.
| def fwd(x, mask): | ||
| attn_out, w = blk.attn( | ||
| blk.norm1(x), | ||
| x, |
There was a problem hiding this comment.
If it's self-attention, it should apply norm1 to x for value and key as well?
There was a problem hiding this comment.
Good catch! Yes, since this is how it’s currently implemented in DP, the same logic was applied here 😢 . I’ve submitted a PR with this fix, but I don't think it has been merged into tier4-main yet, only merged to dev branch.
|
|
||
| If the Notebook and HTML dependencies are not installed, install them once: | ||
|
|
||
| ```bash |
There was a problem hiding this comment.
Rather than installing manually I would like it to be written in uv.lock
| import shutil | ||
| import subprocess |
There was a problem hiding this comment.
| import shutil | |
| import subprocess |
nits: not used
| cd "$REPO_ROOT" | ||
|
|
||
| MODEL_DIR="${MODEL_DIR:-$REPO_ROOT/best_models/20260730/best_model}" | ||
| DATADIR="${DATADIR:-/home/yamashita/work_hdd/sample/mini_datasets/j6_2231_fullseq_mini_20260707}" |
There was a problem hiding this comment.
This default points to a personal home directory, so the script fails with a confusing path error for anyone else (and it leaks an internal username/directory layout into the repo). Since set -u is already enabled, could you make DATADIR required instead?
| cd "$REPO_ROOT" | ||
|
|
||
| MODEL_DIR="${MODEL_DIR:-$REPO_ROOT/best_models/20260730/best_model}" | ||
| DATADIR="${DATADIR:-/home/yamashita/work_hdd/sample/mini_datasets/j6_2231_fullseq_mini_20260707}" |
There was a problem hiding this comment.
Same as the comment on run_token_analysis.sh: please drop the personal-path default and make DATADIR required via ${DATADIR:?...}.
| cd "$REPO_ROOT" | ||
|
|
||
| MODEL_DIR="${MODEL_DIR:-$REPO_ROOT/best_models/20260730/best_model}" | ||
| DATADIR="${DATADIR:-/home/yamashita/work_hdd/sample/mini_datasets/j6_2231_fullseq_mini_20260707}" |
There was a problem hiding this comment.
Same as the comment on run_token_analysis.sh: please drop the personal-path default and make DATADIR required via ${DATADIR:?...}.
| cd "$REPO_ROOT" | ||
|
|
||
| MODEL_DIR="${MODEL_DIR:-$REPO_ROOT/best_models/20260730/best_model}" | ||
| DATADIR="${DATADIR:-/home/yamashita/work_hdd/sample/mini_datasets/j6_2231_fullseq_mini_20260707}" |
There was a problem hiding this comment.
Same as the comment on run_token_analysis.sh: please drop the personal-path default and make DATADIR required via ${DATADIR:?...}.
| fi | ||
|
|
||
| MODEL_DIR="${MODEL_DIR:-$REPO_ROOT/best_models/20260730/best_model}" | ||
| DATADIR="${DATADIR:-/home/yamashita/work_hdd/sample/mini_datasets/j6_2231_fullseq_mini_20260707}" |
There was a problem hiding this comment.
Same as the comment on run_token_analysis.sh: please drop the personal-path default and make DATADIR required via ${DATADIR:?...}.
| # | ||
| # Usage (from repo root on A100): | ||
| # ./run_token_analysis.sh | ||
| # DATADIR=/home/yamashita/work_hdd/sample/il_odaiba_shinagawa_j6_npz \ |
There was a problem hiding this comment.
Please replace this example path with a generic one (/path/to/dataset) as well.
|
|
||
| Usage: | ||
| uv run python scripts/attention_analysis.py \ | ||
| --run_dir /home/isamuyamashita/work/diffusion_plannner/DP_exp/20260725-132546_plantf_V_tail \ |
There was a problem hiding this comment.
The usage example references a personal directory (/home/isamuyamashita/...). Could you align it with the style already used in visualize_neighbor_attention.py?
|
|
||
| Usage (CPU, sshfs checkpoint): | ||
| uv run python scripts/token_importance.py \ | ||
| --run_dir /home/isamuyamashita/work/diffusion_plannner/DP_exp/20260725-132546_plantf_V_tail \ |
There was a problem hiding this comment.
The usage example references a personal directory (/home/isamuyamashita/...). Could you align it with the style already used in visualize_neighbor_attention.py?
| DIST_BINS = [(0, 25), (25, 50), (50, 100), (100, float("inf"))] | ||
|
|
||
|
|
||
| def latest_ckpt(run_dir: Path) -> Path: |
There was a problem hiding this comment.
latest_ckpt, load_model, prepare_inputs, and init_distributed are copy-pasted across token_importance.py, attention_analysis.py, and visualize_neighbor_attention.py (with find_fusion and the neighbor/lane distance helpers duplicated in two of the three, in slightly different variants).
Could we extract these into a shared module, e.g. scripts/token_analysis_common.py? The visualization scripts already import from each other, so the precedent exists.

Token Importance and Attention Analysis Tool Guide
Overview
This guide describes an analysis workflow that evaluates whether the Diffusion Planner
Encoder's token configuration (up to 564 tokens) is appropriate. The workflow
runs and visualizes:
neighbor-Attention MP4 visualization;
The model architecture and training procedure are unchanged. These are offline
analysis tools that operate on a saved checkpoint and an evaluation dataset.
Tool Components
scripts/token_importance.pyscripts/attention_analysis.pyscripts/token_occupancy_scan.pyscripts/visualize_neighbor_attention.pyscripts/visualize_neighbor_attention_video.pyscripts/visualize_all_token_attention.pyscripts/visualize_all_token_attention_video.pyrun_token_analysis.shrun_neighbor_attention_visualization.shrun_neighbor_attention_video.shrun_all_token_attention_visualization.shrun_all_token_attention_video.shnotebook/token_analysis.ipynbnotebook/token_analysis_en.ipynbnotebook/generate_english_notebook.pynotebook/portable_html.j2test_scripts/test_token_analysis_helpers.pyAnalysis
1. Feature Importance Through Input Ablation
For the same evaluation scenes, the workflow compares the unchanged baseline
with runs in which one input group is replaced by zeros.
uses information from that input.
prove that the input is unnecessary; sampling error and out-of-distribution
ablation inputs must also be considered.
For variable-length inputs such as neighbors and maps, zeroed rows become
padding and are excluded by the Attention mask.
Goal pose and turn indicators are fixed-length tokens. Their experiments
replace input information with a constant value rather than completely
removing the token.
2. Nearest-First Top-K
Only the K inputs nearest to the ego vehicle are retained.
The smallest K at which FDE and ADE stabilize near the baseline is a candidate
for reducing the token limit.
3. Distance Cutoffs
Only inputs within a specified physical distance are retained.
Top-K evaluates a count limit, while a distance cutoff evaluates the physical
input range. They answer different questions.
4. Attention Analysis
Fusion Encoder Attention weights are aggregated by token class.
Attention share / count shareSelectivity can be interpreted as follows:
1.0: Attention is approximately proportional to token count.> 1.0: The class is preferred beyond its token-count share.< 1.0: The class receives less Attention than its token-count share.Attention indicates where the model looked; it is not itself a causal measure
of importance to the final prediction. It should be interpreted together with
feature importance.
5. Valid-Token Counts and Utilization
The Attention padding mask is used to count valid tokens in the same evaluation
samples. The following values are saved to the Attention JSON:
p95 and p99 are initial candidates for reducing slot limits. They do not imply
that discarding the remaining high-density scenes is safe. Top-K and
closed-loop evaluations are also required.
Evaluation Metrics
For a model with a single trajectory output, the top and min metrics are
identical.
FDE evaluates the final destination, while ADE evaluates the complete path.
The report therefore includes both.
Prerequisites
The model directory must contain at least:
If the Notebook and HTML dependencies are not installed, install them once:
Recommended Usage
Run
run_token_analysis.shfrom the repository root:If
DATADIR/path_list_valid.jsonexists, it is used automatically.To explicitly select an evaluation list:
If neither
path_list_valid.jsonnorVALID_LISTis available, the Shellrecursively collects every NPZ below
DATADIR. Depending on the directorylayout, that may mix training and validation data. An explicit
VALID_LISTisrecommended for formal evaluation.
Parameters
MODEL_DIRbest_models/20260730/best_modelargs.jsonandbest_model.pthDATADIRVALID_LIST$DATADIR/path_list_valid.jsonN_SAMPLES128BATCH_SIZE32NUM_GPUS1NUM_WORKERS0DEVICEcudacudaorcpuMOVE_MIN_M5.0TURN_DEG15.0OUT_DIRPYTHON_BIN.venv/bin/pythonStart with a small
N_SAMPLESto verify the setup, then use at least 512–1024samples for formal evaluation.
BATCH_SIZEis the value for one GPU. The effective batch size isapproximately
BATCH_SIZE × NUM_GPUS; adjust it to the available GPU memory.Multi-GPU Data Parallel Execution
When
NUM_GPUSis at least 2, the integrated Shell launchestorchrun. Theselected evaluation samples are partitioned across ranks without duplication,
and each GPU processes only its own shard using the same checkpoint.
Moving-scene selection first checks candidates distributed uniformly across
the dataset, then expands to unvisited offsets if necessary. It therefore
selects
N_SAMPLESscenes when enough matching data is available.all_reduceon the per-rank error sums and samplecounts, producing the mean over all selected samples.
then computes means, percentiles, and turning/straight statistics.
without executing the Decoder.
Per-Scene Neighbor-Attention Visualization
Dataset-level Attention statistics describe average behavior but do not identify
which agent the model reads in one scene. The separate visualization tools
overlay ego-query Fusion Attention directly on neighbor-agent positions.
tokens.
LAYER=meanaverages all Fusion layers.lastor a zero-based layer indexcan also be selected.
aggregate Attention, and per-layer Attention.
This is an additional diagnostic workflow. It is intentionally separate from
run_token_analysis.shand does not change the dataset-level Notebook report.Render One Scene
To automatically select a turning scene using the most-attended neighbor token,
regardless of object class:
To select a scene based only on pedestrian tokens:
SELECT_CLASSacceptsany,vehicle,pedestrian, orbicycle. It affectsautomatic scene selection only; the resulting image always draws every valid
neighbor class. To render a known entry from the evaluation list:
SAMPLE_INDEXis the zero-based position inVALID_LIST, not an identifierstored inside the NPZ filename.
Appearance
The sequential Matplotlib colormap and marker-area range are configurable:
LAYERmeanmean,last, or a zero-based Fusion layer indexTOP_K12VIEW_RANGE80COLORMAPviridisMARKER_SIZE_MIN45MARKER_SIZE_MAX950OUTPUT_NAMEneighbor_attentionThe static runner writes:
Create a Continuous MP4
The video runner uses consecutive entries around a center index:
ffmpegwith the H.264 encoder must be available inPATH. All frames use oneglobal Attention maximum so that colors and marker areas remain comparable over
time. Encoding preserves the figure aspect ratio by scaling and padding to the
requested even-sized frame. The output uses BT.709 limited-range
yuv420p,avoiding the gray colors and half-width distortion caused by ambiguous color
metadata or an incorrect sample aspect ratio.
The sequence stops before crossing into a different parent directory in the
data list. A meaningful temporal video therefore requires
VALID_LISTentriesto be in chronological order within each log directory.
STEPcan skip entries,and
KEEP_FRAMES=1retains the intermediate PNG files.Per-Scene All-Token Attention Visualization
The all-token visualization uses the same ego-query Fusion Attention as the
neighbor-only tool but includes every valid encoder token:
Spatial tokens are drawn on the bird's-eye view using a different marker shape
for each class. Color and marker area represent the token's percentage of
ego-query Attention over all valid tokens. The Top-K chart ranks spatial and
non-spatial tokens together. Ego shape and turn indicator have no scene
coordinate, so they appear in the chart and JSON but not as map markers.
The representative positions follow the Encoder definition: current position
for neighbors and static objects, the middle point for lane/route/polygon/line
tokens, the goal coordinate for goal pose, and the origin for ego.
Run with a Fixed Scene
The Shell runner is the simplest entry point:
SAMPLE_INDEXis the zero-based position inVALID_LIST. The command writes:The same operation can be run directly:
Automatically Select a Scene
Without
SAMPLE_INDEX, the runner searches moving scenes and selects the scenecontaining the strongest eligible token:
To search by one token class:
SELECT_CLASSacceptsany,ego,neighbors,static,lanes,route,polygons,line_strings,goal_pose,ego_shape, orturn_indicator.Class selection affects scene search only; the generated report always contains
all valid classes.
Display Parameters
LAYERmeanmean,last, or a zero-based Fusion layer indexTOP_K20VIEW_RANGE80COLORMAPplasmaMARKER_SIZE_MIN25MARKER_SIZE_MAX700SELECT_CLASSanyTURN_ONLY1CANDIDATE_COUNT128OUTPUT_NAMEall_token_attentionThe JSON contains:
The percentages over all valid tokens should sum to approximately 100%, apart
from floating-point rounding. A high-ranked token indicates where the ego query
read strongly in the selected Fusion layer or layer average. It does not prove
that the token caused the final trajectory; compare the result with ablation
metrics and scene context.
Create an All-Token MP4
The video runner uses the same all-token records as the static visualization and
keeps one Attention color/size scale across every frame:
The script writes
all_token_attention_index996.mp4and its JSON metadata underOUT_DIR. It requiresffmpeg, accepts the sameLAYER,TOP_K,VIEW_RANGE,COLORMAP,MARKER_SIZE_MIN, andMARKER_SIZE_MAXsettings as the staticrunner, and supports
STEPandKEEP_FRAMES=1. Frames are scaled and paddedto preserve the figure aspect ratio and encoded as BT.709 limited-range
yuv420pwith a 1:1 sample aspect ratio. As with the neighbor video, theselected list must be chronological within one log directory for the sequence
to represent time.
Outputs
By default,
eval_<dataset name>/is created next toMODEL_DIR.Both HTML reports embed their images and styles. They can be opened as
standalone files without the TSV, JSON, or repository.
Latest Validation Run
The integrated Shell was run end to end on July 31, 2026, using two A100 80GB
GPUs.
The target directory contained 33,275 NPZ files. Because it did not contain
path_list_valid.json, the workflow generatedpath_list_all.json. It selected128 moving scenes and assigned 64 scenes to each rank. Attention analysis
classified 27 scenes as turning and 101 as straight.
This run validates the complete workflow over all NPZ files, not a fixed-split
model benchmark. A formal evaluation should provide
VALID_LISTexplicitly toprevent unintended mixing of training and validation data.
Feature-Importance Results
Values are in meters. Each delta is the ablation value minus the baseline.
Lane and goal-pose ablation produced the largest degradation in this 128-scene
run. Line-string ablation produced a negative FDE delta. These are observations,
not conclusions that an input can be removed. They require reproduction with
more samples, scene-level inspection, retraining, and closed-loop evaluation.
Valid-Token Counts
Neighbors used only 8.13% of their slots on average, but the run included a
dense scene with 161 valid neighbors. Lane p99 was approximately 100, while
line strings reached the 60-slot limit at p95. Capacity decisions must therefore
consider p95, p99, maximum counts, and Top-K results rather than mean utilization
alone.
Attention Results
1.12xfor neighbors,1.71xforroute,
1.29xfor line strings, and1.79xfor goal pose.50–100 m, and 13.09% beyond 100 m.
50–100 m, and 22.42% beyond 100 m.
Distance-bin values are not corrected for the number of tokens in each bin.
They must not be treated as causal evidence that the model prefers distant
inputs. Interpret them together with feature importance, token counts, and
scene-level visualization.
Generated and Validated Artifacts
The workflow generated the 24-configuration TSV, Attention JSON, executed
Japanese and English Notebooks, and portable HTML reports under
best_models/20260730/eval_il_odaiba_shinagawa_j6_npz/.data:image/pngimages.execution_countfields were removed from Markdown cells in theEnglish Notebook.
Notebook and HTML Contents
ONNX
scripts/token_importance.pycan also be used directly with an ONNX model:The ONNX graph does not expose Fusion Encoder Attention weights, so
attention_analysis.pyrequires a PyTorch checkpoint. The integrated Shellalso uses the PyTorch checkpoint.
Interpretation Caveats
evaluation dataset.
safety-critical scenes.
equivalent.
usefulness.
inspection, and closed-loop safety evaluation.
Validation
all_reduceaggregation for all 24 feature-importance configurations