File size: 29,711 Bytes
9897e20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
#!/usr/bin/env python
"""Render MP4 videos for reward-conditioned long-tail search records."""

from __future__ import annotations

import argparse
import json
import time
from collections import defaultdict
from dataclasses import fields
from pathlib import Path
from typing import Any

import mediapy as media
import torch
import yaml

from gpudrive.env.config import EnvConfig, RenderConfig
from gpudrive.env.dataset import SceneDataLoader
from gpudrive.env.env_torch import GPUDriveTorchEnv
from gpudrive.networks.late_fusion import NeuralNet
from gpudrive.visualize.utils import img_from_fig


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", default="baselines/ppo/config/ppo_mini_reward_conditioned.yaml")
    parser.add_argument("--checkpoint", default="")
    parser.add_argument("--search-dir", default="longtail_outputs/reward_conditioned_search")
    parser.add_argument("--events-file", default="")
    parser.add_argument("--data-dir", default="")
    parser.add_argument("--output-dir", default="longtail_outputs/reward_conditioned_search/videos")
    parser.add_argument("--replay-mode", choices=["exact", "fast"], default="exact")
    parser.add_argument("--event-type", choices=["any", "collision", "near_miss", "offroad"], default="any")
    parser.add_argument("--max-videos", type=int, default=4)
    parser.add_argument("--num-worlds", type=int, default=0)
    parser.add_argument("--dataset-size", type=int, default=864)
    parser.add_argument("--steps", type=int, default=0)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--device", default="cuda")
    parser.add_argument("--deterministic", type=int, default=0)
    parser.add_argument("--normal-mode", choices=["policy", "expert", ""], default="")
    parser.add_argument("--normal-style", default="balanced")
    parser.add_argument("--risk-style", default="risk_taker")
    parser.add_argument("--risk-agents-per-world", type=int, default=0)
    parser.add_argument("--risk-collision-weight", type=float, default=None)
    parser.add_argument("--risk-goal-weight", type=float, default=None)
    parser.add_argument("--risk-offroad-weight", type=float, default=None)
    parser.add_argument("--render-every", type=int, default=1)
    parser.add_argument("--fps", type=int, default=5)
    parser.add_argument("--stop-on-collision", type=int, default=1)
    parser.add_argument("--render-3d", type=int, default=0)
    parser.add_argument("--zoom-radius", type=float, default=70.0)
    parser.add_argument("--obs-radius", type=float, default=None)
    parser.add_argument("--polyline-reduction-threshold", type=float, default=None)
    return parser.parse_args()


def load_config(path: str) -> dict[str, Any]:
    with open(path, "r", encoding="utf-8") as f:
        return yaml.safe_load(f)


def normalize_event_record(record: dict[str, Any]) -> dict[str, Any]:
    """Accept raw search events or LLM evaluation wrapper records."""
    if isinstance(record.get("event"), dict):
        event = dict(record["event"])
        for key in ("event_key", "final_valid", "final_score", "final_priority"):
            if key in record:
                event[f"llm_{key}"] = record[key]
        if isinstance(record.get("llm_eval"), dict):
            event["llm_eval"] = record["llm_eval"]
        if isinstance(record.get("rule_eval"), dict):
            event["rule_eval"] = record["rule_eval"]
        return event
    return record


def load_json_records(path: Path) -> list[dict[str, Any]]:
    if path.suffix == ".jsonl":
        records = []
        with open(path, "r", encoding="utf-8") as f:
            for line in f:
                if line.strip():
                    records.append(normalize_event_record(json.loads(line)))
        return records

    with open(path, "r", encoding="utf-8") as f:
        data = json.load(f)
    if isinstance(data, list):
        return [normalize_event_record(record) for record in data]
    raise ValueError(f"Expected a JSON list or JSONL records: {path}")


def load_records(search_dir: Path, events_file: str) -> list[dict[str, Any]]:
    if events_file:
        return load_json_records(Path(events_file))

    top_files = sorted(search_dir.glob("top_*.json"))
    if top_files:
        return load_json_records(max(top_files, key=lambda p: p.stat().st_mtime))

    records = []
    for path in sorted(search_dir.glob("shard_*/events.jsonl")):
        records.extend(load_json_records(path))
    return records


