ExoWrist_Smolvla / code /intent_rack_demo /scripts /audit_direct_visual_dependence.py
Lyndow's picture
Add verified ExoWrist test assets (1-100)
519b688 verified
Raw History Blame Contribute Delete
12.3 kB
#!/usr/bin/env python3
"""Paired image ablations of a bound original SmolVLA action checkpoint.
State, task and Gaussian noise stay fixed. Compare correct images with black
images and images from another validation episode with a similar robot state.
This is an offline diagnostic, never a replacement for physical success tests.
"""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from transformers import AutoTokenizer
from direct_smolvla_core import (IMAGE_KEYS, TASK, cache_videos, cached_images,
load_original, make_batch)
from direct_smolvla_data import load_paired_data, sha256
def donor_for(episodes, episode_index, step, norm):
target = episodes[episode_index]
choices = []
for index, ep in enumerate(episodes):
if index == episode_index or ep['split'] != 'val' or ep['domain'] != target['domain']:
continue
distance = ((ep['state'][ep['indices']] - target['state'][step]) / norm['state_std']) ** 2
distances = distance.mean(axis=1)
selected = int(distances.argmin())
choices.append((float(distances[selected]), index, int(ep['indices'][selected])))
if not choices:
raise ValueError('no other validation episode for a same-domain image donor')
distance, index, donor_step = min(choices)
return index, donor_step, distance ** .5
def metrics(prediction, target, mask):
error = np.abs(prediction - target)
points = int(mask.sum())
return {'valid_control_points': points,
'arm_mae_rad': float((error[:, :, :6] * mask[:, :, None]).sum() / (points * 6)),
'gripper_mae_open_fraction': float((error[:, :, 6] * mask).sum() / points),
'gripper_binary_accuracy': float((((prediction[:, :, 6] >= .5) == (target[:, :, 6] >= .5)) & mask).sum() / points)}
@torch.no_grad()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--training-dir', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--batch-size', type=int, default=16)
parser.add_argument('--seed', type=int, default=26111520)
parser.add_argument('--checkpoint-name', choices=('best', 'last'), default='best')
parser.add_argument('--checkpoint-path', type=Path,
help='Immutable intermediate snapshot; requires expected SHA, never a changing last.pt')
parser.add_argument('--expected-sha256',
help='Required for last.pt when the finished training result has no final-weight hash')
args = parser.parse_args()
result_path = args.training_dir / 'result.json'
result = json.loads(result_path.read_text()) if result_path.exists() else {}
if args.checkpoint_path is None and not result.get('finished'):
raise ValueError('training has not finished; supply an explicitly hashed immutable snapshot')
checkpoint = args.checkpoint_path or args.training_dir / (args.checkpoint_name + '.pt')
if args.checkpoint_path is not None and checkpoint.resolve().parent == args.training_dir.resolve():
raise ValueError('intermediate audit must use a separate immutable snapshot')
expected_sha = args.expected_sha256 if args.checkpoint_path else (
args.expected_sha256 or result.get(args.checkpoint_name + '_checkpoint_sha256'))
if expected_sha is None:
parser.error('provide --expected-sha256 to bind the requested checkpoint')
if sha256(checkpoint) != expected_sha:
raise ValueError('checkpoint does not match finished training result')
args.output.mkdir(parents=True, exist_ok=False)
torch.set_num_threads(1)
saved = torch.load(checkpoint, map_location='cpu', weights_only=False)
if saved['format'] != 'original_smolvla_trainable_delta_v1':
raise ValueError('wrong checkpoint architecture')
cfg = saved['config']
checkpoint_step = saved['step']
if args.checkpoint_path is None:
required_step = result['selected_step'] if args.checkpoint_name == 'best' else result['steps']
if checkpoint_step != required_step:
raise ValueError('checkpoint step does not match the requested finished result')
if sha256(Path(cfg['base']) / 'model.safetensors') != cfg['base_weights_sha256']:
raise ValueError('pretrained base changed')
mode = cfg.get('action_target_mode', 'absolute')
policy = load_original(cfg['base'], chunk_size=cfg['chunk_size'], state_dim=cfg.get('state_dim', 7)).eval()
if set(saved['trainable_weights']) != {k for k, v in policy.named_parameters() if v.requires_grad}:
raise ValueError('incomplete trainable checkpoint')
policy.load_state_dict(saved['trainable_weights'], strict=False)
del saved
manifest = json.loads((args.training_dir / 'data_manifest.json').read_text())
fixed_norm = manifest['normalization'] if manifest.get('fixed_normalization_from_initial_checkpoint') else None
episodes, norm, rebuilt = load_paired_data(manifest['real_source'], manifest['real_prior_quality_audit'],
manifest['sim_source'], normalization_override=fixed_norm,
target_mode=mode, action_horizon=cfg['chunk_size'],
normalization_domain=cfg.get('training_domain', 'mixed'),
state_representation=cfg.get('state_representation', 'measured'))
for key, value in cfg['normalization'].items():
if not np.array_equal(norm[key], np.asarray(value, np.float32)):
raise ValueError('training data or normalization changed')
for before, now in zip(manifest['real'] + manifest['sim'], rebuilt['real'] + rebuilt['sim']):
if before.get('sha256') != now.get('sha256'):
raise ValueError('training source hashes changed')
indices = json.loads((args.training_dir / 'validation_indices.json').read_text())
episode_lookup = {(ep['domain'], ep['name']): i for i, ep in enumerate(episodes)}
requests = {domain: [(episode_lookup[(domain, r['episode'])], r['step']) for r in rows]
for domain, rows in indices.items()}
donors = {domain: [donor_for(episodes, j, step, norm) for j, step in pairs]
for domain, pairs in requests.items()}
used = {}
for domain, pairs in requests.items():
for j, step in pairs + [(j, step) for j, step, _ in donors[domain]]:
used.setdefault(j, set()).add(step)
# Decode only observations selected for this audit; no test episodes loaded.
for j, selected in used.items():
episodes[j]['indices'] = np.array(sorted(selected))
cache_videos([episodes[j] for j in sorted(used)], policy)
tokenizer = AutoTokenizer.from_pretrained(policy.config.vlm_model_name)
if cfg['task'] != TASK:
raise ValueError('task mismatch')
language = tokenizer([TASK + '\n'], padding='max_length', max_length=48,
truncation=True, return_tensors='pt').to('cuda')
with torch.autocast('cuda', dtype=torch.bfloat16):
black, _ = policy.prepare_images({key: torch.zeros(1, 3, 512, 512, device='cuda') for key in IMAGE_KEYS})
black_tokens = torch.stack([policy.model.vlm_with_expert.embed_image(view) for view in black], dim=1)
evidence, arrays = {}, {}
seeds = [args.seed, args.seed + 1]
for domain, pairs in requests.items():
domain_results = []
for seed in seeds:
predictions = {condition: [] for condition in ('correct', 'black', 'other_episode')}
targets, masks = [], []
generator = torch.Generator(device='cuda').manual_seed(seed)
for start in range(0, len(pairs), args.batch_size):
subset = pairs[start:start + args.batch_size]
batch, tokens = make_batch(episodes, subset, norm, language,
horizon=cfg['chunk_size'], target_mode=mode)
other = [(j, step) for j, step, _ in donors[domain][start:start + args.batch_size]]
_, other_tokens = make_batch(episodes, other, norm, language,
horizon=cfg['chunk_size'], target_mode=mode)
noise = torch.randn(len(subset), cfg['chunk_size'], 32, device='cuda', generator=generator)
anchor = np.stack([episodes[j]['state'][s, :6] for j, s in subset])[:, None, :]
for condition, condition_tokens in [('correct', tokens),
('black', black_tokens.expand(len(subset), -1, -1, -1)),
('other_episode', other_tokens)]:
policy.reset()
with cached_images(policy, condition_tokens), torch.autocast('cuda', dtype=torch.bfloat16):
prediction = policy.predict_action_chunk(dict(batch), noise=noise.clone())
raw = prediction[:, :3].float().cpu().numpy() * norm['action_std'] + norm['action_mean']
if mode == 'relative_joint':
raw[:, :, :6] += anchor
if not np.isfinite(raw).all():
raise ValueError('nonfinite predicted action')
predictions[condition].append(raw)
target = batch['action'][:, :3].cpu().numpy() * norm['action_std'] + norm['action_mean']
if mode == 'relative_joint':
target[:, :, :6] += anchor
targets.append(target)
masks.append(~batch['action_is_pad'][:, :3].cpu().numpy())
target = np.concatenate(targets); mask = np.concatenate(masks)
predictions = {key: np.concatenate(value) for key, value in predictions.items()}
rows = {}
for condition, prediction in predictions.items():
row = metrics(prediction, target, mask)
shift = metrics(prediction, predictions['correct'], mask)
row['arm_prediction_shift_from_correct_images_rad'] = shift['arm_mae_rad']
row['gripper_binary_agreement_with_correct_images'] = shift['gripper_binary_accuracy']
rows[condition] = row
arrays[f'{domain}_{seed}_{condition}'] = prediction
arrays[f'{domain}_{seed}_target'] = target
arrays[f'{domain}_{seed}_valid'] = mask
domain_results.append({'seed': seed, 'sampled_observations': len(pairs), 'conditions': rows})
evidence[domain] = {'seeds': domain_results, 'paired_observations': [
{'episode': episodes[j]['name'], 'step': step, 'donor_episode': episodes[dj]['name'],
'donor_step': ds, 'standardized_state_rms_distance': distance}
for (j, step), (dj, ds, distance) in zip(pairs, donors[domain])]}
print(json.dumps({'domain': domain, 'results': domain_results}), flush=True)
np.savez_compressed(args.output / 'predictions.npz', **arrays)
report = {'checkpoint': str(checkpoint), 'checkpoint_sha256': sha256(checkpoint),
'selected_step': checkpoint_step,
'checkpoint_name': 'explicit_snapshot' if args.checkpoint_path else args.checkpoint_name,
'training_finished_when_audit_started': bool(result.get('finished')),
'training_selected_step': result.get('selected_step'), 'by_domain': evidence,
'same_noise_state_and_task_for_all_conditions': True,
'donor_selection': 'nearest standardized measured robot state from another validation episode in the same domain',
'test_data_used': False, 'prediction_noise': 'paired standard Gaussian, two seeds',
'physical_rollout': False, 'proof_of_visual_localization_or_generalization': False,
'scope': 'Offline image-dependence diagnostic using existing validation observations, not independent tasks.'}
if report['checkpoint_sha256'] != expected_sha:
raise ValueError('checkpoint changed during audit')
(args.output / 'result.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
if __name__ == '__main__':
main()