rsm_rise_code / code_src /tdmpc2_rise /diag_ensemble.py
rli14's picture
rsm_rise code snapshot (HF_PUSH_ALL) (part 5)
1c78d11 verified
Raw History Blame Contribute Delete
3.92 kB
"""gen_q#274: does gradient reach `layers.Ensemble.params` at all? CPU, no optimizer.
The GPU diagnostic is blocked behind Adam(capturable=True); this one is not, because gradient flow
needs only forward+backward. If the ensemble's leaves get no gradient here, that -- not the
optimizer -- is why every TD-MPC2 cell reports the uniform-logit value_loss ln(101)*1.75/3.
"""
from __future__ import annotations
import sys
from pathlib import Path
import torch
ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
sys.path.insert(0, str(Path(__file__).parent))
from td_corpus import TD_SRC, install_safe_to, install_ensemble_grad_fix # noqa
sys.path.insert(0, str(TD_SRC))
import tensordict, torch.nn as nn
print("torch", torch.__version__, "tensordict", tensordict.__version__)
from common import layers, init
from common.world_model import WorldModel
# --- (1) the bare Ensemble, nothing else -----------------------------------
mods = [layers.mlp(8, [16, 16], 4).apply(init.weight_init) for _ in range(5)]
ens = layers.Ensemble(mods)
init.zero_([ens.params["2", "weight"]]) # upstream's own zero-init of the last layer
x = torch.randn(3, 8)
out = ens(x)
ref = out.detach().clone()
print("[1] ensemble out", tuple(out.shape), "requires_grad", out.requires_grad,
"grad_fn", type(out.grad_fn).__name__ if out.grad_fn else None)
try:
torch.manual_seed(1); (out - torch.randn_like(out)).square().mean().backward()
gs = {".".join(k) if isinstance(k, tuple) else k:
(None if v.grad is None else float(v.grad.abs().max()))
for k, v in ens.params.items(True, True)}
except RuntimeError as e:
gs = {}; print("[1] backward raised:", e)
print("[1] grads on ensemble leaves:", gs)
print("[1] VERDICT:", "gradient ARRIVES" if any(g for g in gs.values()) else "NO GRADIENT -- ensemble is dead")
# --- (1b) the same ensemble with the runtime fix installed ------------------
install_ensemble_grad_fix()
for _, v in ens.params.items(True, True):
v.grad = None
out2 = ens(x)
same = torch.allclose(out2.detach(), ref, atol=0, rtol=0)
print("[1b] patched out", tuple(out2.shape), "requires_grad", out2.requires_grad,
"| BITWISE IDENTICAL to unpatched forward:", same,
"| max abs diff", float((out2.detach() - ref).abs().max()))
assert same, "the fix changed the forward pass -- refuse it"
torch.manual_seed(1); (out2 - torch.randn_like(out2)).square().mean().backward()
gs1b = {".".join(k) if isinstance(k, tuple) else k:
(None if v.grad is None else float(v.grad.abs().max()))
for k, v in ens.params.items(True, True)}
print("[1b] grads on ensemble leaves:", gs1b)
print("[1b] VERDICT:", "gradient ARRIVES" if any(g for g in gs1b.values()) else "STILL DEAD")
# --- (2) the same question through the real WorldModel.Q --------------------
install_safe_to()
from common.parser import parse_cfg # noqa
sys.path.insert(0, str(Path(__file__).parent))
from td_corpus import build_cfg # noqa
cfg = build_cfg(horizon=3, gamma=0.99, model_size=5, batch_size=8, seed=0, work_dir="/tmp")
torch.manual_seed(0)
m = WorldModel(cfg) # stays on CPU; no optimizer involved
z = m.encode(torch.randn(8, cfg.obs_shape["state"][0]), None)
a = torch.randn(8, cfg.action_dim).clamp(-1, 1)
q = m.Q(z, a, None, return_type="all")
print("[2] Q out", tuple(q.shape), "requires_grad", q.requires_grad)
torch.manual_seed(1); (q - torch.randn_like(q)).square().mean().backward() # fix installed by [1b]
gs2 = {".".join(k) if isinstance(k, tuple) else k:
(None if v.grad is None else float(v.grad.abs().max()))
for k, v in m._Qs.params.items(True, True)}
print("[2] grads on _Qs leaves:", gs2)
print("[2] control, _reward[-1].weight grad:",
None if m._reward[-1].weight.grad is None else float(m._reward[-1].weight.grad.abs().max()))
print("[2] VERDICT:", "gradient ARRIVES" if any(g for g in gs2.values()) else "NO GRADIENT -- _Qs is dead")