def load_shard_summaries(search_dir: Path) -> dict[int, dict[str, Any]]:
    summaries: dict[int, dict[str, Any]] = {}
    for path in sorted(search_dir.glob("shard_*/summary.json")):
        with open(path, "r", encoding="utf-8") as f:
            summary = json.load(f)
        summaries[int(summary.get("shard_id", len(summaries)))] = summary
    return summaries


def find_latest_checkpoint() -> Path:
    patterns = [
        "runs/PPO_MINI_RC*/model_*.pt",
        "gpudrive/runs/PPO_MINI_RC*/model_*.pt",
        "runs/*MINI*RC*/model_*.pt",
        "gpudrive/runs/*MINI*RC*/model_*.pt",
    ]
    for pattern in patterns:
        candidates = list(Path(".").glob(pattern))
        if candidates:
            return max(candidates, key=lambda p: p.stat().st_mtime)
    raise FileNotFoundError("No reward-conditioned checkpoint found. Pass --checkpoint.")


def resolve_checkpoint(args_checkpoint: str, first_summary: dict[str, Any] | None) -> Path:
    if args_checkpoint:
        return Path(args_checkpoint)
    if first_summary and first_summary.get("checkpoint"):
        return Path(first_summary["checkpoint"])
    return find_latest_checkpoint()


def reward_preset(config: EnvConfig, style: str, device: str) -> torch.Tensor:
    presets = {
        "cautious": [
            config.collision_weight_lb * 0.9,
            config.goal_achieved_weight_ub * 0.7,
            config.off_road_weight_lb * 0.9,
        ],
        "aggressive": [
            config.collision_weight_lb * 0.5,
            config.goal_achieved_weight_ub * 0.9,
            config.off_road_weight_lb * 0.6,
        ],
        "balanced": [
            (config.collision_weight_lb + config.collision_weight_ub) / 2,
            (config.goal_achieved_weight_lb + config.goal_achieved_weight_ub) / 2,
            (config.off_road_weight_lb + config.off_road_weight_ub) / 2,
        ],
        "risk_taker": [
            config.collision_weight_lb * 0.3,
            config.goal_achieved_weight_ub,
            config.off_road_weight_lb * 0.4,
        ],
    }
    if style not in presets:
        raise ValueError(f"Unknown style={style}. Available: {sorted(presets)}")
    return torch.tensor(presets[style], dtype=torch.float32, device=device)


def tensor_from_summary_or_preset(
    summary: dict[str, Any] | None,
    key: str,
    fallback: torch.Tensor,
    device: str,
) -> torch.Tensor:
    if summary and key in summary and summary[key] is not None:
        return torch.tensor(summary[key], dtype=torch.float32, device=device)
    return fallback


def apply_weight_overrides(weights: torch.Tensor, args: argparse.Namespace) -> torch.Tensor:
    weights = weights.clone()
    if args.risk_collision_weight is not None:
        weights[0] = args.risk_collision_weight
    if args.risk_goal_weight is not None:
        weights[1] = args.risk_goal_weight
    if args.risk_offroad_weight is not None:
        weights[2] = args.risk_offroad_weight
    return weights


def make_env_config(raw_env: dict[str, Any], num_worlds: int, args: argparse.Namespace) -> EnvConfig:
    env_fields = {field.name for field in fields(EnvConfig)}
    cfg = {k: v for k, v in raw_env.items() if k in env_fields}
    cfg["num_worlds"] = num_worlds
    cfg["reward_type"] = "reward_conditioned"
    cfg["condition_mode"] = "random"
    if args.obs_radius is not None:
        cfg["obs_radius"] = args.obs_radius
    if args.polyline_reduction_threshold is not None:
        cfg["polyline_reduction_threshold"] = args.polyline_reduction_threshold

    steer_disc = int(raw_env.get("action_space_steer_disc", 13))
    accel_disc = int(raw_env.get("action_space_accel_disc", 7))
    cfg["steer_actions"] = torch.round(torch.linspace(-torch.pi, torch.pi, steer_disc), decimals=3)
    cfg["accel_actions"] = torch.round(torch.linspace(-4.0, 4.0, accel_disc), decimals=3)
    return EnvConfig(**cfg)


