File size: 3,096 Bytes
1c78d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""gen_q#274 -- make a TD-MPC2 checkpoint loadable INSIDE the RISE eval environment.

THE SITUATION, measured (status/nb/td_env_probe.txt, LSF 1881480 / 1881553 / 1881557):
  * both TD-MPC2 configurations run in the eval process ($ROOT/env: python 3.10, torch 2.5.1);
  * that environment has no `tensordict`, and venv_tdmpc2's 0.14.2 is compiled against torch 2.14,
    so it cannot simply be copied in;
  * tensordict 0.6.2 / 0.6.1 / 0.6.0 DO import cleanly under torch 2.5.1 (0.5.0 does not: no
    `from_modules`), but loading OUR checkpoint into one of them dies with
        KeyError: You are trying to pop key `('__batch_size',)` which is not in dict
    because a `TensorDictParams.load_state_dict` of that vintage REQUIRES the `__batch_size` /
    `__device` metadata entries, while the tensordict 0.14.2 that SAVED our checkpoints no longer
    emits them.  It is the mirror image of the drift that broke the released-checkpoint reproduction
    (code/tdmpc2_rise/td_repro_compat.py) and, like it, is a library-version fact, not a property of
    the method, of our data or of the numbers.

THE SHIM: before loading, copy the metadata entries the LIVE model's own state_dict advertises into
the checkpoint dict wherever the checkpoint lacks them.  Only metadata keys (`__batch_size`,
`__device`) are ever added; **not one weight is touched or substituted**, and every key added is
printed.

THIS IS NOT SELF-CERTIFYING.  A shim that makes a load succeed can still change what the model
computes.  The acceptance test is therefore numerical and external: `scripts/nb/td_env_probe.sh`
requires `TDMPC2Backend._estimate_value` under the shimmed eval environment to return the SAME value
as venv_tdmpc2 (the environment the model was trained in) on a fixed input.  Nothing in the eval
process may use this shim until that check has passed and its numbers are in the log.
"""
from __future__ import annotations

_META = ("__batch_size", "__device")
_INSTALLED = False


def _inject_metadata(model, sd):
    own = model.state_dict()
    added = []
    for k in own:
        if k.rsplit(".", 1)[-1] in _META and k not in sd:
            sd[k] = own[k]
            added.append(k)
    print(f"[td_env_compat] tensordict metadata entries injected from the live model "
          f"(no weights touched): {added or 'none'}", flush=True)
    return sd


def install_state_dict_metadata_compat():
    """Wrap `td_corpus.load_real_state_dict` so the metadata entries are filled before the load."""
    global _INSTALLED
    if _INSTALLED:
        return
    import td_corpus
    _orig = td_corpus.load_real_state_dict

    def _patched(model, sd):
        return _orig(model, _inject_metadata(model, dict(sd)))

    td_corpus.load_real_state_dict = _patched
    try:                      # td_backend imported the name directly
        import td_backend
        if hasattr(td_backend, "load_real_state_dict"):
            td_backend.load_real_state_dict = _patched
    except Exception:
        pass
    _INSTALLED = True
    print("[td_env_compat] state-dict metadata compat installed", flush=True)