kinejing-open-source / projects /sparse-world-dynamics /evaluate_spatial_interventions.py
zoah111's picture
Publish reviewed KineJing technical release (dataset, batch 10/16)
c9b8d8d verified
Raw History Blame Contribute Delete
3.88 kB
"""Matched histories, same camera, genuinely different physical action futures.
No simulator positions are fed to the model. This diagnostic is not AIM's
density-estimation/RL collection algorithm, and makes no data-efficiency claim.
"""
import argparse,hashlib,json
from pathlib import Path
import numpy as np
import torch
from scratch_persistent_world import scenes,ScratchConfig
from scratch_spatial_world import SpatialPersistentWorld
from train_scratch_persistent import tensors
@torch.no_grad()
def main():
p=argparse.ArgumentParser();p.add_argument('run',type=Path);p.add_argument('--seed',type=int,default=12501);a=p.parse_args()
torch.set_num_threads(4);device='cuda' if torch.cuda.is_available() else 'cpu'
saved=torch.load(a.run/'checkpoint.pt',map_location='cpu',weights_only=True)
model=SpatialPersistentWorld(ScratchConfig(**saved['config'])).to(device).eval();model.load_state_dict(saved['model'])
original=scenes(a.seed,32,16);left=original['actions'].copy();right=left.copy()
# First four transitions and all camera poses are identical. Only subsequent
# object-force directions differ, held constant to produce observable effects.
left[:,4:,:2]=0;right[:,4:,:2]=0;left[:,4:,4]=0;right[:,4:,4]=0
force=np.random.default_rng(a.seed+1).uniform(-1,1,(32,1,2)).astype(np.float32)
force=force/np.maximum(np.linalg.norm(force,axis=-1,keepdims=True),.01)
left[:,4:,2:4]=force;right[:,4:,2:4]=-force
arms=[scenes(a.seed,32,16,actions_override=actions) for actions in (left,right)]
assert np.array_equal(arms[0]['images'][:,:5],arms[1]['images'][:,:5])
assert np.array_equal(arms[0]['poses'],arms[1]['poses'])
predicted=[]
for data in arms:
rgb,poses,actions=tensors(data,device);state=None;frame=rgb[:,0];frames=[]
for t in range(16):
frame,state,_,_=model.step(rgb[:,t] if t<4 else frame,poses[:,t],actions[:,t],poses[:,t+1],state,observe=t<4)
frames.append(frame)
predicted.append(torch.stack(frames,1))
truth=[torch.from_numpy(x['images'][:,1:]).to(device).float()/255 for x in arms]
effect=truth[0]-truth[1];estimate=predicted[0]-predicted[1];rows=[]
for t in range(4,16):
mask=((truth[0][:,t].amax(1,keepdim=True)-truth[0][:,t].amin(1,keepdim=True))>.12)|((truth[1][:,t].amax(1,keepdim=True)-truth[1][:,t].amin(1,keepdim=True))>.12)
def score(error):return float((error.square()*mask).sum()/(3*mask.sum()).clamp_min(1))
rows.append(dict(target_frame=t+1,action_effect_mse=float((estimate[:,t]-effect[:,t]).square().mean()),
zero_response_mse=float(effect[:,t].square().mean()),foreground_action_effect_mse=score(estimate[:,t]-effect[:,t]),
foreground_zero_response_mse=score(effect[:,t]),predicted_effect_energy=float(estimate[:,t].square().mean())))
mean=sum(r['action_effect_mse'] for r in rows)/len(rows);zero=sum(r['zero_response_mse'] for r in rows)/len(rows)
report=dict(status='PAIRED_PHYSICAL_ACTION_DIAGNOSTIC_COMPLETED',scene_seed=a.seed,episodes=32,
identical_first_five_images=True,identical_camera_poses=True,only_future_body_force_intervened=True,
intervention_start_action=4,rows=rows,mean_action_effect_mse=mean,mean_zero_response_mse=zero,
beats_zero_response=mean<zero,model_inputs_include_hidden_physical_state=False,
scope='New synthetic development diagnostic, one trained model seed; not a broad benchmark',
trained_100B_model=False,general_world_model=False,source_sha256={n:hashlib.sha256((Path(__file__).parent/n).read_bytes()).hexdigest()
for n in ['evaluate_spatial_interventions.py','scratch_persistent_world.py','scratch_spatial_world.py']})
(a.run/'physical-interventions.json').write_text(json.dumps(report,indent=2),encoding='utf-8')
print(json.dumps(report))
if __name__=='__main__':main()