def load_policy(checkpoint_path: Path, model_config: dict[str, Any], device: str) -> NeuralNet:
    saved = torch.load(checkpoint_path, map_location=device, weights_only=False)
    arch = saved["model_arch"]
    arch_get = arch.get if hasattr(arch, "get") else lambda key, default=None: getattr(arch, key, default)
    policy = NeuralNet(
        input_dim=arch_get("input_dim"),
        action_dim=saved["action_dim"],
        hidden_dim=arch_get("hidden_dim"),
        dropout=arch_get("dropout", 0.0),
        config=model_config["environment"],
    ).to(device)
    policy.load_state_dict(saved["parameters"])
    policy.eval()
    return policy


def choose_risk_agents(
    control_mask: torch.Tensor,
    risk_agents_per_world: int,
    generator: torch.Generator,
) -> torch.Tensor:
    risk_mask = torch.zeros_like(control_mask, dtype=torch.bool)
    for world_idx in range(control_mask.shape[0]):
        agents = torch.where(control_mask[world_idx])[0]
        if len(agents) == 0:
            continue
        num_risk = min(risk_agents_per_world, len(agents))
        perm = torch.randperm(len(agents), generator=generator, device=control_mask.device)
        risk_mask[world_idx, agents[perm[:num_risk]]] = True
    return risk_mask


def risk_mask_from_records(env: GPUDriveTorchEnv, records: list[dict[str, Any]]) -> torch.Tensor:
    mask = torch.zeros_like(env.cont_agent_mask, dtype=torch.bool, device=env.device)
    for world_idx, record in enumerate(records):
        for agent_idx in record.get("risk_agents", []):
            if 0 <= int(agent_idx) < mask.shape[1]:
                mask[world_idx, int(agent_idx)] = True
    return mask & env.cont_agent_mask


def center_agent_for_record(record: dict[str, Any], control_mask: torch.Tensor, world_idx: int) -> int | None:
    for key in ("min_distance_risk_agent",):
        agent_idx = int(record.get(key, -1))
        if 0 <= agent_idx < control_mask.shape[1] and bool(control_mask[world_idx, agent_idx].item()):
            return agent_idx
    for agent_idx in record.get("risk_agents", []):
        agent_idx = int(agent_idx)
        if 0 <= agent_idx < control_mask.shape[1] and bool(control_mask[world_idx, agent_idx].item()):
            return agent_idx
    agents = torch.where(control_mask[world_idx])[0]
    return int(agents[0].item()) if len(agents) else None


def render(
    env: GPUDriveTorchEnv,
    frames: dict[int, list],
    worlds: list[int],
    center_agents: dict[int, int | None],
    time_step: int,
    policy_masks: dict[str, tuple[NeuralNet, torch.Tensor]],
    zoom_radius: float,
    live_mask: torch.Tensor | None = None,
) -> None:
    render_policy_masks = {}
    for name, (policy_fn, mask) in policy_masks.items():
        draw_mask = mask
        if live_mask is not None:
            draw_mask = draw_mask & live_mask
        render_policy_masks[name] = (policy_fn, draw_mask.detach().cpu())

    figures = env.vis.plot_simulator_state(
        env_indices=worlds,
        time_steps=[time_step] * len(worlds),
        center_agent_indices=[center_agents.get(world) for world in worlds],
        zoom_radius=zoom_radius,
        policy_masks=render_policy_masks,
    )
    for world, fig in zip(worlds, figures):
        frames[world].append(img_from_fig(fig))


