Skip to content

[BUG] ObservationNorm.load_state_dict fails when loc/scale weren't passed at construction #4757

Open

Description

@Bndrwe

Describe the bug

If you build an ObservationNorm without loc/scale (the usual setup when you call init_stats), you can't load a checkpoint into a fresh copy of it. loc and scale are lazy UninitializedBuffers that never get filled in on load, so load_state_dict fails with a size mismatch. This breaks the normal restore flow: rebuild the env the same way as in training, then load the saved state.

To Reproduce

from torchrl.envs import GymEnv, TransformedEnv, ObservationNorm

def make_env():
    return TransformedEnv(GymEnv("Pendulum-v1"), ObservationNorm(in_keys=["observation"]))

env = make_env()
env.transform.init_stats(num_iter=20)
ckpt = env.state_dict()

env2 = make_env()          # rebuilt the same way, e.g. in an eval script
env2.load_state_dict(ckpt)
print("loaded:", env2.transform.loc, env2.transform.scale)
RuntimeError: Error(s) in loading state_dict for ObservationNorm:
	While copying the parameter named "loc", whose dimensions in the model are torch.Size([0]) and whose dimensions in the checkpoint are torch.Size([3]), ...

Expected behavior

loc and scale get filled in from the checkpoint, same as if they'd been computed with init_stats.

System info

torchrl from source at main (df1db3d), torch 2.15.0, numpy 2.5.5, Python 3.12.3, Linux. gymnasium for the repro env.

Reason and Possible fixes

Add a _load_from_state_dict that materializes loc/scale from the incoming tensors before the normal load, like RNDTransform already does for its lazy stats. I have a fix with a test and will open a PR.

Checklist

  • I have checked that there is no similar issue in the repo (required)
  • I have read the documentation (required)
  • I have provided a minimal working example to reproduce the bug (required)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions