CL_lt / REGEN-main /forgetting_task0_run.py
ltttttttttttttt's picture
Add files using upload-large-folder tool
6af6154 verified
Raw
History Blame Contribute Delete
5.85 kB
"""Teacher-vs-Student forgetting on 2 task0 rollouts.
Reuses the *validated* obs-building + model-loading from run_libero_hdf5_replay
(the schema the forgetting_harness TODO(seam) never confirmed), and the harness
forgetting metric (per-query normalised L2 action drift, same seed for both
models so it measures parameter drift, not diffusion sampling noise).
Teacher = base_stage/iter_000020000 (the ckpt task2-ft was finetuned FROM)
Student = student_task2_ft200/iter_000000200 (after 200 steps of task2 finetune)
Old task = task0 "open the middle drawer of the cabinet"
"""
import os
import numpy as np
import h5py
from cosmos_policy.experiments.robot.libero.run_libero_hdf5_replay import (
Hdf5ReplayEvalConfig,
load_libero_demo_sequences,
observation_from_training_hdf5_frame,
)
from cosmos_policy.experiments.robot.cosmos_utils import (
get_action,
get_model,
init_t5_text_embeddings_cache,
load_dataset_stats,
)
from cosmos_policy.experiments.robot.robot_utils import get_image_resize_size
from cosmos_policy.experiments.robot.libero.forgetting_harness import per_query_diff, _tail_mean
ROOT = "/home/azureuser/REGEN-main"
TEACHER = f"{ROOT}/checkpoints/imaginaire4-output/cosmos_policy/cosmos_v2_finetune/cosmos_predict2_2b_480p_libero_goal_base_stage/checkpoints/iter_000020000/model"
STUDENT = f"{ROOT}/checkpoints/imaginaire4-output/cosmos_policy/cosmos_v2_finetune/cosmos_predict2_2b_480p_libero_goal_student_task2_ft200/checkpoints/iter_000000200/model"
ROLLOUT_DIR = f"{ROOT}/LIBERO-Cosmos-Policy/REGEN-DataGen-task0-cosmos_predict2_2b_480p_libero_goal_base_stage-seed195.bak-9rollouts"
FILES = [
f"{ROLLOUT_DIR}/open_the_middle_drawer_of_the_cabinet_demo1.hdf5",
f"{ROLLOUT_DIR}/open_the_middle_drawer_of_the_cabinet_demo2.hdf5",
]
DEMO_KEY = "demo_0" # each rollout file holds a single demo under data/demo_0
TASK = "open the middle drawer of the cabinet"
SEED = 1 # SAME seed for both models (drift, not sampling noise)
cfg = Hdf5ReplayEvalConfig()
cfg.config = "cosmos_predict2_2b_480p_libero_cl_stage_inference_only"
cfg.config_file = "cosmos_policy/config/config.py"
cfg.dataset_stats_path = f"{ROOT}/LIBERO-Cosmos-Policy/success_only/libero_goal_regen/dataset_statistics.json"
cfg.t5_text_embeddings_path = f"{ROOT}/LIBERO-Cosmos-Policy/success_only/t5_embeddings.pkl"
cfg.flip_images = False # rollouts were generated with flip_images=False
cfg.randomize_seed = False
cfg.deterministic = True
cfg.num_denoising_steps_action = 5
STRIDE = cfg.num_open_loop_steps # requery every 16 steps, like eval
print("[setup] init t5 cache + dataset stats + resize", flush=True)
init_t5_text_embeddings_cache(cfg.t5_text_embeddings_path)
dataset_stats = load_dataset_stats(cfg.dataset_stats_path)
resize_size = get_image_resize_size(cfg.model_family)
# per-dim action range so the score is a fraction of the valid action span → [0,1]
astd = np.asarray(dataset_stats["actions_std"], dtype=np.float32).reshape(-1)
amin = np.asarray(dataset_stats["actions_min"], dtype=np.float32).reshape(-1)
amax = np.asarray(dataset_stats["actions_max"], dtype=np.float32).reshape(-1)
arange = np.where((amax - amin) > 1e-6, (amax - amin), 1.0)
print(f"[setup] resize={resize_size} actions_range={np.round(arange,4)}", flush=True)
print(f"[load] teacher <- {TEACHER}", flush=True)
cfg.ckpt_path = TEACHER
model_t, _ = get_model(cfg)
print(f"[load] student <- {STUDENT}", flush=True)
cfg.ckpt_path = STUDENT
model_s, _ = get_model(cfg)
def action_chunk(model, obs):
out = get_action(cfg, model, dataset_stats, obs, TASK, seed=SEED,
randomize_seed=False, num_denoising_steps_action=cfg.num_denoising_steps_action)
a = out["actions"] if isinstance(out, dict) else out
a = np.asarray(a, dtype=np.float32)
return a.reshape(-1, a.shape[-1])
def chunk_forget_score(a_t, a_s):
"""[0,1] forgetting for one chunk: mean over (steps x dims) of
min(|a_teacher - a_student| / action_range, 1). 0 = identical, 1 = fully changed."""
n = min(len(a_t), len(a_s))
frac = np.abs(a_t[:n] - a_s[:n]) / arange # (n, 7) fraction of action range
return float(np.minimum(frac, 1.0).mean())
all_scores = []
per_demo = []
for fi, path in enumerate(FILES):
with h5py.File(path, "r") as f:
demo_key = list(f["data"].keys())[0] # each rollout file holds a single demo
primary, wrist, proprio, actions = load_libero_demo_sequences(path, demo_key)
T = len(actions)
chunk_scores = []
query_ts = list(range(0, T - 1, STRIDE))
for t in query_ts:
obs = observation_from_training_hdf5_frame(primary, wrist, proprio, t, resize_size, cfg.flip_images)
a_t = action_chunk(model_t, obs)
a_s = action_chunk(model_s, obs)
chunk_scores.append(chunk_forget_score(a_t, a_s))
all_scores.extend(chunk_scores)
per_demo.append((os.path.basename(path), query_ts, chunk_scores))
print(f"\n[{fi+1}/{len(FILES)}] {os.path.basename(path)} (demo_key={demo_key}, {len(chunk_scores)} chunks)", flush=True)
for ci, (t, sc) in enumerate(zip(query_ts, chunk_scores)):
print(f" chunk {ci:2d} (t={t:3d}): forget={sc:.3f}", flush=True)
dm = np.asarray(chunk_scores, dtype=np.float32)
print(f" -> demo mean={dm.mean():.3f} min={dm.min():.3f} max={dm.max():.3f}", flush=True)
all_scores = np.asarray(all_scores, dtype=np.float32)
print("\n================ FORGETTING SCORE (0=no forgetting, 1=fully forgotten) ================")
print(f"overall mean forgetting = {all_scores.mean():.3f} over {len(all_scores)} chunks (2 task0 trajectories)")
print(f"chunk score range = [{all_scores.min():.3f}, {all_scores.max():.3f}]")
print("per-chunk metric = mean over (16 action steps x 7 dims) of min(|a_teacher - a_student| / action_range, 1)")