def rollout(
    env: GPUDriveTorchEnv,
    policy: NeuralNet,
    steps: int,
    normal_mode: str,
    deterministic: bool,
    risk_mask: torch.Tensor,
    normal_weights: torch.Tensor,
    risk_weights: torch.Tensor,
    render_worlds: list[int] | None,
    center_agents: dict[int, int | None],
    frames: dict[int, list],
    render_every: int,
    stop_on_collision: bool,
    zoom_radius: float,
) -> dict[str, torch.Tensor]:
    control_mask = env.cont_agent_mask.clone()
    normal_mask = control_mask & ~risk_mask
    env.reward_weights_tensor[:] = normal_weights
    env.reward_weights_tensor[risk_mask] = risk_weights

    policy_masks = {
        "risk_taker": (policy, risk_mask),
        "balanced": (policy, normal_mask),
    }
    live_mask = control_mask.clone()
    collided = torch.zeros_like(control_mask, dtype=torch.bool, device=env.device)
    offroad = torch.zeros_like(control_mask, dtype=torch.bool, device=env.device)
    goal = torch.zeros_like(control_mask, dtype=torch.bool, device=env.device)
    stopped_render_worlds = torch.zeros(env.num_worlds, dtype=torch.bool, device=env.device)

    if render_worlds:
        render(
            env,
            frames,
            render_worlds,
            center_agents,
            0,
            policy_masks,
            zoom_radius,
            live_mask=live_mask,
        )

    expert_actions = None
    if normal_mode == "expert":
        expert_actions, _, _, _ = env.get_expert_actions()

    for step in range(steps):
        active = live_mask & control_mask
        if normal_mode == "expert":
            action_step = min(step, expert_actions.shape[2] - 1)
            actions = expert_actions[:, :, action_step, :].clone()
            active_risk = active & risk_mask
            if bool(active_risk.any().item()):
                obs = env.get_obs(active_risk)
                with torch.no_grad():
                    action, _, _, _ = policy(obs, deterministic=deterministic)
                actions[active_risk] = env.action_keys_tensor[action.to(dtype=torch.long, device=env.device)]
        else:
            actions = torch.zeros((env.num_worlds, env.max_agent_count), dtype=torch.int64, device=env.device)
            if bool(active.any().item()):
                obs = env.get_obs(active)
                with torch.no_grad():
                    action, _, _, _ = policy(obs, deterministic=deterministic)
                actions[active] = action.to(dtype=torch.int64, device=env.device)

        env.step_dynamics(actions)
        infos = env.get_infos()
        collided |= (infos.collided > 0).bool() & active
        offroad |= (infos.off_road > 0).bool() & active
        goal |= (infos.goal_achieved > 0).bool() & active
        live_mask &= ~env.get_dones().bool()

        render_worlds_alive: list[int] = []
        render_collision_worlds = torch.zeros(env.num_worlds, dtype=torch.bool, device=env.device)
        if render_worlds:
            render_collision_worlds = (collided & control_mask).any(dim=1)
            render_worlds_alive = [
                world for world in render_worlds
                if not bool(stopped_render_worlds[world].item())
            ]

        should_render = bool(render_worlds_alive) and (
            (step + 1) % render_every == 0
            or (
                stop_on_collision
                and any(bool(render_collision_worlds[world].item()) for world in render_worlds_alive)
            )
        )
        if should_render:
            render(
                env,
                frames,
                render_worlds_alive,
                center_agents,
                step + 1,
                policy_masks,
                zoom_radius,
                live_mask=live_mask,
            )

        if stop_on_collision and render_worlds:
            for world in render_worlds:
                if bool(render_collision_worlds[world].item()):
                    stopped_render_worlds[world] = True
            if all(bool(stopped_render_worlds[world].item()) for world in render_worlds):
                print(f"[visualize] all rendered worlds stopped on collision at step={step + 1}", flush=True)
                break

        if not bool(live_mask.any().item()):
            break

    return {"collided": collided, "offroad": offroad, "goal": goal}


def event_sort_key(record: dict[str, Any]) -> tuple[int, float]:
    min_dist = record.get("min_distance_m", 1e9)
    try:
        min_dist_f = float(min_dist)
    except (TypeError, ValueError):
        min_dist_f = 1e9
    return (0 if record.get("collision") else 1, min_dist_f)


def select_records(records: list[dict[str, Any]], event_type: str, max_videos: int) -> list[dict[str, Any]]:
    if event_type != "any":
        records = [r for r in records if bool(r.get(event_type))]
    records = sorted(records, key=event_sort_key)
    return records[:max_videos]


