rli14's picture
rsm_rise code snapshot (HF_PUSH_ALL) (part 5)
1c78d11 verified
Raw History Blame Contribute Delete
5.34 kB
"""gen_q#274 -- the PINNED tensordict for running TD-MPC2 inside the RISE eval environment.
WHY A PIN EXISTS AT ALL. Both TD-MPC2 configurations ((a) the shared-candidate scorer, (b) the
MPPI/CEM planner row) run in the eval process, which is $ROOT/env: python 3.10, torch 2.5.1. That
environment ships no `tensordict`, and upstream TD-MPC2 imports it unconditionally
(code/tdmpc2/tdmpc2/common/layers.py:4, `from tensordict import from_modules`). venv_tdmpc2's
tensordict 0.14.2 -- the one the models were TRAINED under -- is compiled against torch 2.14 and
cannot be copied into a torch-2.5.1 process. So the eval side needs its own tensordict, installed
isolated under `_deps/`, and the only honest way to choose one is to MEASURE that it computes the
same thing.
THE MEASUREMENT (status/nb/td_env_probe.txt, LSF 1881576, 2026-09-23 13:47Z). `TDMPC2Backend`
loaded our own v2 checkpoint and ran `_estimate_value` on a FIXED input, first in venv_tdmpc2
(torch 2.14 / tensordict 0.14.2 -- the reference) and then under each candidate:
reference (venv_tdmpc2) [19.00000000, 19.99600601, 18.99999237, 19.97927284]
tensordict 0.6.2 [18.99999619, 19.99600983, 18.99999428, 19.97927475] max|d| 3.8e-6
tensordict 0.6.1 [18.99999619, 19.99601364, 18.99999428, 19.97927475] max|d| 7.6e-6
tensordict 0.6.0 [18.99999619, 19.99600983, 19.00000191, 19.97927475] max|d| 3.8e-6
tensordict 0.5.0 DOES NOT IMPORT (`from_modules` absent)
3.8e-6 on a value of ~20 is 2e-7 relative -- float32 reduction-order noise between two torch
versions, not a change in what the model computes. **0.6.2 is pinned** (newest of the three that
both imports and reproduces). If a future check finds these numbers moving, the pin is what to
revisit; the version actually used is printed at load and recorded in every TD cell's JSON.
WHAT THIS MODULE DOES NOT DO. It does not install anything into a shared environment: `_deps/` is a
`pip install --target` tree owned by this stream. It never shadows an env package -- the pinned
path is APPENDED, so if $ROOT/env ever grows its own tensordict that one wins and this module says
so out loud rather than silently overriding it. Weights are never touched; see td_env_compat.py for
the metadata-only state-dict shim and the same warning about self-certification.
"""
from __future__ import annotations
import sys
from pathlib import Path
PINNED_VERSION = "0.6.2"
DEPS = Path("/proj/dmfexp/zwhong/rsm_rise/code/tdmpc2_rise/_deps")
PIN_PATH = DEPS / f"td{PINNED_VERSION}"
EVIDENCE = "status/nb/td_env_probe.txt (LSF 1881576): max|dQ| 3.8e-6 vs venv_tdmpc2"
_STATE = {"installed": False, "version": None, "source": None}
def install(strict=True, verbose=True):
"""Make `tensordict` importable in this process; return (version, source).
No-op when tensordict already imports (e.g. inside venv_tdmpc2, where 0.14.2 is the native and
correct one) -- in that case `source='native'` and the pin is not used at all.
"""
if _STATE["installed"]:
return _STATE["version"], _STATE["source"]
try:
import tensordict # noqa: F401
src = "native"
except ImportError:
if not PIN_PATH.is_dir():
raise RuntimeError(
f"tensordict is not importable and the pinned copy is missing: {PIN_PATH}. "
f"Re-create it with `pip install --target {PIN_PATH} tensordict=={PINNED_VERSION}` "
f"and RE-RUN scripts/nb/td_env_probe.sh -- the pin is only valid with its "
f"numerical evidence ({EVIDENCE}).")
sys.path.append(str(PIN_PATH)) # APPEND: an env-provided tensordict always wins
import tensordict # noqa: F811
src = str(PIN_PATH)
ver = getattr(tensordict, "__version__", "?")
if strict and src != "native" and ver != PINNED_VERSION:
raise RuntimeError(f"pinned tensordict is {ver}, expected {PINNED_VERSION} ({EVIDENCE})")
if src == "native" and ver != PINNED_VERSION and verbose:
print(f"[td_env_pin] using the ENVIRONMENT's tensordict {ver}, not the pin "
f"{PINNED_VERSION}. That is correct inside venv_tdmpc2 (0.14.2 trained these "
f"models); anywhere else the equivalence evidence does not cover it.", flush=True)
if verbose:
import torch
print(f"[td_env_pin] tensordict {ver} from {src} (torch {torch.__version__}); "
f"equivalence: {EVIDENCE}", flush=True)
# The metadata shim is a no-op under 0.14.2 (the live model advertises no __batch_size keys, so
# nothing is injected), so it is safe to install unconditionally and keeps ONE code path.
try:
sys.path.insert(0, str(Path(__file__).parent))
from td_env_compat import install_state_dict_metadata_compat
install_state_dict_metadata_compat()
except Exception as e: # never let the shim break a process that does not need it
print(f"[td_env_pin] metadata compat not installed ({type(e).__name__}: {e})", flush=True)
_STATE.update(installed=True, version=ver, source=src)
return ver, src
def describe():
return {"tensordict_version": _STATE["version"], "tensordict_source": _STATE["source"],
"tensordict_pin": PINNED_VERSION, "tensordict_equivalence_evidence": EVIDENCE}