Views
No views yet
weights_only=Trueobs_dim inside the checkpointact_dimnet.0, net.2, and net.4.self.net = nn.Sequential(...).fc1, fc2, etc. will break loading.obs_dim and act_dim from the checkpoint.weights_only=True.log_std.1import torch
2import gymnasium as gym
3import numpy as np
4from huggingface_hub import hf_hub_download
5
6ckpt_path = hf_hub_download(
7 repo_id="Nharen/Reward_Rush_SAC_Walker",
8 filename="Walker.pth"
9)
10
11ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=True)
12
13obs_dim = ckpt["obs_dim"]
14act_dim = ckpt["act_dim"]
15hidden_dim = ckpt.get("hidden_dim", 256)
16
17class SACActor(torch.nn.Module):
18 def __init__(self, obs_dim, act_dim, hidden_dim=256):
19 super().__init__()
20 self.net = torch.nn.Sequential(
21 torch.nn.Linear(obs_dim, hidden_dim),
22 torch.nn.ReLU(),
23 torch.nn.Linear(hidden_dim, hidden_dim),
24 torch.nn.ReLU(),
25 torch.nn.Linear(hidden_dim, hidden_dim),
26 torch.nn.ReLU(),
27 )
28 self.mean = torch.nn.Linear(hidden_dim, act_dim)
29 self.log_std = torch.nn.Linear(hidden_dim, act_dim)
30
31 def forward(self, obs):
32 x = self.net(obs)
33 return torch.tanh(self.mean(x))
34
35actor = SACActor(obs_dim, act_dim, hidden_dim)
36actor.load_state_dict(ckpt["actor_state_dict"])
37actor.eval()
38
39env = gym.make("Walker2d-v4")
40
41num_episodes = 100
42episode_rewards = []
43
44for ep in range(num_episodes):
45 obs, _ = env.reset()
46 done = False
47 ep_reward = 0.0
48
49 while not done:
50 with torch.no_grad():
51 obs_t = torch.tensor(obs, dtype=torch.float32).unsqueeze(0)
52 action = actor(obs_t).squeeze(0).cpu().numpy()
53
54 obs, reward, terminated, truncated, _ = env.step(action)
55 ep_reward += reward
56 done = terminated or truncated
57
58 episode_rewards.append(ep_reward)
59 print(f"Episode {ep + 1:3d} | Reward: {ep_reward:.2f}")
60
61env.close()
62
63episode_rewards = np.array(episode_rewards)
64
65print("Episodes:", num_episodes)
66print("Mean reward:", episode_rewards.mean())
67print("Std reward:", episode_rewards.std())
68print("Min reward:", episode_rewards.min())
69print("Max reward:", episode_rewards.max())