def scenario_path(data_dir: Path, record: dict[str, Any]) -> Path:
    scenario_file = Path(str(record["scenario_file"]))
    return scenario_file if scenario_file.is_absolute() else data_dir / scenario_file.name


def write_videos(
    output_dir: Path,
    frames: dict[int, list],
    records_by_world: dict[int, dict[str, Any]],
    fps: int,
    prefix: str,
) -> dict[tuple[int, int, int], str]:
    written = {}
    for world_idx, world_frames in frames.items():
        if not world_frames:
            continue
        record = records_by_world[world_idx]
    shard_id = int(record.get("shard_id", 0))
    batch_idx = int(record.get("batch_idx", 0))
    original_world_idx = int(record.get("world_idx", world_idx))
    tag = "collision" if record.get("collision") else "near_miss" if record.get("near_miss") else "event"
    eval_tag = ""
    if record.get("llm_final_priority"):
        eval_tag = f"_{record['llm_final_priority']}"
    path = output_dir / (
        f"{prefix}_shard{shard_id:03d}"
        f"_batch{batch_idx:03d}"
        f"_world{original_world_idx:04d}_{tag}{eval_tag}.mp4"
    )
    media.write_video(path, world_frames, fps=fps)
    written[(shard_id, batch_idx, original_world_idx)] = str(path)
    print(f"[visualize] wrote {path}", flush=True)
    return written


def run_fast(
    args: argparse.Namespace,
    records: list[dict[str, Any]],
    config: dict[str, Any],
    policy: NeuralNet,
    env_config: EnvConfig,
    data_dir: Path,
    normal_mode: str,
    normal_weights: torch.Tensor,
    risk_weights: torch.Tensor,
) -> list[dict[str, Any]]:
    data_batch = [str(scenario_path(data_dir, record)) for record in records]
    loader = SceneDataLoader(
        root=str(data_dir),
        batch_size=len(records),
        dataset_size=max(args.dataset_size, len(records)),
        sample_with_replacement=False,
        shuffle=False,
        seed=args.seed,
    )
    env = GPUDriveTorchEnv(
        config=env_config,
        data_loader=loader,
        max_cont_agents=env_config.max_controlled_agents,
        device=args.device,
        render_config=RenderConfig(render_3d=bool(args.render_3d)),
    )
    env.swap_data_batch(data_batch)
    env.reset()

    risk_mask = risk_mask_from_records(env, records)
    worlds = list(range(len(records)))
    centers = {world: center_agent_for_record(records[world], env.cont_agent_mask, world) for world in worlds}
    frames = {world: [] for world in worlds}
    stats = rollout(
        env=env,
        policy=policy,
        steps=args.steps or env_config.episode_len,
        normal_mode=normal_mode,
        deterministic=bool(args.deterministic),
        risk_mask=risk_mask,
        normal_weights=normal_weights,
        risk_weights=risk_weights,
        render_worlds=worlds,
        center_agents=centers,
        frames=frames,
        render_every=args.render_every,
        stop_on_collision=bool(args.stop_on_collision),
        zoom_radius=args.zoom_radius,
    )

    records_by_world = {world: records[world] for world in worlds}
    videos = write_videos(Path(args.output_dir), frames, records_by_world, args.fps, "fast")
    return build_render_summaries(records_by_world, stats, videos, world_index_mode="local")


def build_render_summaries(
    records_by_world: dict[int, dict[str, Any]],
    stats: dict[str, torch.Tensor],
    videos: dict[tuple[int, int, int], str],
    world_index_mode: str,
) -> list[dict[str, Any]]:
    summaries = []
    for world, record in records_by_world.items():
        if world_index_mode == "original":
            stats_world = int(record["world_idx"])
        else:
            stats_world = world
        risk_agents = [int(a) for a in record.get("risk_agents", [])]
        risk_collided = any(
            0 <= agent < stats["collided"].shape[1] and bool(stats["collided"][stats_world, agent].item())
            for agent in risk_agents
        )
        video_key = (
            int(record.get("shard_id", 0)),
            int(record.get("batch_idx", 0)),
            int(record.get("world_idx", world)),
        )
        summaries.append(
            {
                "record": record,
                "video_path": videos.get(video_key),
                "risk_agents": risk_agents,
                "rerun_collision": bool(stats["collided"][stats_world].any().item()),
                "rerun_risk_collision": risk_collided,
                "rerun_offroad": bool(stats["offroad"][stats_world].any().item()),
                "rerun_goal_agents": int(stats["goal"][stats_world].sum().item()),
            }
        )
    return summaries


