File size: 3,145 Bytes
4472162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Load a Feel-WM checkpoint and roll it out. Run from a clone of the feel-wm code repo.

    python example.py <weights dir> [image.png]      # e.g. tartandrive1
"""
import sys
from pathlib import Path

import numpy as np
import torch
from PIL import Image
from safetensors.torch import load_file

from feelwm.config import load_config
from feelwm.data.normalize import NormStats, denormalize_feature, normalize_action, normalize_window
from feelwm.data.normalize import resolve_channel_indices
from feelwm.models.encoders.dinov2_reg import Dinov2RegEncoder
from feelwm.models.terrain_wm import ModelConfig, TerrainWorldModel

folder = Path(sys.argv[1])
device = "cuda" if torch.cuda.is_available() else "cpu"
cfg = load_config(folder / "config.yaml")
stats = NormStats.from_json(folder / "norm_stats.json")
model = TerrainWorldModel(ModelConfig(**cfg["model"])).to(device).eval()
model.load_state_dict(load_file(folder / "model.safetensors", device=device))

# --- 4 context frames, oldest first, 0.4 s apart (stride 4). One image is repeated here.
img = (Image.open(sys.argv[2]).convert("RGB") if len(sys.argv) > 2
       else Image.fromarray(np.full((544, 1024, 3), 128, np.uint8)))
x = torch.from_numpy(np.asarray(img, np.float32) / 255.0).permute(2, 0, 1)[None]
x = torch.nn.functional.interpolate(x, size=(224, 224), mode="bicubic", align_corners=False)
x = (x - torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)) / torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
with torch.inference_mode():
    z = Dinov2RegEncoder().to(device).eval()(x.to(device))                 # [1, 256, 768]
z_context = z[:, None].expand(1, 4, 256, 768).contiguous()

# --- proprioception: 50 samples at 100 Hz per frame, always in the full 14-column order.
# Dummy values: level, 3 m/s straight ahead. Replace with your sensor data.
window = np.zeros((4, 50, 14), np.float32)
window[..., 2], window[..., 6] = 9.81, 3.0
window = normalize_window(window, stats)
cols = cfg["data"].get("window_columns")
if cols is not None:                       # TD1: 12 columns, selected AFTER normalization
    window = window[..., cols]

# --- 8 future steps: (dx, dy, dyaw) per 0.1 s in the body frame, normalized, then dt in s.
stride, horizon = 4, cfg["model"]["rollout_horizon"]
rate = normalize_action(np.tile(np.float32([[0.3, 0.0, 0.0]]), (horizon, 1)), stats)
actions = np.concatenate([rate, np.full((horizon, 1), stride * 0.1, np.float32)], axis=1)

batch = {"z_vis_context": z_context,
         "proprio_window_context": torch.from_numpy(window.astype(np.float32))[None].to(device)}
with torch.inference_mode():
    out = model.forward_rollout(batch, torch.from_numpy(actions.astype(np.float32))[None].to(device))

names = cfg["loss"]["channel_names"]
pred = denormalize_feature(out["f_prop_preds"][0].cpu().numpy(), stats, resolve_channel_indices(names))
print("predicted visual features:", tuple(out["z_vis_preds"].shape))
print("predicted proprioceptive features, step 1:", dict(zip(names, pred[0].round(3).tolist())))
print("failure risk per step:", None if out["c_preds"] is None
      else out["c_preds"][0].flatten().cpu().numpy().round(3).tolist())