Log locked motion-transfer run and verified derived artifacts
Browse filesFiles changed (24)
- attention_secondary_motion_transfer_20261202/README.md+9-3
- attention_secondary_motion_transfer_20261202/REPORT.mdAdded+119
- attention_secondary_motion_transfer_20261202/diagnostics/append_mechanics.pyAdded+59
- attention_secondary_motion_transfer_20261202/diagnostics/archived_split.pyAdded+57
- attention_secondary_motion_transfer_20261202/diagnostics/first_impact.pyAdded+72
- attention_secondary_motion_transfer_20261202/diagnostics/impact_trace.pyAdded+224
- attention_secondary_motion_transfer_20261202/diagnostics/launch_direction.pyAdded+77
- attention_secondary_motion_transfer_20261202/diagnostics/report.pyAdded+107
- attention_secondary_motion_transfer_20261202/diagnostics/results/REPORT.md+1-1
- attention_secondary_motion_transfer_20261202/diagnostics/results/all_learned_launch_summary.jsonAdded+62
- attention_secondary_motion_transfer_20261202/diagnostics/results/corrected_launch_direction.jsonAdded+102
- attention_secondary_motion_transfer_20261202/diagnostics/results/corrected_launch_direction_scenes.jsonl.gzAdded+3
- attention_secondary_motion_transfer_20261202/diagnostics/results/corrected_launch_paired_summary.jsonAdded+34
- attention_secondary_motion_transfer_20261202/diagnostics/results/current_launch_direction.jsonAdded+102
- attention_secondary_motion_transfer_20261202/diagnostics/results/current_launch_direction_scenes.jsonl.gzAdded+3
- attention_secondary_motion_transfer_20261202/diagnostics/results/first_impact_scenes.jsonl.gzAdded+3
- attention_secondary_motion_transfer_20261202/diagnostics/results/joint_impulse_scenes.jsonl.gzAdded+3
- attention_secondary_motion_transfer_20261202/diagnostics/results/mass_launch_direction.jsonAdded+102
- attention_secondary_motion_transfer_20261202/diagnostics/results/mass_launch_direction_scenes.jsonl.gzAdded+3
- attention_secondary_motion_transfer_20261202/diagnostics/results/simulator_impacts.jsonl.gzAdded+3
- attention_secondary_motion_transfer_20261202/diagnostics/runner.pyAdded+16
- attention_secondary_motion_transfer_20261202/diagnostics/simulator_contacts.pyAdded+111
- attention_secondary_motion_transfer_20261202/make_final_report.pyAdded+178
- attention_secondary_motion_transfer_20261202/motion_transfer.pngAdded
1123345567891011# JAIS second-impact motion transfer# JAIS motion transfer and third-hit timing
The current attention model reproduced every recipient and impact frame from the earlier run across 5,500 simulator-state test scenes and 127 RGB chains. On the original 29 RGB misses, C left the model’s second hit at 0.591 m/s on average, versus 0.962 m/s in the simulator. Model fitting and final evaluation are in progress on JAIS_setup.On the 127 RGB chains, calibrating the attention model’s inferred relative masses recovered 82/127 ordered third hits, compared with 80 for current attention, 74 for the impulse correction and 82 for the frozen solver. Mass calibration recovered 2/29 of the original misses and preserved 80/80 previous successes. Its RGB C-speed MAE changed by -0.005 [-0.029, +0.019] m/s relative to current attention (paired 95% interval).
[Registered protocol](protocol.json) · [29 diagnostic scene IDs](frozen/fixed_29.json) · [Baseline kinematics](diagnostics/results/matched_impact_kinematics.json)The solver remained stronger on the full state cohort’s 131 edited three-hit chains. It recovered 106 third recipients and timed all three hits within ±2 frames in 44 scenes. The corresponding counts were 99 and 30 for calibrated attention, and 93 and 30 for current attention. On RGB the solver timed all three in 34/127, against 24/127 for mass calibration.
On the original 29 misses, the first speed loss occurs when A hits B. The mean predicted first kick is 1.761 m/s versus 2.606 in the simulator. The trained mass calibration raises B’s outgoing speed from 1.619 to 1.748 m/s. The simulator averages 2.218 m/s on those same 29 scenes.
[Read the full four-model evaluation](REPORT.md) · [Inspect the simulator-force diagnosis](diagnostics/results/REPORT.md)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119# Why C leaves the second hit too slowly
On the 127 RGB chains, calibrating the attention model’s inferred relative masses recovered 82/127 ordered third hits, compared with 80 for current attention, 74 for the impulse correction and 82 for the frozen solver. Mass calibration recovered 2/29 of the original misses and preserved 80/80 previous successes. Its RGB C-speed MAE changed by -0.005 [-0.029, +0.019] m/s relative to current attention (paired 95% interval).
The solver remained stronger on the full state cohort’s 131 edited three-hit chains. It recovered 106 third recipients and timed all three hits within ±2 frames in 44 scenes. The corresponding counts were 99 and 30 for calibrated attention, and 93 and 30 for current attention. On RGB the solver timed all three in 34/127, against 24/127 for mass calibration.

