File size: 35,531 Bytes
68d3a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""bridge_adapt3.py: one adaptation run of the bridge pilot, runner v2.2 (reproduction/BRIDGE-DESIGN.md).

v2.2 = v2.1 (bridge_adapt2.py, which ran the passed one-batch check; its rules are kept unchanged) plus,
after review/ASTRA-L3-L4-REAUDIT-2026-10-09.md and the four overlapping papers:
  - mode dynamics_fixed (Df): only the latent dynamics learn, under the consistency loss; encoder, task
    embedding, reward, policy, value and target frozen (the port of the published dynamics-only methods).
    After research-db/notes/SIMDIST-UPDATE-MAP-2026-10-09.md, Df trains on SimDist's schedule: collect a
    round (DF_ROUND decisions, no updates), then train on it, at B's total update budget; equal weights
    over the horizon (rho 1, as SimDist's uniform weighting); a linear learning-rate warmup over the first
    DF_WARMUP updates. +df_schedule=step restores the per-step schedule (an ablation);
  - mode anchored (R3): the full released update plus lambda * sum over parameters of (theta - theta_0)^2,
    its gradient added to each optimiser's own parameters once per step and BEFORE upstream's gradient
    clipping, so the clipped quantity is clip(g + penalty) (theta_0 after the embedding normalisation);
    clipping events and gradient norms are recorded; +anchor_lambda is required;
  - +calibrate_r3=true: the fixed R3 calibration protocol on the HEALTHY body (lambda = 10^k, k = -5..0 in
    increasing order, stop at the first candidate that passes; writes calibration.json);
  - mode rehearsal (R1): the full update on half-and-half batches: half from the post-change buffer, half
    from the original MT30 walker data (+retention_data=<path to the extracted .pt>);
  - a score curve: a short paired evaluation (run 3, stand 2, walk-backwards 2 episodes) after 2,500, 5,000
    and 10,000 decisions, the full block after 20,000;
  - a probe: the model's own latent prediction error on the first two A-block trajectories of each
    evaluated task (recorded with the released model on the paired bank; saved once as
    probe_trajectories.pt), at A, at each curve point and after. For Df (encoder and embedding fixed) it is
    a latent-prediction measure in one coordinate system; for every arm whose encoder moves it is only a
    self-consistency diagnostic, never evidence of better prediction (a representation that discards
    information also lowers it; review/ASTRA-L8-RUNNER-V22-2026-10-09.md M1);
  - the check also runs dynamics_fixed and anchored (two updates, anchor effect required) and, when
    +retention_data is given, rehearsal.

    python bridge_adapt3.py task=mt30 model_size=48 checkpoint=/path/mt30-48M.pt steps=20000 seed=1 \
      compile=false enable_wandb=false save_video=false +out_dir=/path/seed1/R3 \
      +adapt_task=walker-walk +adapt_mode=anchored +anchor_lambda=0.001 +eval_task=walker-run \
      +gear_joint=right_knee +gear_scale=0.5
"""
import os
os.environ['MUJOCO_GL'] = os.getenv("MUJOCO_GL", 'egl')
import warnings
warnings.filterwarnings('ignore')
import dataclasses
import random
import time
import hydra
import numpy as np
import torch
import torch.nn.functional as F
from tensordict.tensordict import TensorDict
from termcolor import colored
from common.parser import parse_cfg
from common.seed import set_seed
from common.buffer import Buffer
from envs import make_env
from tdmpc2 import TDMPC2
import bridge_logic as BL

torch.backends.cudnn.benchmark = True
WARMUP_EPISODES = 2                 # episodes collected with the pretrained policy before updates start (inside E)
RETENTION_TASKS = ("walker-stand", "walker-walk-backwards")
EVAL_EPISODES_WITHHELD = 10
EVAL_EPISODES_RETENTION = 5
DEFAULT_EVAL_SEED = 1000            # the paired bank: episode i of any block uses eval_seed + i
MODES = ("none", "full", "heads_frozen", "consistency", "dynamics_fixed", "anchored", "rehearsal")
CURVE_AT = (2500, 5000, 10000)       # decisions after which the short curve block runs (the final block follows E)
CURVE_EPISODES = {"run": 3, "retention": 2}
EPISODE_DECISIONS = 500
# the curve runs at episode boundaries, so evaluating never interrupts a training episode or its plan
assert all(c % EPISODE_DECISIONS == 0 for c in CURVE_AT)
PROBE_EPISODES = 2                   # A-block trajectories per task kept for the transfer probe
CALIB_EXPONENTS = (-5, -4, -3, -2, -1, 0)   # R3: lambda = 10^k, tried in increasing order
CALIB_DECISIONS = 3500               # two warm-up episodes, then about 2,500 updates
CALIB_EVAL_SEED = 5000               # the R3 validation bank, used nowhere else
CALIB_EPISODES = 5
CALIB_TOLERANCE = 0.05               # retention within 5 percent of the released model on the same bank
CHECK_ANCHOR_LAMBDA = 1.0            # strong enough that two updates must differ from the full update
DF_ROUND = 5000                      # Df: decisions per collection round (an episode multiple)
DF_WARMUP = 2000                     # Df: updates over which the learning rate rises linearly (SimDist: 2,000)
HEAD_MODULES = ("_reward", "_pi", "_Qs", "_termination")
RESULT_FILE = "bridge_adapt.json"
CHECK_FAILED_EXIT = 3


def progress(line):
    p = os.environ.get("BENCH_PROGRESS_FILE")
    if p:
        with open(p, "a") as f:
            f.write(f"{time.strftime('%H:%M:%S')} {line}\n")


def sub_env(env, task_idx):
    sub = env.envs[task_idx] if hasattr(env, "envs") else env
    return sub.unwrapped if hasattr(sub, "unwrapped") else sub


def task_of(env, task_idx):
    """The dm_control Task of one sub-environment (its _random drives every reset)."""
    e = sub_env(env, task_idx)
    while not hasattr(e, "task") and hasattr(e, "_env"):
        e = e._env
    task = e.task
    assert hasattr(task, "_random"), "dm_control task has no _random; paired evaluation cannot re-seed resets"
    return task


def set_gear(env, task_idx, joint, scale):
    phys = sub_env(env, task_idx).physics
    before = float(phys.named.model.actuator_gear[joint][0])
    phys.named.model.actuator_gear[joint][0] = before * scale
    return before, float(phys.named.model.actuator_gear[joint][0])


def apply_change(env, tasks, idx, joint, scale):
    return {t: set_gear(env, idx[t], joint, scale) for t in tasks if t.startswith("walker")}


class TrainingRng:
    """Saves the training RNG streams around an evaluation block so evaluation never changes training."""
    def __enter__(self):
        self.state = (torch.get_rng_state(), torch.cuda.get_rng_state_all(), np.random.get_state(), random.getstate())
        return self

    def __exit__(self, *exc):
        torch.set_rng_state(self.state[0]); torch.cuda.set_rng_state_all(self.state[1])
        np.random.set_state(self.state[2]); random.setstate(self.state[3])


def evaluate(agent, env, task_idx, episodes, label, eval_seed, record=0):
    """Paired evaluation: episode i re-seeds the task's resets and the planner noise with eval_seed + i.
    record=n keeps the observations and actions of the first n episodes (for the transfer probe)."""
    rewards, trajs = [], []
    with TrainingRng():
        for i in range(episodes):
            task_of(env, task_idx)._random = np.random.RandomState(eval_seed + i)
            torch.manual_seed(eval_seed + i); torch.cuda.manual_seed_all(eval_seed + i)
            obs, done, ep_reward, t = env.reset(task_idx=task_idx), False, 0, 0
            o_list, a_list = [obs.clone()], []
            while not done:
                action = agent.act(obs, t0=t == 0, eval_mode=True, task=task_idx)
                obs, reward, done, info = env.step(action)
                ep_reward += reward; t += 1
                if i < record:
                    o_list.append(obs.clone()); a_list.append(action.clone())
            if i < record:
                trajs.append((torch.stack(o_list), torch.stack(a_list)))
            rewards.append(float(ep_reward))
            progress(f"eval {label} episode {i + 1} R {ep_reward:.1f}")
    result = {"mean": float(np.mean(rewards)), "sd": float(np.std(rewards)), "episodes": rewards, "eval_seed": eval_seed}
    return (result, trajs) if record else result


def eval_block(agent, env, idx, eval_task, eval_seed, label, adapt_task=None, record=0, short=False):
    """The withheld task (10 episodes), the retention tasks (5 each) and, when it is none of those, the
    adapted task (5). short=True is the curve block (3 and 2 episodes, no adapted task). record=n returns
    (block, trajectories) with n recorded episodes per task."""
    n_run = CURVE_EPISODES["run"] if short else EVAL_EPISODES_WITHHELD
    n_ret = CURVE_EPISODES["retention"] if short else EVAL_EPISODES_RETENTION
    block, trajs = {}, {}
    for t, n in [(eval_task, n_run)] + [(t, n_ret) for t in RETENTION_TASKS]:
        r = evaluate(agent, env, idx[t], n, f"{label} {t}", eval_seed, record=record)
        if record:
            block[t], trajs[t] = r
        else:
            block[t] = r
    if short:
        return block
    if adapt_task is not None and adapt_task not in block:
        block[adapt_task] = evaluate(agent, env, idx[adapt_task], EVAL_EPISODES_RETENTION, f"{label} {adapt_task}", eval_seed)
    return (block, trajs) if record else block


def probe(agent, trajs, idx):
    """The transfer probe: per task, the model's own rho-weighted latent prediction error over the horizon,
    averaged over every start point of the recorded trajectories (released-model trajectories under the
    changed body, recorded once in the A block). No gradients, no environment steps."""
    cfg, out = agent.cfg, {}
    with torch.no_grad():
        for t, eps in trajs.items():
            errs = []
            for obs, act in eps:
                obs, act = obs.to(agent.device), act.to(agent.device)
                H, T = cfg.horizon, act.shape[0]
                n = T - H + 1
                task = torch.full((n,), idx[t], dtype=torch.long, device=agent.device)
                z = agent.model.encode(obs[:n], task)
                err = 0.0
                for k in range(H):
                    z = agent.model.next(z, act[k:k + n], task)
                    target = agent.model.encode(obs[k + 1:k + 1 + n], task)
                    err = err + F.mse_loss(z, target).item() * cfg.rho ** k
                errs.append(err / H)
            out[t] = float(np.mean(errs))
    return out


def to_td(env, obs, task_idx, action=None, reward=None, terminated=None):
    """The online trainer's TensorDict for one step, plus the task index the multi-task buffer needs."""
    obs = obs.unsqueeze(0).cpu()
    if action is None:
        action = torch.full_like(env.rand_act(), float('nan'))
    if reward is None:
        reward = torch.tensor(float('nan'))
    if terminated is None:
        terminated = torch.tensor(float('nan'))
    return TensorDict(obs=obs, action=action.unsqueeze(0), reward=reward.unsqueeze(0), terminated=terminated.unsqueeze(0),
                      task=torch.tensor([task_idx], dtype=torch.int64), batch_size=(1,))


def freeze(model, names):
    frozen = 0
    for name in names:
        mod = getattr(model, name, None)
        if mod is not None:
            for p in mod.parameters():
                p.requires_grad_(False); frozen += p.numel()
    return frozen


def normalise_task_embeddings(agent):
    """nn.Embedding(max_norm=1) renormalises a row in place the first time it is looked up. Doing it for
    every row once, right after loading, makes later embedding movement mean learning, not lookup."""
    emb = getattr(agent.model, "_task_emb", None)
    if emb is not None:
        with torch.no_grad():
            emb(torch.arange(emb.num_embeddings, device=emb.weight.device))


def configure_mode(agent, mode):
    """Sets which parameters may move. Returns the number of frozen parameters. heads_frozen and
    consistency also stop the Polyak update of the target value copy, which upstream runs on every
    agent.update regardless of requires_grad."""
    assert mode in MODES, f"adapt_mode must be one of {MODES}, got {mode}"
    ANCHOR["state"] = None              # a fresh agent never inherits a previous agent's anchor
    for p in agent.model.parameters():
        p.requires_grad_(True)
    if mode in ("heads_frozen", "consistency", "dynamics_fixed"):
        agent.model.soft_update_target_Q = lambda: None
    if mode == "heads_frozen":
        return freeze(agent.model, HEAD_MODULES)
    if mode == "consistency":
        return freeze(agent.model, HEAD_MODULES + ("_task_emb",))
    if mode == "dynamics_fixed":
        return freeze(agent.model, HEAD_MODULES + ("_task_emb", "_encoder"))
    return 0


ANCHOR = {"state": None}            # the anchor of the agent currently training (one agent trains at a time)
_CLIP = torch.nn.utils.clip_grad_norm_


def _anchored_clip(parameters, max_norm, *args, **kwargs):
    """Upstream clips through torch.nn.utils.clip_grad_norm_ right before each optimiser step (the model's
    parameters in the model update, the policy's in the actor update). With an anchor installed, this adds
    2 lambda (theta - theta_0) to the gradients of the parameters THAT optimiser owns, then clips the sum:
    the update is clip(g + penalty), i.e. the released loss plus lambda * sum (theta - theta_0)^2 under the
    same clipping. Without an anchor it is upstream's function unchanged."""
    params = list(parameters) if not isinstance(parameters, torch.Tensor) else [parameters]
    st = ANCHOR["state"]
    if st is not None:
        ids = {id(p) for p in params}
        owned = st["actor"] if ids <= st["actor_ids"] else st["model"]
        with torch.no_grad():
            for p, t0 in owned:
                if id(p) in ids:
                    pen = (p.detach() - t0) * (2.0 * st["lam"])
                    if p.grad is None:
                        p.grad = pen.clone()
                    else:
                        p.grad.add_(pen)
    norm = _CLIP(params, max_norm, *args, **kwargs)
    if st is not None:
        n = float(norm)
        st["stats"]["clip_calls"] += 1
        st["stats"]["max_norm_seen"] = max(st["stats"]["max_norm_seen"], n) if n == n else st["stats"]["max_norm_seen"]
        st["stats"]["clipped"] += int(n > max_norm)
        st["stats"]["nonfinite"] += int(not (n == n and n != float("inf")))
    return norm


torch.nn.utils.clip_grad_norm_ = _anchored_clip


def install_anchor(agent, lam):
    """R3 (see _anchored_clip). theta_0 is taken now: call after loading and normalising. The model
    optimiser's parameters (encoder, dynamics, reward, value, task embedding) are anchored in the model
    update and the policy's in the actor update, each exactly once per step: upstream's actor backward
    also reaches the task embedding, but the actor clip only covers the policy, so the embedding is not
    penalised twice (review/CURSOR-BRIDGE-V22-L8-2026-10-09.md)."""
    assert lam > 0, "anchored mode needs +anchor_lambda > 0"
    model_params = [p for g in agent.optim.param_groups for p in g["params"]]
    actor_params = [p for g in agent.pi_optim.param_groups for p in g["params"]]
    ANCHOR["state"] = {"lam": lam, "model": [(p, p.detach().clone()) for p in model_params],
                       "actor": [(p, p.detach().clone()) for p in actor_params],
                       "actor_ids": {id(p) for p in actor_params},
                       "stats": {"clip_calls": 0, "clipped": 0, "nonfinite": 0, "max_norm_seen": 0.0}}
    return sum(p.numel() for p in model_params + actor_params)


def anchor_stats():
    st = ANCHOR["state"]
    return None if st is None else dict(st["stats"])


def consistency_update(agent, buffer, rho=None):
    """The released update's latent rollout and consistency loss alone (same horizon normalisation, same
    coefficient, same gradient clipping, same optimiser; rho as released unless given); no reward, value,
    termination or actor loss, no target update. Only unfrozen parameters move."""
    cfg = agent.cfg
    rho = cfg.rho if rho is None else rho
    obs, action, reward, terminated, task = buffer.sample()
    with torch.no_grad():
        next_z = agent.model.encode(obs[1:], task)
    agent.model.train()
    z = agent.model.encode(obs[0], task)
    loss = 0
    for t, (_action, _next_z) in enumerate(zip(action.unbind(0), next_z.unbind(0))):
        z = agent.model.next(z, _action, task)
        loss = loss + F.mse_loss(z, _next_z) * rho ** t
    loss = cfg.consistency_coef * loss / cfg.horizon
    loss.backward()
    grad_norm = torch.nn.utils.clip_grad_norm_(agent.model.parameters(), cfg.grad_clip_norm)
    agent.optim.step()
    agent.optim.zero_grad(set_to_none=True)
    agent.model.eval()
    return {"consistency_loss": loss.detach(), "grad_norm": grad_norm.detach()}


class MixedBatches:
    """R1: each update sees half its batch from the post-change buffer and half from the original data."""
    def __init__(self, fresh, original):
        self.fresh, self.original = fresh, original

    def sample(self):
        a, b = self.fresh.sample(), self.original.sample()
        obs, action, reward, terminated = (torch.cat([x, y], dim=1) for x, y in zip(a[:4], b[:4]))
        return obs, action, reward, terminated, torch.cat([a[4], b[4]], dim=0)


def df_warmup(agent):
    """Df: linear learning-rate warmup over the first DF_WARMUP updates (SimDist's schedule; no decay)."""
    n = getattr(agent, "_df_updates", 0) + 1
    agent._df_updates = n
    if not hasattr(agent, "_df_base_lr"):
        agent._df_base_lr = [g["lr"] for g in agent.optim.param_groups]
    f = min(1.0, n / DF_WARMUP)
    for g, base in zip(agent.optim.param_groups, agent._df_base_lr):
        g["lr"] = base * f


def do_update(agent, buffer, mode):
    if mode == "dynamics_fixed":
        df_warmup(agent)
        return consistency_update(agent, buffer, rho=1.0)
    if mode == "consistency":
        return consistency_update(agent, buffer)
    if mode == "rehearsal":
        obs, action, reward, terminated, task = buffer.sample()
        return agent._update(obs, action, reward, terminated, task=task)
    return agent.update(buffer)


def half_cfg(cfg, **kw):
    return dataclasses.replace(cfg, batch_size=cfg.batch_size // 2, **kw)


def load_original(cfg, path):
    """The extracted MT30 walker subset (mt30_extract.py) in its own buffer, half the batch size."""
    import hashlib
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for block in iter(lambda: f.read(1 << 24), b""):
            h.update(block)
    td = torch.load(path, weights_only=False)
    rows = int(td.shape[0] * td.shape[1])
    buf = Buffer(half_cfg(cfg, buffer_size=rows, steps=rows))
    buf.load(td)
    return buf, {"path": path, "sha256": h.hexdigest(), "episodes": int(td.shape[0]),
                 "stored_rows": rows, "transitions": int(td.shape[0] * (td.shape[1] - 1)),
                 "tasks": sorted({int(x) for x in td["task"][:, 0].tolist()})}


def target_tensors(model):
    t = getattr(model, BL.TARGET, None)
    return [] if t is None else [v.detach().clone() for v in t.values(include_nested=True, leaves_only=True)]


def snapshot(model):
    snap = {n: p.detach().clone() for n, p in model.named_parameters()}
    snap[BL.TARGET] = target_tensors(model)
    return snap


def param_change(model, before):
    """Per parameter group (the first component of each parameter name): how many parameters changed and by how much."""
    groups = {}
    tb, ta = before[BL.TARGET], target_tensors(model)
    if tb:
        groups[BL.TARGET] = {"total": sum(x.numel() for x in ta), "changed": sum(int((a != b).sum().item()) for a, b in zip(ta, tb)),
                             "sq_change": sum(float(((a - b) ** 2).sum().item()) for a, b in zip(ta, tb)),
                             "sq_norm": sum(float((b ** 2).sum().item()) for b in tb)}
    for n, p in model.named_parameters():
        g = groups.setdefault(n.split(".")[0], {"total": 0, "changed": 0, "sq_change": 0.0, "sq_norm": 0.0})
        d = p.detach() - before[n]
        g["total"] += p.numel(); g["changed"] += int((d != 0).sum().item())
        g["sq_change"] += float((d ** 2).sum().item()); g["sq_norm"] += float((before[n] ** 2).sum().item())
    return {k: {"total": v["total"], "changed": v["changed"],
                "rel_change": (v["sq_change"] ** 0.5) / max(v["sq_norm"] ** 0.5, 1e-12)} for k, v in groups.items()}


def write_result(out_dir, out, stage):
    """Each stage is its own file, written once: bridge_adapt.A.json, bridge_adapt.adapted.json and,
    at the end only, bridge_adapt.json (stage final)."""
    out["stage"] = stage
    name = RESULT_FILE if stage == "final" else f"bridge_adapt.{stage}.json"
    BL.write_once(os.path.join(out_dir, name), out)


def collect(agent, env, buffer, task_idx, adapt_task, E, mode, out, curve=None, add_to=None, rounds=None):
    """The online loop: E decisions on the adapt task; updates from the WARMUP_EPISODES-th episode on.
    curve(step) runs after the update at each CURVE_AT step. add_to: the buffer episodes go into, when the
    update samples from a wrapper (R1); otherwise the same buffer. rounds=R (Df): no updates while
    collecting; after every R decisions (and at the end, after flushing the last episode) as many updates
    as the round's decisions minus the warm-up decisions, so the total equals the per-step schedule's."""
    add_to = add_to or buffer
    warm_decisions = WARMUP_EPISODES * EPISODE_DECISIONS
    if rounds is not None:
        assert rounds % EPISODE_DECISIONS == 0 and E % rounds == 0
    step, ep, tds, done, updates, replay = 0, 0, None, True, 0, 0
    first_update_check = None
    t0 = time.time()

    def train_round(n):
        nonlocal updates, first_update_check
        for _ in range(n):
            if updates == 0:
                before = snapshot(agent.model)
            do_update(agent, buffer, mode); updates += 1
            if updates == 1:
                first_update_check = param_change(agent.model, before); del before
        progress(f"train round: {n} updates (total {updates}) after {step} decisions")

    def flush():
        nonlocal ep, replay, tds
        ep_reward = float(torch.tensor([td['reward'] for td in tds[1:]]).sum())
        add_to.add(torch.cat(tds)); ep += 1; replay += len(tds) - 1
        out["train_episodes"].append({"episode": ep, "step": step, "reward": ep_reward})
        progress(f"train {adapt_task} episode {ep} step {step} R {ep_reward:.1f}")
        tds = None

    while step < E:
        if done:
            if tds is not None:
                flush()
                if rounds is not None and step % rounds == 0:
                    train_round(rounds - (warm_decisions if step == rounds else 0))
                    if curve is not None and step in CURVE_AT:
                        curve(step)
            obs = env.reset(task_idx=task_idx)
            tds = [to_td(env, obs, task_idx)]
        action = agent.act(obs, t0=len(tds) == 1, task=task_idx)
        obs, reward, done, info = env.step(action)
        tds.append(to_td(env, obs, task_idx, action, reward, info['terminated']))
        if rounds is None and ep >= WARMUP_EPISODES:
            if updates == 0:
                before = snapshot(agent.model)
            do_update(agent, buffer, mode); updates += 1
            if updates == 1:
                first_update_check = param_change(agent.model, before); del before
        step += 1
        if rounds is None and curve is not None and step in CURVE_AT:
            curve(step)
        elif rounds is not None and curve is not None and step in CURVE_AT and step % rounds != 0:
            curve(step)                       # a curve point inside a round: the model as last trained
    if rounds is not None and tds is not None:
        flush()                               # the last round trains on the last episode too
        train_round(rounds - (warm_decisions if step == rounds else 0))
    out["accounting"] = BL.accounting(step, replay, len(tds) if tds is not None else 0, updates, time.time() - t0)
    out["accounting"]["schedule"] = "rounds" if rounds is not None else "per-step"
    out["accounting"]["replay_episodes"] = ep
    out["param_check_first_update"] = first_update_check


def run_check(cfg, out_dir, env, eval_env, idx, tasks, adapt_task, eval_task, eval_seed):
    """One update per mode on one batch, from a fresh agent each time, plus the pairing check."""
    check = {"modes": {}, "runner": "bridge_adapt3"}
    agent = TDMPC2(cfg); agent.load(cfg.checkpoint); normalise_task_embeddings(agent)
    a1 = evaluate(agent, eval_env, idx[eval_task], 2, f"check pair-1 {eval_task}", eval_seed)
    a2 = evaluate(agent, eval_env, idx[eval_task], 2, f"check pair-2 {eval_task}", eval_seed)
    a3 = evaluate(agent, eval_env, idx[eval_task], 2, f"check other-bank {eval_task}", eval_seed + 100)
    check["pairing"] = {"same_bank_1": a1["episodes"], "same_bank_2": a2["episodes"], "identical": a1["episodes"] == a2["episodes"],
                        "other_bank": a3["episodes"]}
    original, original_info = (load_original(cfg, str(cfg.retention_data)) if cfg.get("retention_data") else (None, None))
    check["rehearsal_data"] = original_info
    buffer = Buffer(cfg)
    half = Buffer(half_cfg(cfg)) if original is not None else None
    ai = idx[adapt_task]
    for e in range(WARMUP_EPISODES):
        obs, done, tds = env.reset(task_idx=ai), False, None
        tds = [to_td(env, obs, ai)]
        while not done:
            action = agent.act(obs, t0=len(tds) == 1, task=ai)
            obs, reward, done, info = env.step(action)
            tds.append(to_td(env, obs, ai, action, reward, info['terminated']))
        buffer.add(torch.cat(tds))
        if half is not None:
            half.add(torch.cat(tds))
        progress(f"check warm-up episode {e + 1}")
    modes = [m for m in MODES[1:] if m != "rehearsal" or original is not None]
    two_update_change = {}
    for mode in modes:
        agent = TDMPC2(cfg); agent.load(cfg.checkpoint); normalise_task_embeddings(agent)
        frozen = configure_mode(agent, mode)
        if mode == "anchored":
            install_anchor(agent, CHECK_ANCHOR_LAMBDA)
        source = MixedBatches(half, original) if mode == "rehearsal" else buffer
        before = snapshot(agent.model)
        torch.manual_seed(eval_seed)          # the same batch draw for every mode
        info = do_update(agent, source, mode)
        emb = getattr(agent.model, "_task_emb", None)
        pending = None if emb is None or emb.weight.grad is None else float(emb.weight.grad.abs().sum().item())
        check["modes"][mode] = {"frozen_params": frozen, "param_change": param_change(agent.model, before),
                                "losses": {k: float(v) for k, v in info.items() if hasattr(v, "__float__")},
                                # the actor loss reaches the task embedding after the model optimiser has stepped,
                                # so its gradient waits for the NEXT update (upstream order); recorded, not judged
                                "task_emb_grad_pending_after_update": pending}
        if mode in ("full", "anchored"):      # a second update: the anchor acts only once theta has moved
            info2 = do_update(agent, source, mode)
            two_update_change[mode] = sum(v["rel_change"] for v in param_change(agent.model, before).values())
        progress(f"check update {mode}: moved {[k for k, v in check['modes'][mode]['param_change'].items() if v['changed']]}")
        del before
    check["anchor_two_update_rel_change"] = two_update_change
    passed, reasons = BL.check_verdict(check)
    check["verdict"] = {"passed": passed, "reasons": reasons}
    BL.write_once(os.path.join(out_dir, "check.json"), check)
    print("written", os.path.join(out_dir, "check.json"), "PASSED" if passed else f"FAILED: {reasons}", flush=True)
    progress(f"check verdict {'PASSED' if passed else 'FAILED'}")
    if not passed:
        raise SystemExit(CHECK_FAILED_EXIT)


def run_calibration(cfg, out_dir, tasks, idx, adapt_task):
    """R3's fixed calibration protocol (BRIDGE-DESIGN.md, R3). Healthy body only; the changed body and the
    withheld task are never seen. Stops at the first passing candidate (the smallest that passes)."""
    healthy_val = make_env(cfg)                                    # no gear change applied
    released = TDMPC2(cfg); released.load(cfg.checkpoint); normalise_task_embeddings(released)
    base = {t: evaluate(released, healthy_val, idx[t], CALIB_EPISODES, f"calib released {t}", CALIB_EVAL_SEED) for t in RETENTION_TASKS}
    del released
    cal = {"protocol": {"exponents": list(CALIB_EXPONENTS), "decisions": CALIB_DECISIONS, "eval_seed": CALIB_EVAL_SEED,
                        "episodes": CALIB_EPISODES, "tolerance": CALIB_TOLERANCE, "body": "healthy", "train_task": adapt_task},
           "released": base, "candidates": [], "selected_lambda": None}
    for k in CALIB_EXPONENTS:
        lam = 10.0 ** k
        # every candidate starts from the same training randomness: a fresh healthy environment (its task RNG
        # is seeded from cfg.seed at construction) and the same torch, numpy and python seeds. Trajectories
        # still diverge once the candidates' policies differ; that is the effect being measured.
        set_seed(cfg.seed)
        healthy_train = make_env(cfg)
        agent = TDMPC2(cfg); agent.load(cfg.checkpoint); normalise_task_embeddings(agent)
        configure_mode(agent, "anchored"); install_anchor(agent, lam)
        scratch = {"train_episodes": []}
        collect(agent, healthy_train, Buffer(cfg), idx[adapt_task], adapt_task, CALIB_DECISIONS, "anchored", scratch)
        evals = {t: evaluate(agent, healthy_val, idx[t], CALIB_EPISODES, f"calib 1e{k} {t}", CALIB_EVAL_SEED) for t in RETENTION_TASKS}
        passed = all(evals[t]["mean"] >= (1 - CALIB_TOLERANCE) * base[t]["mean"] for t in RETENTION_TASKS)
        cal["candidates"].append({"lambda": lam, "evals": evals, "passed": passed, "accounting": scratch["accounting"],
                                  "anchor_stats": anchor_stats()})
        progress(f"calib lambda 1e{k} {'passed' if passed else 'failed'}")
        del agent, healthy_train
        if passed:
            cal["selected_lambda"] = lam
            break
    BL.write_once(os.path.join(out_dir, "calibration.json"), cal)
    print("written", os.path.join(out_dir, "calibration.json"), "selected", cal["selected_lambda"], flush=True)
    if cal["selected_lambda"] is None:
        raise SystemExit(CHECK_FAILED_EXIT)


@hydra.main(config_name='config', config_path='.')
def main(cfg: dict):
    assert torch.cuda.is_available()
    cfg = parse_cfg(cfg)
    out_dir = str(cfg.get("out_dir", ""))
    assert out_dir, "pass +out_dir=/path (the upstream parser rewrites work_dir)"
    BL.claim_out_dir(out_dir)
    set_seed(cfg.seed)
    adapt_task, mode, eval_task = str(cfg.adapt_task), str(cfg.adapt_mode), str(cfg.eval_task)
    assert mode in MODES, f"adapt_mode must be one of {MODES}, got {mode}"
    joint, scale = str(cfg.gear_joint), float(cfg.gear_scale)
    train_scale = float(cfg.get("train_gear_scale", scale))
    eval_seed = int(cfg.get("eval_seed", DEFAULT_EVAL_SEED))
    E = int(cfg.steps)
    env = make_env(cfg)                 # training only
    eval_env = make_env(cfg)            # evaluation only, re-seeded per episode
    tasks = list(cfg.tasks)
    idx = {t: tasks.index(t) for t in tasks}
    BL.write_once(os.path.join(out_dir, "resolved_config.json"), dataclasses.asdict(cfg))
    out = {"runner": "bridge_adapt3", "checkpoint": cfg.checkpoint, "model_size": cfg.get("model_size"), "seed": cfg.seed, "E": E,
           "adapt_task": adapt_task, "adapt_mode": mode, "eval_task": eval_task, "retention_tasks": list(RETENTION_TASKS),
           "gear_joint": joint, "gear_scale": scale, "train_gear_scale": train_scale, "eval_seed": eval_seed,
           "warmup_episodes": WARMUP_EPISODES, "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
           "gears": {"train_env": apply_change(env, tasks, idx, joint, train_scale), "eval_env": apply_change(eval_env, tasks, idx, joint, scale)},
           "A": {}, "after": {}, "train_episodes": []}
    print(colored(f"change applied: {joint} x{scale} (eval) x{train_scale} (train) on the walker tasks", "yellow"), flush=True)
    if bool(cfg.get("check", False)):
        run_check(cfg, out_dir, env, eval_env, idx, tasks, adapt_task, eval_task, eval_seed)
        return
    if bool(cfg.get("calibrate_r3", False)):
        run_calibration(cfg, out_dir, tasks, idx, adapt_task)
        return
    agent = TDMPC2(cfg)
    agent.load(cfg.checkpoint)
    normalise_task_embeddings(agent)
    out["A"], trajs = eval_block(agent, eval_env, idx, eval_task, eval_seed, "A", record=PROBE_EPISODES)
    with open(os.path.join(out_dir, "probe_trajectories.pt"), "xb") as f:
        torch.save(trajs, f)
    out["probe"] = {"A": probe(agent, trajs, idx)}
    print(colored(f"A: {eval_task} {out['A'][eval_task]['mean']:.1f}", "green"), flush=True)
    write_result(out_dir, out, "A")
    if mode == "none":
        out["after"] = eval_block(agent, eval_env, idx, eval_task, eval_seed, "after")
        out["pairing_max_abs_diff"] = BL.pairing_verdict(out["A"], out["after"])
        out["other_bank"] = eval_block(agent, eval_env, idx, eval_task, eval_seed + 100, "other-bank")
    else:
        out["frozen_params"] = configure_mode(agent, mode)
        if mode == "anchored":
            out["anchor_lambda"] = float(cfg.anchor_lambda)
            out["anchored_params"] = install_anchor(agent, float(cfg.anchor_lambda))
        if mode == "rehearsal":
            original, out["rehearsal_data"] = load_original(cfg, str(cfg.retention_data))
            fresh = Buffer(half_cfg(cfg))
            buffer, add_to = MixedBatches(fresh, original), fresh
        else:
            buffer = add_to = Buffer(cfg)
        out["curve"] = {}

        def curve(step):
            out["curve"][str(step)] = eval_block(agent, eval_env, idx, eval_task, eval_seed, f"curve {step}", short=True)
            out["probe"][str(step)] = probe(agent, trajs, idx)
            write_result(out_dir, out, f"curve{step}")
        rounds = int(cfg.get("df_round", DF_ROUND)) if (mode == "dynamics_fixed" and str(cfg.get("df_schedule", "rounds")) == "rounds") else None
        out["df_schedule"] = {"round_decisions": rounds, "warmup_updates": DF_WARMUP, "rho": 1.0} if mode == "dynamics_fixed" else None
        collect(agent, env, buffer, idx[adapt_task], adapt_task, E, mode, out, curve=curve, add_to=add_to, rounds=rounds)
        agent.save(os.path.join(out_dir, "adapted.pt"))
        write_result(out_dir, out, "adapted")
        out["after"] = eval_block(agent, eval_env, idx, eval_task, eval_seed, "after", adapt_task=adapt_task)
        out["probe"]["after"] = probe(agent, trajs, idx)
        out["anchor_stats"] = anchor_stats()
        print(colored(f"after ({mode} on {adapt_task}, E={E}): {eval_task} {out['after'][eval_task]['mean']:.1f} (A {out['A'][eval_task]['mean']:.1f})", "green"), flush=True)
    out["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    write_result(out_dir, out, "final")
    print("written", os.path.join(out_dir, RESULT_FILE), flush=True)
    if mode == "none" and out["pairing_max_abs_diff"] != 0:
        print(colored(f"PAIRING FAILED: the no-update repeat differs from A by up to {out['pairing_max_abs_diff']}", "red"), flush=True)
        raise SystemExit(CHECK_FAILED_EXIT)


if __name__ == '__main__':
    main()