def run_exact_group(
    args: argparse.Namespace,
    records: list[dict[str, Any]],
    summary: dict[str, Any],
    config: dict[str, Any],
    policy: NeuralNet,
    data_dir: Path,
    normal_mode: str,
    normal_weights: torch.Tensor,
    risk_weights: torch.Tensor,
) -> list[dict[str, Any]]:
    shard_id = int(records[0].get("shard_id", summary.get("shard_id", 0)))
    batch_idx = int(records[0].get("batch_idx", 0))
    seed = args.seed + shard_id * 100_000
    num_worlds = args.num_worlds or int(summary.get("num_worlds", 1000))
    dataset_size = args.dataset_size
    steps = args.steps or int(summary.get("steps", 91))
    risk_agents_per_world = args.risk_agents_per_world or int(summary.get("risk_agents_per_world", 3))
    env_config = make_env_config(config["environment"], num_worlds, args)

    torch.manual_seed(seed)
    generator = torch.Generator(device=args.device)
    generator.manual_seed(seed)

    loader = SceneDataLoader(
        root=str(data_dir),
        batch_size=num_worlds,
        dataset_size=dataset_size,
        sample_with_replacement=True,
        shuffle=True,
        seed=seed,
    )
    env = GPUDriveTorchEnv(
        config=env_config,
        data_loader=loader,
        max_cont_agents=env_config.max_controlled_agents,
        device=args.device,
        render_config=RenderConfig(render_3d=bool(args.render_3d)),
    )

    target_records_by_world = {int(record["world_idx"]): record for record in records}
    frames = {world: [] for world in target_records_by_world}
    final_stats = None

    for current_batch in range(batch_idx + 1):
        if current_batch > 0:
            env.swap_data_batch()
        env.reset()
        risk_mask = choose_risk_agents(env.cont_agent_mask.clone(), risk_agents_per_world, generator)

        render_worlds = None
        centers: dict[int, int | None] = {}
        if current_batch == batch_idx:
            for world, record in target_records_by_world.items():
                actual = Path(env.data_batch[world]).name
                expected = str(record.get("scenario_file", ""))
                if expected and Path(expected).name != actual:
                    print(
                        "[visualize] warning:",
                        f"record scenario_file={expected} but replay batch has {actual}",
                        flush=True,
                    )
                expected_risk = sorted(int(a) for a in record.get("risk_agents", []))
                actual_risk = sorted(torch.where(risk_mask[world])[0].detach().cpu().tolist())
                if expected_risk and expected_risk != actual_risk:
                    print(
                        "[visualize] warning:",
                        f"record risk_agents={expected_risk} but replay risk_agents={actual_risk}",
                        flush=True,
                    )
                centers[world] = center_agent_for_record(record, env.cont_agent_mask, world)
            render_worlds = list(target_records_by_world)

        stats = rollout(
            env=env,
            policy=policy,
            steps=steps,
            normal_mode=normal_mode,
            deterministic=bool(args.deterministic),
            risk_mask=risk_mask,
            normal_weights=normal_weights,
            risk_weights=risk_weights,
            render_worlds=render_worlds,
            center_agents=centers,
            frames=frames,
            render_every=args.render_every,
            stop_on_collision=bool(args.stop_on_collision),
            zoom_radius=args.zoom_radius,
        )
        if current_batch == batch_idx:
            final_stats = stats

    videos = write_videos(Path(args.output_dir), frames, target_records_by_world, args.fps, "exact")
    return build_render_summaries(target_records_by_world, final_stats, videos, world_index_mode="original")