## The error starts when A hits B
The 29 cases were selected because the frozen attention model identifies B and C in order, then reports no third recipient. A arrives at H1 with essentially the correct closing speed (3.853 m/s predicted, 3.813 m/s simulated). The model assigns A a sender mass fraction of 0.430, compared with 0.631 in the simulator. Its normal kick into B averages 1.761 m/s versus 2.606. Using the true mass fraction in that single predicted impulse raises it to 2.469 m/s and cuts kick MAE from 0.971 to 0.403 m/s, improving 24/29. This is an evaluation-only calculation at the original collision.
| Registered mean, original 29 RGB misses | Frozen attention | Simulator ||---|---:|---:|| B speed after H1 (m/s) | 1.619 | 2.218 || B speed entering H2 (m/s) | 1.458 | 2.113 || B–C normal closing speed at H2 (m/s) | 1.226 | 1.752 || Normal kick from B to C (m/s) | 0.614 | 0.822 || C speed after H2 (m/s) | 0.591 | 0.962 || C speed toward D (m/s) | 0.436 | 0.810 |
Simulator readings use the original 240 Hz force and state records. The model readings use the strongest registered contact substep in its own predicted impact frame. At H1 the smaller effective transfer gain accounts for most of the missing kick. At H2 the incoming closing speed is already too low in 25/29. B’s launch heading error averages 4.6°, C’s outgoing heading error 8.2°. In 24/29 the predicted C–D surfaces stay more than 4.5 cm apart, and only 3/29 generate a nonzero subthreshold C→D impulse. A blanket reduction of the contact threshold would leave most misses untouched. [Force records, direction errors, and matched traces](diagnostics/results/REPORT.md).
## What each forecaster uses
| Forecaster | Difference at inference ||---|---|| Current attention | Frozen stochastic attention checkpoint. From the factual prefix it predicts latent physical properties, routes contact messages, and rolls out the intervention. || Impulse correction | The validation-selected correction can rotate a predicted impulse by up to 15° and adjust restitution and friction for prospective first touches on the contact path, including H1. The original attention and gate are frozen. || Mass calibration | A train-fitted linear adjustment to the latent log-mass mean uses object shape and size, prefix motion and slip, and the original prior’s mean and uncertainty. The same corrected mass is used on both sides of each collision and across all substeps. No true mass is supplied during forecasting. || Frozen solver | The registered rigid-body solver uses its previously fitted parameters. It receives the same intervention and prefix state source as the corresponding attention arm. |
The split contains 5,600 training scenes, 1,400 validation scenes and 5,500 state test scenes. The original impulse families used 4,498 eligible training branches from 3,275 training scenes. The 1,069 eligible validation branches came from 786 scenes. An initial secondary-contact-only correction scored 0.60456 on validation, versus 0.59873 for the reported impulse correction and 0.60463 for identity. The first two fits were selected before their holdout results were read.
The force trace of the *existing* attention model motivated the subsequent mass-calibration recipe. That recipe was specified before the coordinator received corrected A/B holdout results. Its fit used 33,698 objects across all 5,600 training scenes with known simulated masses as training labels. The strength (0.50) and frozen checkpoint were chosen by the original validation score (0.59027). The earlier corrected test outcomes were unused in that selection. The validation sender-fraction MAE for A→B changed from 0.124 to 0.111. The original 29 informed the research hypothesis and remain a descriptive subgroup. [Impulse selections](model_lock.json) · [Mass protocol](candidates/prefix_mass/protocol.json) · [Mass selection](candidates/prefix_mass/model_lock.json).
## Third recipients and contact timing
Of the 5,500 edited simulator-state branches, 131 have a true three-hit chain. The 127 RGB chains are a matched subset of those 131. B, C and D denote the first, second and third recipients. A hit counts here only when it follows the correct preceding recipients. H3 within ±2 requires the third timestamp to match. All within ±2 also requires H1 and H2 to match. Timing MAE includes only forecasts with the correct three recipients. Parentheses give its eligible scene count. The video rate is 24 frames/s.
| Cohort | Model | Ordered H2 | Ordered H3 | H3 within ±2 | All within ±2 | H3 timing MAE, frames (n) ||---|---|---:|---:|---:|---:|---:|| State, true three-hit chains | Current attention | 124 | 93 | 31 | 30 | 5.645 (93) || State, true three-hit chains | Impulse correction | 121 | 88 | 31 | 30 | 5.920 (88) || State, true three-hit chains | Mass calibration | 128 | 99 | 31 | 30 | 5.808 (99) || State, true three-hit chains | Frozen solver | 129 | 106 | 45 | 44 | 4.811 (106) || RGB, true three-hit chains | Current attention | 109 | 80 | 24 | 23 | 6.150 (80) || RGB, true three-hit chains | Impulse correction | 107 | 74 | 22 | 21 | 6.419 (74) || RGB, true three-hit chains | Mass calibration | 111 | 82 | 26 | 24 | 6.244 (82) || RGB, true three-hit chains | Frozen solver | 115 | 82 | 35 | 34 | 4.988 (82) || RGB, original 29 misses | Current attention | 29 | 0 | 0 | 0 | — (0) || RGB, original 29 misses | Impulse correction | 28 | 1 | 0 | 0 | 18.000 (1) || RGB, original 29 misses | Mass calibration | 29 | 2 | 1 | 1 | 8.000 (2) || RGB, original 29 misses | Frozen solver | 28 | 10 | 3 | 3 | 4.500 (10) |
## C’s outgoing speed
True-clock speed uses C’s one-frame planar displacement immediately after the true H2. A missed or late model event still receives a speed error. Own-clock speed aligns the model and simulator to their respective H2 timestamps, and requires correct H1 and H2 with a following frame. The two anchors can therefore cover different scenes. All speeds below are in m/s. Parentheses give eligible counts.
| Cohort | Model | True-clock truth | True-clock forecast | True-clock MAE (n) | Own-clock forecast (n) | Own-clock MAE (n) ||---|---|---:|---:|---:|---:|---:|| State, true three-hit chains | Current attention | 1.012 | 0.671 | 0.463 (131) | 0.821 (124) | 0.433 (124) || State, true three-hit chains | Impulse correction | 1.012 | 0.659 | 0.497 (131) | 0.832 (121) | 0.438 (121) || State, true three-hit chains | Mass calibration | 1.012 | 0.747 | 0.442 (131) | 0.869 (128) | 0.398 (128) || State, true three-hit chains | Frozen solver | 1.012 | 0.737 | 0.452 (131) | 0.900 (129) | 0.351 (129) || RGB, true three-hit chains | Current attention | 1.019 | 0.638 | 0.526 (127) | 0.868 (109) | 0.438 (109) || RGB, true three-hit chains | Impulse correction | 1.019 | 0.594 | 0.564 (127) | 0.861 (107) | 0.468 (107) || RGB, true three-hit chains | Mass calibration | 1.019 | 0.673 | 0.522 (127) | 0.903 (111) | 0.441 (111) || RGB, true three-hit chains | Frozen solver | 1.019 | 0.607 | 0.576 (127) | 0.827 (115) | 0.441 (115) || RGB, original 29 misses | Current attention | 0.962 | 0.458 | 0.632 (29) | 0.591 (29) | 0.532 (29) || RGB, original 29 misses | Impulse correction | 0.962 | 0.473 | 0.639 (29) | 0.638 (28) | 0.557 (28) || RGB, original 29 misses | Mass calibration | 0.962 | 0.524 | 0.597 (29) | 0.655 (29) | 0.491 (29) || RGB, original 29 misses | Frozen solver | 0.962 | 0.469 | 0.651 (29) | 0.715 (28) | 0.439 (28) |
## What changed for the same scenes
Gains and losses compare individual outcomes. Error differences are candidate minus comparator. Brackets give paired 95% scene-bootstrap intervals over 4,000 replicates; conditional timing differences use only scenes where both methods recover H3. A negative error change is better. The 29 were selected to have zero baseline H3 successes, so baseline timing MAE is undefined for this subgroup.
| Cohort | Contrast | H3 gained / lost | H3 ±2 gained / lost | Full ±2 gained / lost | Δ C-speed MAE, m/s [95%] | Δ H3 timing MAE, frames [95%] (n) ||---|---|---:|---:|---:|---:|---:|| State, true three-hit chains | Impulse minus current | 1 / 6 | 7 / 7 | 6 / 6 | +0.033 [+0.006, +0.063] | +0.345 [-0.011, +0.759] (87) || State, true three-hit chains | Mass minus current | 6 / 0 | 8 / 8 | 8 / 8 | -0.022 [-0.061, +0.014] | +0.237 [-0.011, +0.473] (93) || State, true three-hit chains | Mass minus impulse | 11 / 0 | 10 / 10 | 9 / 9 | -0.055 [-0.097, -0.017] | -0.114 [-0.557, +0.307] (88) || RGB, true three-hit chains | Impulse minus current | 2 / 8 | 5 / 7 | 5 / 7 | +0.037 [+0.012, +0.066] | -0.125 [-0.556, +0.319] (72) || RGB, true three-hit chains | Mass minus current | 2 / 0 | 8 / 6 | 7 / 6 | -0.005 [-0.029, +0.019] | +0.050 [-0.362, +0.463] (80) || RGB, true three-hit chains | Mass minus impulse | 10 / 2 | 13 / 9 | 12 / 9 | -0.042 [-0.072, -0.015] | +0.264 [-0.236, +0.764] (72) || RGB, original 29 misses | Impulse minus current | 1 / 0 | 0 / 0 | 0 / 0 | +0.007 [-0.024, +0.037] | — (0) || RGB, original 29 misses | Mass minus current | 2 / 0 | 1 / 0 | 1 / 0 | -0.035 [-0.112, +0.033] | — (0) || RGB, original 29 misses | Mass minus impulse | 2 / 1 | 1 / 0 | 1 / 0 | -0.042 [-0.118, +0.025] | — (0) |
The following are own-clock comparisons on the intersection of correctly identified recipients for the candidate and current attention. The simulator speed in each row uses that exact subset.
| Original RGB cohort | Candidate | B after H1, current → candidate (n) | Sim B | C after H2, current → candidate (n) | Sim C ||---|---|---:|---:|---:|---:|| Original 29 misses | Impulse correction | 1.619 → 1.658 (29) | 2.218 | 0.606 → 0.638 (28) | 0.980 || Original 80 successes | Impulse correction | 2.256 → 2.193 (80) | 2.337 | 0.984 → 0.942 (78) | 1.089 || Original 29 misses | Mass calibration | 1.619 → 1.748 (29) | 2.218 | 0.591 → 0.655 (29) | 0.962 || Original 80 successes | Mass calibration | 2.256 → 2.316 (80) | 2.337 | 0.968 → 1.005 (80) | 1.078 |
## All 5,500 scenes, including negatives
Each scene contributes one edited branch and one factual command-off control. H3 positives and false declarations use the entire branch population. C-speed MAE uses every scene with a scoreable second event. ADE is the mean position error in metres. Intervention-effect ADE is the error in the edited-minus-factual predicted 3D displacement against the true difference. This paired effect is shared by both rows for a given model.
| Branch | Model | True H3 | Ordered H3 | False H3 / negatives | C-speed MAE, m/s (n) | ADE, m | Intervention-effect ADE, m ||---|---|---:|---:|---:|---:|---:|---:|| Edited | Current attention | 131 | 93 | 72/5369 | 0.359 (1297) | 0.119 | 0.174 || Edited | Impulse correction | 131 | 88 | 59/5369 | 0.354 (1297) | 0.121 | 0.176 || Edited | Mass calibration | 131 | 99 | 87/5369 | 0.348 (1297) | 0.124 | 0.180 || Edited | Frozen solver | 131 | 106 | 63/5369 | 0.376 (1297) | 0.111 | 0.163 || Factual | Current attention | 296 | 218 | 126/5204 | 0.402 (2094) | 0.163 | 0.174 || Factual | Impulse correction | 296 | 212 | 98/5204 | 0.395 (2094) | 0.164 | 0.176 || Factual | Mass calibration | 296 | 235 | 159/5204 | 0.388 (2094) | 0.168 | 0.180 || Factual | Frozen solver | 296 | 246 | 157/5204 | 0.435 (2094) | 0.160 | 0.163 |
## Scope and reproducibility
All forecasts start from the same pre-intervention factual cutoff within each scene and run autonomously, with the edit enabled or disabled. Attention variants use the same registered draws and contact randomness (32 samples). RGB uses the frozen visual extractor, known camera and object metadata, and registered box prompts. Prefix-frame and segmentation checksums matched the original release and both reference forecasters reproduced their archived events. The simulator-state and RGB arms use different registered initial belief draws. These scores measure graph trajectories and contacts. This experiment did not score rendered Wan pixels. The 127 and the diagnostic subsets overlap the state holdout. The confidence intervals describe variation over scenes for these frozen fits.
[State tables](results/state/comparison.json) · [RGB tables](results/rgb/comparison.json) · [Mass state tables](mass_evaluation/results/state/comparison.json) · [Mass RGB tables](mass_evaluation/results/rgb/comparison.json) · [Paired mass versus impulse](mass_evaluation/results/impulse_comparison.json) · [Protocol](protocol.json) · [Original 29 IDs](frozen/fixed_29.json) · [Source for this report](make_final_report.py)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Add frozen mass sensitivity and launch direction to the generated diagnostic report."""import jsonfrom pathlib import Pathimport numpy as npD=Path('/marimo/jais_motion_transfer_20261202/diagnostics/results')
def readrows(name): return {row['scene']:row for row in map(json.loads,(D/name).read_text().splitlines())}
def add(): a=readrows('first_impact_scenes.jsonl') b=readrows('impact_trace_scenes.jsonl') gt=readrows('simulator_impacts.jsonl') vals={'H1':{},'H2':{}} for stage in vals: for group in ('miss_29','success_80'): rows=[] for k,x in a.items(): if x['group']!=group:continue z,y=b[k],gt[k] if stage=='H1': close,gain,frac,real,truth,pred=(x['model_A_closing'],x['model_gain'],x['model_A_mass_fraction'],x['gt_A_mass_fraction'],x['gt_normal_kick'],x['model_normal_kick']) else: close,gain,frac,real,truth,pred=(z['model_bc_closing_mps'],z['model_normal_gain'],z['model_B_mass_fraction'],z['sim_B_mass_fraction'],y['gt_first_step_normal_kick_xy'],z['model_strongest_pair_normal_kick_mps']) assert abs(close*gain-pred)<.0001;rows.append((pred,close*gain*real/frac,truth)) v=np.asarray(rows);orig,oracle,sim=v.T vals[stage][group]=dict(n=len(rows),original_mps=float(orig.mean()),mass_oracle_mps=float(oracle.mean()),simulator_mps=float(sim.mean()), mean_abs_error_original=float(abs(orig-sim).mean()),mean_abs_error_mass_oracle=float(abs(oracle-sim).mean()), mass_oracle_reduces_error_count=int(sum(abs(oracle-sim)<abs(orig-sim)))) (D/'one_step_mass_sensitivity.json').write_text(json.dumps(vals,indent=2)+'\n') g=vals['H1']['miss_29'] text=(D/'REPORT.md').read_text() if 'At its launch from H1, B’s mean heading error' not in text: ds=json.loads((D/'current_launch_direction.json').read_bytes());a=ds['miss_29'];b=ds['success_80'] details=f"At its launch from H1, B’s mean heading error is {a['B_out_angle_error_deg']['mean']:.1f}° on the 29 misses versus {b['B_out_angle_error_deg']['mean']:.1f}° on the 80 successes. Over the last full frame before H2, the respective B heading errors are {a['B_before_H2_angle_error_deg']['mean']:.1f}° and {b['B_before_H2_angle_error_deg']['mean']:.1f}°. Those headings use position differences over one video frame and are aligned to each forecast’s own hit." text=text.replace('The predicted C heading differs',details+'\n\nThe predicted C heading differs') if 'A one-substep sensitivity check' not in text: details=f"On the 29 misses, A reaches the first hit at nearly the right speed. Its normal closing speed is 3.853 m/s for attention and 3.813 m/s in the simulator. At that hit, attention assigns A a mean sender mass fraction of 0.430. The physical value is 0.631. The learned A→B normal gain averages 0.447 versus an effective 0.704 measured from simulator force. The normal kick falls from 2.606 m/s in the simulator to 1.761 m/s in attention, leaving B underpowered for its encounter with C. On the other 80 scenes, sender fractions are closer, 0.497 for attention versus 0.536 in the simulator.\n\nA one-substep sensitivity check keeps the model’s closing speed, contact normal and learned restitution fixed. Substituting the simulator’s actual sender mass fraction changes the mean predicted A→B normal kick from {g['original_mps']:.3f} to {g['mass_oracle_mps']:.3f} m/s on the 29 (simulator {g['simulator_mps']:.3f}) and changes absolute kick error from {g['mean_abs_error_original']:.3f} to {g['mean_abs_error_mass_oracle']:.3f} m/s. Substituting true mass is an evaluation-only oracle. A free rollout can change contact or medoid after a changed impulse. This scalar check alone does not establish H3 recovery. [All cohorts and both impacts](one_step_mass_sensitivity.json)." text=text.replace('## Reproduction',details+'\n\n## Reproduction') corr=D/'corrected_launch_direction.json' if corr.is_file() and '## After fitting the transfer correction' not in text: records=readrows('corrected_launch_direction_scenes.jsonl');before=readrows('current_launch_direction_scenes.jsonl') result={} for label in ('miss_29','success_80'): panel=[s for s,x in records.items() if x['group']==label] block={} for stage in ('B_out','C_out'): sk=stage+'_predicted';ids=[s for s in panel if sk in before[s] and sk in records[s]] speeds={name:float(np.mean([rows[s][sk] for s in ids])) for name,rows in [('current',before),('corrected',records)]} speeds['simulator']=float(np.mean([records[s][stage+'_truth'] for s in ids]));speeds['n']=len(ids);block[stage]=speeds block['H3_current']=sum(before[s]['H3_correct'] for s in panel) block['H3_corrected']=sum(records[s]['H3_correct'] for s in panel) result[label]=block (D/'corrected_launch_paired_summary.json').write_text(json.dumps(result,indent=2)+'\n') q=result['miss_29'];v=q['B_out'];w=q['C_out'] extra=f"## After fitting the transfer correction\n\nOn the original 29 misses, B’s mean post-H1 speed changes from {v['current']:.3f} to {v['corrected']:.3f} m/s on the {v['n']} scenes where both models identify B (simulator {v['simulator']:.3f}). After H2, C’s post-impact speed changes from {w['current']:.3f} to {w['corrected']:.3f} m/s on {w['n']} paired scenes (simulator {w['simulator']:.3f}). The locked correction recovers {q['H3_corrected']}/29 third recipients on these same IDs. The [paired counts and means](corrected_launch_paired_summary.json) include both success and miss cohorts.\n\n" text=text.replace('## Reproduction',extra+'## Reproduction') (D/'REPORT.md').write_text(text)if __name__=='__main__':add()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Summarize group-matched archived baseline forecasts before reconstructing collision internals."""import argparse,json,hashlibfrom pathlib import Pathfrom statistics import mean,median
def sig(events): out=[] for e in events: if len(e['objects'])!=1:break out.append(e['objects'][0]) return out
def summarize(rows): out={'n':len(rows)} for k in rows[0]: v=[r[k] for r in rows if isinstance(r[k],(float,int)) and r[k] is not None] if v:out[k]={'n':len(v),'mean':mean(v),'median':median(v)} return out
def analyze(root,out): old=json.loads((root/'prior_aligned_rgb.json').read_bytes()) att=old['new']['scenes'];sol=old['solver']['scenes'] reg=set(json.loads((root/'fixed_29.json').read_bytes())) successes=[s for s,r in att.items() if r['H3_correct_order']] assert reg=={s for s,r in att.items() if r['H2_correct_order'] and not r['H3_correct_order']} rows=[json.loads(l) for l in (root/'rgb/current/per_scene.jsonl').read_bytes().splitlines()] ss=[json.loads(l) for l in (root/'rgb/solver/per_scene.jsonl').read_bytes().splitlines()] assert len(set(r['scene'] for r in rows))==127 sr={r['scene']:r for r in ss};rows={r['scene']:r for r in rows} records=[];summary={} for label,ids in [('fixed_29',sorted(reg)),('correct_H3_80',sorted(successes))]: table=[] for sid in ids: a,b=att[sid],sol[sid] truth=rows[sid]['branches']['on']['truth'] pred=rows[sid]['branches']['on']['pred'] t=a['H2_true_frame'];gt=a['C_true_speed'];at=a['C_speed_at_true_H2'];own=a['C_speed_at_model_H2'] row={'scene':sid,'group':label,'attention_pred_h2_lag':a['H2_frame_error'],'H3_true_frame':truth[2]['frame'], 'H2_H3_true_interval':truth[2]['frame']-t,'true_C_mps':gt,'attention_true_anchor_mps':at,'attention_own_anchor_mps':own, 'attention_pure_alignment_change_mps':own-at,'remaining_true_minus_model_own_mps':gt-own, 'number_below_true_after_alignment':bool(own<gt),'number_lower_than_half_after_alignment':bool(own<0.5*gt), 'number_at_least_two_frames_late_h2':bool(a['H2_frame_error']>=2),'number_early_h2':bool(a['H2_frame_error']<0), 'model_named_an_alternative_third':bool(len(sig(pred))==3 and sig(pred)!=sig(truth)), 'model_has_no_unique_third':bool(len(sig(pred))<3),'solver_correct_H2':bool(b['H2_correct_order']), 'solver_correct_H3':bool(b['H3_correct_order']),'solver_true_anchor_mps':b['C_speed_at_true_H2'], 'solver_own_anchor_mps':b.get('C_speed_at_model_H2'),'solver_own_H2_lag':b.get('H2_frame_error')} table.append(row);records.append(row) summary[label]=summarize(table) for name in ['solver_correct_H2','solver_correct_H3','model_named_an_alternative_third','model_has_no_unique_third','number_lower_than_half_after_alignment','number_below_true_after_alignment','number_at_least_two_frames_late_h2','number_early_h2']: summary[label][name]={'count':sum(bool(r[name]) for r in table),'n':len(table)} result={'source_revision':'e9650b409d59e8f770659578304c2ee04ac0a2d6','cohort_sha256':hashlib.sha256(('\n'.join(sorted(reg))+'\n').encode()).hexdigest(),'groups':summary} out.mkdir(parents=True,exist_ok=True) (out/'matched_impact_kinematics.json').write_text(json.dumps(result,indent=2,allow_nan=False)+'\n') (out/'matched_impact_kinematics_scenes.jsonl').write_text(''.join(json.dumps(r,allow_nan=False)+'\n' for r in records)) print(json.dumps(summary['fixed_29']))if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--frozen',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args();analyze(a.frozen,a.out)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Trace the first transfer on the same selected medoids to locate the preceding velocity error."""import jsonfrom pathlib import Pathimport syssys.path.insert(0,str(Path(__file__).parent))import osimport numpy as npimport torchfrom simulator_contacts import force_row, ROOT, OUTfrom impact_trace import Trace,read_rows,read_rgb, BASE_SHA,SEED,DRAWS,digest,arrfrom matched_model import ProbContactAttentionPropagator,ProbContactConfigimport concurrent.futures as cf
@torch.inference_mode()def main(): from audit_metrics import signature frozen=ROOT/'frozen' ids=json.loads((ROOT/'rgb_cache/three_hit_split.json').read_bytes())['test'] baseline=read_rows(frozen/'rgb/current/per_scene.jsonl') locked=set(json.loads((frozen/'fixed_29.json').read_bytes())) records=read_rows(OUT/'impact_trace_scenes.jsonl') b=torch.load('/tmp/jais_cutoff_registered.pt',map_location='cpu',mmap=True,weights_only=False) ix={s:i for i,s in enumerate(b['scene_ids'])} # Reuse the same simulator onset reader with A and B and the first event frame selected. def actual(s): r=baseline[s];ctx=r['branches']['on']['truth'] fake={'branches':{'on':{'truth':[{'objects':[int(b['subject'][ix[s]])]},ctx[0]]}}} return s,force_row(s,fake,b,ix,locked) with cf.ThreadPoolExecutor(max_workers=5) as ex:truth=dict(ex.map(actual,records)) prev=Path('/marimo/attention_retrain_cutoff_20261201') base=prev/'attention_stochastic/prob_contact_attn_best.pt'; assert digest(base)==BASE_SHA device=torch.device('cuda');torch.set_num_threads(2) ck=torch.load(base,map_location=device,weights_only=False) model=ProbContactAttentionPropagator(ProbContactConfig(**ck['config'])).to(device).eval() model.load_state_dict(ck['state_dict']) kk=torch.tensor([ix[s] for s in ids]) step=b['step'][kk].to(device);cuts=(step-1)//10;static=b['static'][kk].to(device);subject=b['subject'][kk].to(device) n=b['n'][kk].to(device);present=torch.arange(static.shape[1],device=device)[None]<n[:,None] objects=torch.tensor([list(signature(baseline[s]['branches']['on']['truth'])[:2]) for s in ids],device=device) obj=torch.cat((subject[:,None],objects),dim=1) med=torch.tensor([baseline[s]['branches']['on']['medoid_k'] for s in ids],device=device) trace=Trace(med,obj);trace.attach(model) prefix,init=read_rgb(ROOT/'rgb_cache',ids,b,kk,device,Path((ROOT/'rgb_cache/encoder.path').read_text().strip())) mu,logsd=model.prior(prefix,static,cuts+1);z=model.sample_latents(mu,logsd,K=DRAWS,deterministic_first=True) pred=model.rollout(prefix,static,present,subject,b['heading'][kk].to(device),step,cuts,z,init_state_samples=init, apply_edit=True,stochastic_gates=True,gate_seed=SEED) raw=np.stack(trace.records,axis=1); frames=int(cuts.min())+1+np.arange(raw.shape[1])//model.cfg.substeps out=[] for i,s in enumerate(ids): if s not in records:continue t=int(baseline[s]['branches']['on']['pred'][0]['frame']);B=int(obj[i,1].item());gt=truth[s];raw_i=raw[i] h=np.flatnonzero((frames==t)&(raw_i[:,16]>=model.cfg.impact_threshold));d=raw_i[h[raw_i[h,16].argmax()]] xy=arr(pred['xyz'][i,med[i]]) v=24*np.linalg.norm(xy[t+1,B,:2]-xy[t,B,:2]);a=records[s] assert abs(v-a['model_B_post_H1_speed'])<2e-4 oc=dict(scene=s,group=a['group'],H1_true_receiver=B,H1_sim_step=gt['h2_step'],H1_model_frame=t,H1_true_frame=gt['h2_frame'], gt_A_in_speed=gt['gt_b_speed_pre'],model_A_in_speed=float(np.linalg.norm(d[:2])),gt_A_closing=gt['gt_com_planar_closing'], model_A_closing=float(d[13]),gt_A_mass_fraction=gt['gt_b_mass_fraction'],model_A_mass_fraction=float(d[27]), gt_normal_kick=gt['gt_first_step_normal_kick_xy'],model_normal_kick=float(d[23]),gt_gain=gt['gt_first_step_effective_gain'],model_gain=float((1+d[19])*d[27]), gt_frame_normal_kick=gt['gt_frame_normal_kick_xy'], gt_receiver_other_simultaneous=gt['receiver_other_nonfloor_contact_same_step'], gt_B_post_H1=a['true_B_post_H1_speed'], model_B_post_H1=a['model_B_post_H1_speed']) if oc['gt_gain'] is not None and not oc['gt_receiver_other_simultaneous']: oc['closing_contribution_mps']=(oc['gt_A_closing']-oc['model_A_closing'])*(oc['gt_gain']+oc['model_gain'])/2 oc['gain_contribution_mps']=(oc['gt_gain']-oc['model_gain'])*(oc['gt_A_closing']+oc['model_A_closing'])/2 assert abs(oc['closing_contribution_mps']+oc['gain_contribution_mps']-(oc['gt_normal_kick']-oc['model_normal_kick']))<1e-4 out.append(oc) assert len(out)==109 (OUT/'first_impact_scenes.jsonl').write_text(''.join(json.dumps(x,allow_nan=False)+'\n' for x in out)) from simulator_contacts import summarize (OUT/'first_impact_summary.json').write_text(json.dumps(summarize(out),indent=2)+'\n') print('Matched A-to-B onset audit complete',len(out),flush=True)if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224"""Read-only contact-law tracing on the exact registered representative RGB rollouts."""import argparseimport hashlibimport inspectimport jsonfrom pathlib import Pathfrom statistics import medianimport textwrapimport typesimport numpy as npimport torchfrom audit_metrics import normalise, signaturefrom eval.contact_chains import chainfrom evaluate_transfer import BASE_SHA, DRAWS, SEED, read_rgb, digestfrom matched_model import ProbContactAttentionPropagator, ProbContactConfig, pair_geometry_batched, yaw_from_quat_torch
def arr(x): return x.detach().cpu().numpy()
def norm(x): return float(np.linalg.norm(x))
def angle(a,b): d=norm(a)*norm(b) return float(np.rad2deg(np.arccos(np.clip(a@b/d,-1,1)))) if d>1.e-6 else None
def read_rows(path): return {r['scene']:r for r in (json.loads(line) for line in path.read_text().splitlines())}
class Trace: """Select registered draw/object slots only for recording, after the original law has run.""" def __init__(self, med, objects): self.med=med self.row=torch.arange(len(med),device=med.device) self.B,self.C,self.D=objects.unbind(1) self.params=None self.records=[]
def candidates(self, cb,ck,ci,cj,closing,mu,restitution,j_n,j_t,j_vec,gate,inv_i,inv_j,normal): which=(ck==self.med[cb]) & (((ci==self.C[cb])&(cj==self.B[cb])) | ((cj==self.C[cb])&(ci==self.B[cb]))) s=cb[which] direction=torch.where(ci[which]==self.C[s],1.,-1.) inverse_receiver=torch.where(direction>0,inv_i[which],inv_j[which]) values=torch.stack([restitution[which],mu[which],closing[which],gate[which], j_n[which]*inverse_receiver,j_t[which].abs()*inverse_receiver, j_vec[which,0]*direction*inverse_receiver,j_vec[which,1]*direction*inverse_receiver, inverse_receiver/(inv_i[which]+inv_j[which])],dim=1) self.params=torch.full((len(self.row),values.shape[1]),float('nan'),device=s.device) self.params[s]=values
def after(self,pos,vel,gap,outward,closing,imp,gate,dv,dpos): i,k,B,C,D=self.row,self.med,self.B,self.C,self.D pair=self.params if self.params is not None else torch.full((len(i),9),float('nan'),device=i.device) # Un-gated geometry and pre/post velocities are available even if no candidate was proposed. geom=torch.cat([vel[i,k,B],vel[i,k,C],vel[i,k,D],dv[i,k,C],dpos[i,k,C], outward[i,k,C,B], gap[i,k,C,B,None],closing[i,k,C,B,None], gap[i,k,D,C,None],closing[i,k,D,C,None], imp[i,k,B,C,None], imp[i,k,C,D,None],gate[i,k,C,D,None],pair],dim=1) self.records.append(arr(geom));self.params=None
def attach(self, model): base=model.contact_attn.step_contacts.__func__ code=textwrap.dedent(inspect.getsource(base)) first=' # Scatter symmetric +J/m_i' assert code.count(first)==1 code=code.replace(first," diagnostic.candidates(cb,ck,ci,cj,closing_c,mu_c,e_c,j_n,j_t,j_vec,gate_c,inv_mi_c,inv_mj_c,out_c)\n"+first) end=' return dv, droll, dpos, impulse_mag, gate_prob' assert code.count(end)==1 code=code.replace(end," diagnostic.after(pos,vel,gap,outward,closing,impulse_mag,gate_prob,dv,dpos)\n"+end) namespace={**base.__globals__,'diagnostic':self} exec(compile(code,'<read-only contact trace>','exec'),namespace) model.contact_attn.step_contacts=types.MethodType(namespace[base.__name__],model.contact_attn) return hashlib.sha256(inspect.getsource(base).encode()).hexdigest()
def summarize(rows): out={'n':len(rows)} for k in sorted({k for s in rows for k,v in s.items() if type(v) in (int,float)}): x=[s[k] for s in rows if type(s.get(k)) in (int,float) and np.isfinite(s[k])] if x:out[k]={'n':len(x),'mean':float(np.mean(x)),'median':float(median(x))} return out
@torch.inference_mode()def run(a): assert digest(a.base)==BASE_SHA reg=read_rows(a.frozen/'rgb/current/per_scene.jsonl') sols=read_rows(a.frozen/'rgb/solver/per_scene.jsonl') aligned=json.loads((a.frozen/'prior_aligned_rgb.json').read_bytes()) locked=set(json.loads((a.frozen/'fixed_29.json').read_bytes())) ids=json.loads(a.splits.read_text())['test'] assert len(set(ids))==len(ids)==127 and set(ids)==set(reg)==set(sols) bundle=torch.load(a.data,map_location='cpu',mmap=True,weights_only=False) ix={k:i for i,k in enumerate(bundle['scene_ids'])} kk=torch.tensor([ix[s] for s in ids]);device=torch.device('cuda');torch.set_num_threads(2) cuts=((bundle['step'][kk]-1)//10).to(device);static=bundle['static'][kk].to(device);step=bundle['step'][kk].to(device) n=bundle['n'][kk].to(device);mask=torch.arange(static.shape[1],device=device)[None]<n[:,None] subj=bundle['subject'][kk].to(device);heading=bundle['heading'][kk].to(device) ck=torch.load(a.base,map_location=device,weights_only=False) model=ProbContactAttentionPropagator(ProbContactConfig(**ck['config'])).to(device).eval() model.load_state_dict(ck['state_dict']) med=torch.tensor([reg[s]['branches']['on']['medoid_k'] for s in ids],device=device) objects=torch.tensor([signature(reg[s]['branches']['on']['truth']) for s in ids],device=device) trace=Trace(med,objects) source_sha=trace.attach(model) prefix,init=read_rgb(a.rgb_cache,ids,bundle,kk,device,a.encoder) mu,logstd=model.prior(prefix,static,cuts+1) z=model.sample_latents(mu,logstd,K=DRAWS,deterministic_first=True) pred=model.rollout(prefix,static,mask,subj,heading,step,cuts,z,init_state_samples=init,apply_edit=True, stochastic_gates=True,gate_seed=SEED) row=torch.arange(len(ids),device=device) xyz=arr(pred['xyz'][row,med]) imp=arr(pred['impulse'][row,med]) records=np.stack(trace.records,axis=1) S=model.cfg.substeps; start=int(cuts.min())+1 frames=start+np.arange(records.shape[1])//S assert frames[-1]==47 and records.shape[-1]==28 details=[] for i,sid in enumerate(ids): base=reg[sid]['branches']['on']; sol=sols[sid]['branches']['on'];truth=base['truth'] B,C,D=signature(truth) genuine=normalise(chain(imp[i,:,:n[i],:n[i]]>=model.cfg.impact_threshold,int(subj[i]),int(cuts[i]))) matched=(genuine==base['pred']) if not matched: raise ValueError(f'Frozen medoid did not reproduce original sequence for {sid}: {genuine} vs {base["pred"]}') if signature(genuine)[:2]!=(B,C):continue h2=int(truth[1]['frame']);t=int(genuine[1]['frame']);gt3=int(truth[2]['frame']) success=signature(genuine)[:3]==(B,C,D) assert success==(sid not in locked) raw=records[i]; window=np.flatnonzero((frames==t)&(raw[:,16]>=model.cfg.impact_threshold)) assert len(window),sid # There may be multiple substeps in the impact frame. The scorer registers the maximum. h=window[np.argmax(raw[window,16])] d=raw[h];nBC=d[10:12] if not (d[22]>=.5 and np.isfinite(d).all()):raise ValueError('trace indexing: '+str(sid)) true_state=bundle['state_cf'][kk[i]] yaw=yaw_from_quat_torch(true_state[h2-1,:,3:7]) gap_gt,normal,_,closing_gt,_,_=pair_geometry_batched(true_state[h2-1,:,:2],true_state[h2-1,:,7:9],yaw,bundle['static'][kk[i]],1/24) ng=normal[C,B].numpy() vp=true_state[h2-1,:,7:9].numpy() va=true_state[h2,:,7:9].numpy() c_true=24*(true_state[h2+1,C,:2]-true_state[h2,C,:2]).numpy() c_pred=24*(xyz[i,t+1,C,:2]-xyz[i,t,C,:2]) assert abs(norm(c_pred)-aligned['new']['scenes'][sid]['C_speed_at_model_H2'])<2e-4,sid attrs=bundle['attrs'][kk[i],:,0].numpy() true_mass_fraction=float(1/(1+np.exp(float(attrs[C]-attrs[B])))) p_before=float(max(0.,d[13])); g_before=float(closing_gt[C,B]) true_kick=float((va[C]-vp[C])@ng) ph_d=raw[frames>t] net_pair=raw[frames==t,25:27] count_C=len(np.flatnonzero((bundle['contact_cf'][kk[i],h2-1,C,:]|bundle['contact_cf'][kk[i],h2-1,:,C]).numpy())) r=dict(scene=sid,group='success_80' if success else 'miss_29',h2_true=h2,h2_model=t,h2_lag=t-h2,h3_true=gt3, solver_h2_correct=signature(sol['pred'])[:2]==(B,C),solver_h3_correct=signature(sol['pred'])[:3]==(B,C,D), expected_B_speed_before_h2=norm(vp[B]),model_B_speed_before_h2=norm(d[0:2]), true_C_speed_before_h2=norm(vp[C]),model_C_speed_before_h2=norm(d[2:4]), true_C_speed_after_h2=norm(c_true),model_C_speed_after_h2=norm(c_pred), model_C_speed_after_h2_at_true_time=aligned['new']['scenes'][sid]['C_speed_at_true_H2'], model_C_heading_error_degrees=angle(c_pred,c_true),bc_normal_error_degrees=angle(nBC,ng), true_bc_closing_approx_mps=g_before,model_bc_closing_mps=p_before, gt_net_C_normal_velocity_change_approx_mps=true_kick,model_strongest_pair_normal_kick_mps=float(d[23]), model_strongest_pair_tangent_kick_mps=float(d[24]),model_strongest_pair_kick_mps=float(d[16]), model_C_speed_immediately_after_substep=norm(d[2:4]+d[6:8]), model_pair_sum_kick_mps=norm(np.nansum(net_pair,axis=0)), model_true_mass_fractions=[float(d[27]),true_mass_fraction], model_B_mass_fraction=float(d[27]),sim_B_mass_fraction=true_mass_fraction, model_restitution=float(d[19]),model_normal_gain=float((1+d[19])*d[27]), true_C_distinct_contact_partners_impact_frame=count_C, post_h2_min_surface_gap_to_D_m=float(ph_d[:,14].min()),post_h2_max_C_to_D_kick_mps=float(ph_d[:,17].max()), post_h2_max_C_D_gate_probability=float(ph_d[:,18].max()), cd_exact_geometry_overlap=bool(ph_d[:,14].min()<=0), cd_never_within_4p5cm=bool(ph_d[:,14].min()>.045), cd_any_qualifying_kick=bool(ph_d[:,17].max()>=model.cfg.impact_threshold), cd_had_subthreshold_kick_only=bool(0<ph_d[:,17].max()<model.cfg.impact_threshold), third_status='correct' if success else ('competing_or_ambiguous' if len(genuine)>2 and genuine[2]['objects'] else 'no_third'), h2_pair_qualifying_substeps=len(window)) # B's incoming deficit can already be present immediately after H1, or # can grow in transit before H2. Keep these aligned windows distinct. gt1=int(truth[0]['frame']);pr1=int(genuine[0]['frame']) b1t=24*(true_state[gt1+1,B,:2]-true_state[gt1,B,:2]).numpy() b1p=24*(xyz[i,pr1+1,B,:2]-xyz[i,pr1,B,:2]) r.update(true_B_post_H1_speed=norm(b1t),model_B_post_H1_speed=norm(b1p), true_H1_to_H2_frames=h2-gt1,model_H1_to_H2_frames=t-pr1, true_B_speed_change_H1_to_H2=norm(vp[B])-norm(b1t), model_B_speed_change_H1_to_H2=norm(d[:2])-norm(b1p)) target_t=(true_state[h2,D,:2]-true_state[h2,C,:2]).numpy() target_p=xyz[i,t,D,:2]-xyz[i,t,C,:2] r.update(C_gt_heading_error_to_D_deg=angle(c_true,target_t),C_model_heading_error_to_D_deg=angle(c_pred,target_p), true_C_to_D_center_distance_at_H2=norm(target_t),model_C_to_D_center_distance_at_H2=norm(target_p), true_C_speed_toward_D=float(c_true@(target_t/max(norm(target_t),1.e-8))), model_C_speed_toward_D=float(c_pred@(target_p/max(norm(target_p),1.e-8)))) # Compare normal gain only in well-resolved closing cases with exactly one GT partner. if g_before>.05 and true_kick>0 and count_C==1: gtrue=true_kick/g_before; gmodel=r['model_normal_gain'] r.update(gt_effective_normal_gain=gtrue, same_frame_gt_minus_model_normal_change=true_kick-r['model_strongest_pair_normal_kick_mps'], closing_contribution_mps=(g_before-p_before)*(gtrue+gmodel)/2, gain_contribution_mps=(gtrue-gmodel)*(g_before+p_before)/2) assert abs(r['closing_contribution_mps']+r['gain_contribution_mps']-r['same_frame_gt_minus_model_normal_change'])<3e-5 details.append(r) groups={k:[v for v in details if v['group']==k] for k in ['miss_29','success_80']} assert {v['scene'] for v in groups['miss_29']}==locked and len(groups['success_80'])==80 out={k:summarize(v) for k,v in groups.items()} for name,rows in groups.items(): for term in ['solver_h2_correct','solver_h3_correct','cd_exact_geometry_overlap','cd_never_within_4p5cm','cd_any_qualifying_kick','cd_had_subthreshold_kick_only']: out[name][term]={'n':len(rows),'count':sum(int(x[term]) for x in rows)} out[name]['third_status']={v:sum(x['third_status']==v for x in rows) for v in ['correct','competing_or_ambiguous','no_third']} a.out.mkdir(parents=True,exist_ok=True) (a.out/'impact_trace_summary.json').write_text(json.dumps({'checkpoint_sha256':BASE_SHA,'registered_medoid_signatures_reproduced':127, 'source_sha256':source_sha,'threshold_mps':model.cfg.impact_threshold,'dt':1/24,'substeps':S, 'definition':'Strongest directed B→C impulse during predicted H2. GT normal closing, change in C velocity and normal direction are frame-boundary proxies. Bookkeeping identity on positive single-partner closing subsets is descriptive, not a causal intervention.', 'groups':out},indent=2,allow_nan=False)+'\n') (a.out/'impact_trace_scenes.jsonl').write_text(''.join(json.dumps(v,allow_nan=False)+'\n' for v in details)) print({k:{key:v[key] for key in ('n','model_C_speed_after_h2','model_bc_closing_mps','model_restitution','cd_never_within_4p5cm')} for k,v in out.items()},flush=True)
if __name__=='__main__': p=argparse.ArgumentParser() for name in ('data','splits','frozen','base','encoder','rgb-cache','out'):p.add_argument('--'+name,type=Path,required=True) run(p.parse_args())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""First-hit launch and incoming direction at H2 for locked RGB chains and selected checkpoints."""from pathlib import Pathimport syssys.path.insert(0,str(Path(__file__).parent))import osimport argparseimport jsonimport numpy as npimport torchfrom impact_trace import read_rows,read_rgb,BASE_SHA,SEED,DRAWS,digest,arr,anglefrom matched_model import ProbContactAttentionPropagator,ProbContactConfigfrom simulator_contacts import ROOT,OUTfrom eval.contact_chains import chainfrom audit_metrics import normalise,signature
@torch.inference_mode()def main(arm): prefix_dir=ROOT/'rgb_cache' ids=json.loads((prefix_dir/'three_hit_split.json').read_bytes())['test'] prior=read_rows(ROOT/'frozen/rgb/current/per_scene.jsonl') test_rows=read_rows((ROOT/('frozen/rgb/current' if arm=='current' else ('mass_evaluation/rgb/corrected' if arm=='mass' else 'rgb/corrected')))/'per_scene.jsonl') membership=read_rows(OUT/'impact_trace_scenes.jsonl') b=torch.load('/tmp/jais_cutoff_registered.pt',map_location='cpu',mmap=True,weights_only=False) ix={s:i for i,s in enumerate(b['scene_ids'])} base=Path('/marimo/attention_retrain_cutoff_20261201/attention_stochastic/prob_contact_attn_best.pt');assert digest(base)==BASE_SHA dev=torch.device('cuda');torch.set_num_threads(2) if arm=='current': ck=torch.load(base,map_location=dev,weights_only=False) model=ProbContactAttentionPropagator(ProbContactConfig(**ck['config'])).to(dev) model.load_state_dict(ck['state_dict']) else: lock=json.loads((ROOT/('candidates/prefix_mass/model_lock.json' if arm=='mass' else 'model_lock.json')).read_bytes());assert lock['test_used_for_selection'] is False adapter=ROOT/lock['checkpoint_relative'];assert digest(adapter)==lock['checkpoint_sha256'] if arm=='mass': from mass_transfer import load_corrected else: from transfer_model import load_corrected model=load_corrected(base,adapter,dev) model.eval();kk=torch.tensor([ix[s] for s in ids]);step=b['step'][kk].to(dev);cuts=(step-1)//10;static=b['static'][kk].to(dev) n=b['n'][kk].to(dev);subj=b['subject'][kk].to(dev);mask=torch.arange(static.shape[1],device=dev)[None]<n[:,None] prefix,init=read_rgb(prefix_dir,ids,b,kk,dev,Path((prefix_dir/'encoder.path').read_text().strip())) mu,logstd=model.prior(prefix,static,cuts+1);z=model.sample_latents(mu,logstd,K=DRAWS,deterministic_first=True) pred=model.rollout(prefix,static,mask,subj,b['heading'][kk].to(dev),step,cuts,z,init_state_samples=init,apply_edit=True, stochastic_gates=True,gate_seed=SEED) med=torch.tensor([test_rows[s]['branches']['on']['medoid_k'] for s in ids],device=dev) ar=torch.arange(len(ids),device=dev) xyz=arr(pred['xyz'][ar,med]);hits=arr(pred['impulse'][ar,med]>=model.cfg.impact_threshold) rows=[] for i,s in enumerate(ids): entry=test_rows[s]['branches']['on']; truth=entry['truth'] events=normalise(chain(hits[i],int(subj[i]),int(cuts[i]))) assert events==entry['pred'],s if s not in membership:continue y=b['state_cf'][kk[i]].numpy();p=xyz[i] gold=signature(truth);sig=signature(events);B,C,D=gold x=dict(scene=s,group=membership[s]['group'],H1_correct=sig[:1]==gold[:1],H2_correct=sig[:2]==gold[:2],H3_correct=sig[:3]==gold[:3]) for tag,hits_required,offset,obj,f1,f2 in [('B_out',1,0,B,0,1),('B_before_H2',2,1,B,-2,-1),('C_out',2,1,C,0,1)]: if sig[:hits_required]!=gold[:hits_required]:continue a1=events[offset]['frame'];a2=truth[offset]['frame'] if min(a1+f1,a2+f1)<0 or max(a1+f2,a2+f2)>47:continue mv=24*(p[a1+f2,obj,:2]-p[a1+f1,obj,:2]);tv=24*(y[a2+f2,obj,:2]-y[a2+f1,obj,:2]) x[tag+'_predicted']=float(np.linalg.norm(mv));x[tag+'_truth']=float(np.linalg.norm(tv)) x[tag+'_angle_error_deg']=angle(tv,mv) if arm=='current' and tag=='B_out': assert abs(x[tag+'_predicted']-membership[s]['model_B_post_H1_speed'])<2e-4 rows.append(x) def summ(g): result={} for k in sorted({k for x in g for k in x if k not in ['scene','group']}): vs=[x[k] for x in g if x.get(k) is not None];result[k]=dict(n=len(vs),mean=float(np.mean(vs)) if vs else None) return result stats={g:summ([r for r in rows if r['group']==g]) for g in ['miss_29','success_80']} (OUT/f'{arm}_launch_direction.json').write_text(json.dumps(stats,indent=2)+'\n') (OUT/f'{arm}_launch_direction_scenes.jsonl').write_text(''.join(json.dumps(r,allow_nan=False)+'\n' for r in rows)) print(arm,len(rows),stats['miss_29']['B_out_predicted'],flush=True)
if __name__=='__main__':main(sys.argv[1])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107"""Build the final descriptive, scene-paired report on the notebook after all frozen traces pass."""from pathlib import Pathimport syssys.path.insert(0,str(Path(__file__).parent))import jsonimport numpy as npfrom simulator_contacts import OUTimport matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as plt
def read(name): return {r['scene']:r for r in (json.loads(l) for l in (OUT/name).read_text().splitlines())}
def agg(records, key): vals=[r[key] for r in records if r.get(key) is not None] return float(np.mean(vals)) if vals else None
def m(x):return f'{x:.3f}'def bootstrap(values): a=np.asarray(values);rng=np.random.default_rng(20261202) means=a[rng.integers(0,len(a),size=(10000,len(a)))].mean(1) return np.quantile(means,[.025,.975]).tolist()
def main(): frozen=read('matched_impact_kinematics_scenes.jsonl') trace=read('impact_trace_scenes.jsonl') raw=read('simulator_impacts.jsonl') h1=read('first_impact_scenes.jsonl') assert set(raw)==set(trace)==set(frozen)==set(h1) rows=[] for sid,model in trace.items(): sim=raw[sid]; one=h1[sid] r={'scene':sid,'group':model['group'],'true_A_H1':one['gt_A_in_speed'],'pred_A_H1':one['model_A_in_speed'], 'true_B_H1':model['true_B_post_H1_speed'],'pred_B_H1':model['model_B_post_H1_speed'], 'true_B_preH2':sim['gt_b_speed_pre'],'pred_B_preH2':model['model_B_speed_before_h2'], 'true_closing':sim['gt_com_planar_closing'],'pred_closing':model['model_bc_closing_mps'], 'true_kick':sim['gt_first_step_normal_kick_xy'],'pred_kick':model['model_strongest_pair_normal_kick_mps'], 'true_C_ownH2':model['true_C_speed_after_h2'],'pred_C_ownH2':model['model_C_speed_after_h2'], 'true_C_towards_D':model['true_C_speed_toward_D'],'pred_C_towards_D':model['model_C_speed_toward_D'], 'model_C_heading_error':model['model_C_heading_error_degrees'],'CD_min_gap':model['post_h2_min_surface_gap_to_D_m'], 'CD_subthreshold':model['cd_had_subthreshold_kick_only'],'solver_correct_H3':model['solver_h3_correct'], 'true_massfrac':sim['gt_b_mass_fraction'],'pred_massfrac':model['model_B_mass_fraction'], 'true_gain':sim['gt_first_step_effective_gain'],'pred_gain':model['model_normal_gain'], 'H1_closing_contribution':one.get('closing_contribution_mps'),'H1_gain_contribution':one.get('gain_contribution_mps'), 'true_H1_closing':one['gt_A_closing'],'pred_H1_closing':one['model_A_closing'], 'true_H1_kick':one['gt_normal_kick'],'pred_H1_kick':one['model_normal_kick'], 'true_H1_massfrac':one['gt_A_mass_fraction'],'model_H1_massfrac':one['model_A_mass_fraction']} if r['true_gain'] is not None and not sim['receiver_other_nonfloor_contact_same_step']: gt,gm=r['true_gain'],r['pred_gain'];ct,cm=r['true_closing'],r['pred_closing'] r['closing_contribution']=(ct-cm)*(gt+gm)/2 r['gain_contribution']=(gt-gm)*(ct+cm)/2 assert abs(r['closing_contribution']+r['gain_contribution']-(r['true_kick']-r['pred_kick']))<1e-4 rows.append(r) groups={k:[r for r in rows if r['group']==k] for k in ('miss_29','success_80')} out={} for k,rr in groups.items(): summary={} for stage in ['A_H1','B_H1','B_preH2','closing','kick','C_ownH2','C_towards_D','massfrac','H1_closing','H1_kick']: vals=[x['true_'+stage]-x['pred_'+stage] for x in rr] summary[stage]=dict(n=len(rr),truth=agg(rr,'true_'+stage),model=agg(rr,'pred_'+stage),sim_minus_model=float(np.mean(vals)), scene_bootstrap_mean_difference_ci=bootstrap(vals),n_model_below_truth=sum(v>0 for v in vals)) summary['B_transit']={'model_loss':agg(rr,'pred_B_H1')-agg(rr,'pred_B_preH2'),'simulator_loss':agg(rr,'true_B_H1')-agg(rr,'true_B_preH2')} for stage in ('closing_contribution','gain_contribution','H1_closing_contribution','H1_gain_contribution'): vals=[x[stage] for x in rr if x.get(stage) is not None] summary[stage]={'n':len(vals),'mean':float(np.mean(vals)),'ci':bootstrap(vals)} out[k]=summary (OUT/'joint_impulse_attribution.json').write_text(json.dumps(out,indent=2,allow_nan=False)+'\n') (OUT/'joint_impulse_scenes.jsonl').write_text(''.join(json.dumps(r,allow_nan=False)+'\n' for r in rows))
plt.rcParams.update({'font.size':10,'axes.spines.top':False,'axes.spines.right':False}) fig,axes=plt.subplots(1,3,figsize=(11.2,3.55),constrained_layout=True) for k,c in [('success_80','#187a77'),('miss_29','#be5037')]: rr=groups[k];lab='H3 correct (80)' if k=='success_80' else 'H3 missed (29)' for ax,s in zip(axes[:2],('B_H1','C_ownH2')): ax.scatter([x['true_'+s] for x in rr],[x['pred_'+s] for x in rr],c=c,s=19,alpha=.72,label=lab,linewidths=0) gaps=np.sort([100*x['CD_min_gap'] for x in rr]) axes[2].step(gaps,(np.arange(len(rr))+1)/len(rr),where='post',color=c,label=lab,lw=2) for i,title in enumerate(('B after the first hit','C after the second hit')): ax=axes[i];top=max(ax.get_xlim()[1],ax.get_ylim()[1]);ax.plot([0,top],[0,top],color='#999',lw=1,ls='--');ax.set(xlim=(0,top),ylim=(0,top),aspect='equal',xlabel='Simulator speed (m/s)',ylabel='Predicted speed (m/s)',title=title) axes[2].axvline(4.5,color='#999',ls='--',lw=1) axes[2].set(xlabel='Closest post-H2 C–D gap (cm)',ylabel='Fraction of scenes',title='Approach to D',ylim=(0,1.025)) axes[2].legend(loc='lower right',frameon=False,fontsize=8) fig.savefig(OUT/'motion_transfer_diagnosis.png',dpi=170);plt.close(fig)
tt=['# Why C leaves the second hit too slowly','','The current attention model misses the third recipient after identifying the second on 29 of 127 RGB chains. All 29 forecasts stop before naming a third object. The other 80 forecasts that correctly identify H2 also correctly identify H3. The remaining 18 forecasts fail before reaching the H2 diagnostic. All 127 archived representative chains were reproduced.','','## Where speed is lost','','The pairs below give the simulator and current attention means in m/s. Each uses the same registered scenes and compares the models at their own impact times.','','| Measurement | 29 third-hit misses, simulator / attention | 80 successes, simulator / attention |','|---|---:|---:|'] for key,label in [('A_H1','A immediately before H1'),('B_H1','B in the first frame after H1'),('B_preH2','B immediately before H2'),('closing','B–C normal closing speed at H2'),('kick','B→C normal kick at H2'),('C_ownH2','C in the first frame after H2'),('C_towards_D','C speed projected toward D')]: vals=[f"{m(x[key]['truth'])} / {m(x[key]['model'])}" for x in out.values()] tt.append(f"| {label} | {' | '.join(vals)} |") miss=out['miss_29'];succ=out['success_80'] ft=frozen tt+=['','','', f"On the 29 misses, B is already too slow immediately after H1 in {miss['B_H1']['n_model_below_truth']}/29 cases. By H2, B approaches C too slowly in {miss['closing']['n_model_below_truth']}/29 cases. Aligning C to the model’s own H2 recovers 0.133 m/s from its mean deficit and leaves 0.371 m/s. C remains slower in 23/29 and below half its true speed in 12/29. The frozen RGB solver correctly recovers H3 on 10/29 of these scenes and 68/80 of the attention successes.",'', f"B loses {miss['B_transit']['model_loss']:.3f} m/s in attention and {miss['B_transit']['simulator_loss']:.3f} m/s in the simulator between its outgoing H1 frame and the instant before H2. On H3 successes the losses are {succ['B_transit']['model_loss']:.3f} and {succ['B_transit']['simulator_loss']:.3f} m/s, respectively. Most of B’s deficit on the misses is already present in its launch from the first hit.",'', "The predicted C heading differs from its simulated heading by 8.2° on average in the 29. Its speed toward D is 0.436 m/s versus the simulator’s 0.810 m/s. After predicted H2, 24/29 never approach D within 4.5 cm of surface separation. None has an observed pre-update surface overlap in the sampled substeps. Only three have a nonzero C–D impulse below the 0.07 m/s event threshold. Geometric separation accounts for most missed contacts. The 4.5 cm value is a descriptive gap threshold. The native predictor also considers swept motion over the next substep.",'','## What contributes to the weak impulse','', "Among the 29 misses, the native attention substep uses mean restitution 0.027 and mean learned sender mass fraction 0.497 at H2. The simulator’s true sender mass fraction averages 0.466. On the other 80 the corresponding figures are 0.053, 0.505, and 0.527. These learned restitution values are parameters of the planar contact law. The force-based effective gain is separately measured in the simulator. The simulator’s 240 Hz force logs identify the first true B–C impulse. The learned forecaster produces a planar normal kick equal to pre-impact normal closing speed times a gain, (1 + restitution) × sender mass fraction. The bookkeeping below splits the difference in kick between these two factors, using the average gain and average closing speed between forecast and simulator. The empirical simulator gain divides its recorded normal kick per unit recipient mass by incoming planar center-of-mass closing speed. This ratio includes simulator effects such as off-center impacts. The calculation excludes overlaps with another moving partner and closing speeds at or below 0.05 m/s.",'', '| Impact and cohort | Contributing scenes | From incoming closing speed (m/s) | From effective gain (m/s) |','|---|---:|---:|---:|'] for name,x in [('H1, misses',miss),('H1, successes',succ),('H2, misses',miss),('H2, successes',succ)]: pre='H1_' if name.startswith('H1') else '';a=x[pre+'closing_contribution'];b=x[pre+'gain_contribution'] tt.append(f"| {name} | {a['n']} | {a['mean']:+.3f} | {b['mean']:+.3f} |") tt+=['','Positive values indicate a model shortfall. Comparing speed and gain terms at H2 identifies the incoming normal velocity as the larger contributor on the selected misses. The table gives a descriptive decomposition at each model’s own event. The predicted kick is the strongest registered simulated substep in that frame and the ground truth uses the first 240 Hz force onset. The downstream outcome depends on direction, gap, multi-step contact and friction as well. These data alone do not establish that increasing a single coefficient will repair H3.','', '## Reproduction','','Model evaluation uses the pre-intervention factual RGB prefixes, the registered edit and the original frozen K=32 samples, shared gates and medoids. Force and state logs are joined only after the forecasts, using the simulator’s original 240 Hz records. Each raw file was verified against its active manifest. All 48 downsampled simulator positions and object-slot correspondences were cross-checked against the registered evaluation tensors. All 109 predicted outgoing speed measurements were matched to the prior frozen results. The reported counts describe the 127 RGB chains. The 29 misses are selected on the baseline outcome and do not estimate prevalence in the 5,500-scene holdout.','', 'Scene-paired means and bootstrap intervals are in [joint_impulse_attribution.json](joint_impulse_attribution.json). [Per-scene measurements](joint_impulse_scenes.jsonl), [native traces](impact_trace_scenes.jsonl), [H1 logs](first_impact_scenes.jsonl) and [H2 logs](simulator_impacts.jsonl) preserve the underlying measurements. Raw simulator revision `9bbe26d1a1fb7899eec4a2e6e986093a305f4d4f`. Baseline checkpoint SHA-256 `26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187`.'] (OUT/'REPORT.md').write_text('\n'.join(tt)+'\n') print('wrote',len(rows),'paired diagnostic records and figure',flush=True)
if __name__=='__main__':main()50 unmodified lines515253545450 unmodified lines
Model evaluation uses the pre-intervention factual RGB prefixes, the registered edit and the original frozen K=32 samples, shared gates and medoids. Force and state logs are joined only after the forecasts, using the simulator’s original 240 Hz records. Each raw file was verified against its active manifest. All 48 downsampled simulator positions and object-slot correspondences were cross-checked against the registered evaluation tensors. All 109 predicted outgoing speed measurements were matched to the prior frozen results. The reported counts describe the 127 RGB chains. The 29 misses are selected on the baseline outcome and do not estimate prevalence in the 5,500-scene holdout.
Scene-paired means and bootstrap intervals are in [joint_impulse_attribution.json](joint_impulse_attribution.json). [Per-scene measurements](joint_impulse_scenes.jsonl), [native traces](impact_trace_scenes.jsonl), [H1 logs](first_impact_scenes.jsonl) and [H2 logs](simulator_impacts.jsonl) preserve the underlying measurements. Raw simulator revision `9bbe26d1a1fb7899eec4a2e6e986093a305f4d4f`. Baseline checkpoint SHA-256 `26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187`.Scene-paired means and bootstrap intervals are in [joint_impulse_attribution.json](joint_impulse_attribution.json). [Per-scene measurements](joint_impulse_scenes.jsonl.gz), [native traces](impact_trace_scenes.jsonl.gz), [H1 logs](first_impact_scenes.jsonl.gz) and [H2 logs](simulator_impacts.jsonl.gz) preserve the underlying measurements. Raw simulator revision `9bbe26d1a1fb7899eec4a2e6e986093a305f4d4f`. Baseline checkpoint SHA-256 `26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187`.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162{ "corrected": { "miss_29": { "B_out": { "current": 1.619114090656412, "corrected": 1.6578822958058324, "n": 29, "sim": 2.217506194936818 }, "C_out": { "current": 0.605686502797263, "corrected": 0.6375161829803672, "n": 28, "sim": 0.979799249874694 } }, "success_80": { "B_out": { "current": 2.2561780489981174, "corrected": 2.192902337014675, "n": 80, "sim": 2.33701349273324 }, "C_out": { "current": 0.9842218235135078, "corrected": 0.9423710608329529, "n": 78, "sim": 1.088507959093803 } } }, "mass": { "miss_29": { "B_out": { "current": 1.619114090656412, "mass": 1.7478089353133892, "n": 29, "sim": 2.217506194936818 }, "C_out": { "current": 0.5909272848532118, "mass": 0.6554016712410696, "n": 29, "sim": 0.9621206701829516 } }, "success_80": { "B_out": { "current": 2.2561780489981174, "mass": 2.315839370340109, "n": 80, "sim": 2.33701349273324 }, "C_out": { "current": 0.968342206068337, "mass": 1.0049573270604015, "n": 80, "sim": 1.0779536670073866 } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102{ "miss_29": { "B_before_H2_angle_error_deg": { "n": 28, "mean": 5.825014840279307 }, "B_before_H2_predicted": { "n": 28, "mean": 1.36464752469744 }, "B_before_H2_truth": { "n": 28, "mean": 2.0944384932518005 }, "B_out_angle_error_deg": { "n": 29, "mean": 5.982356104357489 }, "B_out_predicted": { "n": 29, "mean": 1.6578822958058324 }, "B_out_truth": { "n": 29, "mean": 2.217506194936818 }, "C_out_angle_error_deg": { "n": 28, "mean": 8.890655190816947 }, "C_out_predicted": { "n": 28, "mean": 0.6375161829803672 }, "C_out_truth": { "n": 28, "mean": 0.979799249874694 }, "H1_correct": { "n": 29, "mean": 1.0 }, "H2_correct": { "n": 29, "mean": 0.9655172413793104 }, "H3_correct": { "n": 29, "mean": 0.034482758620689655 } }, "success_80": { "B_before_H2_angle_error_deg": { "n": 77, "mean": 9.373616599804395 }, "B_before_H2_predicted": { "n": 78, "mean": 1.866422287746667 }, "B_before_H2_truth": { "n": 78, "mean": 2.2458965136454654 }, "B_out_angle_error_deg": { "n": 80, "mean": 5.317990451864898 }, "B_out_predicted": { "n": 80, "mean": 2.192902337014675 }, "B_out_truth": { "n": 80, "mean": 2.33701349273324 }, "C_out_angle_error_deg": { "n": 78, "mean": 7.762967703696818 }, "C_out_predicted": { "n": 78, "mean": 0.9423710608329529 }, "C_out_truth": { "n": 78, "mean": 1.088507959093803 }, "H1_correct": { "n": 80, "mean": 1.0 }, "H2_correct": { "n": 80, "mean": 0.975 }, "H3_correct": { "n": 80, "mean": 0.9 } }}123version https://git-lfs.github.com/spec/v1oid sha256:09d2bb1d18817ee99f956572db053b049c287f82133546010bc8513a28290f0csize 1107412345678910111213141516171819202122232425262728293031323334{ "miss_29": { "B_out": { "current": 1.619114090656412, "corrected": 1.6578822958058324, "simulator": 2.217506194936818, "n": 29 }, "C_out": { "current": 0.605686502797263, "corrected": 0.6375161829803672, "simulator": 0.979799249874694, "n": 28 }, "H3_current": 0, "H3_corrected": 1 }, "success_80": { "B_out": { "current": 2.2561780489981174, "corrected": 2.192902337014675, "simulator": 2.33701349273324, "n": 80 }, "C_out": { "current": 0.9842218235135078, "corrected": 0.9423710608329529, "simulator": 1.088507959093803, "n": 78 }, "H3_current": 80, "H3_corrected": 72 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102{ "miss_29": { "B_before_H2_angle_error_deg": { "n": 29, "mean": 4.420920487107901 }, "B_before_H2_predicted": { "n": 29, "mean": 1.379935685930581 }, "B_before_H2_truth": { "n": 29, "mean": 2.108006321150681 }, "B_out_angle_error_deg": { "n": 29, "mean": 4.6435394626239255 }, "B_out_predicted": { "n": 29, "mean": 1.619114090656412 }, "B_out_truth": { "n": 29, "mean": 2.217506194936818 }, "C_out_angle_error_deg": { "n": 29, "mean": 8.157653812704416 }, "C_out_predicted": { "n": 29, "mean": 0.5909272848532118 }, "C_out_truth": { "n": 29, "mean": 0.9621206701829516 }, "H1_correct": { "n": 29, "mean": 1.0 }, "H2_correct": { "n": 29, "mean": 1.0 }, "H3_correct": { "n": 29, "mean": 0.0 } }, "success_80": { "B_before_H2_angle_error_deg": { "n": 80, "mean": 6.882870390731841 }, "B_before_H2_predicted": { "n": 80, "mean": 1.984494783732225 }, "B_before_H2_truth": { "n": 80, "mean": 2.2354346007108687 }, "B_out_angle_error_deg": { "n": 80, "mean": 4.480613082461059 }, "B_out_predicted": { "n": 80, "mean": 2.2561780489981174 }, "B_out_truth": { "n": 80, "mean": 2.33701349273324 }, "C_out_angle_error_deg": { "n": 80, "mean": 7.3464733101427555 }, "C_out_predicted": { "n": 80, "mean": 0.968342206068337 }, "C_out_truth": { "n": 80, "mean": 1.0779536670073866 }, "H1_correct": { "n": 80, "mean": 1.0 }, "H2_correct": { "n": 80, "mean": 1.0 }, "H3_correct": { "n": 80, "mean": 1.0 } }}123version https://git-lfs.github.com/spec/v1oid sha256:b7b1a24d6cd18a95194daa3bff5e6130ee10b1fac8fc84921451ab66529e16a4size 11259123version https://git-lfs.github.com/spec/v1oid sha256:9bb73bbd0c3fd74640f2f4ad5545e81c6eaac72220b0bac27ef64273262251e1size 19021123version https://git-lfs.github.com/spec/v1oid sha256:cb9f7a652947eb957608d5d567b48bddd051095e208835a84a65758f89b8b6c7size 36970123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102{ "miss_29": { "B_before_H2_angle_error_deg": { "n": 28, "mean": 4.417003980704716 }, "B_before_H2_predicted": { "n": 29, "mean": 1.5023353901402703 }, "B_before_H2_truth": { "n": 29, "mean": 2.108006321150681 }, "B_out_angle_error_deg": { "n": 29, "mean": 4.72771392762661 }, "B_out_predicted": { "n": 29, "mean": 1.7478089353133892 }, "B_out_truth": { "n": 29, "mean": 2.217506194936818 }, "C_out_angle_error_deg": { "n": 29, "mean": 8.07243682187179 }, "C_out_predicted": { "n": 29, "mean": 0.6554016712410696 }, "C_out_truth": { "n": 29, "mean": 0.9621206701829516 }, "H1_correct": { "n": 29, "mean": 1.0 }, "H2_correct": { "n": 29, "mean": 1.0 }, "H3_correct": { "n": 29, "mean": 0.06896551724137931 } }, "success_80": { "B_before_H2_angle_error_deg": { "n": 79, "mean": 6.938981346314466 }, "B_before_H2_predicted": { "n": 80, "mean": 1.9422955431073206 }, "B_before_H2_truth": { "n": 80, "mean": 2.2354346007108687 }, "B_out_angle_error_deg": { "n": 80, "mean": 4.442855009064078 }, "B_out_predicted": { "n": 80, "mean": 2.315839370340109 }, "B_out_truth": { "n": 80, "mean": 2.33701349273324 }, "C_out_angle_error_deg": { "n": 80, "mean": 7.382640535477549 }, "C_out_predicted": { "n": 80, "mean": 1.0049573270604015 }, "C_out_truth": { "n": 80, "mean": 1.0779536670073866 }, "H1_correct": { "n": 80, "mean": 1.0 }, "H2_correct": { "n": 80, "mean": 1.0 }, "H3_correct": { "n": 80, "mean": 1.0 } }}123version https://git-lfs.github.com/spec/v1oid sha256:d08a81eb199a558cd3f18a16e4fd541675b1bbbd25516215bc580e8e0d33790csize 11266123version https://git-lfs.github.com/spec/v1oid sha256:fe03f64d335d2964151423e1e9ca314765c800bf8e97080a19b7135a4d143a0asize 2246612345678910111213141516import subprocess,sys,time,os,jsonfrom pathlib import Pathr=Path('/marimo/jais_motion_transfer_20261202');d=r/'diagnostics';f=r/'frozen';rgb=r/'rgb_cache';old=Path('/marimo/attention_retrain_cutoff_20261201')def until(condition): while not condition():time.sleep(5)until(lambda:(f/'registration.json').is_file())subprocess.run([sys.executable,'-u',str(d/'archived_split.py'),'--frozen',str(f),'--out',str(d/'results')],check=True)print('archived registered kinematics complete',flush=True)until(lambda:(rgb/'restoration.json').is_file() and Path('/tmp/jais_cutoff_registered.pt').is_file() and (old/'attention_stochastic/prob_contact_attn_best.pt').is_file())print('starting substep contact trace',flush=True)ev=next(r.glob('**/evaluate_transfer.py')).parentpaths=[ev,old/'eval_code',old/'extras','/marimo/prob_contact_attn','/marimo/mass-ratio/repo',r/'code']env={**os.environ,'PYTHONPATH':os.pathsep.join(map(str,paths)),'OMP_NUM_THREADS':'2','OPENBLAS_NUM_THREADS':'1'}split=next(p for p in [rgb/'three_hit_split.json',r/'three_hit_split.json'] if p.is_file())enc=Path((rgb/'encoder.path').read_text().strip())subprocess.run([sys.executable,'-u',str(d/'impact_trace.py'),'--data','/tmp/jais_cutoff_registered.pt','--splits',str(split),'--frozen',str(f),'--base',str(old/'attention_stochastic/prob_contact_attn_best.pt'),'--encoder',str(enc),'--rgb-cache',str(rgb),'--out',str(d/'results')],env=env,cwd=r,check=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Match untouched RGB forecasts to simulator contact forces. Used only after forecasting."""import concurrent.futures as cfimport hashlibimport ioimport jsonimport timefrom pathlib import Path
import numpy as npimport torchfrom huggingface_hub import hf_hub_download
ROOT = Path('/marimo/jais_motion_transfer_20261202')REV = '9bbe26d1a1fb7899eec4a2e6e986093a305f4d4f'HF = 'pineapplechoco/jais'OUT = ROOT/'diagnostics/results'norm = np.linalg.norm
def force_row(sid, row, bundle, ids, locked): base = 'instances/'+sid+'/counterfactual/sim_log/' def read(name): for attempt in range(5): try: return Path(hf_hub_download(HF,base+name,revision=REV,repo_type='dataset')).read_bytes() except Exception: if attempt==4: raise time.sleep(2**attempt) m=json.loads(read('manifest.json'))['files'] def checked(name): v=read(m[name]['path']) assert len(v)==m[name]['size'] and hashlib.sha256(v).hexdigest()==m[name]['sha256'] return v meta=json.loads(checked('metadata.json')) states=np.load(io.BytesIO(checked('states.npy')),allow_pickle=False) contacts=[json.loads(l) for l in checked('contacts.jsonl').splitlines()] ix=ids[sid] n=int(bundle['n'][ix]); frame_states=bundle['state_cf'][ix,:,:n,:].numpy() assert meta['steps']==list(range(len(states))) and meta['step_rate']==240 # Establish a one-to-one slot mapping by position, then check all archived positions. ds=norm(frame_states[0,:,None,:3]-states[0,None,:,:3],axis=-1) rids=ds.argmin(axis=1) assert len(set(rids.tolist()))==n and max(ds.min(axis=1))<2e-4 assert np.max(abs(states[::10][:48,rids,:3]-frame_states[:,:,:3]))<2e-4 truth=row['branches']['on']['truth'] B,C=[v['objects'][0] for v in truth[:2]] t=truth[1]['frame']; x0=(t-1)*10; x1=t*10 b,c=rids[B],rids[C] nb,nc=[meta['object_ids'][j] for j in (b,c)] pairs=[e for e in contacts if {e['object_a'],e['object_b']}=={nb,nc} and x0<=e['step']<x1] assert pairs, (sid,t) first=min(e['step'] for e in pairs) at=[e for e in pairs if e['step']==first] dominant=max(at,key=lambda e:e['normal_force']) def unit(e): return np.array(e['normal'])*(1 if e['object_a']==nc else -1) nrm=unit(dominant);assert np.isclose(norm(nrm),1) sb,sc=states[first-1,[b,c]] vc0=sc[7:10];vb0=sb[7:10];vc1=states[first,c,7:10] p=np.asarray(dominant['position']) vc_surface=vc0+np.cross(sc[10:13],p-sc[:3]) vb_surface=vb0+np.cross(sb[10:13],p-sb[:3]) mC=float(np.exp(bundle['attrs'][ix,C,0].item()));mB=float(np.exp(bundle['attrs'][ix,B,0].item())) def impulse(events): return sum(e['normal_force']*unit(e) for e in events)/(mC*meta['step_rate']) impulse0=impulse(at);impulse1=impulse(pairs) other=[e for e in contacts if e['step']==first and nc in (e['object_a'],e['object_b']) and nb not in (e['object_a'],e['object_b']) and 'floor' not in (e['object_a'],e['object_b'])] closing=float((vb0[:2]-vc0[:2])@(nrm[:2]/max(1e-9,norm(nrm[:2])))) field=lambda v:float(v) return dict(scene=sid,group='miss_29' if sid in locked else 'success_80',h2_frame=t,h2_step=first,gt_receiver_mass=mC,gt_sender_mass=mB, gt_b_speed_pre=field(norm(vb0[:2])),gt_c_speed_pre=field(norm(vc0[:2])),gt_c_speed_after=field(norm(vc1[:2])),gt_outgoing_heading_xy=vc1[:2].tolist(), gt_bc_normal_xy=nrm[:2].tolist(),gt_com_planar_closing=closing, gt_contact_point_3d_closing=field((vb_surface-vc_surface)@nrm),gt_com_3d_closing=field((vb0-vc0)@nrm), gt_strongest_normal_z=field(nrm[2]),gt_first_step_normal_kick_xy=field(norm(impulse0[:2])),gt_frame_normal_kick_xy=field(norm(impulse1[:2])), gt_observed_first_step_delta_vxy=field(norm(vc1[:2]-vc0[:2])),gt_b_mass_fraction=mB/(mB+mC), gt_first_step_effective_gain=field(norm(impulse0[:2])/closing) if closing>.05 else None, receiver_other_nonfloor_contact_same_step=bool(other),contact_points_first_step=len(at),contact_records_frame=len(pairs))
def summarize(records): stats={} for label in ('miss_29','success_80'): rows=[r for r in records if r['group']==label] stats[label]={} for key in sorted({k for r in rows for k,v in r.items() if isinstance(v,(int,float)) and not isinstance(v,bool)}): values=[r[key] for r in rows if r.get(key) is not None] stats[label][key]={'n':len(values),'mean':float(np.mean(values)),'median':float(np.median(values))} return stats
def main(): OUT.mkdir(parents=True,exist_ok=True) ledger=[json.loads(l) for l in (ROOT/'frozen/rgb/current/per_scene.jsonl').read_text().splitlines()] kinematics=[json.loads(l) for l in (OUT/'matched_impact_kinematics_scenes.jsonl').read_text().splitlines()] target={r['scene'] for r in kinematics} locked=set(json.loads((ROOT/'frozen/fixed_29.json').read_bytes())) assert len(target)==109 and len(locked)==29 b=torch.load('/tmp/jais_cutoff_registered.pt',map_location='cpu',mmap=True,weights_only=False) ids={s:i for i,s in enumerate(b['scene_ids'])} rows=[] cache=ROOT/'diagnostics/contact_row_cache';cache.mkdir(exist_ok=True) def worker(row): sid=row['scene']; fn=cache/(sid+'.json') if not fn.exists():fn.write_text(json.dumps(force_row(sid,row,b,ids,locked),allow_nan=False)) return json.loads(fn.read_bytes()) with cf.ThreadPoolExecutor(max_workers=5) as ex: for r in ex.map(worker,[r for r in ledger if r['scene'] in target]): rows.append(r) if len(rows)%12==0:print(len(rows),flush=True) (OUT/'simulator_impacts.jsonl').write_text(''.join(json.dumps(r,allow_nan=False)+'\n' for r in rows)) (OUT/'simulator_impacts_summary.json').write_text(json.dumps(dict(source=HF,revision=REV,step_rate=240,groups=summarize(rows)),indent=2)+'\n') print('verified original contact logs for',len(rows),flush=True)
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178"""Render four-arm motion and timing results after all registered cohorts finish on Molab."""import jsonfrom pathlib import Pathimport hashlibimport re
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltimport numpy as np
R=Path(__file__).resolve().parent
def read(p):return json.loads((R/p).read_bytes())def fmt(x,d=3):return '—' if x is None else f'{x:.{d}f}'def mean(x,k):return x[k]['mean']def named(v,k):return f"{fmt(mean(v,k))} ({v[k]['n']})"def change(v,scale=1): if v['first_minus_second'] is None:return '—' lo,hi=v['bootstrap_95'] return f"{scale*v['first_minus_second']:+.3f} [{scale*lo:+.3f}, {scale*hi:+.3f}]"def pairs(v):return f"{len(v['only_first'])} / {len(v['only_second'])}"def delta_pair(v):return f"{len(v['only_first'])} gained, {len(v['only_second'])} lost"def write_atomic(name,body): p=R/name;t=p.with_name(p.name+'.rendering');t.write_text(body);t.replace(p)def per_scene(name):return {x['scene']:x for x in map(json.loads,(R/name).read_text().splitlines())}
def main(): arms={'current':'Current attention','impulse':'Impulse correction','mass':'Mass calibration','solver':'Frozen solver'} colors={'current':'#677583','impulse':'#b85e35','mass':'#007965','solver':'#4763ac'} scope=[('state','on_true_H3','State, true three-hit chains'),('rgb','on_true_H3','RGB, true three-hit chains'),('rgb','fixed_29','RGB, original 29 misses')] set_names={'state':'State','rgb':'RGB'} op={s:read(f'results/{s}/comparison.json') for s in set_names} ma={s:read(f'mass_evaluation/results/{s}/comparison.json') for s in set_names} direct=read('mass_evaluation/results/impulse_comparison.json')['groups'] for s in set_names: assert op[s]['registered']==ma[s]['registered']==(5500 if s=='state' else 127) for m in ['current','solver']: assert op[s]['row_hashes'][m]==ma[s]['row_hashes'][m] def stat(s,g,m): comp=ma if m=='mass' else op key='corrected' if m in ('mass','impulse') else m return comp[s]['groups'][g]['arms'][key] def paired(s,g,m): if m=='mass-impulse':return direct[s][g]['contrasts']['mass minus impulse'] comp=ma if m=='mass' else op return comp[s]['groups'][g]['contrasts']['corrected minus current'] for e,g,_ in scope: assert len(set(stat(e,g,m)['n'] for m in arms))==1 A=read('model_lock.json');M=read('candidates/prefix_mass/model_lock.json') assert A['validation_selection_complete'] and M['validation_selection_complete'] and not A['test_used_for_selection'] and not M['test_used_for_selection'] assert M['validation_selected_family']=='prefix_mass' and A['selected_variant']=='direction_speed' assert M['registered_protocol_sha256']==hashlib.sha256((R/'candidates/prefix_mass/protocol.json').read_bytes()).hexdigest() d=read('diagnostics/results/joint_impulse_attribution.json')['miss_29'] force=read('diagnostics/results/one_step_mass_sensitivity.json')['H1']['miss_29'] single=read('diagnostics/results/first_impact_summary.json')['miss_29'] state=stat('state','on_true_H3','mass');rgb=stat('rgb','on_true_H3','mass') rs=stat('rgb','on_true_H3','solver');ss=stat('state','on_true_H3','solver');rc=stat('rgb','on_true_H3','current');sc=stat('state','on_true_H3','current') mass29=stat('rgb','fixed_29','mass');r29=stat('rgb','fixed_29','current') r29p=paired('rgb','fixed_29','mass') ma_pair=paired('rgb','on_true_H3','mass') known={name:per_scene('diagnostics/results/'+name+'_launch_direction_scenes.jsonl') for name in ['current','corrected','mass']} launch={} for new in ('corrected','mass'): launch[new]={} for k in ('miss_29','success_80'): pane=[s for s,x in known['current'].items() if x['group']==k] group={} for which in ('B_out','C_out'): pred=which+'_predicted';gt=which+'_truth' joint=[s for s in pane if pred in known['current'][s] and pred in known[new][s]] group[which]={arm:float(np.mean([known[arm][s][pred] for s in joint])) for arm in ('current',new)} group[which].update(n=len(joint),sim=float(np.mean([known[new][s][gt] for s in joint]))) launch[new][k]=group write_atomic('diagnostics/results/all_learned_launch_summary.json',json.dumps(launch,indent=2)+'\n') vshare=read('candidates/prefix_mass/validation_mass_shares.json')['sender_fraction']['A_into_B'] eligible=read('train/registration.json') mscore=M['candidate_scores'] details=[] for s,g,label in scope: for m,nm in arms.items(): v=stat(s,g,m) details.append(f"| {label} | {nm} | {v['h2']} | {v['h3']} | {v['h3_only_timed']} | {v['h3_timed']} | {named(v,'h3_abs')} |") motion=[] for s,g,label in scope: for m,nm in arms.items(): v=stat(s,g,m) motion.append(f"| {label} | {nm} | {fmt(mean(v,'true_c'))} | {fmt(mean(v,'pred_c'))} | {named(v,'speed_mae')} | {named(v,'own_c')} | {named(v,'own_speed_mae')} |") full=[] for g,br in [('on_all','Edited'),('off_all','Factual')]: for m,nm in arms.items(): v=stat('state',g,m);fp=v['false_declared_H3'] full.append(f"| {br} | {nm} | {v['true_h3']} | {v['h3']} | {fp['called']}/{fp['n_without_H3']} | {named(v,'speed_mae')} | {fmt(mean(v,'ade'))} | {fmt(mean(v,'effect_ade'))} |") P=[] for s,g,label in scope: for m,k in [('impulse','Impulse minus current'),('mass','Mass minus current'),('mass-impulse','Mass minus impulse')]: z=paired(s,g,m) P.append(f"| {label} | {k} | {pairs(z['h3'])} | {pairs(z['h3_only_timed'])} | {pairs(z['h3_timed'])} | {change(z['speed_mae'])} | {change(z['h3_abs'])} ({z['h3_abs']['n']}) |") vm=launch['mass']['miss_29'];vi=launch['corrected']['miss_29'] launch_lines=[] for nm in ('corrected','mass'): for k,kk in [('miss_29','Original 29 misses'),('success_80','Original 80 successes')]: q=launch[nm][k];x=q['B_out'];y=q['C_out'] launch_lines.append(f"| {kk} | {arms['mass' if nm=='mass' else 'impulse']} | {x['current']:.3f} → {x[nm]:.3f} ({x['n']}) | {x['sim']:.3f} | {y['current']:.3f} → {y[nm]:.3f} ({y['n']}) | {y['sim']:.3f} |") fig,ax=plt.subplots(1,2,figsize=(11,4.1),layout='constrained') for i,m in enumerate(arms): for axis,scname,label in [(ax[0],'state','State'),(ax[1],'rgb','RGB prefix')]: v=stat(scname,'on_true_H3',m); xs=np.arange(3)+(i-1.5)*.20 bars=axis.bar(xs,[v[k] for k in ('h3','h3_only_timed','h3_timed')],width=.19,label=arms[m],color=colors[m]) axis.bar_label(bars,fmt='%d',fontsize=8,padding=1) axis.set_xticks(range(3),['Ordered H3','H3 within ±2','All hits within ±2'],fontsize=9) axis.set_ylim(0,132);axis.set_title(f'{label} ({v["n"]} true three-hit chains)',fontsize=12) axis.spines[['top','right']].set_visible(False);axis.grid(axis='y',alpha=.15);axis.set_axisbelow(True) ax[0].set_ylabel('Number of scenes');ax[1].legend(ncol=2,loc='upper right',fontsize=8,frameon=False) fig.savefig(R/'motion_transfer.png',dpi=170);plt.close(fig) key1=(f"On the 127 RGB chains, calibrating the attention model’s inferred relative masses recovered {rgb['h3']}/127 ordered third hits, compared with {rc['h3']} for current attention, {stat('rgb','on_true_H3','impulse')['h3']} for the impulse correction and {rs['h3']} for the frozen solver. Mass calibration recovered {mass29['h3']}/29 of the original misses and preserved {stat('rgb','original_80_successes','mass')['h3']}/80 previous successes. Its RGB C-speed MAE changed by {change(ma_pair['speed_mae'])} m/s relative to current attention (paired 95% interval).") key2=(f"The solver remained stronger on the full state cohort’s {state['n']} edited three-hit chains. It recovered {ss['h3']} third recipients and timed all three hits within ±2 frames in {ss['h3_timed']} scenes. The corresponding counts were {state['h3']} and {state['h3_timed']} for calibrated attention, and {sc['h3']} and {sc['h3_timed']} for current attention. On RGB the solver timed all three in {rs['h3_timed']}/127, against {rgb['h3_timed']}/127 for mass calibration.") rows=['# Why C leaves the second hit too slowly','',key1,'',key2,'','','', '## The error starts when A hits B','', f"The 29 cases were selected because the frozen attention model identifies B and C in order, then reports no third recipient. A arrives at H1 with essentially the correct closing speed ({single['model_A_closing']['mean']:.3f} m/s predicted, {single['gt_A_closing']['mean']:.3f} m/s simulated). The model assigns A a sender mass fraction of {single['model_A_mass_fraction']['mean']:.3f}, compared with {single['gt_A_mass_fraction']['mean']:.3f} in the simulator. Its normal kick into B averages {d['H1_kick']['model']:.3f} m/s versus {d['H1_kick']['truth']:.3f}. Using the true mass fraction in that single predicted impulse raises it to {force['mass_oracle_mps']:.3f} m/s and cuts kick MAE from {force['mean_abs_error_original']:.3f} to {force['mean_abs_error_mass_oracle']:.3f} m/s, improving {force['mass_oracle_reduces_error_count']}/29. This is an evaluation-only calculation at the original collision.",'', '| Registered mean, original 29 RGB misses | Frozen attention | Simulator |','|---|---:|---:|', *[f"| {label} | {d[k]['model']:.3f} | {d[k]['truth']:.3f} |" for k,label in [('B_H1','B speed after H1 (m/s)'),('B_preH2','B speed entering H2 (m/s)'),('closing','B–C normal closing speed at H2 (m/s)'),('kick','Normal kick from B to C (m/s)'),('C_ownH2','C speed after H2 (m/s)'),('C_towards_D','C speed toward D (m/s)')]],'', "Simulator readings use the original 240 Hz force and state records. The model readings use the strongest registered contact substep in its own predicted impact frame. At H1 the smaller effective transfer gain accounts for most of the missing kick. At H2 the incoming closing speed is already too low in 25/29. B’s launch heading error averages 4.6°, C’s outgoing heading error 8.2°. In 24/29 the predicted C–D surfaces stay more than 4.5 cm apart, and only 3/29 generate a nonzero subthreshold C→D impulse. A blanket reduction of the contact threshold would leave most misses untouched. [Force records, direction errors, and matched traces](diagnostics/results/REPORT.md).",'', '## What each forecaster uses','', '| Forecaster | Difference at inference |','|---|---|', '| Current attention | Frozen stochastic attention checkpoint. From the factual prefix it predicts latent physical properties, routes contact messages, and rolls out the intervention. |', '| Impulse correction | The validation-selected correction can rotate a predicted impulse by up to 15° and adjust restitution and friction for prospective first touches on the contact path, including H1. The original attention and gate are frozen. |', '| Mass calibration | A train-fitted linear adjustment to the latent log-mass mean uses object shape and size, prefix motion and slip, and the original prior’s mean and uncertainty. The same corrected mass is used on both sides of each collision and across all substeps. No true mass is supplied during forecasting. |', '| Frozen solver | The registered rigid-body solver uses its previously fitted parameters. It receives the same intervention and prefix state source as the corresponding attention arm. |','', f"The split contains 5,600 training scenes, 1,400 validation scenes and 5,500 state test scenes. The original impulse families used {eligible['train_h2_branches']:,} eligible training branches from {eligible['train_eventful_scenes']:,} training scenes. The 1,069 eligible validation branches came from 786 scenes. An initial secondary-contact-only correction scored {mscore['values']:.5f} on validation, versus {mscore['direction_speed']:.5f} for the reported impulse correction and {mscore['identity']:.5f} for identity. The first two fits were selected before their holdout results were read.",'', f"The force trace of the *existing* attention model motivated the subsequent mass-calibration recipe. That recipe was specified before the coordinator received corrected A/B holdout results. Its fit used {M['train_nodes']:,} objects across all {M['train_scenes']:,} training scenes with known simulated masses as training labels. The strength ({M['strength']:.2f}) and frozen checkpoint were chosen by the original validation score ({mscore['prefix_mass']:.5f}). The earlier corrected test outcomes were unused in that selection. The validation sender-fraction MAE for A→B changed from {vshare['frozen']['abs_error']:.3f} to {vshare['corrected']['abs_error']:.3f}. The original 29 informed the research hypothesis and remain a descriptive subgroup. [Impulse selections](model_lock.json) · [Mass protocol](candidates/prefix_mass/protocol.json) · [Mass selection](candidates/prefix_mass/model_lock.json).",'', '## Third recipients and contact timing','', f"Of the 5,500 edited simulator-state branches, {state['n']} have a true three-hit chain. The 127 RGB chains are a matched subset of those {state['n']}. B, C and D denote the first, second and third recipients. A hit counts here only when it follows the correct preceding recipients. H3 within ±2 requires the third timestamp to match. All within ±2 also requires H1 and H2 to match. Timing MAE includes only forecasts with the correct three recipients. Parentheses give its eligible scene count. The video rate is 24 frames/s.",'', '| Cohort | Model | Ordered H2 | Ordered H3 | H3 within ±2 | All within ±2 | H3 timing MAE, frames (n) |','|---|---|---:|---:|---:|---:|---:|',*details,'', '## C’s outgoing speed','', 'True-clock speed uses C’s one-frame planar displacement immediately after the true H2. A missed or late model event still receives a speed error. Own-clock speed aligns the model and simulator to their respective H2 timestamps, and requires correct H1 and H2 with a following frame. The two anchors can therefore cover different scenes. All speeds below are in m/s. Parentheses give eligible counts.','', '| Cohort | Model | True-clock truth | True-clock forecast | True-clock MAE (n) | Own-clock forecast (n) | Own-clock MAE (n) |','|---|---|---:|---:|---:|---:|---:|',*motion,'', '## What changed for the same scenes','', 'Gains and losses compare individual outcomes. Error differences are candidate minus comparator. Brackets give paired 95% scene-bootstrap intervals over 4,000 replicates; conditional timing differences use only scenes where both methods recover H3. A negative error change is better. The 29 were selected to have zero baseline H3 successes, so baseline timing MAE is undefined for this subgroup.','', '| Cohort | Contrast | H3 gained / lost | H3 ±2 gained / lost | Full ±2 gained / lost | Δ C-speed MAE, m/s [95%] | Δ H3 timing MAE, frames [95%] (n) |','|---|---|---:|---:|---:|---:|---:|',*P,'', 'The following are own-clock comparisons on the intersection of correctly identified recipients for the candidate and current attention. The simulator speed in each row uses that exact subset.','', '| Original RGB cohort | Candidate | B after H1, current → candidate (n) | Sim B | C after H2, current → candidate (n) | Sim C |','|---|---|---:|---:|---:|---:|',*launch_lines,'', '## All 5,500 scenes, including negatives','', 'Each scene contributes one edited branch and one factual command-off control. H3 positives and false declarations use the entire branch population. C-speed MAE uses every scene with a scoreable second event. ADE is the mean position error in metres. Intervention-effect ADE is the error in the edited-minus-factual predicted 3D displacement against the true difference. This paired effect is shared by both rows for a given model.','', '| Branch | Model | True H3 | Ordered H3 | False H3 / negatives | C-speed MAE, m/s (n) | ADE, m | Intervention-effect ADE, m |','|---|---|---:|---:|---:|---:|---:|---:|',*full,'', '## Scope and reproducibility','', 'All forecasts start from the same pre-intervention factual cutoff within each scene and run autonomously, with the edit enabled or disabled. Attention variants use the same registered draws and contact randomness (32 samples). RGB uses the frozen visual extractor, known camera and object metadata, and registered box prompts. Prefix-frame and segmentation checksums matched the original release and both reference forecasters reproduced their archived events. The simulator-state and RGB arms use different registered initial belief draws. These scores measure graph trajectories and contacts. This experiment did not score rendered Wan pixels. The 127 and the diagnostic subsets overlap the state holdout. The confidence intervals describe variation over scenes for these frozen fits.','', '[State tables](results/state/comparison.json) · [RGB tables](results/rgb/comparison.json) · [Mass state tables](mass_evaluation/results/state/comparison.json) · [Mass RGB tables](mass_evaluation/results/rgb/comparison.json) · [Paired mass versus impulse](mass_evaluation/results/impulse_comparison.json) · [Protocol](protocol.json) · [Original 29 IDs](frozen/fixed_29.json) · [Source for this report](make_final_report.py)'] write_atomic('REPORT.md','\n'.join(rows)+'\n') write_atomic('README.md','\n'.join(['# JAIS motion transfer and third-hit timing','',key1,'',key2,'', f"On the original 29 misses, the first speed loss occurs when A hits B. The mean predicted first kick is {d['H1_kick']['model']:.3f} m/s versus {d['H1_kick']['truth']:.3f} in the simulator. The trained mass calibration raises B’s outgoing speed from {vm['B_out']['current']:.3f} to {vm['B_out']['mass']:.3f} m/s. The simulator averages {vm['B_out']['sim']:.3f} m/s on those same {vm['B_out']['n']} scenes.",'', '[Read the full four-model evaluation](REPORT.md) · [Inspect the simulator-force diagnosis](diagnostics/results/REPORT.md)','', '',''])) # Published per-scene records are gzipped by publish.py. Align references with remote names. p=R/'diagnostics/results/REPORT.md' p.write_text(re.sub(r'\.jsonl\)', '.jsonl.gz)',p.read_text())) # Remove the retired intermediate filename if making the report again. extras=R/'publish_extras.txt' extra=set(extras.read_text().splitlines())|{'REPORT.md','README.md','motion_transfer.png','make_final_report.py','protocol.json','direction_registration.json','results/input_comparison.json','mass_evaluation/results/impulse_comparison.json','candidates/prefix_mass/model_lock.json','candidates/prefix_mass/protocol.json','candidates/prefix_mass/best.pt','candidates/prefix_mass/history.json','candidates/prefix_mass/validation_mass_shares.json'} for mask in ['diagnostics/results/*','mass_evaluation/results/*/comparison.json','mass_evaluation/*/corrected/{per_scene.jsonl,complete.json}','diagnostics/*.py']: if '{' in mask:continue extra.update(str(q.relative_to(R)) for q in R.glob(mask) if q.is_file()) for s in set_names: for name in ('per_scene.jsonl','complete.json'): extra.add(f'mass_evaluation/{s}/corrected/{name}') write_atomic('publish_extras.txt','\n'.join(sorted(extra))+'\n') # Resolve all relative report/image links including the publisher's gzip mapping. for name in ['REPORT.md','README.md','diagnostics/results/REPORT.md']: src=R/name for href in re.findall(r'\]\(([^)]+)\)',src.read_text()): if '://' in href:continue local=src.parent/href if str(local).endswith('.jsonl.gz'):local=Path(str(local)[:-3]) assert local.is_file(),(name,href) assert len(rows)>100 and (R/'motion_transfer.png').stat().st_size>10000 print('Rendered four-model report, verified references and registered publication extras.',flush=True)
if __name__=='__main__':main()attention_secondary_motion_transfer_20261202/README.md+9-3
attention_secondary_motion_transfer_20261202/REPORT.mdAdded+119
attention_secondary_motion_transfer_20261202/diagnostics/append_mechanics.pyAdded+59
attention_secondary_motion_transfer_20261202/diagnostics/archived_split.pyAdded+57
attention_secondary_motion_transfer_20261202/diagnostics/first_impact.pyAdded+72
attention_secondary_motion_transfer_20261202/diagnostics/impact_trace.pyAdded+224
attention_secondary_motion_transfer_20261202/diagnostics/launch_direction.pyAdded+77
attention_secondary_motion_transfer_20261202/diagnostics/report.pyAdded+107
attention_secondary_motion_transfer_20261202/diagnostics/results/REPORT.md+1-1
attention_secondary_motion_transfer_20261202/diagnostics/results/all_learned_launch_summary.jsonAdded+62
attention_secondary_motion_transfer_20261202/diagnostics/results/corrected_launch_direction.jsonAdded+102
attention_secondary_motion_transfer_20261202/diagnostics/results/corrected_launch_direction_scenes.jsonl.gzAdded+3
attention_secondary_motion_transfer_20261202/diagnostics/results/corrected_launch_paired_summary.jsonAdded+34
attention_secondary_motion_transfer_20261202/diagnostics/results/current_launch_direction.jsonAdded+102
attention_secondary_motion_transfer_20261202/diagnostics/results/current_launch_direction_scenes.jsonl.gzAdded+3
attention_secondary_motion_transfer_20261202/diagnostics/results/first_impact_scenes.jsonl.gzAdded+3
attention_secondary_motion_transfer_20261202/diagnostics/results/joint_impulse_scenes.jsonl.gzAdded+3
attention_secondary_motion_transfer_20261202/diagnostics/results/mass_launch_direction.jsonAdded+102
attention_secondary_motion_transfer_20261202/diagnostics/results/mass_launch_direction_scenes.jsonl.gzAdded+3
attention_secondary_motion_transfer_20261202/diagnostics/results/simulator_impacts.jsonl.gzAdded+3
attention_secondary_motion_transfer_20261202/diagnostics/runner.pyAdded+16
attention_secondary_motion_transfer_20261202/diagnostics/simulator_contacts.pyAdded+111
attention_secondary_motion_transfer_20261202/make_final_report.pyAdded+178
attention_secondary_motion_transfer_20261202/motion_transfer.pngAdded

Large File Pointer Details
- SHA256: 0a137346983f097ce0e46d0030b9fcd9b427aa2b47f2470d89c6adc3d1562312
- Pointer size: 130 Bytes
- Size of remote file: 85.4 kB