File size: 12,293 Bytes
519b688
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/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()