def main() -> None:
    args = parse_args()
    args.device = args.device if torch.cuda.is_available() or args.device == "cpu" else "cpu"
    search_dir = Path(args.search_dir)
    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    records = load_records(search_dir, args.events_file)
    if not records:
        raise RuntimeError(f"No event records found under {search_dir}")
    records = select_records(records, args.event_type, args.max_videos)
    if not records:
        raise RuntimeError(f"No records matched event_type={args.event_type}")

    shard_summaries = load_shard_summaries(search_dir)
    first_summary = shard_summaries.get(int(records[0].get("shard_id", 0)), None)
    config = load_config(args.config)
    data_dir = Path(args.data_dir or (first_summary or {}).get("data_dir", "/mingli01/data/GPUDrive_mini/training"))
    checkpoint = resolve_checkpoint(args.checkpoint, first_summary)

    num_worlds_for_config = len(records) if args.replay_mode == "fast" else int((first_summary or {}).get("num_worlds", args.num_worlds or 1000))
    env_config = make_env_config(config["environment"], num_worlds_for_config, args)
    normal_mode = args.normal_mode or str((first_summary or {}).get("normal_mode", "policy"))

    normal_weights = tensor_from_summary_or_preset(
        first_summary,
        "normal_weights",
        reward_preset(env_config, args.normal_style, args.device),
        args.device,
    )
    risk_weights = tensor_from_summary_or_preset(
        first_summary,
        "risk_weights",
        reward_preset(env_config, args.risk_style, args.device),
        args.device,
    )
    risk_weights = apply_weight_overrides(risk_weights, args)

    policy = load_policy(checkpoint, config, args.device)
    print(
        "[visualize] start:",
        f"mode={args.replay_mode}",
        f"records={len(records)}",
        f"checkpoint={checkpoint}",
        f"data_dir={data_dir}",
        f"normal_mode={normal_mode}",
        f"normal_weights={normal_weights.detach().cpu().tolist()}",
        f"risk_weights={risk_weights.detach().cpu().tolist()}",
        flush=True,
    )

    start = time.time()
    if args.replay_mode == "fast":
        summaries = run_fast(
            args=args,
            records=records,
            config=config,
            policy=policy,
            env_config=make_env_config(config["environment"], len(records), args),
            data_dir=data_dir,
            normal_mode=normal_mode,
            normal_weights=normal_weights,
            risk_weights=risk_weights,
        )
    else:
        summaries = []
        groups: dict[tuple[int, int], list[dict[str, Any]]] = defaultdict(list)
        for record in records:
            groups[(int(record.get("shard_id", 0)), int(record.get("batch_idx", 0)))].append(record)
        for (shard_id, batch_idx), group_records in sorted(groups.items()):
            summary = shard_summaries.get(shard_id, first_summary or {})
            print(
                "[visualize] exact group:",
                f"shard={shard_id}",
                f"batch={batch_idx}",
                f"worlds={[int(r['world_idx']) for r in group_records]}",
                flush=True,
            )
            summaries.extend(
                run_exact_group(
                    args=args,
                    records=group_records,
                    summary=summary,
                    config=config,
                    policy=policy,
                    data_dir=data_dir,
                    normal_mode=normal_mode,
                    normal_weights=normal_weights,
                    risk_weights=risk_weights,
                )
            )

    output_summary = {
        "search_dir": str(search_dir),
        "output_dir": str(output_dir),
        "replay_mode": args.replay_mode,
        "checkpoint": str(checkpoint),
        "data_dir": str(data_dir),
        "normal_mode": normal_mode,
        "normal_weights": normal_weights.detach().cpu().tolist(),
        "risk_weights": risk_weights.detach().cpu().tolist(),
        "stop_on_collision": bool(args.stop_on_collision),
        "render_3d": bool(args.render_3d),
        "rendered_records": len(summaries),
        "videos": [s.get("video_path") for s in summaries if s.get("video_path")],
        "elapsed_sec": round(time.time() - start, 3),
        "records": summaries,
    }
    with open(output_dir / "render_summary.json", "w", encoding="utf-8") as f:
        json.dump(output_summary, f, indent=2)
    print(json.dumps({k: v for k, v in output_summary.items() if k != "records"}, indent=2), flush=True)


if __name__ == "__main__":
    main()