Log locked motion-transfer run and verified derived artifacts
Browse filesFiles changed (31)
- attention_secondary_motion_transfer_20261202/candidates/direction_speed/best.ptAdded+3
- attention_secondary_motion_transfer_20261202/candidates/direction_speed/finished.jsonAdded+36
- attention_secondary_motion_transfer_20261202/candidates/direction_speed/history.jsonAdded+119
- attention_secondary_motion_transfer_20261202/candidates/direction_speed/identity.ptAdded+3
- attention_secondary_motion_transfer_20261202/candidates/direction_speed/last.ptAdded+3
- attention_secondary_motion_transfer_20261202/candidates/direction_speed/registration.jsonAdded+23
- attention_secondary_motion_transfer_20261202/candidates/prefix_mass/best.ptAdded+3
- attention_secondary_motion_transfer_20261202/candidates/prefix_mass/history.jsonAdded+77
- attention_secondary_motion_transfer_20261202/candidates/prefix_mass/model_lock.jsonAdded+53
- attention_secondary_motion_transfer_20261202/candidates/prefix_mass/protocol.jsonAdded+10
- attention_secondary_motion_transfer_20261202/candidates/prefix_mass/validation_mass_shares.jsonAdded+42
- attention_secondary_motion_transfer_20261202/candidates/provenance.jsonAdded+187
- attention_secondary_motion_transfer_20261202/candidates/values/best.ptAdded+3
- attention_secondary_motion_transfer_20261202/candidates/values/finished.jsonAdded+36
- attention_secondary_motion_transfer_20261202/candidates/values/history.jsonAdded+119
- attention_secondary_motion_transfer_20261202/candidates/values/identity.ptAdded+3
- attention_secondary_motion_transfer_20261202/candidates/values/last.ptAdded+3
- attention_secondary_motion_transfer_20261202/candidates/values/registration.jsonAdded+22
- attention_secondary_motion_transfer_20261202/code/build_transfer.pyAdded+86
- attention_secondary_motion_transfer_20261202/code/check_transfer.pyAdded+89
- attention_secondary_motion_transfer_20261202/code/finalize_transfer.pyAdded+38
- attention_secondary_motion_transfer_20261202/code/mass_transfer.pyAdded+49
- attention_secondary_motion_transfer_20261202/code/run_training.pyAdded+32
- attention_secondary_motion_transfer_20261202/code/train_mass_transfer.pyAdded+90
- attention_secondary_motion_transfer_20261202/code/train_transfer.pyAdded+273
- attention_secondary_motion_transfer_20261202/code/transfer_direction_dynamics.pyAdded+1238
- attention_secondary_motion_transfer_20261202/code/transfer_dynamics.pyAdded+1229
- attention_secondary_motion_transfer_20261202/code/transfer_model.pyAdded+25
- attention_secondary_motion_transfer_20261202/code/verify_mass_shares.pyAdded+29
- attention_secondary_motion_transfer_20261202/direction_registration.jsonAdded+7
- attention_secondary_motion_transfer_20261202/train/verification.jsonAdded+31
123version https://git-lfs.github.com/spec/v1oid sha256:ce300934b2534be05320c15941acd737d9984db78870c2fbc0093ee9e52e427asize 2381123456789101112131415161718192021222324252627282930313233343536{ "selected": 1, "improved_over_identity": true, "checkpoint_sha256": "ce300934b2534be05320c15941acd737d9984db78870c2fbc0093ee9e52e427a", "base_validation": { "score": 0.604632705476781, "c_mae_mps": 0.37077100576919364, "c_vector_error_mps": 0.39487123018970166, "c_mean_mps": 0.5423193962262874, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 806, "h3_n": 293, "h3_ordered": 105, "h3_timed": 51, "h3_timing_bias_frames": -3.4, "h3_capped_error_with_misses_frames": 9.017064846416382 }, "selected_metrics": { "epoch": 1, "train_loss": 0.7215451255757758, "weight_norm": 1.640528678894043, "score": 0.5987337233152157, "c_mae_mps": 0.36316713342491685, "c_vector_error_mps": 0.38945685393059754, "c_mean_mps": 0.5382862402802449, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 792, "h3_n": 293, "h3_ordered": 106, "h3_timed": 50, "h3_timing_bias_frames": -3.056603773584906, "h3_capped_error_with_misses_frames": 9.054607508532424 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119[ { "epoch": 0, "score": 0.604632705476781, "c_mae_mps": 0.37077100576919364, "c_vector_error_mps": 0.39487123018970166, "c_mean_mps": 0.5423193962262874, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 806, "h3_n": 293, "h3_ordered": 105, "h3_timed": 51, "h3_timing_bias_frames": -3.4, "h3_capped_error_with_misses_frames": 9.017064846416382 }, { "epoch": 1, "train_loss": 0.7215451255757758, "weight_norm": 1.640528678894043, "score": 0.5987337233152157, "c_mae_mps": 0.36316713342491685, "c_vector_error_mps": 0.38945685393059754, "c_mean_mps": 0.5382862402802449, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 792, "h3_n": 293, "h3_ordered": 106, "h3_timed": 50, "h3_timing_bias_frames": -3.056603773584906, "h3_capped_error_with_misses_frames": 9.054607508532424 }, { "epoch": 2, "train_loss": 0.7131195600996626, "weight_norm": 2.6135406494140625, "score": 0.6127170108763311, "c_mae_mps": 0.36329508992999443, "c_vector_error_mps": 0.39357907664161484, "c_mean_mps": 0.542125625933454, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 786, "h3_n": 293, "h3_ordered": 91, "h3_timed": 37, "h3_timing_bias_frames": -2.7472527472527473, "h3_capped_error_with_misses_frames": 9.552901023890785 }, { "epoch": 3, "train_loss": 0.7026066158680205, "weight_norm": 3.366201400756836, "score": 0.6019552336981722, "c_mae_mps": 0.3609216307946435, "c_vector_error_mps": 0.3882043772669392, "c_mean_mps": 0.5501348763117377, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 805, "h3_n": 293, "h3_ordered": 96, "h3_timed": 48, "h3_timing_bias_frames": -2.7291666666666665, "h3_capped_error_with_misses_frames": 9.25938566552901 }, { "epoch": 4, "train_loss": 0.7040611150416922, "weight_norm": 3.711326837539673, "score": 0.6037081289790461, "c_mae_mps": 0.36071774392704414, "c_vector_error_mps": 0.39090967781526037, "c_mean_mps": 0.5555284206304207, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 803, "h3_n": 293, "h3_ordered": 97, "h3_timed": 40, "h3_timing_bias_frames": -2.8556701030927836, "h3_capped_error_with_misses_frames": 9.296928327645052 }, { "epoch": 5, "train_loss": 0.6955734491348267, "weight_norm": 3.91483736038208, "score": 0.6022845573326171, "c_mae_mps": 0.3602238374107815, "c_vector_error_mps": 0.3899536368949144, "c_mean_mps": 0.5642206928251893, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 809, "h3_n": 293, "h3_ordered": 97, "h3_timed": 47, "h3_timing_bias_frames": -3.051546391752577, "h3_capped_error_with_misses_frames": 9.266211604095563 }, { "epoch": 6, "train_loss": 0.700089100827562, "weight_norm": 4.012718677520752, "score": 0.600916568819104, "c_mae_mps": 0.35878971273020216, "c_vector_error_mps": 0.3879771221309652, "c_mean_mps": 0.5568356473577296, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 799, "h3_n": 293, "h3_ordered": 95, "h3_timed": 46, "h3_timing_bias_frames": -2.8, "h3_capped_error_with_misses_frames": 9.276450511945393 }]123version https://git-lfs.github.com/spec/v1oid sha256:d3ea1ab5b75a841634c315377fcbd3606d495c50a33db0d08d4bcb3ea7b21469size 2413123version https://git-lfs.github.com/spec/v1oid sha256:025eb8fb67fb057c2d3209f678f16b7ecd685bc33c9f045a78332b4865e4b9c3size 23811234567891011121314151617181920212223{ "base_sha256": "26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187", "seed": 20261202, "epochs": 6, "variant": "direction_speed", "train_scene_count": 5600, "validation_scene_count": 1400, "train_eventful_scenes": 3275, "validation_eventful_scenes": 786, "train_h2_branches": 4498, "val_h2_branches": 1069, "eligible_h2_full_followup_frames": 1, "zero_adapter_max": { "xyz": 0.0, "vel": 0.0, "impulse": 0.0, "contact_prob": 0.0, "route_logits": 0.0 }, "corrected_parameters": 27, "validation_objective": "0.65 C speed MAE + 0.35 C vector error + 0.025 H3 timing error capped at 12 frames incl missed chains", "simulation": "Both factual and edited autonomous rollouts from the same factual prefix and known command; annotated contact identity/time only index training losses and validation scores. H2 requires complete next frame."}123version https://git-lfs.github.com/spec/v1oid sha256:bea4ec64cd4a6f0952581efd262b88a0845180a5e1cb640529d374a1f3bd44fbsize 23591234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677[ { "strength": 0.0, "score": 0.604632705476781, "c_mae_mps": 0.37077100576919364, "c_vector_error_mps": 0.39487123018970166, "c_mean_mps": 0.5423193962262874, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 806, "h3_n": 293, "h3_ordered": 105, "h3_timed": 51, "h3_timing_bias_frames": -3.4, "h3_capped_error_with_misses_frames": 9.017064846416382 }, { "strength": 0.25, "score": 0.5943957493012436, "c_mae_mps": 0.35913716557134395, "c_vector_error_mps": 0.3855220025568204, "c_mean_mps": 0.5783652547846698, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 803, "h3_n": 293, "h3_ordered": 106, "h3_timed": 44, "h3_timing_bias_frames": -3.349056603773585, "h3_capped_error_with_misses_frames": 9.040955631399317 }, { "strength": 0.5, "score": 0.5902738727172707, "c_mae_mps": 0.3526291980113399, "c_vector_error_mps": 0.3797368497796259, "c_mean_mps": 0.6110219834657169, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 801, "h3_n": 293, "h3_ordered": 103, "h3_timed": 46, "h3_timing_bias_frames": -3.436893203883495, "h3_capped_error_with_misses_frames": 9.126279863481228 }, { "strength": 0.75, "score": 0.5997095541332707, "c_mae_mps": 0.35501057230670596, "c_vector_error_mps": 0.38325827269854873, "c_mean_mps": 0.6453799320018625, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 804, "h3_n": 293, "h3_ordered": 95, "h3_timed": 43, "h3_timing_bias_frames": -3.431578947368421, "h3_capped_error_with_misses_frames": 9.392491467576791 }, { "strength": 1.0, "score": 0.6017454036967633, "c_mae_mps": 0.35442152370474567, "c_vector_error_mps": 0.38358677809442054, "c_mean_mps": 0.6875773142421356, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 795, "h3_n": 293, "h3_ordered": 92, "h3_timed": 42, "h3_timing_bias_frames": -3.6630434782608696, "h3_capped_error_with_misses_frames": 9.484641638225256 }]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{ "selected_variant": "prefix_mass", "strength": 0.5, "checkpoint_relative": "candidates/prefix_mass/best.pt", "base_sha256": "26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187", "checkpoint_sha256": "bea4ec64cd4a6f0952581efd262b88a0845180a5e1cb640529d374a1f3bd44fb", "identity_score": 0.604632705476781, "candidate_scores": { "identity": 0.604632705476781, "values": 0.6045577354895304, "direction_speed": 0.5987337233152157, "prefix_mass": 0.5902738727172707 }, "validation_selected_family": "prefix_mass", "validation_selection_complete": true, "test_used_for_selection": false, "selected_metrics": { "strength": 0.5, "score": 0.5902738727172707, "c_mae_mps": 0.3526291980113399, "c_vector_error_mps": 0.3797368497796259, "c_mean_mps": 0.6110219834657169, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 801, "h3_n": 293, "h3_ordered": 103, "h3_timed": 46, "h3_timing_bias_frames": -3.436893203883495, "h3_capped_error_with_misses_frames": 9.126279863481228 }, "train_scenes": 5600, "train_nodes": 33698, "registered_protocol_sha256": "de26a99ac2c0321fc71e37bb78b1a0150be5d5c531cfc7eb98e30a3ed2aad7a7", "verification": { "samples": 64, "max_momentum_residual": 2.384185791015625e-07, "max_planar_kinetic_energy_gain": -2.211484670639038, "max_log_mass_shift": 0.013877809047698975, "unchanged_log_std": true, "unchanged_other_latents": true, "zero_command_max": { "xyz": 0.0, "vel": 0.0, "impulse": 0.0, "contact_prob": 0.0, "route_logits": 0.0 }, "trainable_base_params": 0, "finite_coefficients": true, "coefficient_count": 10 }}12345678910{ "variant": "prefix_mass", "registered_at": "2026-12-02T14:13:21.164011+00:00", "base_sha256": "26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187", "selection_inputs": "Pre-existing 29/80 native baseline diagnostics motivated candidate. No corrected test outcomes seen; A/B unchanged.", "fit": "One linear ridge lambda 0.01 on per-scene-centered log-mass differences for valid nodes across ALL registered 5600 training scenes. Uniform scene weights. Existing prior mass mean plus additive 1.5*tanh(delta/1.5). Fit analytic linear coefficients to centered target residual; shared coefficients and shift per node. Features: sphere, box, log geometry extents, prefix speed/deceleration, rolling slip, original prior log mass mean and log uncertainty; exclude true mass from inputs. Correction strengths 0.25/0.50/0.75/1.0 evaluated once on the same validation free-rollout objective. No full-test or RGB feedback.", "simulation": "Original frozen checkpoint, unchanged prior uncertainty, contact/geometry and full model weights; inference modification only node prior mass mean before common K draws. Corrected mass used consistently through all substeps and both bodies, no oracle resets.", "validation": "Original 1400 registered validation scenes, two-hit eligible subset; use the same seeds and criterion as A/B for within-C and final cross-family choice. Report identity, A, B, C separately.", "final_comparison": "lowest original composite validation score across frozen identity and all three candidates. No holdout used."}123456789101112131415161718192021222324252627282930313233343536373839404142{ "subset": "All 1069 train-selection validation branches with eligible H2, factual or edited; latent prior mean world only; labels for scoring, no resets", "branches": 1069, "distinct_scenes": 786, "checkpoint_sha256": "bea4ec64cd4a6f0952581efd262b88a0845180a5e1cb640529d374a1f3bd44fb", "sender_fraction": { "A_into_B": { "sim": { "mean": 0.521078317604743, "abs_error": 0.0, "signed_error": 0.0 }, "frozen": { "mean": 0.4550685751259717, "abs_error": 0.12411099217894815, "signed_error": -0.06600974247877123 }, "corrected": { "mean": 0.4849232723492122, "abs_error": 0.11059351838337583, "signed_error": -0.03615504525553076 } }, "B_into_C": { "sim": { "mean": 0.5020593985761851, "abs_error": 0.0, "signed_error": 0.0 }, "frozen": { "mean": 0.49989944303336825, "abs_error": 0.11548452295355979, "signed_error": -0.0021599555428168616 }, "corrected": { "mean": 0.5000706220253034, "abs_error": 0.11465197606439118, "signed_error": -0.0019887765508817667 } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187{ "provenance_created_utc": "2026-12-02T14:19:39.666299+00:00", "timestamp_semantics": "pod_mtime_utc gives the observed sandbox file timestamp, including restored or preserved copies. The supplemental prefix-mass protocol includes the time of its advance registration.", "registered_prefix_mass_at": "2026-12-02T14:13:21.164011+00:00", "variants": { "values": "Bounded logit corrections to normal restitution and tangential friction only after prior non-subject path contacts; no future input, 18 learned coefficients.", "direction_speed": "Restitution, friction and effective impulse normal (up to 15 degrees) on causal path contacts from H1 onward, 27 learned coefficients. Same score, extra training signal on receiver speed at H1/H2.", "prefix_mass": "Analytic ridge, lambda .01, with equal scene weights on 5600 train scenes / 33698 node instances. Simulator log mass labels are used to fit differences of per-scene-centered log masses for training only. Ten input descriptors available from the factual prefix. Corrected prior mean log mass is shared across substeps; original prior uncertainty/other latents held fixed. Tested strengths 0.25/0.50/0.75/1.0 on identical validation random draws, plus identity. Registered after tracing the historical 29 baseline misses. Previously trained A/B subgroup outcomes were communicated to the fitting team after the C protocol was fixed. No corrected holdout metrics entered fitting or selection." }, "frozen_base_checkpoint": "26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187", "original_source_sha256": "dc6e5de84e9123f24a914983bbb2835e6de966c17e0e02f8e8d83440213641ca", "initial_pair_lock": "model_lock.json", "independent_extension_lock": "candidates/prefix_mass/model_lock.json", "validation_decision": "prefix_mass", "files": { "code/build_transfer.py": { "bytes": 5099, "sha256": "bb13a9608345e2dd47e61d793d4f98f95744dd890e8ca83cd277fc544c553880", "pod_mtime_utc": "2026-12-02T14:01:50.481760+00:00" }, "code/train_transfer.py": { "bytes": 14613, "sha256": "0fe7f0a81f8fe9e73f7b1b696af882c0257259d199627830761b7898ff96dcb5", "pod_mtime_utc": "2026-12-02T14:01:50.486418+00:00" }, "code/run_training.py": { "bytes": 1796, "sha256": "f5521098ad1431bd15607d584c914a094a4e1f084d81ddab8661a2252355faba", "pod_mtime_utc": "2026-12-02T13:52:11.472763+00:00" }, "code/transfer_model.py": { "bytes": 1408, "sha256": "a18533471f30471fd26eccc8f1ac39a9e33e1e12f238bc635c0d521de949800b", "pod_mtime_utc": "2026-12-02T14:01:50.482445+00:00" }, "code/transfer_dynamics.py": { "bytes": 60304, "sha256": "b399640247e30e74db90bbe243c371f7c376863d43e9912e7c2d27a79e29263a", "pod_mtime_utc": "2026-12-02T13:52:11.575788+00:00" }, "code/transfer_direction_dynamics.py": { "bytes": 60949, "sha256": "deeb7ba4b8b8b5be041765e0e4058e067b80273021f91dff39c93dde2170b92d", "pod_mtime_utc": "2026-12-02T14:01:50.550219+00:00" }, "code/finalize_transfer.py": { "bytes": 2806, "sha256": "985cbd50c9586b088729a6c35cfd6699a809e9fafdec2f5b6198fccace1a1e8f", "pod_mtime_utc": "2026-12-02T14:01:50.488941+00:00" }, "code/check_transfer.py": { "bytes": 5254, "sha256": "56c65444cda6255ff30d9a486fd897536ab88fb7ba03930892dbd3da09cb56ca", "pod_mtime_utc": "2026-12-02T14:08:39.252630+00:00" }, "code/mass_transfer.py": { "bytes": 2395, "sha256": "756105881a8f6407354df04c04d5ddcd6b359f61dc3702302c4060d1d7406d58", "pod_mtime_utc": "2026-12-02T14:16:11.283063+00:00" }, "code/train_mass_transfer.py": { "bytes": 6492, "sha256": "b818bfb76b1959025a233d16faf4a023c9263d2819cac248d1024a76be17281a", "pod_mtime_utc": "2026-12-02T14:16:11.285113+00:00" }, "code/verify_mass_shares.py": { "bytes": 2403, "sha256": "0a07dc29cc8c8f6710f2abceaa48d9b5c2c10ae9274f9de701bc46e8837ca73a", "pod_mtime_utc": "2026-12-02T14:17:45.656108+00:00" }, "protocol.json": { "bytes": 1557, "sha256": "f355f517ca3c887677f5d8c1607398444798d0e97be564929b599f4e4a81101c", "pod_mtime_utc": "2026-12-02T13:54:27.428186+00:00" }, "direction_registration.json": { "bytes": 756, "sha256": "2361c61ba95830527d7ad81489b18f8630b61d9fdb622da2d269e25f4d6de6a1", "pod_mtime_utc": "2026-12-02T14:01:50.556180+00:00" }, "model_lock.json": { "bytes": 4147, "sha256": "68ed3f9a22761f8883c4a4ff5f10f8ea825f5ea348201b3bfee2f81093320ec6", "pod_mtime_utc": "2026-12-02T14:10:58.998883+00:00" }, "train/best.pt": { "bytes": 2381, "sha256": "ce300934b2534be05320c15941acd737d9984db78870c2fbc0093ee9e52e427a", "pod_mtime_utc": "2026-12-02T14:03:37.878663+00:00" }, "train/finished.json": { "bytes": 4164, "sha256": "ba3f5add5049bc701b37cc6ef286285051401a91e37fa6cac3a91377d01e43d4", "pod_mtime_utc": "2026-12-02T14:10:58.998700+00:00" }, "train/verification.json": { "bytes": 886, "sha256": "00d68345752e4d2d2f1babccd8945c4113111161b067d0a4adb7bdd5c560afa0", "pod_mtime_utc": "2026-12-02T14:10:58.650366+00:00" }, "candidates/values/registration.json": { "bytes": 869, "sha256": "07ce45af51c3ef07c8cf5d16181e5bb48e63d1dcf774d974eee1d1a6157fad99", "pod_mtime_utc": "2026-12-02T13:53:46.098096+00:00" }, "candidates/values/history.json": { "bytes": 3427, "sha256": "4a9457a5fff1034d4c3f5b7ecf3322523650ca7a04b8e5f0ea0f002e5b4159fc", "pod_mtime_utc": "2026-12-02T14:02:40.453483+00:00" }, "candidates/values/finished.json": { "bytes": 1087, "sha256": "1f9e666db7618d4bd1376e04d5a006d780d19467cd8c6a155c0686fae42d85c0", "pod_mtime_utc": "2026-12-02T14:02:40.454870+00:00" }, "candidates/values/identity.pt": { "bytes": 2349, "sha256": "af7f8e84f4ea62f90fd3d65bc217a94f09e5ef320b17ae161875971dae9f575b", "pod_mtime_utc": "2026-12-02T13:53:56.073966+00:00" }, "candidates/values/best.pt": { "bytes": 2253, "sha256": "8e58553528c0778771b0122039bcc34cdf6e607bebdd42420ee0d7291d768ec2", "pod_mtime_utc": "2026-12-02T13:55:22.653315+00:00" }, "candidates/values/last.pt": { "bytes": 2253, "sha256": "ab4830fdb9ce0348e7e066f13d610c923a2c4caf6199a10330c4094a5073b2dd", "pod_mtime_utc": "2026-12-02T14:02:40.453014+00:00" }, "candidates/direction_speed/registration.json": { "bytes": 901, "sha256": "d252f82fe57cc9d6749ef89d0e5ab7c2a347b592b6b7ba4ae47144d1b0ff1ee6", "pod_mtime_utc": "2026-12-02T14:01:55.509472+00:00" }, "candidates/direction_speed/history.json": { "bytes": 3421, "sha256": "506eb93bc3c8e1d1f21886c14b3cf238c28f2b0430172ecf73d7b4a9d36a16e8", "pod_mtime_utc": "2026-12-02T14:10:50.519650+00:00" }, "candidates/direction_speed/finished.json": { "bytes": 1086, "sha256": "954bc4dfa7da95ddaaf664de5a16b04daaf0da66c811c9132dfb84c34b610c61", "pod_mtime_utc": "2026-12-02T14:10:50.521061+00:00" }, "candidates/direction_speed/identity.pt": { "bytes": 2413, "sha256": "d3ea1ab5b75a841634c315377fcbd3606d495c50a33db0d08d4bcb3ea7b21469", "pod_mtime_utc": "2026-12-02T14:02:07.623991+00:00" }, "candidates/direction_speed/best.pt": { "bytes": 2381, "sha256": "ce300934b2534be05320c15941acd737d9984db78870c2fbc0093ee9e52e427a", "pod_mtime_utc": "2026-12-02T14:03:37.878663+00:00" }, "candidates/direction_speed/last.pt": { "bytes": 2381, "sha256": "025eb8fb67fb057c2d3209f678f16b7ecd685bc33c9f045a78332b4865e4b9c3", "pod_mtime_utc": "2026-12-02T14:10:50.519070+00:00" }, "candidates/prefix_mass/protocol.json": { "bytes": 1560, "sha256": "de26a99ac2c0321fc71e37bb78b1a0150be5d5c531cfc7eb98e30a3ed2aad7a7", "pod_mtime_utc": "2026-12-02T14:13:21.164166+00:00" }, "candidates/prefix_mass/history.json": { "bytes": 2155, "sha256": "41ed37c48d020b3a4a366b698c89f6e00e5ac257967c47a125c10ce36df1e41a", "pod_mtime_utc": "2026-12-02T14:16:58.248002+00:00" }, "candidates/prefix_mass/best.pt": { "bytes": 2359, "sha256": "bea4ec64cd4a6f0952581efd262b88a0845180a5e1cb640529d374a1f3bd44fb", "pod_mtime_utc": "2026-12-02T14:16:58.249348+00:00" }, "candidates/prefix_mass/model_lock.json": { "bytes": 1742, "sha256": "aaaefb421ef5cab50a29f15d8c5084897524ffc11da5e34bea4e7f8ed85d8259", "pod_mtime_utc": "2026-12-02T14:16:59.647097+00:00" }, "candidates/prefix_mass/validation_mass_shares.json": { "bytes": 1209, "sha256": "df47a41e67301f1d0ab82772bf75511394330a077543f06373943412a9d84b95", "pod_mtime_utc": "2026-12-02T14:17:48.006167+00:00" } }}123version https://git-lfs.github.com/spec/v1oid sha256:8e58553528c0778771b0122039bcc34cdf6e607bebdd42420ee0d7291d768ec2size 2253123456789101112131415161718192021222324252627282930313233343536{ "selected": 1, "improved_over_identity": true, "checkpoint_sha256": "8e58553528c0778771b0122039bcc34cdf6e607bebdd42420ee0d7291d768ec2", "base_validation": { "score": 0.604632705476781, "c_mae_mps": 0.37077100576919364, "c_vector_error_mps": 0.39487123018970166, "c_mean_mps": 0.5423193962262874, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 806, "h3_n": 293, "h3_ordered": 105, "h3_timed": 51, "h3_timing_bias_frames": -3.4, "h3_capped_error_with_misses_frames": 9.017064846416382 }, "selected_metrics": { "epoch": 1, "train_loss": 0.42636338447002653, "weight_norm": 1.4303864240646362, "score": 0.6045577354895304, "c_mae_mps": 0.36793104282658745, "c_vector_error_mps": 0.3918863909518169, "c_mean_mps": 0.5403502332305063, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 804, "h3_n": 293, "h3_ordered": 102, "h3_timed": 49, "h3_timing_bias_frames": -3.480392156862745, "h3_capped_error_with_misses_frames": 9.129692832764505 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119[ { "epoch": 0, "score": 0.604632705476781, "c_mae_mps": 0.37077100576919364, "c_vector_error_mps": 0.39487123018970166, "c_mean_mps": 0.5423193962262874, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 806, "h3_n": 293, "h3_ordered": 105, "h3_timed": 51, "h3_timing_bias_frames": -3.4, "h3_capped_error_with_misses_frames": 9.017064846416382 }, { "epoch": 1, "train_loss": 0.42636338447002653, "weight_norm": 1.4303864240646362, "score": 0.6045577354895304, "c_mae_mps": 0.36793104282658745, "c_vector_error_mps": 0.3918863909518169, "c_mean_mps": 0.5403502332305063, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 804, "h3_n": 293, "h3_ordered": 102, "h3_timed": 49, "h3_timing_bias_frames": -3.480392156862745, "h3_capped_error_with_misses_frames": 9.129692832764505 }, { "epoch": 2, "train_loss": 0.427582416128605, "weight_norm": 1.5736825466156006, "score": 0.6080641275050139, "c_mae_mps": 0.36931867002151664, "c_vector_error_mps": 0.3929892603936737, "c_mean_mps": 0.5382863555608508, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 803, "h3_n": 293, "h3_ordered": 99, "h3_timed": 49, "h3_timing_bias_frames": -3.525252525252525, "h3_capped_error_with_misses_frames": 9.218430034129693 }, { "epoch": 3, "train_loss": 0.425460769140974, "weight_norm": 1.6273605823516846, "score": 0.6093435449228344, "c_mae_mps": 0.37088384576106376, "c_vector_error_mps": 0.3947131178663663, "c_mean_mps": 0.540467807541194, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 804, "h3_n": 293, "h3_ordered": 100, "h3_timed": 48, "h3_timing_bias_frames": -3.44, "h3_capped_error_with_misses_frames": 9.204778156996587 }, { "epoch": 4, "train_loss": 0.42626624855589357, "weight_norm": 1.6597381830215454, "score": 0.6087215448420052, "c_mae_mps": 0.3695354570166476, "c_vector_error_mps": 0.3932460736215214, "c_mean_mps": 0.5372098634610235, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 797, "h3_n": 293, "h3_ordered": 99, "h3_timed": 49, "h3_timing_bias_frames": -3.525252525252525, "h3_capped_error_with_misses_frames": 9.235494880546074 }, { "epoch": 5, "train_loss": 0.42178390317774833, "weight_norm": 1.6256253719329834, "score": 0.6101273873591515, "c_mae_mps": 0.3702439124601103, "c_vector_error_mps": 0.3939967953993504, "c_mean_mps": 0.5357080875539321, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 800, "h3_n": 293, "h3_ordered": 98, "h3_timed": 49, "h3_timing_bias_frames": -3.642857142857143, "h3_capped_error_with_misses_frames": 9.262798634812286 }, { "epoch": 6, "train_loss": 0.42611455029629647, "weight_norm": 1.554359793663025, "score": 0.6087771624114148, "c_mae_mps": 0.3688091308763492, "c_vector_error_mps": 0.3925598206839965, "c_mean_mps": 0.5366077607801638, "c_true_mps": 0.7540970467599603, "h2_n": 1069, "h2_ordered": 802, "h3_n": 293, "h3_ordered": 98, "h3_timed": 49, "h3_timing_bias_frames": -3.6122448979591835, "h3_capped_error_with_misses_frames": 9.266211604095563 }]123version https://git-lfs.github.com/spec/v1oid sha256:af7f8e84f4ea62f90fd3d65bc217a94f09e5ef320b17ae161875971dae9f575bsize 2349123version https://git-lfs.github.com/spec/v1oid sha256:ab4830fdb9ce0348e7e066f13d610c923a2c4caf6199a10330c4094a5073b2ddsize 225312345678910111213141516171819202122{ "base_sha256": "26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187", "seed": 20261202, "epochs": 6, "train_scene_count": 5600, "validation_scene_count": 1400, "train_eventful_scenes": 3275, "validation_eventful_scenes": 786, "train_h2_branches": 4498, "val_h2_branches": 1069, "eligible_h2_full_followup_frames": 1, "zero_adapter_max": { "xyz": 0.0, "vel": 0.0, "impulse": 0.0, "contact_prob": 0.0, "route_logits": 0.0 }, "corrected_parameters": 18, "validation_objective": "0.65 C speed MAE + 0.35 C vector error + 0.025 H3 timing error capped at 12 frames incl missed chains", "simulation": "Both factual and edited autonomous rollouts from the same factual prefix and known command; annotated contact identity/time only index training losses and validation scores. H2 requires complete next frame."}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586"""Generate the sparse pair-value adapter from the frozen corrected model source."""import argparseimport hashlibfrom pathlib import Path
SOURCE_SHA = "dc6e5de84e9123f24a914983bbb2835e6de966c17e0e02f8e8d83440213641ca"
def generate(source, destination, direction=False): original = Path(source).read_bytes() if hashlib.sha256(original).hexdigest() != SOURCE_SHA: raise ValueError("The frozen propagation source does not match the registered digest") body = original.decode() def replace(mark, replacement): nonlocal body if body.count(mark) != 1: raise ValueError(mark) body = body.replace(mark, replacement) mark = " self.gate_logit = nn.Linear(H, 1)" replace(mark, mark + """ self.transfer_head = nn.Linear(8, 2) nn.init.zeros_(self.transfer_head.weight) nn.init.zeros_(self.transfer_head.bias)""") mark = " gate_uniform: torch.Tensor | None = None," replace(mark, mark + """ reached: torch.Tensor | None = None, subject: torch.Tensor | None = None,""") old = """ e_c = self.cfg.max_restitution * torch.sigmoid(self.rest_head(h_c).squeeze(-1) + rest_bias_c) mu_c = self.cfg.max_friction * torch.sigmoid(self.fric_head(h_c).squeeze(-1))""" replace(old, """ rest_logit = self.rest_head(h_c).squeeze(-1) + rest_bias_c fric_logit = self.fric_head(h_c).squeeze(-1) if reached is not None: i_seen = reached[cb, ck, ci] j_seen = reached[cb, ck, cj] active = (i_seen ^ j_seen) & (ci != subject[cb]) & (cj != subject[cb]) # Sender is identified by a prior forecast contact along the command path. # Signed contrasts are sender-minus-receiver, independently of array ordering. orientation = torch.where(i_seen, 1., -1.) features = torch.stack(( closing_c / 3., torch.abs(slip_c) / (closing_c + .25), orientation * (log_m[cb, ck, ci] - log_m[cb, ck, cj]), orientation * torch.log(st_i[:,3].clamp_min(.01) / st_j[:,3].clamp_min(.01)), torch.where(i_seen, sh_i[:,0], sh_j[:,0]), torch.where(i_seen, sh_j[:,0], sh_i[:,0]), orientation * (spd_i - spd_j) / 3., torch.abs(roll_c) / 3. ), dim=-1).clamp(-4., 4.) shift = 3. * torch.tanh(self.transfer_head(features) / 3.) rest_logit = rest_logit + active * shift[:,0] fric_logit = fric_logit + active * shift[:,1] e_c = self.cfg.max_restitution * torch.sigmoid(rest_logit) mu_c = self.cfg.max_friction * torch.sigmoid(fric_logit)""") mark = " min_cut = int(cut.min().item())" replace(mark, """ reached = F.one_hot(subject, num_classes=N).bool().unsqueeze(1).expand(B, K, N).clone()""" + mark) mark = " sub_dt=sub_dt, tau=tau, stochastic=stochastic_gates, gate_uniform=gate_uniform," replace(mark,mark + """ reached=reached, subject=subject,""") mark = " p_next = p_next + dpos" replace(mark, """ # Update only from forecast directed impulses above the frozen event threshold. # Changes cannot affect this substep's routing or the first impact. new_recipients = (reached.unsqueeze(-1) & (imp_s.detach() > self.cfg.impact_threshold)).any(dim=-2) reached = reached | (new_recipients & active_scene & obj_mask.unsqueeze(1))""" + mark) if direction: replace("active = (i_seen ^ j_seen) & (ci != subject[cb]) & (cj != subject[cb])", "active = i_seen ^ j_seen") replace("self.transfer_head = nn.Linear(8, 2)","self.transfer_head = nn.Linear(8, 3)") replace(" shift = 3. * torch.tanh(self.transfer_head(features) / 3.)", """ raw = self.transfer_head(features) shift = 3. * torch.tanh(raw / 3.) # Preserve reflection equivariance and the original direction on dead-center impacts. angle = active * (math.pi / 12.) * torch.tanh(raw[:,2]) * torch.tanh(slip_c / .25) ca,sa = angle.cos(),angle.sin() still_closing = ca * closing_c + sa * slip_c > 0. ca = torch.where(still_closing,ca,torch.ones_like(ca)) sa = torch.where(still_closing,sa,torch.zeros_like(sa)) closing_c,slip_c = ca * closing_c + sa * slip_c, -sa * closing_c + ca * slip_c out_c,tan_c = ca[:,None] * out_c + sa[:,None] * tan_c, -sa[:,None] * out_c + ca[:,None] * tan_c""") compile(body,str(destination),"exec") Path(destination).write_text(body)
if __name__ == "__main__": p=argparse.ArgumentParser() p.add_argument("source",type=Path) p.add_argument("destination",type=Path) p.add_argument("--direction",action="store_true") a=p.parse_args() generate(a.source,a.destination,a.direction)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Check the trained fix on synthetic impacts and validation prefixes, independent of test scores."""import argparseimport jsonfrom pathlib import Pathimport numpy as npimport torchfrom matched_model import ProbContactAttentionPropagator as Base, ProbContactConfigfrom transfer_model import load_corrected,digestfrom train_transfer import examples,prospective,data_loss
@torch.no_grad()def check(args): d=args.device;fit=load_corrected(args.base,args.adapter,d) old_ck=torch.load(args.base,map_location="cpu",weights_only=False) old=Base(ProbContactConfig(**old_ck["config"])).to(d).eval() old.load_state_dict(old_ck["state_dict"],strict=True) diff=max(float((p-old.state_dict()[k]).abs().max()) for k,p in fit.state_dict().items() if k in old_ck["state_dict"]) assert diff==0. data=torch.load(args.data,map_location="cpu",weights_only=False,mmap=True) val=json.loads(args.splits.read_bytes())["catalog"]["val"] idmap={s:j for j,s in enumerate(data["scene_ids"])} rows=examples(data,val,idmap)[::19][:64] fixed=dict(data) fixed["heading"]=torch.zeros_like(data["heading"]) a=prospective(fit,fixed,rows,4,91312,d)[0] b=prospective(old,fixed,rows,4,91312,d)[0] opposite=rows.copy();opposite[:,1]=1-opposite[:,1] c=prospective(fit,fixed,opposite,4,91312,d)[0] noop={k:float((a[k]-c[k]).abs().max()) for k in a} assert max(noop.values())==0. grid_old=(b["impulse"]>fit.cfg.impact_threshold).cpu().numpy() grid_new=(a["impulse"]>fit.cfg.impact_threshold).cpu().numpy() from eval.contact_chains import chain checks=0;equal_h1=0 max_pre=0. for i,row in enumerate(rows): j=row[0];sub=int(data["subject"][j]);n=int(data["n"][j]);cut=(int(data["step"][j])-1)//10 for k in range(grid_old.shape[1]): old_path=chain(grid_old[i,k,:,:n,:n],sub,cut) new_path=chain(grid_new[i,k,:,:n,:n],sub,cut) p0=old_path[0] if old_path else {"frame":-1,"objects":[]} p1=new_path[0] if new_path else {"frame":-1,"objects":[]} equal_h1+=int(p0==p1) t=p0["frame"] if t<0 and p1["frame"]<0: t=a["xyz"].shape[2] if t>0: err=float((a["xyz"][i,k,:t]-b["xyz"][i,k,:t]).abs().max()) max_pre=max(err,max_pre) checks+=1 if fit.contact_attn.transfer_head.out_features==2: assert max_pre==0. and equal_h1==checks # The same frozen pair geometry and same original positive latent masses see # equal and opposite impulses. Here slot 0 is a separate, inactive launcher. n=3;k=1;B=50 torch.manual_seed(31415) pos=torch.rand(B,k,n,2,device=d)*.03 pos[:,:,0]=8.;pos[:,:,1,0]=0;pos[:,:,2,0]=.485 vel=torch.zeros_like(pos);vel[:,:,1,0]=3.;vel[:,:,1,1]=.8 static=torch.zeros(B,n,8,device=d);static[:,:,0]=1;static[:,:,3:6]=.25 z=torch.randn(B,k,n,fit.cfg.z_dim,device=d);m=z[...,0].clamp(-fit.cfg.log_mass_clip,fit.cfg.log_mass_clip).exp() seen=torch.tensor([True,True,False],device=d).view(1,1,3).expand(B,k,n) dv,*_=fit.contact_attn.step_contacts(pos,vel,torch.zeros_like(pos),torch.zeros(B,k,n,device=d),static, torch.ones(B,n,dtype=torch.bool,device=d),z,torch.zeros(B,k,n,n,device=d),1/72, stochastic=False,reached=seen,subject=torch.zeros(B,dtype=torch.long,device=d)) impulse_change=float((m.unsqueeze(-1)*dv).sum(2).abs().max()) ke_delta=.5*(m.unsqueeze(-1)*((vel+dv).square()-vel.square())).sum((2,3)) assert dv.norm()>0 and impulse_change<2e-5 and ke_delta.max()<=2e-5 with torch.enable_grad(): head=fit.contact_attn.transfer_head;head.requires_grad_(True) out,gt,meta=prospective(fit,data,rows[:16],3,4910,d) val=data_loss(out,gt,meta,fit.cfg.impact_threshold) val.backward() grads=[p.grad for p in head.parameters()] assert all(g is not None and torch.isfinite(g).all() for g in grads) gnorm=float(torch.nn.utils.clip_grad_norm_(head.parameters(),1.,error_if_nonfinite=True)) assert all(torch.isfinite(v).all() for v in fit.contact_attn.transfer_head.parameters()) result=dict(learned_parameters=sum(v.numel() for v in fit.contact_attn.transfer_head.parameters()), finite_weights_and_gradients=True,verification_gradient_norm=gnorm, latent_mass_preserved=True,restitution_range=[0,fit.cfg.max_restitution], friction_range=[0,fit.cfg.max_friction],maximum_direction_adjustment_degrees=15 if head.out_features==3 else 0, base_sha256=digest(args.base),adapter_sha=digest(args.adapter),frozen_parameter_max_diff=diff,no_op_max=noop, first_events_equal=equal_h1,first_event_equality_checked_worlds=checks,positions_before_first_impact_max_diff_m=max_pre, synthetic_two_body_impacts=B,net_impulse_max_abs=impulse_change,max_planar_kinetic_energy_gain=float(ke_delta.max())) args.out.write_text(json.dumps(result,indent=2));print(result)if __name__=='__main__': p=argparse.ArgumentParser() for k in ('base','adapter','data','splits','out'):p.add_argument('--'+k,type=Path,required=True) p.add_argument('--device',default='cuda');check(p.parse_args())1234567891011121314151617181920212223242526272829303132333435363738"""Select a trained correction on validation only and seal the exact parameters before testing."""from pathlib import Pathimport fcntl,hashlib,json,os,shutil,subprocess,sys,timefrom train_transfer import save_jsonfrom transfer_model import digest
def main(): r=Path('/marimo/jais_motion_transfer_20261202');c=r/'code';train=r/'train' base=Path('/marimo/attention_retrain_cutoff_20261201/attention_stochastic/prob_contact_attn_best.pt') with (train/'selection.lock').open('a') as lock: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) if (r/'model_lock.json').exists():return direct=r/'candidates'/'direction_speed';values=r/'candidates'/'values';values.mkdir(parents=True,exist_ok=True) while not (train/'finished.json').is_file() or not (direct/'finished.json').is_file():time.sleep(5) for n in ['finished.json','registration.json','history.json','identity.pt','best.pt','last.pt','resume.pt']: p=train/n if not (values/n).exists():shutil.copy2(p,values/n) cases={'values':values,'direction_speed':direct} results={k:json.loads((p/'finished.json').read_bytes()) for k,p in cases.items()} scores={k:v['selected_metrics']['score'] for k,v in results.items()} choose=min(scores,key=scores.get);src=cases[choose]/'best.pt' assert digest(src)==results[choose]['checkpoint_sha256'] verified=train/'verification.json' subprocess.run([sys.executable,'-u',str(c/'check_transfer.py'),'--base',str(base),'--adapter',str(src), '--data','/tmp/jais_cutoff_registered.pt','--splits',str(r/'splits.json'),'--out',str(verified)],check=True) tmp=train/'selected.tmp';shutil.copy2(src,tmp);tmp.replace(train/'best.pt') bscore=results[choose]['base_validation']['score'] receipt=dict(selected_variant=choose,selected_epoch=results[choose]['selected'], checkpoint_relative='train/best.pt',checkpoint_sha256=digest(train/'best.pt'),base_sha256=digest(base), candidate_scores=scores,identity_score=bscore,improved_over_identity=scores[choose]<bscore, criterion='argmin over trained candidates of unchanged validation-only objective; report identity independently', candidate_metrics=results,verification=json.loads(verified.read_bytes()), validation_selection_complete=True,test_used_for_selection=False) save_json(train/'finished.json',dict(selected=receipt['selected_epoch'],**receipt)) save_json(r/'model_lock.json',receipt) print(json.dumps({k:receipt[k] for k in ('selected_variant','selected_epoch','candidate_scores','identity_score','checkpoint_sha256')},indent=2),flush=True)
if __name__=='__main__':main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Shift the frozen prefix prior's node log-mass means, before sampling the world."""import torchfrom torch import nnfrom matched_model import ProbContactConfig, ProbContactAttentionPropagatorfrom transfer_model import digest
FEATURES = ['sphere','box','log_x_extent','log_y_extent','log_z_extent','last_speed', 'observed_deceleration','roll_slip','base_log_mass_mean','base_log_mass_log_std']
def descriptors(prior,prefix,static,lengths,mu,log_std): measured = prior._node_features(prefix,static,lengths) visible_slots = static[...,:3].abs().sum(-1)>0 features = torch.cat((static[...,:2],static[...,3:6].clamp_min(.01).log(), measured[...,[9,10,12]],mu[...,:1],log_std[...,:1]),dim=-1) return centered(features,visible_slots),visible_slots
def centered(x,valid): mask = valid.to(x.dtype).unsqueeze(-1) return (x-(x*mask).sum(-2,keepdim=True)/mask.sum(-2,keepdim=True).clamp_min(1))*mask
class PrefixMassPrior(nn.Module): def __init__(self,prior,coefficients=None,strength=0.): super().__init__() self.original=prior self.register_buffer('coefficients',torch.zeros(len(FEATURES)) if coefficients is None else coefficients.clone().float()) self.strength=float(strength)
def forward(self,prefix,static,lengths): mu,log_std=self.original(prefix,static,lengths) features,_=descriptors(self.original,prefix,static,lengths,mu,log_std) delta=self.strength*1.5*torch.tanh((features@self.coefficients)/1.5) return torch.cat((mu[...,:1]+delta.unsqueeze(-1),mu[...,1:]),-1),log_std
def load_corrected(base_checkpoint,adapter_checkpoint,device): base=torch.load(base_checkpoint,weights_only=False,map_location='cpu') model=ProbContactAttentionPropagator(ProbContactConfig(**base['config'])) model.load_state_dict(base['state_dict'],strict=True) if adapter_checkpoint is None: model.prior=PrefixMassPrior(model.prior) else: ck=torch.load(adapter_checkpoint,weights_only=False,map_location='cpu') if ck['base_sha256']!=digest(base_checkpoint) or ck['features']!=FEATURES: raise ValueError('The base checkpoint and prefix feature schema must match the sealed fit') model.prior=PrefixMassPrior(model.prior,ck['coefficients'],ck['strength']) return model.requires_grad_(False).to(device).eval()1234567891011121314151617181920212223242526272829303132"""Start or resume a single registered transfer fit after the original state bundle is ready."""import fcntlimport osfrom pathlib import Pathimport subprocessimport sysimport time
def main(): root=Path("/marimo/jais_motion_transfer_20261202") previous=Path("/marimo/attention_retrain_cutoff_20261201") code=Path(__file__).resolve().parent out=root/"train" out.mkdir(parents=True,exist_ok=True) with (out/"run.lock").open("a") as lock: fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) if (out/"finished.json").is_file():return data=Path("/tmp/jais_cutoff_registered.pt") base=previous/"attention_stochastic/prob_contact_attn_best.pt" candidates=[code/"matched_model.py",previous/"eval_code/matched_model.py", previous/"code/matched_model.py",root/"code/matched_model.py"] while not any(p.is_file() for p in candidates):time.sleep(5) src=next(p for p in candidates if p.is_file()) subprocess.run([sys.executable,str(code/"build_transfer.py"),str(src),str(code/"transfer_dynamics.py")],check=True) env={**os.environ,"PYTHONPATH":os.pathsep.join(map(str,[code,src.parent,root/"code",root/"evaluation",previous/"extras", previous/"eval_code","/marimo/prob_contact_attn","/marimo/mass-ratio/repo",os.environ.get("PYTHONPATH","")])), "OMP_NUM_THREADS":"2","OPENBLAS_NUM_THREADS":"1","MKL_NUM_THREADS":"1"} while not all(p.is_file() for p in (data,base,root/"splits.json")):time.sleep(10) subprocess.run([sys.executable,"-u",str(code/"train_transfer.py"),"--data",str(data),"--base",str(base), "--splits",str(root/"splits.json"),"--out",str(out)],env=env,cwd=root,check=True)
if __name__=="__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Fit relative mass with train-only simulator labels, then select the scale using frozen validation."""import argparse,jsonfrom pathlib import Pathimport torchfrom train_transfer import examples,prospective,validation,save_jsonfrom mass_transfer import load_corrected,centered,descriptors,FEATURESfrom transfer_model import digest
def fit(model,data,ids,index,device): gram=torch.zeros(len(FEATURES),len(FEATURES),dtype=torch.float64,device=device) rhs=torch.zeros(len(FEATURES),dtype=torch.float64,device=device) nobjects=0 for start in range(0,len(ids),128): ix=torch.tensor([index[s] for s in ids[start:start+128]]) cut=(data['step'][ix].to(device)-1)//10 prefix=data['state_f'][ix,:int(cut.max())+1].to(device) prefix=prefix.masked_fill((torch.arange(prefix.size(1),device=device)[None,:]>cut[:,None])[:,:,None,None],0.) static=data['static'][ix].to(device) prior=model.prior.original mu,log_std=prior(prefix,static,cut+1) x,valid=descriptors(prior,prefix,static,cut+1,mu,log_std) assert torch.equal(valid.sum(1),data['n'][ix].to(device)) # attrs[...,0] contains log physical mass, read only for these train indices. target=centered(data['attrs'][ix,:,:1].to(device)-mu[...,:1],valid).squeeze(-1) inv_n=1./valid.sum(1).double() x=x.double(); y=target.double() gram+=torch.einsum('bni,bnj,b->ij',x,x,inv_n) rhs+=torch.einsum('bni,bn,b->i',x,y,inv_n) nobjects+=int(valid.sum()) coefficients=torch.linalg.solve(gram/len(ids)+.01*torch.eye(len(FEATURES),dtype=torch.float64,device=device),rhs/len(ids)) assert torch.isfinite(coefficients).all() return coefficients.float(),nobjects
def physical_checks(model,device): g=torch.Generator(device=device).manual_seed(49120) b=64;n=2;k=1 static=torch.zeros(b,n,8,device=device);static[...,0]=1 radii=.15+.2*torch.rand((b,n),generator=g,device=device) static[...,3:6]=radii.unsqueeze(-1) prefix=torch.zeros(b,3,n,13,device=device);prefix[...,3]=1.;prefix[:,:,0,7]=3.;prefix[:,:,0,8]=.5 mu,ls=model.prior(prefix,static,torch.full((b,),3,device=device,dtype=torch.long));oldmu,olds=model.prior.original(prefix,static,torch.full((b,),3,device=device,dtype=torch.long)) assert torch.equal(ls,olds) and torch.equal(oldmu[...,1:],mu[...,1:]) p=torch.zeros(b,k,n,2,device=device);p[:,:,1,0]=(radii.sum(-1)-.005)[:,None] v=torch.zeros_like(p);v[:,:,0,0]=3.;v[:,:,0,1]=.5 z=mu[:,None];m=z[...,0].clamp(-model.cfg.log_mass_clip,model.cfg.log_mass_clip).exp() dv,*_=model.contact_attn.step_contacts(p,v,torch.zeros_like(p),torch.zeros(b,k,n,device=device),static,torch.ones(b,n,dtype=torch.bool,device=device),z,torch.zeros(b,k,n,n,device=device),1/72,stochastic=False) imbalance=float((m[...,None]*dv).sum(2).abs().max()) ke=.5*(m[...,None]*((v+dv).square()-v.square())).sum((2,3)) assert dv.norm()>0 and imbalance<2e-5 and ke.max()<2e-5 return dict(samples=b,max_momentum_residual=imbalance,max_planar_kinetic_energy_gain=float(ke.max()),max_log_mass_shift=float((mu[...,0]-oldmu[...,0]).abs().max()),unchanged_log_std=True,unchanged_other_latents=True)
@torch.no_grad()def main(): p=argparse.ArgumentParser() for key in ('root','base','data'):p.add_argument('--'+key,type=Path,required=True) p.add_argument('--device',default='cuda');a=p.parse_args() d=a.root/'candidates/prefix_mass';lock=d/'model_lock.json' if lock.exists():return assert (d/'protocol.json').is_file();torch.set_num_threads(2) split=json.loads((a.root/'splits.json').read_bytes())['catalog'];tr,va=split['train'],split['val'] assert len(tr)==5600 and len(va)==1400 and not set(tr)&set(va) data=torch.load(a.data,weights_only=False,map_location='cpu',mmap=True);idx={s:i for i,s in enumerate(data['scene_ids'])} base_sha=digest(a.base);assert base_sha=='26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187' model=load_corrected(a.base,None,a.device);weights,num_nodes=fit(model,data,tr,idx,a.device) valrows=examples(data,va,idx); model.prior.coefficients.copy_(weights) print('Fitted using registered train scenes/nodes',len(tr),num_nodes,flush=True) scores=[] for strength in (0.,.25,.50,.75,1.): model.prior.strength=strength stats=validation(model,data,valrows,a.device) scores.append(dict(strength=strength,**stats));save_json(d/'history.json',scores) print('Validation',strength,stats['score'],flush=True) selected=min(scores[1:],key=lambda x:x['score']);model.prior.strength=selected['strength'] ck=dict(variant='prefix_mass',base_sha256=base_sha,features=FEATURES,strength=model.prior.strength, coefficients=weights.cpu(),train_scenes=len(tr),train_nodes=num_nodes,validation=selected) tmp=d/'candidate.tmp';torch.save(ck,tmp);tmp.replace(d/'best.pt');verify=physical_checks(model,a.device) data_invalid=dict(data);data_invalid['heading']=torch.zeros_like(data['heading']);rows=valrows[::47] mode2=rows.copy();mode2[:,1]=1-mode2[:,1] x=prospective(model,data_invalid,rows,4,8174,a.device)[0];y=prospective(model,data_invalid,mode2,4,8174,a.device)[0] paired_noop={k:float((x[k]-y[k]).abs().max()) for k in x}; assert max(paired_noop.values())==0. verify.update(zero_command_max=paired_noop,trainable_base_params=sum(p.numel() for p in model.parameters() if p.requires_grad),finite_coefficients=bool(torch.isfinite(weights).all()),coefficient_count=len(FEATURES)) other=json.loads((a.root/'model_lock.json').read_bytes());assert abs(scores[0]['score']-other['identity_score'])<1e-5 cross=dict(identity=other['identity_score'],**other['candidate_scores'],prefix_mass=selected['score']) record=dict(selected_variant='prefix_mass',strength=selected['strength'],checkpoint_relative='candidates/prefix_mass/best.pt',base_sha256=base_sha,checkpoint_sha256=digest(d/'best.pt'),identity_score=scores[0]['score'],candidate_scores=cross,validation_selected_family=min(cross,key=cross.get),validation_selection_complete=True,test_used_for_selection=False,selected_metrics=selected,train_scenes=len(tr),train_nodes=num_nodes,registered_protocol_sha256=digest(d/'protocol.json'),verification=verify) save_json(lock,record);print('LOCK',json.dumps({k:record[k] for k in ('candidate_scores','validation_selected_family','strength','checkpoint_sha256')}),flush=True)
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273"""Fit the frozen attention model's 18 secondary-contact value coefficients on autonomous rollouts."""import argparseimport hashlibimport jsonimport osfrom collections import Counterfrom pathlib import Path
import numpy as npimport torchfrom torch.nn import functional as Ffrom eval.contact_chains import chainfrom matched_model import ProbContactAttentionPropagator as Base, ProbContactConfigfrom transfer_model import load_corrected, digest
def save_json(file, obj): tmp = file.with_suffix(".tmp") tmp.write_text(json.dumps(obj, indent=2, allow_nan=False)) tmp.replace(file)
def examples(bundle, registered, index): rows = [] for sid in registered: j = index[sid] n, sub = int(bundle["n"][j]), int(bundle["subject"][j]) cut = (int(bundle["step"][j])-1)//10 for edited, tag in [(False,"f"),(True,"cf")]: contacts = bundle["contact_"+tag][j,:,:n,:n].numpy().astype(bool) hits = chain(np.pad(contacts,((1,0),(0,0),(0,0))),sub,cut) if len(hits)<2 or any(len(h["objects"])!=1 for h in hits[:2]): continue b,c = [h["objects"][0] for h in hits[:2]] h1,h2 = [h["frame"] for h in hits[:2]] if h2>=47 or not bundle["present_"+tag][j,h2:h2+2,[b,c]].all(): continue has3 = len(hits)==3 and len(hits[2]["objects"])==1 d,h3 = (hits[2]["objects"][0],hits[2]["frame"]) if has3 else (0,-1) rows.append((j,int(edited),b,c,h1,h2,d,h3)) return np.array(rows,dtype=np.int64)
def prospective(model, bundle, batch, K, seed, device): ix = torch.from_numpy(batch[:,0].copy()) j, edited, b,c,h1,h2,d,h3 = torch.as_tensor(batch,device=device).T n=bundle["n"][ix].to(device) valid=torch.arange(10,device=device)[None]<n[:,None] subject=bundle["subject"][ix].to(device) step=bundle["step"][ix].to(device) cut=(step-1)//10 heading=bundle["heading"][ix].to(device)*edited static=bundle["static"][ix].to(device) prefix=bundle["state_f"][ix,:int(cut.max())+1].to(device) # Every shorter scene has literal zeros beyond its own last observed frame. prefix=prefix.masked_fill((torch.arange(prefix.size(1),device=device)[None,:]>cut[:,None])[:,:,None,None],0.) mu,sd=model.prior(prefix,static,cut+1) torch.manual_seed(seed) z=model.sample_latents(mu,sd,K=K,deterministic_first=True) outputs=model.rollout(prefix,static,valid,subject,heading,step,cut,z,stochastic_gates=True,gate_seed=seed) truth=torch.where(edited[:,None,None,None].bool(),bundle["state_cf"][ix,:,:,:2].to(device), bundle["state_f"][ix,:,:,:2].to(device)) return outputs,truth,(subject,cut,b,c,h1,h2,d,h3)
def pred_path(out, meta, threshold): subject,cut,b,c,h1,h2,d,h3=meta grid=out["impulse"].detach()>threshold B,K,T,N,_=grid.shape batch=torch.arange(B,device=grid.device)[:,None] particle=torch.arange(K,device=grid.device)[None,:] t=torch.arange(T,device=grid.device) n=torch.arange(N,device=grid.device) prev=cut[:,None].expand(B,K) exclude=(n[None,None,:]==subject[:,None,None]) sender=subject[:,None].expand(B,K) chain_ok=torch.ones_like(prev,dtype=torch.bool) records=[] for hop,target in enumerate([b,c,d]): edges=grid[batch,particle,:,sender,:] if hop: edges=edges & ~torch.cat([torch.zeros_like(edges[:,:,:1]),edges[:,:,:-1]],2) edges=edges & ~exclude[:,:,None,:] & (t[None,None,:]>prev[:,:,None]).unsqueeze(-1) seen=edges.any(-1) first=torch.where(seen,t[None,None,:],T).amin(-1) chosen=edges[batch,particle,first.clamp_max(T-1)] chosen_id=chosen.long().argmax(-1) chain_ok=chain_ok & (first<T) & (chosen.sum(-1)==1) & (chosen_id==target[:,None]) records.append((first,chain_ok)) exclude=exclude | (chosen_id[:,:,None]==n[None,None,:]) sender=chosen_id prev=first return records
def vectors(x, t, obj, gap, scale): batch=torch.arange(x.size(0),device=x.device)[:,None] particle=torch.arange(x.size(1),device=x.device)[None,:] t=t.expand(x.shape[:2]).clamp(0,x.size(2)-1-gap) return (x[batch,particle,t+gap,obj[:,None],:2]-x[batch,particle,t,obj[:,None],:2])*scale
def data_loss(out,gt,meta,threshold,variant="values"): _,_,b,c,h1,h2,d,h3=meta xyz=out["xyz"] hops=pred_path(out,meta,threshold) hp,ok=hops[1] a=vectors(xyz,h2[:,None],c,1,24.) target=vectors(gt[:,None],h2[:,None],c,1,24.).expand_as(a) def loss(a,t,mask=None): diff=F.smooth_l1_loss(a,t,reduction="none",beta=.25).sum(-1) if mask is None:return diff.mean() return (diff*mask).sum()/mask.sum().clamp_min(1) loss_true=loss(a,target) loss_aligned=loss(vectors(xyz,hp,c,1,24.),target,ok&(hp<47)) donor=vectors(xyz,hp,b,1,24.) donor_t=vectors(gt[:,None],h2[:,None],b,1,24.).expand_as(donor) travel=vectors(xyz,h2[:,None],c,4,6.) travel_t=vectors(gt[:,None],h2[:,None],c,4,6.).expand_as(travel) dtravel=vectors(xyz,h3[:,None],d,4,6.) dtarget=vectors(gt[:,None],h3[:,None],d,4,6.).expand_as(dtravel) outloss=(.4*loss_true+.4*loss_aligned+.1*loss(donor,donor_t,ok&(hp<47))+ .2*loss(travel,travel_t,(h2[:,None]<=43).expand_as(ok))+ .1*loss(dtravel,dtarget,((h3[:,None]>=0)&(h3[:,None]<=43)).expand_as(ok))) if variant=="direction_speed": def speed_loss(velocity,mask,goal=target): residual=velocity.norm(dim=-1)-goal.norm(dim=-1) val=F.smooth_l1_loss(residual,torch.zeros_like(residual),reduction="none",beta=.25) # Negative errors give the recipient too little outgoing motion. val=val*torch.where(residual<0,1.5,1.) return (val*mask).sum()/mask.sum().clamp_min(1) aligned=vectors(xyz,hp,c,1,24.) matched=ok&(hp<47) power=.5*speed_loss(a,torch.ones_like(ok))+.5*speed_loss(aligned,matched) chain_power=speed_loss(aligned,matched&(h3[:,None]>=0)) first_t,first_ok=hops[0] donor_goal=vectors(gt[:,None],h1[:,None],b,1,24.).expand_as(a) b_at_h1=vectors(xyz,h1[:,None],b,1,24.) b_at_pred=vectors(xyz,first_t,b,1,24.) first_power=.5*speed_loss(b_at_h1,torch.ones_like(ok),donor_goal)+.5*speed_loss( b_at_pred,first_ok&(first_t<47),donor_goal) outloss=.5*outloss+.45*power+.30*chain_power+.30*first_power return outloss
@torch.no_grad()def validation(model,bundle,rows,device,batch_size=96): maes=[]; vector_errors=[]; refs=[]; preds=[]; e3=[]; ordered=[]; timed=[]; h2_ordered=[]; signed=[] from audit_metrics import select_medoid,normalise for start in range(0,len(rows),batch_size): part=rows[start:start+batch_size] out,truth,meta=prospective(model,bundle,part,8,20261202+start,device) points=out["xyz"].cpu().numpy() impacts=(out["impulse"]>model.cfg.impact_threshold).cpu().numpy() gt=truth.cpu().numpy() for i,row in enumerate(part): j,edit,b,c,t1,t2,d,t3=row n,sub=int(bundle["n"][j]),int(bundle["subject"][j]) cut=(int(bundle["step"][j])-1)//10 paths=[normalise(chain(g[:,:n,:n],sub,cut)) for g in impacts[i]] k=select_medoid(paths,points[i],n,cut) chain_pred=paths[k] dv0=(gt[i,t2+1,c]-gt[i,t2,c])*24. dv=(points[i,k,t2+1,c,:2]-points[i,k,t2,c,:2])*24. v0=float(np.linalg.norm(dv0)); v=float(np.linalg.norm(dv)) maes.append(abs(v-v0)); refs.append(v0);preds.append(v);vector_errors.append(float(np.linalg.norm(dv-dv0))) ids=[p["objects"] for p in chain_pred] h2_ordered.append(ids[:2]==[[b],[c]]) if t3<0:continue hit=ids[:3]==[[b],[c],[d]] errs=[abs(chain_pred[h]["frame"]-target) for h,target in enumerate([t1,t2,t3])] if hit else [] ordered.append(hit);timed.append(hit and max(errs)<=2) e3.append(min(errs[-1],12) if hit else 12) if hit:signed.append(int(chain_pred[2]["frame"]-t3)) def avg(v):return float(np.mean(v)) if v else 0. # Fixed validation objective: physical velocity at true H2 and miss-penalized third-hit timing. score=.65*avg(maes)+.35*avg(vector_errors)+.025*avg(e3) return dict(score=score,c_mae_mps=avg(maes),c_vector_error_mps=avg(vector_errors),c_mean_mps=avg(preds), c_true_mps=avg(refs),h2_n=len(maes),h2_ordered=int(sum(h2_ordered)),h3_n=len(e3), h3_ordered=int(sum(ordered)),h3_timed=int(sum(timed)),h3_timing_bias_frames=avg(signed), h3_capped_error_with_misses_frames=avg(e3))
def main(): p=argparse.ArgumentParser() for k in ["data","splits","base","out"]:p.add_argument("--"+k,type=Path,required=True) p.add_argument("--epochs",type=int,default=6);p.add_argument("--batch",type=int,default=96) p.add_argument("--variant",choices=["values","direction_speed"],default="values") p.add_argument("--device",default="cuda");a=p.parse_args() a.out.mkdir(parents=True,exist_ok=True) if (a.out/"finished.json").exists(): print("Using finished validation-selected fit",flush=True) return torch.set_num_threads(2);torch.manual_seed(20261202);np_rng=np.random.default_rng(20261202) data=torch.load(a.data,weights_only=False,map_location="cpu",mmap=True) index={str(k):i for i,k in enumerate(data["scene_ids"])} splits=json.loads(a.splits.read_bytes())["catalog"] train_ids,val_ids=splits["train"],splits["val"] assert len(set(train_ids))==5600 and len(set(val_ids))==1400 and not set(train_ids)&set(val_ids) base_sha=digest(a.base) assert base_sha=="26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187" tr=examples(data,train_ids,index);va=examples(data,val_ids,index) print("Eligible train/val branch records",len(tr),len(va),flush=True) model=load_corrected(a.base,None,a.device,variant=a.variant);head=model.contact_attn.transfer_head def save_weight(name,ep,status): f=a.out/name;tmp=f.with_suffix(".tmp") torch.save(dict(head={k:v.detach().cpu() for k,v in head.state_dict().items()}, base_sha256=base_sha,variant=a.variant,epoch=ep,metrics=status),tmp);tmp.replace(f) original=torch.load(a.base,map_location="cpu",weights_only=False) reference=Base(ProbContactConfig(**original["config"])).to(a.device).eval() reference.load_state_dict(original["state_dict"],strict=True) with torch.no_grad(): args=(data,tr[:8],3,54392,a.device) x=prospective(model,*args)[0];y=prospective(reference,*args)[0] err={name:float((x[name]-y[name]).abs().max()) for name in x} if max(err.values())>1e-6:raise ValueError(f"Zero-adapter initialization differs from frozen model: {err}") del reference,x,y save_json(a.out/"registration.json",dict(base_sha256=base_sha,seed=20261202,epochs=a.epochs, variant=a.variant,train_scene_count=len(train_ids),validation_scene_count=len(val_ids), train_eventful_scenes=int(np.unique(tr[:,0]).size),validation_eventful_scenes=int(np.unique(va[:,0]).size), train_h2_branches=len(tr),val_h2_branches=len(va),eligible_h2_full_followup_frames=1,zero_adapter_max=err, corrected_parameters=sum(v.numel() for v in head.parameters()), validation_objective="0.65 C speed MAE + 0.35 C vector error + 0.025 H3 timing error capped at 12 frames incl missed chains", simulation="Both factual and edited autonomous rollouts from the same factual prefix and known command; annotated contact identity/time only index training losses and validation scores. H2 requires complete next frame.")) head.requires_grad_(True) opt=torch.optim.AdamW(head.parameters(),lr=.035,weight_decay=.04) resume=a.out/"resume.pt" if resume.exists(): ck=torch.load(resume,map_location="cpu",weights_only=False) if ck["base_sha256"]!=base_sha or ck["epochs"]!=a.epochs or ck["batch"]!=a.batch: raise ValueError("Resume parameters differ from registered fit") head.load_state_dict(ck["head"]);opt.load_state_dict(ck["optimizer"]) np_rng.bit_generator.state=ck["permutation_rng"] history=ck["history"];base_val=history[0];best=ck["best"];start_epoch=ck["epoch"]+1 print("Resuming at epoch",start_epoch,flush=True) else: base_val=validation(model,data,va,a.device) print("Validation baseline",base_val,flush=True) save_weight("identity.pt",0,base_val) history=[dict(epoch=0,**base_val)] save_json(a.out/"history.json",history) best=float("inf");start_epoch=1 for ep in range(start_epoch,a.epochs+1): order=np_rng.permutation(len(tr));losses=[] for start in range(0,len(tr),a.batch): part=tr[order[start:start+a.batch]] out,truth,meta=prospective(model,data,part,3,20261202+ep*100003+start,a.device) value=data_loss(out,truth,meta,model.cfg.impact_threshold,a.variant) reg=.003*sum(w.square().mean() for w in head.parameters()) opt.zero_grad(set_to_none=True);loss=value+reg if not torch.isfinite(loss):raise FloatingPointError("Non-finite contact transfer training loss") loss.backward() torch.nn.utils.clip_grad_norm_(head.parameters(),1.,error_if_nonfinite=True) opt.step() losses.append(float(value.detach())) val=validation(model,data,va,a.device) history.append(dict(epoch=ep,train_loss=float(np.mean(losses)),weight_norm=float(head.weight.detach().norm()),**val)) if val["score"]<best: save_weight("best.pt",ep,val);best=val["score"] save_weight("last.pt",ep,val) save_json(a.out/"history.json",history) tmp=a.out/"resume.tmp" torch.save(dict(base_sha256=base_sha,epochs=a.epochs,batch=a.batch,epoch=ep,head=head.state_dict(), optimizer=opt.state_dict(),permutation_rng=np_rng.bit_generator.state, history=history,best=best),tmp) tmp.replace(resume) print("Epoch",ep,history[-1],flush=True) winner=min(history[1:],key=lambda x:x["score"]) save_json(a.out/"finished.json",dict(selected=winner["epoch"],improved_over_identity=best<base_val["score"], checkpoint_sha256=digest(a.out/"best.pt"),base_validation=base_val,selected_metrics=winner))
if __name__=="__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238"""Probabilistic Contact-Attention Propagator (Prob-ContactAttn).
A 100% learned, genuinely probabilistic neural contact-graph dynamics model thatdirectly extends JAIS Contact Attention (`contact_attention.py`, `contact_recipient.py`)while resolving soft-attention mean-hedging and physical-plausibility instabilities:
1. Per-node latent physical belief Z = (log_mass, log_drag, rest_logit, compliance): - Prospective prior p_theta(Z | prefix, static) for prefix-only forecasting. - Amortized spatio-temporal graph attention posterior q_psi(Z | trajectory, static) trained purely from trajectory kinematics (zero ground-truth mass labels needed) and reusable for Pearl counterfactual abduction when factual trajectories exist.2. Stochastic hard-edge Contact Attention with explicit null-contact key: - Straight-Through Gumbel-Sigmoid contact gates replace soft-attention impulse dilution (`w_ij * impulse`), eliminating half-strength ghost collisions.3. Exact Newton-3rd-law & energy-passive symmetric attention value operator: - Predicts symmetric pairwise normal + dissipative tangential impulses J_ij in latent mass space (dm_i dv_i + dm_j dv_j == 0 identically; dKE <= 0), making super-elastic velocity explosions (>10 m/s) mathematically impossible.4. Strictly proper distributional training via Paired Counterfactual Energy Score (CRPS) + contact-onset Brier/BCE + variational KL with shared latent Z across factual and counterfactual branches."""
from __future__ import annotations
import mathfrom dataclasses import dataclassfrom typing import Any
import torchimport torch.nn as nnimport torch.nn.functional as F
DT = 1.0 / 24.0EPS = 1e-6MAX_N = 10
@dataclassclass ProbContactConfig: arm: str = "attention_stochastic" z_dim: int = 6 # [log_mass, log_drag, rest_logit, 3 compliance dims] hidden_dim: int = 64 substeps: int = 3 # 72 Hz internal integration per 24 Hz frame max_restitution: float = 0.92 max_friction: float = 0.60 contact_margin: float = 0.045 # m, candidate neighborhood for grazing stochasticity depen_beta: float = 0.28 # mild Baumgarte positional separation factor depen_slop: float = 0.002 # m allowed numerical slop before separation impact_threshold: float = 0.07 # m/s directed contact onset threshold (matches JAIS) log_mass_clip: float = 2.0 # exp([-2, 2]) ~= [0.14, 7.4] relative mass range log_drag_clip: float = 1.1
def yaw_from_quat_torch(q: torch.Tensor) -> torch.Tensor: """Convert wxyz quaternions [..., 4] to planar yaw [...].""" w, x, y, z = q.unbind(dim=-1) return torch.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z))
def roll_velocity_torch(state: torch.Tensor, radius: torch.Tensor) -> torch.Tensor: """Radius-scaled horizontal rolling velocity from angular velocity [..., 13] -> [..., 2].""" # Matches intervention_contact.roll_velocity: r * [omega_y, -omega_x] return radius.unsqueeze(-1) * torch.stack([state[..., 11], -state[..., 10]], dim=-1)
def _safe_norm(v: torch.Tensor, eps: float = EPS) -> tuple[torch.Tensor, torch.Tensor]: length = torch.sqrt(torch.sum(v * v, dim=-1).clamp_min(eps * eps)) unit = v / length.unsqueeze(-1) # Zero out direction when norm is negligible is_zero = (torch.sum(v * v, dim=-1) < (eps * eps)).unsqueeze(-1) unit = torch.where(is_zero, torch.zeros_like(unit), unit) length = torch.where(is_zero.squeeze(-1), torch.zeros_like(length), length) return unit, length
def _box_query_torch( point: torch.Tensor, size: torch.Tensor, yaw: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """Differentiable signed distance and outward normal from oriented box to point.
Args: point: [..., 2] vector from box center to query point. size: [..., 2] box half-extents (rx, ry). yaw: [...] box yaw angle in radians. """ c = torch.cos(yaw) s = torch.sin(yaw) px, py = point[..., 0], point[..., 1] lx = c * px + s * py ly = -s * px + c * py local = torch.stack([lx, ly], dim=-1) edge = torch.abs(local) - size outside = F.relu(edge) * torch.sign(local) out_dir, out_dist = _safe_norm(outside)
sgn_x = torch.where(lx >= 0.0, torch.ones_like(lx), -torch.ones_like(lx)) sgn_y = torch.where(ly >= 0.0, torch.ones_like(ly), -torch.ones_like(ly)) inside_dir = torch.where( (edge[..., 0] > edge[..., 1]).unsqueeze(-1), torch.stack([sgn_x, torch.zeros_like(lx)], dim=-1), torch.stack([torch.zeros_like(ly), sgn_y], dim=-1), ) outward_local = torch.where((out_dist > EPS).unsqueeze(-1), out_dir, inside_dir) wx = c * outward_local[..., 0] - s * outward_local[..., 1] wy = s * outward_local[..., 0] + c * outward_local[..., 1] world_normal = torch.stack([wx, wy], dim=-1) signed_dist = out_dist + torch.minimum(edge.amax(dim=-1), torch.zeros_like(out_dist)) return signed_dist, world_normal
def pair_geometry_batched( pos: torch.Tensor, vel: torch.Tensor, yaw: torch.Tensor, static: torch.Tensor, dt: float,) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Exact differentiable planar contact geometry for all ordered pairs (i, j).
Normal `outward` points FROM sender j TO receiver i. Closing speed `closing = (v_j - v_i) . outward` is positive when approaching.
Args: pos: [..., N, 2] vel: [..., N, 2] yaw: [..., N] static: [..., N, 8] (broadcastable to pos[..., :1]) Returns: gap: [..., N, N] signed surface gap (m) outward: [..., N, N, 2] unit normal from j -> i tangent: [..., N, N, 2] unit tangent closing: [..., N, N] normal closing speed (m/s) slip: [..., N, N] tangential relative velocity (v_j - v_i) . tangent (m/s) radial_dot: [..., N, N] alignment between center-to-center ray and contact normal """ # delta[..., i, j, :] = pos_i - pos_j (points from j -> i) delta = pos.unsqueeze(-2) - pos.unsqueeze(-3) rel_v = vel.unsqueeze(-3) - vel.unsqueeze(-2) # v_j - v_i radial, dist = _safe_norm(delta)
ri = static[..., :, 3].unsqueeze(-1) # [..., N, 1] rj = static[..., :, 3].unsqueeze(-2) # [..., 1, N] is_box_i = (static[..., :, 1] > 0.5).unsqueeze(-1) is_box_j = (static[..., :, 1] > 0.5).unsqueeze(-2)
gap = dist - ri - rj outward = radial
# Case 1: j is box, i is sphere/cyl j_only = is_box_j & (~is_box_i) if j_only.any(): size_j = static[..., :, 3:5].unsqueeze(-3).expand(*delta.shape[:-1], 2) yaw_j = yaw.unsqueeze(-2).expand(delta.shape[:-1]) gd, nd = _box_query_torch(delta, size_j, yaw_j) gap = torch.where(j_only, gd - ri, gap) outward = torch.where(j_only.unsqueeze(-1), nd, outward)
# Case 2: i is box, j is sphere/cyl i_only = is_box_i & (~is_box_j) if i_only.any(): size_i = static[..., :, 3:5].unsqueeze(-2).expand(*delta.shape[:-1], 2) yaw_i = yaw.unsqueeze(-1).expand(delta.shape[:-1]) gd, nd = _box_query_torch(-delta, size_i, yaw_i) gap = torch.where(i_only, gd - rj, gap) outward = torch.where(i_only.unsqueeze(-1), -nd, outward)
# Case 3: both i and j are boxes (exact 4-axis SAT) both_box = is_box_i & is_box_j if both_box.any(): yi = yaw.unsqueeze(-1).expand(delta.shape[:-1]) yj = yaw.unsqueeze(-2).expand(delta.shape[:-1]) angles = torch.stack([yi, yi + 0.5 * math.pi, yj, yj + 0.5 * math.pi], dim=-1) # [..., N, N, 4] axes = torch.stack([torch.cos(angles), torch.sin(angles)], dim=-1) # [..., N, N, 4, 2] proj = (delta.unsqueeze(-2) * axes).sum(dim=-1) # [..., N, N, 4]
si_xy = static[..., :, 3:5].unsqueeze(-2).expand(*delta.shape[:-1], 2) sj_xy = static[..., :, 3:5].unsqueeze(-3).expand(*delta.shape[:-1], 2) ri_rect = ( torch.abs(torch.cos(angles - yi.unsqueeze(-1))) * si_xy[..., 0:1] + torch.abs(torch.sin(angles - yi.unsqueeze(-1))) * si_xy[..., 1:2] ) rj_rect = ( torch.abs(torch.cos(angles - yj.unsqueeze(-1))) * sj_xy[..., 0:1] + torch.abs(torch.sin(angles - yj.unsqueeze(-1))) * sj_xy[..., 1:2] ) gaps_sat = torch.abs(proj) - ri_rect - rj_rect max_gap, ax_idx = gaps_sat.max(dim=-1) sgn_proj = torch.where(proj >= 0.0, torch.ones_like(proj), -torch.ones_like(proj)) signed_axes = axes * sgn_proj.unsqueeze(-1) # [..., N, N, 4, 2] gather_idx = ax_idx.unsqueeze(-1).unsqueeze(-1).expand(*delta.shape[:-1], 1, 2) sat_n = torch.gather(signed_axes, dim=-2, index=gather_idx).squeeze(-2) gap = torch.where(both_box, max_gap, gap) outward = torch.where(both_box.unsqueeze(-1), sat_n, outward)
tangent = torch.stack([-outward[..., 1], outward[..., 0]], dim=-1) closing = (rel_v * outward).sum(dim=-1) slip = (rel_v * tangent).sum(dim=-1) radial_dot = (radial * outward).sum(dim=-1) return gap, outward, tangent, closing, slip, radial_dot
class PrefixLatentPrior(nn.Module): """Prospective prior p_theta(Z | prefix, static) over per-node latent physics.
Uses strictly pre-intervention observations (static geometry + prefix speeds & deceleration). Never sees simulator masses or post-intervention states. """
def __init__(self, z_dim: int = 6, hidden: int = 64): super().__init__() # Per-node input: static[8] + log_vol[1] + [speed, decel, decel_valid, roll_slip, is_moving, pref_len] = 15 self.net = nn.Sequential( nn.Linear(15, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU(), ) self.mu = nn.Linear(hidden, z_dim) self.log_std = nn.Linear(hidden, z_dim) # Initialize with reasonable physics prior spread (log_mass std ~= 0.55) nn.init.zeros_(self.mu.weight) nn.init.zeros_(self.mu.bias) nn.init.zeros_(self.log_std.weight) nn.init.constant_(self.log_std.bias, -0.6)
@staticmethod def _node_features(prefix: torch.Tensor, static: torch.Tensor, prefix_len: torch.Tensor) -> torch.Tensor: """Build [B, N, 15] prefix-only node descriptors.""" B, T, N, _ = prefix.shape # Estimate observed deceleration strictly from prefix frames vel = prefix[:, :, :, 7:9] # [B, T, N, 2] speed_seq = torch.linalg.norm(vel, dim=-1) # [B, T, N] rows = torch.arange(B, device=prefix.device) last = prefix_len - 1 speed_last = speed_seq[rows, last] # [B, N] if T > 1: rates = -(speed_seq[:, 1:] - speed_seq[:, :-1]) / DT # [B, T-1, N] # Mask valid prefix frames up to prefix_len t_idx = torch.arange(T - 1, device=prefix.device).view(1, T - 1, 1) valid_t = t_idx < (prefix_len.view(B, 1, 1) - 1) valid_f = valid_t.float() decel = (rates * valid_f).sum(dim=1) / valid_f.sum(dim=1).clamp_min(1.0) decel_valid = ((prefix_len.view(B, 1) > 1) & (speed_last > 0.25) & (decel >= 0.0) & (decel < 10.0)).float() decel = torch.where(decel_valid > 0.5, decel, torch.zeros_like(decel)) else: decel = torch.zeros_like(speed_last) decel_valid = torch.zeros_like(speed_last)
roll_v = roll_velocity_torch(prefix[rows, last], static[:, :, 3]) roll_slip = torch.linalg.norm(vel[rows, last] - roll_v, dim=-1) is_moving = (speed_last > 0.15).float() vol = (static[:, :, 3] * static[:, :, 4] * static[:, :, 5]).clamp_min(1e-5) log_vol = torch.log(vol) plen_norm = prefix_len.float().view(B, 1).expand(B, N) / 10.0
feat = torch.cat( [ static, log_vol.unsqueeze(-1), (speed_last / 4.0).unsqueeze(-1), (decel / 4.0).unsqueeze(-1), decel_valid.unsqueeze(-1), (roll_slip / 4.0).unsqueeze(-1), is_moving.unsqueeze(-1), plen_norm.unsqueeze(-1), ], dim=-1, ) return torch.clamp(feat, -10.0, 10.0)
def forward( self, prefix: torch.Tensor, static: torch.Tensor, prefix_len: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: feat = self._node_features(prefix, static, prefix_len) h = self.net(feat) mu = self.mu(h) log_std = self.log_std(h).clamp(-2.5, 0.5) return mu, log_std
class TrajectoryLatentPosterior(nn.Module): """Amortized spatio-temporal graph attention posterior q_psi(Z | trajectory, static).
Infers per-node latent physics (mass ratio, floor drag, restitution) purely from observed kinematics & pairwise momentum exchange — NEVER uses ground-truth mass labels. Used during training (variational ELBO/Energy-Score) and optionally for Pearl abduction when a factual trajectory is available. """
def __init__(self, z_dim: int = 6, hidden: int = 64): super().__init__() # Node temporal encoder over [pos_xy(2), vel_xy(2), acc_xy(2), speed(1), static(8)] = 15 self.node_in = nn.Sequential(nn.Linear(15, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU()) # Edge encoder at each frame for pairwise interaction cues # [rel_pos(2), rel_vel(2), dist/scale(1), closing(1), dvel_i_dot_n(1), dvel_j_dot_n(1)] = 8 self.edge_enc = nn.Sequential(nn.Linear(8, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU()) self.edge_gate = nn.Linear(hidden, 1) # Temporal attention pooling per node self.time_attn = nn.Linear(hidden * 2, 1) self.out_mlp = nn.Sequential(nn.Linear(hidden * 2, hidden), nn.SiLU()) self.mu = nn.Linear(hidden, z_dim) self.log_std = nn.Linear(hidden, z_dim) nn.init.zeros_(self.mu.weight) nn.init.zeros_(self.mu.bias) nn.init.zeros_(self.log_std.weight) nn.init.constant_(self.log_std.bias, -1.2)
def forward( self, traj: torch.Tensor, static: torch.Tensor, obj_mask: torch.Tensor, present: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: """Encode full or partial trajectory [B, T, N, 13] -> posterior (mu, log_std) [B, N, z_dim].""" B, T, N, _ = traj.shape pos = traj[:, :, :, :2] vel = traj[:, :, :, 7:9] acc = torch.zeros_like(vel) if T > 1: acc[:, 1:] = (vel[:, 1:] - vel[:, :-1]) / DT speed = torch.linalg.norm(vel, dim=-1, keepdim=True) static_exp = static.unsqueeze(1).expand(B, T, N, 8) node_x = torch.cat([pos / 4.0, vel / 4.0, acc / 20.0, speed / 4.0, static_exp], dim=-1) node_x = torch.clamp(node_x, -10.0, 10.0) h_node = self.node_in(node_x) # [B, T, N, H]
# Pairwise spatial graph attention encoding momentum exchange across collisions delta = pos.unsqueeze(-2) - pos.unsqueeze(-3) # [B, T, N, N, 2] radial, dist = _safe_norm(delta) scale = (static[:, :, 3].unsqueeze(-1) + static[:, :, 3].unsqueeze(-2)).unsqueeze(1).clamp_min(0.05) rel_v = vel.unsqueeze(-3) - vel.unsqueeze(-2) closing = (rel_v * radial).sum(dim=-1, keepdim=True) acc_i_n = (acc.unsqueeze(-2) * radial).sum(dim=-1, keepdim=True) acc_j_n = (acc.unsqueeze(-3) * radial).sum(dim=-1, keepdim=True) edge_x = torch.cat( [ delta / 4.0, rel_v / 4.0, (dist / scale).unsqueeze(-1), closing / 4.0, acc_i_n / 20.0, acc_j_n / 20.0, ], dim=-1, ) edge_x = torch.clamp(edge_x, -10.0, 10.0) h_edge = self.edge_enc(edge_x) # [B, T, N, N, H] # Mask invalid edges and distant non-interacting pairs gently via proximity bias eye = torch.eye(N, device=traj.device, dtype=torch.bool).view(1, 1, N, N) pair_valid = obj_mask.unsqueeze(1).unsqueeze(3) & obj_mask.unsqueeze(1).unsqueeze(2) & (~eye) prox_bias = -2.0 * F.relu(dist / scale - 1.4) e_logits = self.edge_gate(h_edge).squeeze(-1) + prox_bias e_logits = e_logits.masked_fill(~pair_valid, -1e4) # Explicit null-interaction key (logit 0) so free-flight frames stay clean e_odds = torch.exp(e_logits.clamp(-12.0, 12.0)) * pair_valid.float() e_w = e_odds / (e_odds.sum(dim=-1, keepdim=True) + 1.0) h_inter = (e_w.unsqueeze(-1) * h_edge).sum(dim=-2) # [B, T, N, H]
h_cat = torch.cat([h_node, h_inter], dim=-1) # [B, T, N, 2H] t_logits = self.time_attn(h_cat).squeeze(-1) # [B, T, N] if present is not None: t_logits = t_logits.masked_fill(~present, -1e4) t_w = torch.softmax(t_logits, dim=1) # [B, T, N] pooled = (t_w.unsqueeze(-1) * h_cat).sum(dim=1) # [B, N, 2H] out = self.out_mlp(pooled) mu = self.mu(out) log_std = self.log_std(out).clamp(-2.8, 0.2) return mu, log_std
class ProbFirstHitSelector(nn.Module): """Batched probabilistic global first-recipient attention (extends `Selector`).
Computes calibrated categorical probabilities over {0..N-1, null} for the first post-intervention contact of the commanded subject. Supplies a geometric prior logit to local contact attention without hard-suppressing multi-hop events. """
def __init__(self, hidden: int = 48): super().__init__() # Matches contact_recipient.make_features (25 dims) self.encode = nn.Sequential(nn.Linear(25, hidden), nn.SiLU(), nn.Linear(hidden, 32), nn.SiLU()) self.edge = nn.Linear(32, 1) self.none = nn.Sequential(nn.Linear(64, 16), nn.SiLU(), nn.Linear(16, 1))
@staticmethod def build_features( pos: torch.Tensor, vel: torch.Tensor, static: torch.Tensor, subject: torch.Tensor, heading: torch.Tensor, step: torch.Tensor, cut: torch.Tensor, ) -> torch.Tensor: """Build [B, K, N, 25] candidate features matching JAIS contact_recipient.""" B, K, N, _ = pos.shape device = pos.device pre_dt = ((step - 1 - 10 * cut).float() / 240.0).view(B, 1, 1, 1) pos_e = pos + pre_dt * vel
# Gather subject pose & velocity: [B, K, 1, 2] sub_idx = subject.view(B, 1, 1, 1).expand(B, K, 1, 2) sub_pos = torch.gather(pos_e, 2, sub_idx) sub_vel = torch.gather(vel, 2, sub_idx) c = torch.cos(heading).view(B, 1, 1) s = torch.sin(heading).view(B, 1, 1) vx, vy = sub_vel[..., 0], sub_vel[..., 1] edit_vel = torch.stack([c * vx - s * vy, s * vx + c * vy], dim=-1) # [B, K, 1, 2]
delta = pos_e - sub_pos # [B, K, N, 2] rel_v = edit_vel - vel speed = torch.linalg.norm(rel_v, dim=-1).clamp_min(1e-3) direction = rel_v / speed.unsqueeze(-1)
sub_static_idx = subject.view(B, 1, 1).expand(B, 1, 8) sub_static = torch.gather(static, 1, sub_static_idx).unsqueeze(1).expand(B, K, N, 8) st_exp = static.unsqueeze(1).expand(B, K, N, 8) radius = (st_exp[..., 7] + sub_static[..., 7]).clamp_min(0.05)
along = (delta * direction).sum(dim=-1) cross = direction[..., 0] * delta[..., 1] - direction[..., 1] * delta[..., 0] norm = torch.linalg.norm(delta, dim=-1) flight = ((47.0 - cut.float()) / 24.0 - (step - 1 - 10 * cut).float() / 240.0).view(B, 1, 1).expand(B, K, N) ray_t = torch.clamp(along / speed, min=torch.zeros_like(along), max=flight) miss = torch.linalg.norm(delta - ray_t.unsqueeze(-1) * rel_v, dim=-1)
sin_h = torch.sin(heading).view(B, 1, 1).expand(B, K, N) cos_h = torch.cos(heading).view(B, 1, 1).expand(B, K, N)
feats = torch.cat( [ (along / 4.0).unsqueeze(-1), (cross / 4.0).unsqueeze(-1), (torch.abs(cross) / radius).unsqueeze(-1), (along / radius).unsqueeze(-1), (norm / 4.0).unsqueeze(-1), (speed / 5.0).unsqueeze(-1), ray_t.unsqueeze(-1), (miss / radius).unsqueeze(-1), radius.unsqueeze(-1), ((delta * rel_v).sum(dim=-1) / (norm + 0.01) / 5.0).unsqueeze(-1), flight.unsqueeze(-1), sin_h.unsqueeze(-1), cos_h.unsqueeze(-1), sub_static[..., :6], st_exp[..., :6], ], dim=-1, ) return torch.clamp(feats, -30.0, 30.0)
def in_scores(self, pos, vel, static, obj_mask, subject, heading, step, cut): x = self.build_features(pos, vel, static, subject, heading, step, cut) n = x.shape[-2] valid = obj_mask[:, None, :, None] & obj_mask[:, None, None, :] valid = valid & ~torch.eye(n, dtype=torch.bool, device=x.device)[None, None] # For each receiver accumulate learned messages from the other objects. messages = self.encode(x.unsqueeze(-2) - x.unsqueeze(-3)) nodes = (messages * valid.unsqueeze(-1)).sum(dim=-2) scores = self.edge(nodes).squeeze(-1) cand = obj_mask.clone() cand[torch.arange(len(subject), device=subject.device), subject] = False scores = scores.masked_fill(~cand[:, None], -1e4) mean = (nodes * cand[:, None, :, None]).sum(dim=2) / cand.sum(1).clamp_min(1)[:, None, None] mx = nodes.masked_fill(~cand[:, None, :, None], -1e4).amax(dim=2) null = self.none(torch.cat([mean, mx], dim=-1)) return torch.cat([scores, null], dim=-1)
def forward( self, pos: torch.Tensor, vel: torch.Tensor, static: torch.Tensor, obj_mask: torch.Tensor, subject: torch.Tensor, heading: torch.Tensor, step: torch.Tensor, cut: torch.Tensor, ) -> torch.Tensor: """Return logits [B, K, N+1] over candidate recipients and explicit null outcome.""" B, K, N, _ = pos.shape x = self.build_features(pos, vel, static, subject, heading, step, cut) emb = self.encode(x) # [B, K, N, 32] cand_mask = obj_mask.unsqueeze(1).expand(B, K, N).clone() b_idx = torch.arange(B, device=pos.device) cand_mask[b_idx, :, subject] = False
scores = self.edge(emb).squeeze(-1).masked_fill(~cand_mask, -1e4) mask_f = cand_mask.float().unsqueeze(-1) mean_emb = (emb * mask_f).sum(dim=2) / mask_f.sum(dim=2).clamp_min(1.0) max_emb = emb.masked_fill(~cand_mask.unsqueeze(-1), -1e4).amax(dim=2) none_score = self.none(torch.cat([mean_emb, max_emb], dim=-1)) # [B, K, 1] return torch.cat([scores, none_score], dim=-1)
class StochasticContactAttention(nn.Module): """Physics-consistent stochastic hard-edge Contact Attention operator.
Key properties: 1. Explicit null-contact key (logit 0) competing with learned contact logit s_ij. 2. Straight-Through Gumbel-Sigmoid stochastic hard gate g_ij in {0, 1} in the grazing/near-contact zone (eliminates soft-attention velocity dilution). 3. Exact symmetric Newton-3rd-law impulse J_ij = J_n n + J_t t in latent mass space with e_ij in (0, max_restitution) and dissipative tangential impulse, guaranteeing: - sum_i m_i dv_i == 0 identically (momentum conservation) - dKE <= 0 at every pairwise collision (energy passivity, zero blow-ups) """
def __init__(self, cfg: ProbContactConfig): super().__init__() self.cfg = cfg # Symmetric pair features: # [gap/s, swept_gap/s, ttc, closing/4, |slip|/4, speed_sum/4, speed_diff/4, # radial_dot, roll_closing/4, roll_slip/4, # shape_i+shape_j(3), shape_i*shape_j(3), size_sum(2), size_diff(2), # z_sum(z_dim), |z_diff|(z_dim), route_prob(1)] = 21 + 2*z_dim in_dim = 21 + 2 * cfg.z_dim H = cfg.hidden_dim self.edge_mlp = nn.Sequential( nn.Linear(in_dim, H), nn.SiLU(), nn.Linear(H, H), nn.SiLU(), ) # Contact gate logit vs explicit null key (0) self.gate_logit = nn.Linear(H, 1) self.transfer_head = nn.Linear(8, 3) nn.init.zeros_(self.transfer_head.weight) nn.init.zeros_(self.transfer_head.bias) # Symmetric value head: effective restitution logit, tangential friction logit, # and sphere rolling-coupling fraction self.rest_head = nn.Linear(H, 1) self.fric_head = nn.Linear(H, 1) self.roll_couple_head = nn.Linear(H, 1)
# Conservative physical initialization: low restitution (~0.15), moderate friction (~0.25) nn.init.constant_(self.rest_head.bias, -1.7) nn.init.constant_(self.fric_head.bias, -0.3) nn.init.constant_(self.roll_couple_head.bias, -1.0) nn.init.constant_(self.gate_logit.bias, 0.5)
def step_contacts( self, pos: torch.Tensor, vel: torch.Tensor, roll: torch.Tensor, yaw: torch.Tensor, static: torch.Tensor, obj_mask: torch.Tensor, z: torch.Tensor, route_pair_prob: torch.Tensor, sub_dt: float, tau: float = 0.5, stochastic: bool = True, gate_uniform: torch.Tensor | None = None, reached: torch.Tensor | None = None, subject: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Compute one sub-step of momentum-conserving stochastic contact attention.
Returns: dv: [B, K, N, 2] velocity impulse droll: [B, K, N, 2] rolling-velocity impulse dpos: [B, K, N, 2] mild Baumgarte depenetration shift impulse_mag: [B, K, N, N] directed impact dv magnitude on receiver i from sender j gate_prob: [B, K, N, N] contact probability for auxiliary contact Brier/BCE loss """ B, K, N, _ = pos.shape device = pos.device st_exp = static.unsqueeze(1).expand(B, K, N, 8) gap, outward, tangent, closing, slip, radial_dot = pair_geometry_batched( pos, vel, yaw, st_exp, sub_dt ) # Undirected pair mask i < j (valid objects only) tri = torch.triu(torch.ones(N, N, device=device, dtype=torch.bool), diagonal=1) pair_valid = obj_mask.unsqueeze(1).unsqueeze(3) & obj_mask.unsqueeze(1).unsqueeze(2) & tri.view(1, 1, N, N)
scale = (st_exp[..., :, 3].unsqueeze(-1) + st_exp[..., :, 3].unsqueeze(-2)).clamp_min(0.05) swept_reach = F.relu(closing) * sub_dt + self.cfg.contact_margin cand = pair_valid & (closing > 0.02) & (gap < swept_reach) & (gap > -0.8 * scale)
# Latent positive masses: m_i = exp(clip(z_i[..., 0])) log_m = z[..., 0].clamp(-self.cfg.log_mass_clip, self.cfg.log_mass_clip) mass = torch.exp(log_m) # [B, K, N] inv_m = 1.0 / mass inv_m_i = inv_m.unsqueeze(-1) # [B, K, N, 1] inv_m_j = inv_m.unsqueeze(-2) # [B, K, 1, N] m_red = 1.0 / (inv_m_i + inv_m_j).clamp_min(EPS) # [B, K, N, N]
dv = torch.zeros_like(vel) droll = torch.zeros_like(roll) dpos = torch.zeros_like(pos) impulse_mag = torch.zeros(B, K, N, N, device=device, dtype=vel.dtype) gate_prob = torch.zeros(B, K, N, N, device=device, dtype=vel.dtype)
if cand.any(): # Evaluate edge MLP STRICTLY on active sparse candidates (~0.5% of B*K*N*N) # -> mathematically identical, ~100x faster & ~20x lower VRAM! cb, ck, ci, cj = torch.nonzero(cand, as_tuple=True) n_cand = cb.numel()
vel_i = vel[cb, ck, ci] # [M, 2] vel_j = vel[cb, ck, cj] roll_i = roll[cb, ck, ci] roll_j = roll[cb, ck, cj] out_c = outward[cb, ck, ci, cj] tan_c = tangent[cb, ck, ci, cj] gap_c = gap[cb, ck, ci, cj] scale_c = scale[cb, ck, ci, cj] closing_c = closing[cb, ck, ci, cj] slip_c = slip[cb, ck, ci, cj] rdot_c = radial_dot[cb, ck, ci, cj] rp_c = route_pair_prob[cb, ck, ci, cj]
spd_i = torch.linalg.norm(vel_i, dim=-1) spd_j = torch.linalg.norm(vel_j, dim=-1) rel_roll_c = roll_j - roll_i roll_c = (rel_roll_c * out_c).sum(dim=-1) roll_s = torch.abs((rel_roll_c * tan_c).sum(dim=-1))
st_i = static[cb, ci] # [M, 8] st_j = static[cb, cj] sh_i, sh_j = st_i[:, :3], st_j[:, :3] sz_i = torch.stack([st_i[:, 3], st_i[:, 5]], dim=-1) sz_j = torch.stack([st_j[:, 3], st_j[:, 5]], dim=-1) z_i = z[cb, ck, ci] z_j = z[cb, ck, cj]
swept_gap_c = gap_c - F.relu(closing_c) * sub_dt ttc_c = torch.clamp(gap_c / (F.relu(closing_c) * sub_dt).clamp_min(0.002), -2.0, 4.0) feat_c = torch.cat( [ (gap_c / scale_c).unsqueeze(-1), (swept_gap_c / scale_c).unsqueeze(-1), ttc_c.unsqueeze(-1), (closing_c / 4.0).unsqueeze(-1), (torch.abs(slip_c) / 4.0).unsqueeze(-1), ((spd_i + spd_j) / 4.0).unsqueeze(-1), (torch.abs(spd_i - spd_j) / 4.0).unsqueeze(-1), rdot_c.unsqueeze(-1), (roll_c / 4.0).unsqueeze(-1), (roll_s / 4.0).unsqueeze(-1), sh_i + sh_j, sh_i * sh_j, sz_i + sz_j, torch.abs(sz_i - sz_j), z_i + z_j, torch.abs(z_i - z_j), rp_c.unsqueeze(-1), ], dim=-1, ) feat_c = torch.clamp(feat_c, -10.0, 10.0) h_c = self.edge_mlp(feat_c) # [M, H]
geom_logit = -swept_gap_c / 0.012 logits_c = self.gate_logit(h_c).squeeze(-1) + geom_logit p_hit_c = torch.sigmoid(logits_c)
# Scatter symmetric gate_prob gate_prob = gate_prob.clone() gate_prob.index_put_((cb, ck, ci, cj), p_hit_c) gate_prob.index_put_((cb, ck, cj, ci), p_hit_c)
must_hit_c = swept_gap_c <= -0.002 if stochastic: u = (torch.rand_like(logits_c) if gate_uniform is None else gate_uniform[cb % gate_uniform.shape[0], ck, ci, cj]).clamp(1e-5, 1.0 - 1e-5) gumbel_noise = torch.log(u) - torch.log1p(-u) soft_g = torch.sigmoid((logits_c + gumbel_noise) / max(tau, 0.1)) hard_g = (soft_g > 0.5).float() gate_c = hard_g - soft_g.detach() + soft_g else: hard_g = (p_hit_c > 0.5).float() gate_c = hard_g - p_hit_c.detach() + p_hit_c gate_c = torch.where(must_hit_c, torch.ones_like(gate_c), gate_c)
rest_bias_c = 0.5 * (z_i[:, 2] + z_j[:, 2]) rest_logit = self.rest_head(h_c).squeeze(-1) + rest_bias_c fric_logit = self.fric_head(h_c).squeeze(-1) if reached is not None: i_seen = reached[cb, ck, ci] j_seen = reached[cb, ck, cj] active = i_seen ^ j_seen # Sender is identified by a prior forecast contact along the command path. # Signed contrasts are sender-minus-receiver, independently of array ordering. orientation = torch.where(i_seen, 1., -1.) features = torch.stack(( closing_c / 3., torch.abs(slip_c) / (closing_c + .25), orientation * (log_m[cb, ck, ci] - log_m[cb, ck, cj]), orientation * torch.log(st_i[:,3].clamp_min(.01) / st_j[:,3].clamp_min(.01)), torch.where(i_seen, sh_i[:,0], sh_j[:,0]), torch.where(i_seen, sh_j[:,0], sh_i[:,0]), orientation * (spd_i - spd_j) / 3., torch.abs(roll_c) / 3. ), dim=-1).clamp(-4., 4.) raw = self.transfer_head(features) shift = 3. * torch.tanh(raw / 3.) # Preserve reflection equivariance and the original direction on dead-center impacts. angle = active * (math.pi / 12.) * torch.tanh(raw[:,2]) * torch.tanh(slip_c / .25) ca,sa = angle.cos(),angle.sin() still_closing = ca * closing_c + sa * slip_c > 0. ca = torch.where(still_closing,ca,torch.ones_like(ca)) sa = torch.where(still_closing,sa,torch.zeros_like(sa)) closing_c,slip_c = ca * closing_c + sa * slip_c, -sa * closing_c + ca * slip_c out_c,tan_c = ca[:,None] * out_c + sa[:,None] * tan_c, -sa[:,None] * out_c + ca[:,None] * tan_c rest_logit = rest_logit + active * shift[:,0] fric_logit = fric_logit + active * shift[:,1] e_c = self.cfg.max_restitution * torch.sigmoid(rest_logit) mu_c = self.cfg.max_friction * torch.sigmoid(fric_logit) roll_cw = 0.4 * torch.sigmoid(self.roll_couple_head(h_c).squeeze(-1))
inv_mi_c = inv_m[cb, ck, ci] inv_mj_c = inv_m[cb, ck, cj] m_red_c = 1.0 / (inv_mi_c + inv_mj_c).clamp_min(EPS)
# Exact Newton's 3rd Law & Energy-Passive Pairwise Impulse j_n = (1.0 + e_c) * m_red_c * F.relu(closing_c) max_jt = torch.minimum(mu_c * j_n, 0.85 * m_red_c * torch.abs(slip_c)) j_t = torch.sign(slip_c) * max_jt j_vec = gate_c.unsqueeze(-1) * (j_n.unsqueeze(-1) * out_c + j_t.unsqueeze(-1) * tan_c)
# Scatter symmetric +J/m_i and -J/m_j (EXACT momentum conservation!) dv = torch.zeros_like(vel) dv.index_put_((cb, ck, ci), j_vec * inv_mi_c.unsqueeze(-1), accumulate=True) dv.index_put_((cb, ck, cj), -j_vec * inv_mj_c.unsqueeze(-1), accumulate=True)
is_sph_i = (st_i[:, 0] > 0.5).float().unsqueeze(-1) is_sph_j = (st_j[:, 0] > 0.5).float().unsqueeze(-1) r_imp = (gate_c * roll_cw * j_t).unsqueeze(-1) * tan_c droll = torch.zeros_like(roll) droll.index_put_((cb, ck, ci), is_sph_i * r_imp * inv_mi_c.unsqueeze(-1), accumulate=True) droll.index_put_((cb, ck, cj), -is_sph_j * r_imp * inv_mj_c.unsqueeze(-1), accumulate=True)
# Directed impact magnitude: impulse_mag[b, k, sender, receiver] j_norm = torch.linalg.norm(j_vec, dim=-1) impulse_mag = impulse_mag.clone() impulse_mag.index_put_((cb, ck, cj, ci), j_norm * inv_mi_c, accumulate=True) impulse_mag.index_put_((cb, ck, ci, cj), j_norm * inv_mj_c, accumulate=True)
# Mild Baumgarte positional depenetration (mass-weighted, symmetric -> zero COM shift!) pen = F.relu(-gap - self.cfg.depen_slop) * pair_valid.float() if (pen > 0.0).any(): corr_mag = self.cfg.depen_beta * pen * m_red # proportional to m_red corr_vec = corr_mag.unsqueeze(-1) * outward dpos_i = (corr_vec * inv_m_i.unsqueeze(-1)).sum(dim=-2) dpos_j = (-corr_vec * inv_m_j.unsqueeze(-1)).sum(dim=-3) dpos = dpos_i + dpos_j
return dv, droll, dpos, impulse_mag, gate_prob
class ProbContactAttentionPropagator(nn.Module): """End-to-end Differentiable Probabilistic Contact-Attention Propagator.
Combines: - PrefixLatentPrior p_theta(Z | prefix, static) - TrajectoryLatentPosterior q_psi(Z | trajectory, static) - ProbFirstHitSelector (global intervention attention with null key) - StochasticContactAttention (local hard-edge momentum-conserving attention) - Latent-modulated passive free-motion integrator (sphere rolling-to-sliding + box/cyl drag) """
def __init__(self, cfg: ProbContactConfig | None = None): super().__init__() self.cfg = cfg or ProbContactConfig() self.prior = PrefixLatentPrior(self.cfg.z_dim, self.cfg.hidden_dim) self.posterior = TrajectoryLatentPosterior(self.cfg.z_dim, self.cfg.hidden_dim) self.selector = ProbFirstHitSelector(hidden=48) self.contact_attn = StochasticContactAttention(self.cfg)
# Learnable base floor drag parameters (initialized from physical JAIS scales, strictly positive!) # Per-shape [sphere, box, cyl]: base sliding drag & rolling drag (m/s^2) self.log_slide_drag = nn.Parameter(torch.log(torch.tensor([2.0, 2.0, 1.8], dtype=torch.float32))) self.log_roll_drag = nn.Parameter(torch.log(torch.tensor([0.16, 2.0, 1.8], dtype=torch.float32))) # Sphere inertia ratio (2.5 for solid sphere sliding-to-rolling coupling) self.log_inertia_ratio = nn.Parameter(torch.log(torch.tensor(2.3, dtype=torch.float32)))
def _free_step( self, pos: torch.Tensor, vel: torch.Tensor, roll: torch.Tensor, static: torch.Tensor, z: torch.Tensor, dt: float, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Strictly passive free-motion step with analytical sphere sliding-to-rolling transition.""" B, K, N, _ = vel.shape sh_weights = static[:, :, :3].unsqueeze(1).expand(B, K, N, 3) drag_scale = torch.exp(z[..., 1].clamp(-self.cfg.log_drag_clip, self.cfg.log_drag_clip)) slide_base = (sh_weights * torch.exp(self.log_slide_drag).view(1, 1, 1, 3)).sum(dim=-1) * drag_scale roll_base = (sh_weights * torch.exp(self.log_roll_drag).view(1, 1, 1, 3)).sum(dim=-1) * drag_scale
# Non-sphere (box/cylinder) passive linear drag u_v, spd = _safe_norm(vel) next_spd = F.relu(spd - slide_base * dt) next_v_drag = u_v * next_spd.unsqueeze(-1) disp_drag = 0.5 * (vel + next_v_drag) * dt
# Sphere analytical sliding-to-rolling transition (strictly passive) is_sph = (static[:, :, 0] > 0.5).unsqueeze(1).expand(B, K, N) ratio = torch.exp(self.log_inertia_ratio).clamp(0.5, 5.0) u_slip, slip = _safe_norm(vel - roll) until_roll = slip / ((1.0 + ratio) * slide_base.clamp_min(0.05)) t_slip = torch.minimum(torch.full_like(until_roll, dt), until_roll) slide_dv = (slide_base * t_slip).unsqueeze(-1) * u_slip mid_v = vel - slide_dv t_post = F.relu(dt - t_slip) u_mid, mid_spd = _safe_norm(mid_v) end_v_sph = u_mid * F.relu(mid_spd - roll_base * t_post).unsqueeze(-1) disp_sph = 0.5 * (vel + mid_v) * t_slip.unsqueeze(-1) + 0.5 * (mid_v + end_v_sph) * t_post.unsqueeze(-1) next_roll_sph = torch.where((until_roll <= dt).unsqueeze(-1), end_v_sph, roll + ratio * slide_dv)
next_v = torch.where(is_sph.unsqueeze(-1), end_v_sph, next_v_drag) next_roll = torch.where(is_sph.unsqueeze(-1), next_roll_sph, next_v_drag) next_pos = pos + torch.where(is_sph.unsqueeze(-1), disp_sph, disp_drag) return next_pos, next_v, next_roll
def sample_latents( self, mu: torch.Tensor, log_std: torch.Tensor, K: int, deterministic_first: bool = False, ) -> torch.Tensor: """Reparameterized draw [B, K, N, z_dim].""" B, N, D = mu.shape std = torch.exp(log_std) eps = torch.randn(B, K, N, D, device=mu.device, dtype=mu.dtype) if deterministic_first and K > 0: eps[:, 0] = 0.0 return mu.unsqueeze(1) + std.unsqueeze(1) * eps
def rollout( self, prefix: torch.Tensor, static: torch.Tensor, obj_mask: torch.Tensor, subject: torch.Tensor, heading: torch.Tensor, step: torch.Tensor, cut: torch.Tensor, z: torch.Tensor, *, init_state_samples: torch.Tensor | None = None, horizon: int = 48, apply_edit: bool = True, tau: float = 0.5, stochastic_gates: bool = True, gate_seed: int | None = None, paired_batch: bool = False, ) -> dict[str, torch.Tensor]: """Differentiable batched rollout for B scenes x K worlds over `horizon` frames.
Args: prefix: [B, T_max, N, 13] observed prefix states (valid up to `cut[b]`). static: [B, N, 8] obj_mask: [B, N] bool subject: [B] int heading: [B] float (radians) step: [B] int (240 Hz intervention tick) cut: [B] int = (step - 1) // 10 z: [B, K, N, z_dim] sampled latent physics init_state_samples: optional [B, K, N, 13] sampled initial cutoff state from ProbabilisticHybridGraphEncoder (zero teleportation: frame `cut` is anchored smoothly to `init_state_samples`). """ B, T_pre, N, _ = prefix.shape K = z.shape[1] device = prefix.device stochastic_gates = stochastic_gates and self.cfg.arm != "attention_deterministic" if paired_batch and B % 2: raise ValueError("Paired training requires equal on and off batches") if gate_seed is None: gate_seed = int(torch.randint(0, 2**31 - 1, (), device="cpu")) gate_rng = torch.Generator(device=device).manual_seed(gate_seed) gate_rows = B // 2 if paired_batch else B
# Gather exact state at frame cut[b] for each scene in batch cut_idx = cut.view(B, 1, 1, 1).expand(B, 1, N, 13) state_cut = torch.gather(prefix, 1, cut_idx).squeeze(1) # [B, N, 13] if init_state_samples is None: s0 = state_cut.unsqueeze(1).expand(B, K, N, 13).clone() else: s0 = init_state_samples.clone()
pos = s0[..., :2].clone() z_height = s0[..., 2].clone() vel = s0[..., 7:9].clone() yaw = yaw_from_quat_torch(s0[..., 3:7]) omega_z = s0[..., 12].clone() # Initialize sphere rolling velocity cleanly (bounded to avoid visual spin blowup) roll_raw = roll_velocity_torch(s0, static[:, :, 3].unsqueeze(1)) roll_spd = torch.linalg.norm(roll_raw, dim=-1, keepdim=True) vel_spd = torch.linalg.norm(vel, dim=-1, keepdim=True) roll = torch.where(roll_spd > (2.0 * vel_spd + 0.5), vel, roll_raw)
# Global probabilistic first-hit attention prior eff_heading = heading if apply_edit else torch.zeros_like(heading) if self.cfg.arm == "in_stochastic": route_logits = self.selector.in_scores(pos, vel, static, obj_mask, subject, eff_heading, step, cut) route_probs = torch.sigmoid(route_logits) else: route_logits = self.selector(pos, vel, static, obj_mask, subject, eff_heading, step, cut) route_probs = torch.softmax(route_logits, dim=-1) # [B, K, N+1]
# Build symmetric pair-prior matrix for (subject, b) — fully vectorized over B b_idx = torch.arange(B, device=device) route_pair = torch.zeros(B, K, N, N, device=device, dtype=pos.dtype) p_cand = route_probs[:, :, :N] # [B, K, N] route_pair[b_idx, :, subject, :] = p_cand route_pair[b_idx, :, :, subject] = p_cand
# Pre-allocate output tensors out_xyz = torch.zeros(B, K, horizon, N, 3, device=device, dtype=pos.dtype) out_vel = torch.zeros(B, K, horizon, N, 2, device=device, dtype=pos.dtype) out_imp = torch.zeros(B, K, horizon, N, N, device=device, dtype=pos.dtype) out_gate = torch.zeros(B, K, horizon, N, N, device=device, dtype=pos.dtype)
# Fill observed prefix verbatim up to cut (and anchor cut to s0 so cut->cut+1 has ZERO jump!) for t in range(min(T_pre, horizon)): t_le_cut = (t <= cut).view(B, 1, 1, 1) out_xyz[:, :, t] = torch.where(t_le_cut, prefix[:, t, :, :3].unsqueeze(1), out_xyz[:, :, t]) out_vel[:, :, t] = torch.where(t_le_cut, prefix[:, t, :, 7:9].unsqueeze(1), out_vel[:, :, t]) out_xyz[b_idx, :, cut, :, :2] = pos out_xyz[b_idx, :, cut, :, 2] = z_height out_vel[b_idx, :, cut] = vel
substeps = self.cfg.substeps sub_dt = DT / substeps # Exact pre-edit duration inside the first post-cut frame (cut -> cut+1) before_sec = ((step - 1 - 10 * cut).float() / 240.0).clamp(0.0, DT) # [B] cos_h = torch.cos(eff_heading).view(B, 1) sin_h = torch.sin(eff_heading).view(B, 1) sub_one_hot = F.one_hot(subject, num_classes=N).to(dtype=torch.bool).view(B, 1, N, 1)
reached = F.one_hot(subject, num_classes=N).bool().unsqueeze(1).expand(B, K, N).clone() min_cut = int(cut.min().item()) for t in range(min_cut + 1, horizon): active_scene = (t > cut).view(B, 1, 1) # [B, 1, 1] is_edit_frame = (t == (cut + 1)) # [B] frame_imp = torch.zeros(B, K, N, N, device=device, dtype=pos.dtype) frame_gate = torch.zeros(B, K, N, N, device=device, dtype=pos.dtype)
# Decay global first-hit prior cleanly after edit window (~10 frames) age_after_cut = (t - cut).float().clamp_min(0.0).view(B, 1, 1, 1) rp_t = route_pair * torch.exp(-age_after_cut / 10.0)
for s_idx in range(substeps): # Apply heading intervention at exact sub-step matching `before_sec` (vectorized!) sub_start = s_idx * sub_dt sub_end = (s_idx + 1) * sub_dt apply_here = is_edit_frame & (before_sec >= sub_start - 1e-7) & ( (before_sec < sub_end - 1e-7) | (s_idx == substeps - 1) ) if apply_edit and apply_here.any(): edit_mask = (apply_here & (eff_heading != 0)).view(B, 1, 1, 1) & sub_one_hot # [B, 1, N, 1] vx = vel[..., 0] vy = vel[..., 1] nvx = cos_h.unsqueeze(-1) * vx - sin_h.unsqueeze(-1) * vy nvy = sin_h.unsqueeze(-1) * vx + cos_h.unsqueeze(-1) * vy nv = torch.stack([nvx, nvy], dim=-1) nv_u, nv_spd = _safe_norm(nv) r_spd = torch.linalg.norm(roll, dim=-1, keepdim=True) nr = torch.where((nv_spd > 1e-5).unsqueeze(-1), nv_u * r_spd, roll) vel = torch.where(edit_mask, nv, vel) roll = torch.where(edit_mask, nr, roll)
# 1. Passive free motion p_next, v_next, r_next = self._free_step(pos, vel, roll, static, z, sub_dt) yaw_next = yaw + omega_z * sub_dt
# 2. Stochastic hard-edge momentum-conserving contact attention # Draw by fixed scene, world, frame/substep and pair slot, independently of candidate counts. gate_uniform = torch.rand((gate_rows, K, N, N), generator=gate_rng, device=device) if stochastic_gates else None dv, droll, dpos, imp_s, gate_s = self.contact_attn.step_contacts( p_next, v_next, r_next, yaw_next, static, obj_mask, z, rp_t, sub_dt=sub_dt, tau=tau, stochastic=stochastic_gates, gate_uniform=gate_uniform, reached=reached, subject=subject, ) # Update only from forecast directed impulses above the frozen event threshold. # Changes cannot affect this substep's routing or the first impact. new_recipients = (reached.unsqueeze(-1) & (imp_s.detach() > self.cfg.impact_threshold)).any(dim=-2) reached = reached | (new_recipients & active_scene & obj_mask.unsqueeze(1)) p_next = p_next + dpos v_next = v_next + dv r_next = r_next + droll
# Keep padded/inactive scenes untouched upd_mask = active_scene.unsqueeze(-1) & obj_mask.view(B, 1, N, 1) pos = torch.where(upd_mask, p_next, pos) vel = torch.where(upd_mask, v_next, vel) roll = torch.where(upd_mask, r_next, roll) yaw = torch.where(active_scene & obj_mask.view(B, 1, N), yaw_next, yaw)
frame_imp = torch.maximum(frame_imp, imp_s) frame_gate = torch.maximum(frame_gate, gate_s)
# Store frame t for active scenes store_mask = active_scene.unsqueeze(-1) # [B, 1, 1, 1] xyz_t = torch.cat([pos, z_height.unsqueeze(-1)], dim=-1) out_xyz[:, :, t] = torch.where(store_mask, xyz_t, out_xyz[:, :, t]) out_vel[:, :, t] = torch.where(store_mask, vel, out_vel[:, :, t]) out_imp[:, :, t] = torch.where(active_scene.unsqueeze(-1), frame_imp, out_imp[:, :, t]) out_gate[:, :, t] = torch.where(active_scene.unsqueeze(-1), frame_gate, out_gate[:, :, t])
return { "xyz": out_xyz, # [B, K, 48, N, 3] "vel": out_vel, # [B, K, 48, N, 2] "impulse": out_imp, # [B, K, 48, N, N] (sender -> receiver dv m/s) "contact_prob": out_gate, # [B, K, 48, N, N] "route_logits": route_logits, # [B, K, N+1] }
def trajectory_energy_score( pred_xyz: torch.Tensor, true_xyz: torch.Tensor, mask: torch.Tensor, beta: float = 1.0,) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Strictly proper Energy Score (multivariate CRPS) over K stochastic trajectories.
ES(P, y) = E_P[||X - y||^beta] - 0.5 * E_{P,P}[||X - X'||^beta]
Uniquely minimized iff P == P_true (Gneiting & Raftery, 2007). Actively prevents MSE conditional-mean velocity shrinkage via the diversity term!
Args: pred_xyz: [B, K, T, N, D] true_xyz: [B, T, N, D] mask: [B, T, N] bool (post-cut present objects) """ B, K, T, N, D = pred_xyz.shape m = mask.float() # [B, T, N] denom = m.sum(dim=(1, 2)).clamp_min(1.0) # [B]
# Term 1: accuracy E[||X_k - y||] normalized per valid object-frame diff_gt = pred_xyz - true_xyz.unsqueeze(1) # [B, K, T, N, D] dist_gt = torch.sqrt((diff_gt * diff_gt).sum(dim=-1) + 1e-8) # [B, K, T, N] per_k_err = (dist_gt * m.unsqueeze(1)).sum(dim=(2, 3)) / denom.unsqueeze(1) # [B, K] if beta != 1.0: per_k_err = per_k_err.pow(beta) acc_term = per_k_err.mean(dim=1) # [B]
# Term 2: pairwise dispersion 0.5 * E[||X_k - X_k'||] if K > 1: # Compute pairwise L2 over flattened masked coordinates: [B, K, K] # Per-object-frame Euclidean distance averaged over valid (t, n) (exact frame-wise CRPS!) # Memory-friendly vectorized computation over K pair_sum = torch.zeros(B, device=pred_xyz.device, dtype=pred_xyz.dtype) for k1 in range(K): d_pair = pred_xyz[:, k1:k1 + 1] - pred_xyz[:, k1 + 1:] # [B, K-1-k1, T, N, D] if d_pair.shape[1] == 0: continue l2 = torch.sqrt((d_pair * d_pair).sum(dim=-1) + 1e-8) avg_l2 = (l2 * m.unsqueeze(1)).sum(dim=(2, 3)) / denom.unsqueeze(1) if beta != 1.0: avg_l2 = avg_l2.pow(beta) pair_sum = pair_sum + 2.0 * avg_l2.sum(dim=1) spread_term = pair_sum / (K * (K - 1)) else: spread_term = torch.zeros_like(acc_term)
es = acc_term - 0.5 * spread_term return es.mean(), acc_term.mean(), spread_term.mean()
def gaussian_kl( mu_q: torch.Tensor, log_std_q: torch.Tensor, mu_p: torch.Tensor, log_std_p: torch.Tensor, obj_mask: torch.Tensor,) -> torch.Tensor: """Per-node KL(N(mu_q, std_q^2) || N(mu_p, std_p^2)) masked over valid objects.""" var_q = torch.exp(2.0 * log_std_q) var_p = torch.exp(2.0 * log_std_p) kl = (log_std_p - log_std_q) + (var_q + (mu_q - mu_p) ** 2) / (2.0 * var_p) - 0.5 kl_node = kl.sum(dim=-1) # [B, N] return (kl_node * obj_mask.float()).sum() / obj_mask.float().sum().clamp_min(1.0)
def paired_probabilistic_loss( model: ProbContactAttentionPropagator, batch: dict[str, torch.Tensor], *, K_prior: int = 8, tau: float = 0.5, kl_weight: float = 0.02, effect_weight: float = 0.6, contact_weight: float = 0.25, route_weight: float = 0.15, post_weight: float = 0.5,) -> tuple[torch.Tensor, dict[str, float]]: """Compute Paired Structural Variational + Strictly Proper Energy Score loss.
CRITICAL PROPERTIES: - Zero ground-truth mass labels used anywhere (`attrs` is NEVER accessed!). - Same latent physics Z is shared across factual (apply_edit=False) and counterfactual (apply_edit=True) branches (Pearl structural invariance). - Optimizes BOTH the amortized posterior reconstruction AND the prospective prefix-only predictive distribution (Energy Score on trajectory & paired intervention effect + contact Brier/BCE). """ state_f = batch["state_f"] # [B, 48, N, 13] state_cf = batch["state_cf"] # [B, 48, N, 13] contact_cf = batch["contact_cf"] # [B, 47, N, N] bool present_cf = batch["present_cf"] # [B, 48, N] bool present_f = batch["present_f"] # [B, 48, N] bool static = batch["static"] # [B, N, 8] obj_mask = batch["obj_mask"] # [B, N] bool subject = batch["subject"] # [B] heading = batch["heading"] # [B] step = batch["step"] # [B] cut = (step - 1) // 10 # [B]
B, T, N, _ = state_f.shape device = state_f.device max_cut = int(cut.max().item()) prefix = state_f[:, : max_cut + 1] prefix_len = cut + 1
# Mask strictly post-cut valid object-frames t_grid = torch.arange(T, device=device).view(1, T, 1) post_mask_cf = (t_grid > cut.view(B, 1, 1)) & present_cf & obj_mask.view(B, 1, N) post_mask_both = post_mask_cf & present_f
# 1. Prefix-only Prior p_theta(Z | prefix) & Amortized Posterior q_psi(Z | state_cf) mu_p, lstd_p = model.prior(prefix, static, prefix_len) mu_q, lstd_q = model.posterior(state_cf, static, obj_mask, present_cf) loss_kl = gaussian_kl(mu_q, lstd_q, mu_p, lstd_p, obj_mask)
# 2 & 3. Fused Single-Call Rollout: [cf, f] along batch (2*B) x [z_post, z_prior] along K (1+K_prior)! # Mathematically identical to 4 separate rollout calls, ~4x faster on GPU. z_post = model.sample_latents(mu_q, lstd_q, K=1) z_prior = model.sample_latents(mu_p, lstd_p, K=K_prior) z_all = torch.cat([z_post, z_prior], dim=1) # [B, 1+K_prior, N, z_dim]
prefix_2 = torch.cat([prefix, prefix], dim=0) static_2 = torch.cat([static, static], dim=0) mask_2 = torch.cat([obj_mask, obj_mask], dim=0) subj_2 = torch.cat([subject, subject], dim=0) head_2 = torch.cat([heading, torch.zeros_like(heading)], dim=0) step_2 = torch.cat([step, step], dim=0) cut_2 = torch.cat([cut, cut], dim=0) z_2 = torch.cat([z_all, z_all], dim=0)
out_all = model.rollout( prefix_2, static_2, mask_2, subj_2, head_2, step_2, cut_2, z_2, apply_edit=True, tau=tau, stochastic_gates=True, paired_batch=True, )
xyz_cf_all = out_all["xyz"][:B] # [B, 1+K_prior, 48, N, 3] xyz_f_all = out_all["xyz"][B:] vel_cf_all = out_all["vel"][:B] imp_cf_pr = out_all["impulse"][:B, 1:] gate_cf_pr = out_all["contact_prob"][:B, 1:] rlog_cf_pr = out_all["route_logits"][:B, 1:]
# Posterior Reconstruction Path (index 0): teaches exact latent-mass contact dynamics! diff_post = xyz_cf_all[:, 0, :, :, :2] - state_cf[:, :, :, :2] loss_post_pos = (F.smooth_l1_loss(diff_post, torch.zeros_like(diff_post), beta=0.05, reduction="none").sum(-1) * post_mask_cf.float()).sum() / post_mask_cf.float().sum().clamp_min(1.0) diff_post_v = vel_cf_all[:, 0] - state_cf[:, :, :, 7:9] loss_post_vel = (F.smooth_l1_loss(diff_post_v, torch.zeros_like(diff_post_v), beta=0.15, reduction="none").sum(-1) * post_mask_cf.float()).sum() / post_mask_cf.float().sum().clamp_min(1.0) diff_post_f = xyz_f_all[:, 0, :, :, :2] - state_f[:, :, :, :2] loss_post_f = (F.smooth_l1_loss(diff_post_f, torch.zeros_like(diff_post_f), beta=0.05, reduction="none").sum(-1) * post_mask_both.float()).sum() / post_mask_both.float().sum().clamp_min(1.0) loss_post = loss_post_pos + 0.35 * loss_post_vel + 0.4 * loss_post_f
# Prospective Prior Path (indices 1..K_prior): Strictly Proper Energy Score on BOTH # (a) Counterfactual Trajectory S_cf and (b) Paired Intervention Effect (S_cf - S_f)! xyz_cf_pr = xyz_cf_all[:, 1:] xyz_f_pr = xyz_f_all[:, 1:] vel_cf_pr = vel_cf_all[:, 1:]
loss_es_pos, acc_pos, spr_pos = trajectory_energy_score( xyz_cf_pr[..., :2], state_cf[..., :2], post_mask_cf ) loss_es_vel, _, _ = trajectory_energy_score( vel_cf_pr, state_cf[..., 7:9], post_mask_cf )
pred_eff = xyz_cf_pr[..., :2] - xyz_f_pr[..., :2] true_eff = state_cf[..., :2] - state_f[..., :2] loss_es_eff, acc_eff, spr_eff = trajectory_energy_score(pred_eff, true_eff, post_mask_both)
# 4. Distributional Contact-Event Proper Scoring Rule (Brier on marginal contact probs) gt_ct = contact_cf.float() # [B, 47, N, N] pred_ct_prob = gate_cf_pr[:, :, 1:].mean(dim=1) # [B, 47, N, N] imp_prob = torch.sigmoid((imp_cf_pr[:, :, 1:] - model.cfg.impact_threshold) / 0.05).mean(dim=1) marg_ct = 0.5 * (pred_ct_prob + imp_prob) eye = torch.eye(N, device=device, dtype=torch.bool).view(1, 1, N, N) ct_tmask = (torch.arange(1, T, device=device).view(1, T - 1, 1, 1) > cut.view(B, 1, 1, 1)) ct_valid = ct_tmask & obj_mask.view(B, 1, N, 1) & obj_mask.view(B, 1, 1, N) & (~eye) gt_ct_sym = torch.maximum(gt_ct, gt_ct.transpose(-1, -2)) pos_w = torch.where(gt_ct_sym > 0.5, torch.full_like(gt_ct_sym, 12.0), torch.ones_like(gt_ct_sym)) brier_ct = ((marg_ct - gt_ct_sym) ** 2 * pos_w * ct_valid.float()).sum() / ct_valid.float().sum().clamp_min(1.0)
# 5. Global First-Recipient Probabilistic Attention NLL (Cross-Entropy) first_targets = torch.full((B,), N, device=device, dtype=torch.long) # default = null class N for b_i in range(B): si = int(subject[b_i].item()) c_i = int(cut[b_i].item()) ct_sub = contact_cf[b_i, c_i:, si, :].clone() # [47-c_i, N] ct_sub[:, si] = False hits = torch.nonzero(ct_sub.any(dim=-1), as_tuple=False) if len(hits) > 0: f0 = int(hits[0].item()) recs = torch.nonzero(ct_sub[f0], as_tuple=False).flatten() if len(recs) == 1: first_targets[b_i] = int(recs[0].item()) r_logits = rlog_cf_pr.mean(dim=1) # [B, N+1] loss_route = F.cross_entropy(r_logits, first_targets)
total = ( loss_es_pos + 0.25 * loss_es_vel + effect_weight * loss_es_eff + post_weight * loss_post + kl_weight * loss_kl + contact_weight * brier_ct + route_weight * loss_route )
metrics = { "total": float(total.detach()), "es_pos": float(loss_es_pos.detach()), "es_acc": float(acc_pos.detach()), "es_spread": float(spr_pos.detach()), "es_eff": float(loss_es_eff.detach()), "post_pos": float(loss_post_pos.detach()), "kl": float(loss_kl.detach()), "ct_brier": float(brier_ct.detach()), "route_ce": float(loss_route.detach()), } return total, metrics12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229"""Probabilistic Contact-Attention Propagator (Prob-ContactAttn).
A 100% learned, genuinely probabilistic neural contact-graph dynamics model thatdirectly extends JAIS Contact Attention (`contact_attention.py`, `contact_recipient.py`)while resolving soft-attention mean-hedging and physical-plausibility instabilities:
1. Per-node latent physical belief Z = (log_mass, log_drag, rest_logit, compliance): - Prospective prior p_theta(Z | prefix, static) for prefix-only forecasting. - Amortized spatio-temporal graph attention posterior q_psi(Z | trajectory, static) trained purely from trajectory kinematics (zero ground-truth mass labels needed) and reusable for Pearl counterfactual abduction when factual trajectories exist.2. Stochastic hard-edge Contact Attention with explicit null-contact key: - Straight-Through Gumbel-Sigmoid contact gates replace soft-attention impulse dilution (`w_ij * impulse`), eliminating half-strength ghost collisions.3. Exact Newton-3rd-law & energy-passive symmetric attention value operator: - Predicts symmetric pairwise normal + dissipative tangential impulses J_ij in latent mass space (dm_i dv_i + dm_j dv_j == 0 identically; dKE <= 0), making super-elastic velocity explosions (>10 m/s) mathematically impossible.4. Strictly proper distributional training via Paired Counterfactual Energy Score (CRPS) + contact-onset Brier/BCE + variational KL with shared latent Z across factual and counterfactual branches."""
from __future__ import annotations
import mathfrom dataclasses import dataclassfrom typing import Any
import torchimport torch.nn as nnimport torch.nn.functional as F
DT = 1.0 / 24.0EPS = 1e-6MAX_N = 10
@dataclassclass ProbContactConfig: arm: str = "attention_stochastic" z_dim: int = 6 # [log_mass, log_drag, rest_logit, 3 compliance dims] hidden_dim: int = 64 substeps: int = 3 # 72 Hz internal integration per 24 Hz frame max_restitution: float = 0.92 max_friction: float = 0.60 contact_margin: float = 0.045 # m, candidate neighborhood for grazing stochasticity depen_beta: float = 0.28 # mild Baumgarte positional separation factor depen_slop: float = 0.002 # m allowed numerical slop before separation impact_threshold: float = 0.07 # m/s directed contact onset threshold (matches JAIS) log_mass_clip: float = 2.0 # exp([-2, 2]) ~= [0.14, 7.4] relative mass range log_drag_clip: float = 1.1
def yaw_from_quat_torch(q: torch.Tensor) -> torch.Tensor: """Convert wxyz quaternions [..., 4] to planar yaw [...].""" w, x, y, z = q.unbind(dim=-1) return torch.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z))
def roll_velocity_torch(state: torch.Tensor, radius: torch.Tensor) -> torch.Tensor: """Radius-scaled horizontal rolling velocity from angular velocity [..., 13] -> [..., 2].""" # Matches intervention_contact.roll_velocity: r * [omega_y, -omega_x] return radius.unsqueeze(-1) * torch.stack([state[..., 11], -state[..., 10]], dim=-1)
def _safe_norm(v: torch.Tensor, eps: float = EPS) -> tuple[torch.Tensor, torch.Tensor]: length = torch.sqrt(torch.sum(v * v, dim=-1).clamp_min(eps * eps)) unit = v / length.unsqueeze(-1) # Zero out direction when norm is negligible is_zero = (torch.sum(v * v, dim=-1) < (eps * eps)).unsqueeze(-1) unit = torch.where(is_zero, torch.zeros_like(unit), unit) length = torch.where(is_zero.squeeze(-1), torch.zeros_like(length), length) return unit, length
def _box_query_torch( point: torch.Tensor, size: torch.Tensor, yaw: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """Differentiable signed distance and outward normal from oriented box to point.
Args: point: [..., 2] vector from box center to query point. size: [..., 2] box half-extents (rx, ry). yaw: [...] box yaw angle in radians. """ c = torch.cos(yaw) s = torch.sin(yaw) px, py = point[..., 0], point[..., 1] lx = c * px + s * py ly = -s * px + c * py local = torch.stack([lx, ly], dim=-1) edge = torch.abs(local) - size outside = F.relu(edge) * torch.sign(local) out_dir, out_dist = _safe_norm(outside)
sgn_x = torch.where(lx >= 0.0, torch.ones_like(lx), -torch.ones_like(lx)) sgn_y = torch.where(ly >= 0.0, torch.ones_like(ly), -torch.ones_like(ly)) inside_dir = torch.where( (edge[..., 0] > edge[..., 1]).unsqueeze(-1), torch.stack([sgn_x, torch.zeros_like(lx)], dim=-1), torch.stack([torch.zeros_like(ly), sgn_y], dim=-1), ) outward_local = torch.where((out_dist > EPS).unsqueeze(-1), out_dir, inside_dir) wx = c * outward_local[..., 0] - s * outward_local[..., 1] wy = s * outward_local[..., 0] + c * outward_local[..., 1] world_normal = torch.stack([wx, wy], dim=-1) signed_dist = out_dist + torch.minimum(edge.amax(dim=-1), torch.zeros_like(out_dist)) return signed_dist, world_normal
def pair_geometry_batched( pos: torch.Tensor, vel: torch.Tensor, yaw: torch.Tensor, static: torch.Tensor, dt: float,) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Exact differentiable planar contact geometry for all ordered pairs (i, j).
Normal `outward` points FROM sender j TO receiver i. Closing speed `closing = (v_j - v_i) . outward` is positive when approaching.
Args: pos: [..., N, 2] vel: [..., N, 2] yaw: [..., N] static: [..., N, 8] (broadcastable to pos[..., :1]) Returns: gap: [..., N, N] signed surface gap (m) outward: [..., N, N, 2] unit normal from j -> i tangent: [..., N, N, 2] unit tangent closing: [..., N, N] normal closing speed (m/s) slip: [..., N, N] tangential relative velocity (v_j - v_i) . tangent (m/s) radial_dot: [..., N, N] alignment between center-to-center ray and contact normal """ # delta[..., i, j, :] = pos_i - pos_j (points from j -> i) delta = pos.unsqueeze(-2) - pos.unsqueeze(-3) rel_v = vel.unsqueeze(-3) - vel.unsqueeze(-2) # v_j - v_i radial, dist = _safe_norm(delta)
ri = static[..., :, 3].unsqueeze(-1) # [..., N, 1] rj = static[..., :, 3].unsqueeze(-2) # [..., 1, N] is_box_i = (static[..., :, 1] > 0.5).unsqueeze(-1) is_box_j = (static[..., :, 1] > 0.5).unsqueeze(-2)
gap = dist - ri - rj outward = radial
# Case 1: j is box, i is sphere/cyl j_only = is_box_j & (~is_box_i) if j_only.any(): size_j = static[..., :, 3:5].unsqueeze(-3).expand(*delta.shape[:-1], 2) yaw_j = yaw.unsqueeze(-2).expand(delta.shape[:-1]) gd, nd = _box_query_torch(delta, size_j, yaw_j) gap = torch.where(j_only, gd - ri, gap) outward = torch.where(j_only.unsqueeze(-1), nd, outward)
# Case 2: i is box, j is sphere/cyl i_only = is_box_i & (~is_box_j) if i_only.any(): size_i = static[..., :, 3:5].unsqueeze(-2).expand(*delta.shape[:-1], 2) yaw_i = yaw.unsqueeze(-1).expand(delta.shape[:-1]) gd, nd = _box_query_torch(-delta, size_i, yaw_i) gap = torch.where(i_only, gd - rj, gap) outward = torch.where(i_only.unsqueeze(-1), -nd, outward)
# Case 3: both i and j are boxes (exact 4-axis SAT) both_box = is_box_i & is_box_j if both_box.any(): yi = yaw.unsqueeze(-1).expand(delta.shape[:-1]) yj = yaw.unsqueeze(-2).expand(delta.shape[:-1]) angles = torch.stack([yi, yi + 0.5 * math.pi, yj, yj + 0.5 * math.pi], dim=-1) # [..., N, N, 4] axes = torch.stack([torch.cos(angles), torch.sin(angles)], dim=-1) # [..., N, N, 4, 2] proj = (delta.unsqueeze(-2) * axes).sum(dim=-1) # [..., N, N, 4]
si_xy = static[..., :, 3:5].unsqueeze(-2).expand(*delta.shape[:-1], 2) sj_xy = static[..., :, 3:5].unsqueeze(-3).expand(*delta.shape[:-1], 2) ri_rect = ( torch.abs(torch.cos(angles - yi.unsqueeze(-1))) * si_xy[..., 0:1] + torch.abs(torch.sin(angles - yi.unsqueeze(-1))) * si_xy[..., 1:2] ) rj_rect = ( torch.abs(torch.cos(angles - yj.unsqueeze(-1))) * sj_xy[..., 0:1] + torch.abs(torch.sin(angles - yj.unsqueeze(-1))) * sj_xy[..., 1:2] ) gaps_sat = torch.abs(proj) - ri_rect - rj_rect max_gap, ax_idx = gaps_sat.max(dim=-1) sgn_proj = torch.where(proj >= 0.0, torch.ones_like(proj), -torch.ones_like(proj)) signed_axes = axes * sgn_proj.unsqueeze(-1) # [..., N, N, 4, 2] gather_idx = ax_idx.unsqueeze(-1).unsqueeze(-1).expand(*delta.shape[:-1], 1, 2) sat_n = torch.gather(signed_axes, dim=-2, index=gather_idx).squeeze(-2) gap = torch.where(both_box, max_gap, gap) outward = torch.where(both_box.unsqueeze(-1), sat_n, outward)
tangent = torch.stack([-outward[..., 1], outward[..., 0]], dim=-1) closing = (rel_v * outward).sum(dim=-1) slip = (rel_v * tangent).sum(dim=-1) radial_dot = (radial * outward).sum(dim=-1) return gap, outward, tangent, closing, slip, radial_dot
class PrefixLatentPrior(nn.Module): """Prospective prior p_theta(Z | prefix, static) over per-node latent physics.
Uses strictly pre-intervention observations (static geometry + prefix speeds & deceleration). Never sees simulator masses or post-intervention states. """
def __init__(self, z_dim: int = 6, hidden: int = 64): super().__init__() # Per-node input: static[8] + log_vol[1] + [speed, decel, decel_valid, roll_slip, is_moving, pref_len] = 15 self.net = nn.Sequential( nn.Linear(15, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU(), ) self.mu = nn.Linear(hidden, z_dim) self.log_std = nn.Linear(hidden, z_dim) # Initialize with reasonable physics prior spread (log_mass std ~= 0.55) nn.init.zeros_(self.mu.weight) nn.init.zeros_(self.mu.bias) nn.init.zeros_(self.log_std.weight) nn.init.constant_(self.log_std.bias, -0.6)
@staticmethod def _node_features(prefix: torch.Tensor, static: torch.Tensor, prefix_len: torch.Tensor) -> torch.Tensor: """Build [B, N, 15] prefix-only node descriptors.""" B, T, N, _ = prefix.shape # Estimate observed deceleration strictly from prefix frames vel = prefix[:, :, :, 7:9] # [B, T, N, 2] speed_seq = torch.linalg.norm(vel, dim=-1) # [B, T, N] rows = torch.arange(B, device=prefix.device) last = prefix_len - 1 speed_last = speed_seq[rows, last] # [B, N] if T > 1: rates = -(speed_seq[:, 1:] - speed_seq[:, :-1]) / DT # [B, T-1, N] # Mask valid prefix frames up to prefix_len t_idx = torch.arange(T - 1, device=prefix.device).view(1, T - 1, 1) valid_t = t_idx < (prefix_len.view(B, 1, 1) - 1) valid_f = valid_t.float() decel = (rates * valid_f).sum(dim=1) / valid_f.sum(dim=1).clamp_min(1.0) decel_valid = ((prefix_len.view(B, 1) > 1) & (speed_last > 0.25) & (decel >= 0.0) & (decel < 10.0)).float() decel = torch.where(decel_valid > 0.5, decel, torch.zeros_like(decel)) else: decel = torch.zeros_like(speed_last) decel_valid = torch.zeros_like(speed_last)
roll_v = roll_velocity_torch(prefix[rows, last], static[:, :, 3]) roll_slip = torch.linalg.norm(vel[rows, last] - roll_v, dim=-1) is_moving = (speed_last > 0.15).float() vol = (static[:, :, 3] * static[:, :, 4] * static[:, :, 5]).clamp_min(1e-5) log_vol = torch.log(vol) plen_norm = prefix_len.float().view(B, 1).expand(B, N) / 10.0
feat = torch.cat( [ static, log_vol.unsqueeze(-1), (speed_last / 4.0).unsqueeze(-1), (decel / 4.0).unsqueeze(-1), decel_valid.unsqueeze(-1), (roll_slip / 4.0).unsqueeze(-1), is_moving.unsqueeze(-1), plen_norm.unsqueeze(-1), ], dim=-1, ) return torch.clamp(feat, -10.0, 10.0)
def forward( self, prefix: torch.Tensor, static: torch.Tensor, prefix_len: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: feat = self._node_features(prefix, static, prefix_len) h = self.net(feat) mu = self.mu(h) log_std = self.log_std(h).clamp(-2.5, 0.5) return mu, log_std
class TrajectoryLatentPosterior(nn.Module): """Amortized spatio-temporal graph attention posterior q_psi(Z | trajectory, static).
Infers per-node latent physics (mass ratio, floor drag, restitution) purely from observed kinematics & pairwise momentum exchange — NEVER uses ground-truth mass labels. Used during training (variational ELBO/Energy-Score) and optionally for Pearl abduction when a factual trajectory is available. """
def __init__(self, z_dim: int = 6, hidden: int = 64): super().__init__() # Node temporal encoder over [pos_xy(2), vel_xy(2), acc_xy(2), speed(1), static(8)] = 15 self.node_in = nn.Sequential(nn.Linear(15, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU()) # Edge encoder at each frame for pairwise interaction cues # [rel_pos(2), rel_vel(2), dist/scale(1), closing(1), dvel_i_dot_n(1), dvel_j_dot_n(1)] = 8 self.edge_enc = nn.Sequential(nn.Linear(8, hidden), nn.SiLU(), nn.Linear(hidden, hidden), nn.SiLU()) self.edge_gate = nn.Linear(hidden, 1) # Temporal attention pooling per node self.time_attn = nn.Linear(hidden * 2, 1) self.out_mlp = nn.Sequential(nn.Linear(hidden * 2, hidden), nn.SiLU()) self.mu = nn.Linear(hidden, z_dim) self.log_std = nn.Linear(hidden, z_dim) nn.init.zeros_(self.mu.weight) nn.init.zeros_(self.mu.bias) nn.init.zeros_(self.log_std.weight) nn.init.constant_(self.log_std.bias, -1.2)
def forward( self, traj: torch.Tensor, static: torch.Tensor, obj_mask: torch.Tensor, present: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: """Encode full or partial trajectory [B, T, N, 13] -> posterior (mu, log_std) [B, N, z_dim].""" B, T, N, _ = traj.shape pos = traj[:, :, :, :2] vel = traj[:, :, :, 7:9] acc = torch.zeros_like(vel) if T > 1: acc[:, 1:] = (vel[:, 1:] - vel[:, :-1]) / DT speed = torch.linalg.norm(vel, dim=-1, keepdim=True) static_exp = static.unsqueeze(1).expand(B, T, N, 8) node_x = torch.cat([pos / 4.0, vel / 4.0, acc / 20.0, speed / 4.0, static_exp], dim=-1) node_x = torch.clamp(node_x, -10.0, 10.0) h_node = self.node_in(node_x) # [B, T, N, H]
# Pairwise spatial graph attention encoding momentum exchange across collisions delta = pos.unsqueeze(-2) - pos.unsqueeze(-3) # [B, T, N, N, 2] radial, dist = _safe_norm(delta) scale = (static[:, :, 3].unsqueeze(-1) + static[:, :, 3].unsqueeze(-2)).unsqueeze(1).clamp_min(0.05) rel_v = vel.unsqueeze(-3) - vel.unsqueeze(-2) closing = (rel_v * radial).sum(dim=-1, keepdim=True) acc_i_n = (acc.unsqueeze(-2) * radial).sum(dim=-1, keepdim=True) acc_j_n = (acc.unsqueeze(-3) * radial).sum(dim=-1, keepdim=True) edge_x = torch.cat( [ delta / 4.0, rel_v / 4.0, (dist / scale).unsqueeze(-1), closing / 4.0, acc_i_n / 20.0, acc_j_n / 20.0, ], dim=-1, ) edge_x = torch.clamp(edge_x, -10.0, 10.0) h_edge = self.edge_enc(edge_x) # [B, T, N, N, H] # Mask invalid edges and distant non-interacting pairs gently via proximity bias eye = torch.eye(N, device=traj.device, dtype=torch.bool).view(1, 1, N, N) pair_valid = obj_mask.unsqueeze(1).unsqueeze(3) & obj_mask.unsqueeze(1).unsqueeze(2) & (~eye) prox_bias = -2.0 * F.relu(dist / scale - 1.4) e_logits = self.edge_gate(h_edge).squeeze(-1) + prox_bias e_logits = e_logits.masked_fill(~pair_valid, -1e4) # Explicit null-interaction key (logit 0) so free-flight frames stay clean e_odds = torch.exp(e_logits.clamp(-12.0, 12.0)) * pair_valid.float() e_w = e_odds / (e_odds.sum(dim=-1, keepdim=True) + 1.0) h_inter = (e_w.unsqueeze(-1) * h_edge).sum(dim=-2) # [B, T, N, H]
h_cat = torch.cat([h_node, h_inter], dim=-1) # [B, T, N, 2H] t_logits = self.time_attn(h_cat).squeeze(-1) # [B, T, N] if present is not None: t_logits = t_logits.masked_fill(~present, -1e4) t_w = torch.softmax(t_logits, dim=1) # [B, T, N] pooled = (t_w.unsqueeze(-1) * h_cat).sum(dim=1) # [B, N, 2H] out = self.out_mlp(pooled) mu = self.mu(out) log_std = self.log_std(out).clamp(-2.8, 0.2) return mu, log_std
class ProbFirstHitSelector(nn.Module): """Batched probabilistic global first-recipient attention (extends `Selector`).
Computes calibrated categorical probabilities over {0..N-1, null} for the first post-intervention contact of the commanded subject. Supplies a geometric prior logit to local contact attention without hard-suppressing multi-hop events. """
def __init__(self, hidden: int = 48): super().__init__() # Matches contact_recipient.make_features (25 dims) self.encode = nn.Sequential(nn.Linear(25, hidden), nn.SiLU(), nn.Linear(hidden, 32), nn.SiLU()) self.edge = nn.Linear(32, 1) self.none = nn.Sequential(nn.Linear(64, 16), nn.SiLU(), nn.Linear(16, 1))
@staticmethod def build_features( pos: torch.Tensor, vel: torch.Tensor, static: torch.Tensor, subject: torch.Tensor, heading: torch.Tensor, step: torch.Tensor, cut: torch.Tensor, ) -> torch.Tensor: """Build [B, K, N, 25] candidate features matching JAIS contact_recipient.""" B, K, N, _ = pos.shape device = pos.device pre_dt = ((step - 1 - 10 * cut).float() / 240.0).view(B, 1, 1, 1) pos_e = pos + pre_dt * vel
# Gather subject pose & velocity: [B, K, 1, 2] sub_idx = subject.view(B, 1, 1, 1).expand(B, K, 1, 2) sub_pos = torch.gather(pos_e, 2, sub_idx) sub_vel = torch.gather(vel, 2, sub_idx) c = torch.cos(heading).view(B, 1, 1) s = torch.sin(heading).view(B, 1, 1) vx, vy = sub_vel[..., 0], sub_vel[..., 1] edit_vel = torch.stack([c * vx - s * vy, s * vx + c * vy], dim=-1) # [B, K, 1, 2]
delta = pos_e - sub_pos # [B, K, N, 2] rel_v = edit_vel - vel speed = torch.linalg.norm(rel_v, dim=-1).clamp_min(1e-3) direction = rel_v / speed.unsqueeze(-1)
sub_static_idx = subject.view(B, 1, 1).expand(B, 1, 8) sub_static = torch.gather(static, 1, sub_static_idx).unsqueeze(1).expand(B, K, N, 8) st_exp = static.unsqueeze(1).expand(B, K, N, 8) radius = (st_exp[..., 7] + sub_static[..., 7]).clamp_min(0.05)
along = (delta * direction).sum(dim=-1) cross = direction[..., 0] * delta[..., 1] - direction[..., 1] * delta[..., 0] norm = torch.linalg.norm(delta, dim=-1) flight = ((47.0 - cut.float()) / 24.0 - (step - 1 - 10 * cut).float() / 240.0).view(B, 1, 1).expand(B, K, N) ray_t = torch.clamp(along / speed, min=torch.zeros_like(along), max=flight) miss = torch.linalg.norm(delta - ray_t.unsqueeze(-1) * rel_v, dim=-1)
sin_h = torch.sin(heading).view(B, 1, 1).expand(B, K, N) cos_h = torch.cos(heading).view(B, 1, 1).expand(B, K, N)
feats = torch.cat( [ (along / 4.0).unsqueeze(-1), (cross / 4.0).unsqueeze(-1), (torch.abs(cross) / radius).unsqueeze(-1), (along / radius).unsqueeze(-1), (norm / 4.0).unsqueeze(-1), (speed / 5.0).unsqueeze(-1), ray_t.unsqueeze(-1), (miss / radius).unsqueeze(-1), radius.unsqueeze(-1), ((delta * rel_v).sum(dim=-1) / (norm + 0.01) / 5.0).unsqueeze(-1), flight.unsqueeze(-1), sin_h.unsqueeze(-1), cos_h.unsqueeze(-1), sub_static[..., :6], st_exp[..., :6], ], dim=-1, ) return torch.clamp(feats, -30.0, 30.0)
def in_scores(self, pos, vel, static, obj_mask, subject, heading, step, cut): x = self.build_features(pos, vel, static, subject, heading, step, cut) n = x.shape[-2] valid = obj_mask[:, None, :, None] & obj_mask[:, None, None, :] valid = valid & ~torch.eye(n, dtype=torch.bool, device=x.device)[None, None] # For each receiver accumulate learned messages from the other objects. messages = self.encode(x.unsqueeze(-2) - x.unsqueeze(-3)) nodes = (messages * valid.unsqueeze(-1)).sum(dim=-2) scores = self.edge(nodes).squeeze(-1) cand = obj_mask.clone() cand[torch.arange(len(subject), device=subject.device), subject] = False scores = scores.masked_fill(~cand[:, None], -1e4) mean = (nodes * cand[:, None, :, None]).sum(dim=2) / cand.sum(1).clamp_min(1)[:, None, None] mx = nodes.masked_fill(~cand[:, None, :, None], -1e4).amax(dim=2) null = self.none(torch.cat([mean, mx], dim=-1)) return torch.cat([scores, null], dim=-1)
def forward( self, pos: torch.Tensor, vel: torch.Tensor, static: torch.Tensor, obj_mask: torch.Tensor, subject: torch.Tensor, heading: torch.Tensor, step: torch.Tensor, cut: torch.Tensor, ) -> torch.Tensor: """Return logits [B, K, N+1] over candidate recipients and explicit null outcome.""" B, K, N, _ = pos.shape x = self.build_features(pos, vel, static, subject, heading, step, cut) emb = self.encode(x) # [B, K, N, 32] cand_mask = obj_mask.unsqueeze(1).expand(B, K, N).clone() b_idx = torch.arange(B, device=pos.device) cand_mask[b_idx, :, subject] = False
scores = self.edge(emb).squeeze(-1).masked_fill(~cand_mask, -1e4) mask_f = cand_mask.float().unsqueeze(-1) mean_emb = (emb * mask_f).sum(dim=2) / mask_f.sum(dim=2).clamp_min(1.0) max_emb = emb.masked_fill(~cand_mask.unsqueeze(-1), -1e4).amax(dim=2) none_score = self.none(torch.cat([mean_emb, max_emb], dim=-1)) # [B, K, 1] return torch.cat([scores, none_score], dim=-1)
class StochasticContactAttention(nn.Module): """Physics-consistent stochastic hard-edge Contact Attention operator.
Key properties: 1. Explicit null-contact key (logit 0) competing with learned contact logit s_ij. 2. Straight-Through Gumbel-Sigmoid stochastic hard gate g_ij in {0, 1} in the grazing/near-contact zone (eliminates soft-attention velocity dilution). 3. Exact symmetric Newton-3rd-law impulse J_ij = J_n n + J_t t in latent mass space with e_ij in (0, max_restitution) and dissipative tangential impulse, guaranteeing: - sum_i m_i dv_i == 0 identically (momentum conservation) - dKE <= 0 at every pairwise collision (energy passivity, zero blow-ups) """
def __init__(self, cfg: ProbContactConfig): super().__init__() self.cfg = cfg # Symmetric pair features: # [gap/s, swept_gap/s, ttc, closing/4, |slip|/4, speed_sum/4, speed_diff/4, # radial_dot, roll_closing/4, roll_slip/4, # shape_i+shape_j(3), shape_i*shape_j(3), size_sum(2), size_diff(2), # z_sum(z_dim), |z_diff|(z_dim), route_prob(1)] = 21 + 2*z_dim in_dim = 21 + 2 * cfg.z_dim H = cfg.hidden_dim self.edge_mlp = nn.Sequential( nn.Linear(in_dim, H), nn.SiLU(), nn.Linear(H, H), nn.SiLU(), ) # Contact gate logit vs explicit null key (0) self.gate_logit = nn.Linear(H, 1) self.transfer_head = nn.Linear(8, 2) nn.init.zeros_(self.transfer_head.weight) nn.init.zeros_(self.transfer_head.bias) # Symmetric value head: effective restitution logit, tangential friction logit, # and sphere rolling-coupling fraction self.rest_head = nn.Linear(H, 1) self.fric_head = nn.Linear(H, 1) self.roll_couple_head = nn.Linear(H, 1)
# Conservative physical initialization: low restitution (~0.15), moderate friction (~0.25) nn.init.constant_(self.rest_head.bias, -1.7) nn.init.constant_(self.fric_head.bias, -0.3) nn.init.constant_(self.roll_couple_head.bias, -1.0) nn.init.constant_(self.gate_logit.bias, 0.5)
def step_contacts( self, pos: torch.Tensor, vel: torch.Tensor, roll: torch.Tensor, yaw: torch.Tensor, static: torch.Tensor, obj_mask: torch.Tensor, z: torch.Tensor, route_pair_prob: torch.Tensor, sub_dt: float, tau: float = 0.5, stochastic: bool = True, gate_uniform: torch.Tensor | None = None, reached: torch.Tensor | None = None, subject: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: """Compute one sub-step of momentum-conserving stochastic contact attention.
Returns: dv: [B, K, N, 2] velocity impulse droll: [B, K, N, 2] rolling-velocity impulse dpos: [B, K, N, 2] mild Baumgarte depenetration shift impulse_mag: [B, K, N, N] directed impact dv magnitude on receiver i from sender j gate_prob: [B, K, N, N] contact probability for auxiliary contact Brier/BCE loss """ B, K, N, _ = pos.shape device = pos.device st_exp = static.unsqueeze(1).expand(B, K, N, 8) gap, outward, tangent, closing, slip, radial_dot = pair_geometry_batched( pos, vel, yaw, st_exp, sub_dt ) # Undirected pair mask i < j (valid objects only) tri = torch.triu(torch.ones(N, N, device=device, dtype=torch.bool), diagonal=1) pair_valid = obj_mask.unsqueeze(1).unsqueeze(3) & obj_mask.unsqueeze(1).unsqueeze(2) & tri.view(1, 1, N, N)
scale = (st_exp[..., :, 3].unsqueeze(-1) + st_exp[..., :, 3].unsqueeze(-2)).clamp_min(0.05) swept_reach = F.relu(closing) * sub_dt + self.cfg.contact_margin cand = pair_valid & (closing > 0.02) & (gap < swept_reach) & (gap > -0.8 * scale)
# Latent positive masses: m_i = exp(clip(z_i[..., 0])) log_m = z[..., 0].clamp(-self.cfg.log_mass_clip, self.cfg.log_mass_clip) mass = torch.exp(log_m) # [B, K, N] inv_m = 1.0 / mass inv_m_i = inv_m.unsqueeze(-1) # [B, K, N, 1] inv_m_j = inv_m.unsqueeze(-2) # [B, K, 1, N] m_red = 1.0 / (inv_m_i + inv_m_j).clamp_min(EPS) # [B, K, N, N]
dv = torch.zeros_like(vel) droll = torch.zeros_like(roll) dpos = torch.zeros_like(pos) impulse_mag = torch.zeros(B, K, N, N, device=device, dtype=vel.dtype) gate_prob = torch.zeros(B, K, N, N, device=device, dtype=vel.dtype)
if cand.any(): # Evaluate edge MLP STRICTLY on active sparse candidates (~0.5% of B*K*N*N) # -> mathematically identical, ~100x faster & ~20x lower VRAM! cb, ck, ci, cj = torch.nonzero(cand, as_tuple=True) n_cand = cb.numel()
vel_i = vel[cb, ck, ci] # [M, 2] vel_j = vel[cb, ck, cj] roll_i = roll[cb, ck, ci] roll_j = roll[cb, ck, cj] out_c = outward[cb, ck, ci, cj] tan_c = tangent[cb, ck, ci, cj] gap_c = gap[cb, ck, ci, cj] scale_c = scale[cb, ck, ci, cj] closing_c = closing[cb, ck, ci, cj] slip_c = slip[cb, ck, ci, cj] rdot_c = radial_dot[cb, ck, ci, cj] rp_c = route_pair_prob[cb, ck, ci, cj]
spd_i = torch.linalg.norm(vel_i, dim=-1) spd_j = torch.linalg.norm(vel_j, dim=-1) rel_roll_c = roll_j - roll_i roll_c = (rel_roll_c * out_c).sum(dim=-1) roll_s = torch.abs((rel_roll_c * tan_c).sum(dim=-1))
st_i = static[cb, ci] # [M, 8] st_j = static[cb, cj] sh_i, sh_j = st_i[:, :3], st_j[:, :3] sz_i = torch.stack([st_i[:, 3], st_i[:, 5]], dim=-1) sz_j = torch.stack([st_j[:, 3], st_j[:, 5]], dim=-1) z_i = z[cb, ck, ci] z_j = z[cb, ck, cj]
swept_gap_c = gap_c - F.relu(closing_c) * sub_dt ttc_c = torch.clamp(gap_c / (F.relu(closing_c) * sub_dt).clamp_min(0.002), -2.0, 4.0) feat_c = torch.cat( [ (gap_c / scale_c).unsqueeze(-1), (swept_gap_c / scale_c).unsqueeze(-1), ttc_c.unsqueeze(-1), (closing_c / 4.0).unsqueeze(-1), (torch.abs(slip_c) / 4.0).unsqueeze(-1), ((spd_i + spd_j) / 4.0).unsqueeze(-1), (torch.abs(spd_i - spd_j) / 4.0).unsqueeze(-1), rdot_c.unsqueeze(-1), (roll_c / 4.0).unsqueeze(-1), (roll_s / 4.0).unsqueeze(-1), sh_i + sh_j, sh_i * sh_j, sz_i + sz_j, torch.abs(sz_i - sz_j), z_i + z_j, torch.abs(z_i - z_j), rp_c.unsqueeze(-1), ], dim=-1, ) feat_c = torch.clamp(feat_c, -10.0, 10.0) h_c = self.edge_mlp(feat_c) # [M, H]
geom_logit = -swept_gap_c / 0.012 logits_c = self.gate_logit(h_c).squeeze(-1) + geom_logit p_hit_c = torch.sigmoid(logits_c)
# Scatter symmetric gate_prob gate_prob = gate_prob.clone() gate_prob.index_put_((cb, ck, ci, cj), p_hit_c) gate_prob.index_put_((cb, ck, cj, ci), p_hit_c)
must_hit_c = swept_gap_c <= -0.002 if stochastic: u = (torch.rand_like(logits_c) if gate_uniform is None else gate_uniform[cb % gate_uniform.shape[0], ck, ci, cj]).clamp(1e-5, 1.0 - 1e-5) gumbel_noise = torch.log(u) - torch.log1p(-u) soft_g = torch.sigmoid((logits_c + gumbel_noise) / max(tau, 0.1)) hard_g = (soft_g > 0.5).float() gate_c = hard_g - soft_g.detach() + soft_g else: hard_g = (p_hit_c > 0.5).float() gate_c = hard_g - p_hit_c.detach() + p_hit_c gate_c = torch.where(must_hit_c, torch.ones_like(gate_c), gate_c)
rest_bias_c = 0.5 * (z_i[:, 2] + z_j[:, 2]) rest_logit = self.rest_head(h_c).squeeze(-1) + rest_bias_c fric_logit = self.fric_head(h_c).squeeze(-1) if reached is not None: i_seen = reached[cb, ck, ci] j_seen = reached[cb, ck, cj] active = (i_seen ^ j_seen) & (ci != subject[cb]) & (cj != subject[cb]) # Sender is identified by a prior forecast contact along the command path. # Signed contrasts are sender-minus-receiver, independently of array ordering. orientation = torch.where(i_seen, 1., -1.) features = torch.stack(( closing_c / 3., torch.abs(slip_c) / (closing_c + .25), orientation * (log_m[cb, ck, ci] - log_m[cb, ck, cj]), orientation * torch.log(st_i[:,3].clamp_min(.01) / st_j[:,3].clamp_min(.01)), torch.where(i_seen, sh_i[:,0], sh_j[:,0]), torch.where(i_seen, sh_j[:,0], sh_i[:,0]), orientation * (spd_i - spd_j) / 3., torch.abs(roll_c) / 3. ), dim=-1).clamp(-4., 4.) shift = 3. * torch.tanh(self.transfer_head(features) / 3.) rest_logit = rest_logit + active * shift[:,0] fric_logit = fric_logit + active * shift[:,1] e_c = self.cfg.max_restitution * torch.sigmoid(rest_logit) mu_c = self.cfg.max_friction * torch.sigmoid(fric_logit) roll_cw = 0.4 * torch.sigmoid(self.roll_couple_head(h_c).squeeze(-1))
inv_mi_c = inv_m[cb, ck, ci] inv_mj_c = inv_m[cb, ck, cj] m_red_c = 1.0 / (inv_mi_c + inv_mj_c).clamp_min(EPS)
# Exact Newton's 3rd Law & Energy-Passive Pairwise Impulse j_n = (1.0 + e_c) * m_red_c * F.relu(closing_c) max_jt = torch.minimum(mu_c * j_n, 0.85 * m_red_c * torch.abs(slip_c)) j_t = torch.sign(slip_c) * max_jt j_vec = gate_c.unsqueeze(-1) * (j_n.unsqueeze(-1) * out_c + j_t.unsqueeze(-1) * tan_c)
# Scatter symmetric +J/m_i and -J/m_j (EXACT momentum conservation!) dv = torch.zeros_like(vel) dv.index_put_((cb, ck, ci), j_vec * inv_mi_c.unsqueeze(-1), accumulate=True) dv.index_put_((cb, ck, cj), -j_vec * inv_mj_c.unsqueeze(-1), accumulate=True)
is_sph_i = (st_i[:, 0] > 0.5).float().unsqueeze(-1) is_sph_j = (st_j[:, 0] > 0.5).float().unsqueeze(-1) r_imp = (gate_c * roll_cw * j_t).unsqueeze(-1) * tan_c droll = torch.zeros_like(roll) droll.index_put_((cb, ck, ci), is_sph_i * r_imp * inv_mi_c.unsqueeze(-1), accumulate=True) droll.index_put_((cb, ck, cj), -is_sph_j * r_imp * inv_mj_c.unsqueeze(-1), accumulate=True)
# Directed impact magnitude: impulse_mag[b, k, sender, receiver] j_norm = torch.linalg.norm(j_vec, dim=-1) impulse_mag = impulse_mag.clone() impulse_mag.index_put_((cb, ck, cj, ci), j_norm * inv_mi_c, accumulate=True) impulse_mag.index_put_((cb, ck, ci, cj), j_norm * inv_mj_c, accumulate=True)
# Mild Baumgarte positional depenetration (mass-weighted, symmetric -> zero COM shift!) pen = F.relu(-gap - self.cfg.depen_slop) * pair_valid.float() if (pen > 0.0).any(): corr_mag = self.cfg.depen_beta * pen * m_red # proportional to m_red corr_vec = corr_mag.unsqueeze(-1) * outward dpos_i = (corr_vec * inv_m_i.unsqueeze(-1)).sum(dim=-2) dpos_j = (-corr_vec * inv_m_j.unsqueeze(-1)).sum(dim=-3) dpos = dpos_i + dpos_j
return dv, droll, dpos, impulse_mag, gate_prob
class ProbContactAttentionPropagator(nn.Module): """End-to-end Differentiable Probabilistic Contact-Attention Propagator.
Combines: - PrefixLatentPrior p_theta(Z | prefix, static) - TrajectoryLatentPosterior q_psi(Z | trajectory, static) - ProbFirstHitSelector (global intervention attention with null key) - StochasticContactAttention (local hard-edge momentum-conserving attention) - Latent-modulated passive free-motion integrator (sphere rolling-to-sliding + box/cyl drag) """
def __init__(self, cfg: ProbContactConfig | None = None): super().__init__() self.cfg = cfg or ProbContactConfig() self.prior = PrefixLatentPrior(self.cfg.z_dim, self.cfg.hidden_dim) self.posterior = TrajectoryLatentPosterior(self.cfg.z_dim, self.cfg.hidden_dim) self.selector = ProbFirstHitSelector(hidden=48) self.contact_attn = StochasticContactAttention(self.cfg)
# Learnable base floor drag parameters (initialized from physical JAIS scales, strictly positive!) # Per-shape [sphere, box, cyl]: base sliding drag & rolling drag (m/s^2) self.log_slide_drag = nn.Parameter(torch.log(torch.tensor([2.0, 2.0, 1.8], dtype=torch.float32))) self.log_roll_drag = nn.Parameter(torch.log(torch.tensor([0.16, 2.0, 1.8], dtype=torch.float32))) # Sphere inertia ratio (2.5 for solid sphere sliding-to-rolling coupling) self.log_inertia_ratio = nn.Parameter(torch.log(torch.tensor(2.3, dtype=torch.float32)))
def _free_step( self, pos: torch.Tensor, vel: torch.Tensor, roll: torch.Tensor, static: torch.Tensor, z: torch.Tensor, dt: float, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Strictly passive free-motion step with analytical sphere sliding-to-rolling transition.""" B, K, N, _ = vel.shape sh_weights = static[:, :, :3].unsqueeze(1).expand(B, K, N, 3) drag_scale = torch.exp(z[..., 1].clamp(-self.cfg.log_drag_clip, self.cfg.log_drag_clip)) slide_base = (sh_weights * torch.exp(self.log_slide_drag).view(1, 1, 1, 3)).sum(dim=-1) * drag_scale roll_base = (sh_weights * torch.exp(self.log_roll_drag).view(1, 1, 1, 3)).sum(dim=-1) * drag_scale
# Non-sphere (box/cylinder) passive linear drag u_v, spd = _safe_norm(vel) next_spd = F.relu(spd - slide_base * dt) next_v_drag = u_v * next_spd.unsqueeze(-1) disp_drag = 0.5 * (vel + next_v_drag) * dt
# Sphere analytical sliding-to-rolling transition (strictly passive) is_sph = (static[:, :, 0] > 0.5).unsqueeze(1).expand(B, K, N) ratio = torch.exp(self.log_inertia_ratio).clamp(0.5, 5.0) u_slip, slip = _safe_norm(vel - roll) until_roll = slip / ((1.0 + ratio) * slide_base.clamp_min(0.05)) t_slip = torch.minimum(torch.full_like(until_roll, dt), until_roll) slide_dv = (slide_base * t_slip).unsqueeze(-1) * u_slip mid_v = vel - slide_dv t_post = F.relu(dt - t_slip) u_mid, mid_spd = _safe_norm(mid_v) end_v_sph = u_mid * F.relu(mid_spd - roll_base * t_post).unsqueeze(-1) disp_sph = 0.5 * (vel + mid_v) * t_slip.unsqueeze(-1) + 0.5 * (mid_v + end_v_sph) * t_post.unsqueeze(-1) next_roll_sph = torch.where((until_roll <= dt).unsqueeze(-1), end_v_sph, roll + ratio * slide_dv)
next_v = torch.where(is_sph.unsqueeze(-1), end_v_sph, next_v_drag) next_roll = torch.where(is_sph.unsqueeze(-1), next_roll_sph, next_v_drag) next_pos = pos + torch.where(is_sph.unsqueeze(-1), disp_sph, disp_drag) return next_pos, next_v, next_roll
def sample_latents( self, mu: torch.Tensor, log_std: torch.Tensor, K: int, deterministic_first: bool = False, ) -> torch.Tensor: """Reparameterized draw [B, K, N, z_dim].""" B, N, D = mu.shape std = torch.exp(log_std) eps = torch.randn(B, K, N, D, device=mu.device, dtype=mu.dtype) if deterministic_first and K > 0: eps[:, 0] = 0.0 return mu.unsqueeze(1) + std.unsqueeze(1) * eps
def rollout( self, prefix: torch.Tensor, static: torch.Tensor, obj_mask: torch.Tensor, subject: torch.Tensor, heading: torch.Tensor, step: torch.Tensor, cut: torch.Tensor, z: torch.Tensor, *, init_state_samples: torch.Tensor | None = None, horizon: int = 48, apply_edit: bool = True, tau: float = 0.5, stochastic_gates: bool = True, gate_seed: int | None = None, paired_batch: bool = False, ) -> dict[str, torch.Tensor]: """Differentiable batched rollout for B scenes x K worlds over `horizon` frames.
Args: prefix: [B, T_max, N, 13] observed prefix states (valid up to `cut[b]`). static: [B, N, 8] obj_mask: [B, N] bool subject: [B] int heading: [B] float (radians) step: [B] int (240 Hz intervention tick) cut: [B] int = (step - 1) // 10 z: [B, K, N, z_dim] sampled latent physics init_state_samples: optional [B, K, N, 13] sampled initial cutoff state from ProbabilisticHybridGraphEncoder (zero teleportation: frame `cut` is anchored smoothly to `init_state_samples`). """ B, T_pre, N, _ = prefix.shape K = z.shape[1] device = prefix.device stochastic_gates = stochastic_gates and self.cfg.arm != "attention_deterministic" if paired_batch and B % 2: raise ValueError("Paired training requires equal on and off batches") if gate_seed is None: gate_seed = int(torch.randint(0, 2**31 - 1, (), device="cpu")) gate_rng = torch.Generator(device=device).manual_seed(gate_seed) gate_rows = B // 2 if paired_batch else B
# Gather exact state at frame cut[b] for each scene in batch cut_idx = cut.view(B, 1, 1, 1).expand(B, 1, N, 13) state_cut = torch.gather(prefix, 1, cut_idx).squeeze(1) # [B, N, 13] if init_state_samples is None: s0 = state_cut.unsqueeze(1).expand(B, K, N, 13).clone() else: s0 = init_state_samples.clone()
pos = s0[..., :2].clone() z_height = s0[..., 2].clone() vel = s0[..., 7:9].clone() yaw = yaw_from_quat_torch(s0[..., 3:7]) omega_z = s0[..., 12].clone() # Initialize sphere rolling velocity cleanly (bounded to avoid visual spin blowup) roll_raw = roll_velocity_torch(s0, static[:, :, 3].unsqueeze(1)) roll_spd = torch.linalg.norm(roll_raw, dim=-1, keepdim=True) vel_spd = torch.linalg.norm(vel, dim=-1, keepdim=True) roll = torch.where(roll_spd > (2.0 * vel_spd + 0.5), vel, roll_raw)
# Global probabilistic first-hit attention prior eff_heading = heading if apply_edit else torch.zeros_like(heading) if self.cfg.arm == "in_stochastic": route_logits = self.selector.in_scores(pos, vel, static, obj_mask, subject, eff_heading, step, cut) route_probs = torch.sigmoid(route_logits) else: route_logits = self.selector(pos, vel, static, obj_mask, subject, eff_heading, step, cut) route_probs = torch.softmax(route_logits, dim=-1) # [B, K, N+1]
# Build symmetric pair-prior matrix for (subject, b) — fully vectorized over B b_idx = torch.arange(B, device=device) route_pair = torch.zeros(B, K, N, N, device=device, dtype=pos.dtype) p_cand = route_probs[:, :, :N] # [B, K, N] route_pair[b_idx, :, subject, :] = p_cand route_pair[b_idx, :, :, subject] = p_cand
# Pre-allocate output tensors out_xyz = torch.zeros(B, K, horizon, N, 3, device=device, dtype=pos.dtype) out_vel = torch.zeros(B, K, horizon, N, 2, device=device, dtype=pos.dtype) out_imp = torch.zeros(B, K, horizon, N, N, device=device, dtype=pos.dtype) out_gate = torch.zeros(B, K, horizon, N, N, device=device, dtype=pos.dtype)
# Fill observed prefix verbatim up to cut (and anchor cut to s0 so cut->cut+1 has ZERO jump!) for t in range(min(T_pre, horizon)): t_le_cut = (t <= cut).view(B, 1, 1, 1) out_xyz[:, :, t] = torch.where(t_le_cut, prefix[:, t, :, :3].unsqueeze(1), out_xyz[:, :, t]) out_vel[:, :, t] = torch.where(t_le_cut, prefix[:, t, :, 7:9].unsqueeze(1), out_vel[:, :, t]) out_xyz[b_idx, :, cut, :, :2] = pos out_xyz[b_idx, :, cut, :, 2] = z_height out_vel[b_idx, :, cut] = vel
substeps = self.cfg.substeps sub_dt = DT / substeps # Exact pre-edit duration inside the first post-cut frame (cut -> cut+1) before_sec = ((step - 1 - 10 * cut).float() / 240.0).clamp(0.0, DT) # [B] cos_h = torch.cos(eff_heading).view(B, 1) sin_h = torch.sin(eff_heading).view(B, 1) sub_one_hot = F.one_hot(subject, num_classes=N).to(dtype=torch.bool).view(B, 1, N, 1)
reached = F.one_hot(subject, num_classes=N).bool().unsqueeze(1).expand(B, K, N).clone() min_cut = int(cut.min().item()) for t in range(min_cut + 1, horizon): active_scene = (t > cut).view(B, 1, 1) # [B, 1, 1] is_edit_frame = (t == (cut + 1)) # [B] frame_imp = torch.zeros(B, K, N, N, device=device, dtype=pos.dtype) frame_gate = torch.zeros(B, K, N, N, device=device, dtype=pos.dtype)
# Decay global first-hit prior cleanly after edit window (~10 frames) age_after_cut = (t - cut).float().clamp_min(0.0).view(B, 1, 1, 1) rp_t = route_pair * torch.exp(-age_after_cut / 10.0)
for s_idx in range(substeps): # Apply heading intervention at exact sub-step matching `before_sec` (vectorized!) sub_start = s_idx * sub_dt sub_end = (s_idx + 1) * sub_dt apply_here = is_edit_frame & (before_sec >= sub_start - 1e-7) & ( (before_sec < sub_end - 1e-7) | (s_idx == substeps - 1) ) if apply_edit and apply_here.any(): edit_mask = (apply_here & (eff_heading != 0)).view(B, 1, 1, 1) & sub_one_hot # [B, 1, N, 1] vx = vel[..., 0] vy = vel[..., 1] nvx = cos_h.unsqueeze(-1) * vx - sin_h.unsqueeze(-1) * vy nvy = sin_h.unsqueeze(-1) * vx + cos_h.unsqueeze(-1) * vy nv = torch.stack([nvx, nvy], dim=-1) nv_u, nv_spd = _safe_norm(nv) r_spd = torch.linalg.norm(roll, dim=-1, keepdim=True) nr = torch.where((nv_spd > 1e-5).unsqueeze(-1), nv_u * r_spd, roll) vel = torch.where(edit_mask, nv, vel) roll = torch.where(edit_mask, nr, roll)
# 1. Passive free motion p_next, v_next, r_next = self._free_step(pos, vel, roll, static, z, sub_dt) yaw_next = yaw + omega_z * sub_dt
# 2. Stochastic hard-edge momentum-conserving contact attention # Draw by fixed scene, world, frame/substep and pair slot, independently of candidate counts. gate_uniform = torch.rand((gate_rows, K, N, N), generator=gate_rng, device=device) if stochastic_gates else None dv, droll, dpos, imp_s, gate_s = self.contact_attn.step_contacts( p_next, v_next, r_next, yaw_next, static, obj_mask, z, rp_t, sub_dt=sub_dt, tau=tau, stochastic=stochastic_gates, gate_uniform=gate_uniform, reached=reached, subject=subject, ) # Update only from forecast directed impulses above the frozen event threshold. # Changes cannot affect this substep's routing or the first impact. new_recipients = (reached.unsqueeze(-1) & (imp_s.detach() > self.cfg.impact_threshold)).any(dim=-2) reached = reached | (new_recipients & active_scene & obj_mask.unsqueeze(1)) p_next = p_next + dpos v_next = v_next + dv r_next = r_next + droll
# Keep padded/inactive scenes untouched upd_mask = active_scene.unsqueeze(-1) & obj_mask.view(B, 1, N, 1) pos = torch.where(upd_mask, p_next, pos) vel = torch.where(upd_mask, v_next, vel) roll = torch.where(upd_mask, r_next, roll) yaw = torch.where(active_scene & obj_mask.view(B, 1, N), yaw_next, yaw)
frame_imp = torch.maximum(frame_imp, imp_s) frame_gate = torch.maximum(frame_gate, gate_s)
# Store frame t for active scenes store_mask = active_scene.unsqueeze(-1) # [B, 1, 1, 1] xyz_t = torch.cat([pos, z_height.unsqueeze(-1)], dim=-1) out_xyz[:, :, t] = torch.where(store_mask, xyz_t, out_xyz[:, :, t]) out_vel[:, :, t] = torch.where(store_mask, vel, out_vel[:, :, t]) out_imp[:, :, t] = torch.where(active_scene.unsqueeze(-1), frame_imp, out_imp[:, :, t]) out_gate[:, :, t] = torch.where(active_scene.unsqueeze(-1), frame_gate, out_gate[:, :, t])
return { "xyz": out_xyz, # [B, K, 48, N, 3] "vel": out_vel, # [B, K, 48, N, 2] "impulse": out_imp, # [B, K, 48, N, N] (sender -> receiver dv m/s) "contact_prob": out_gate, # [B, K, 48, N, N] "route_logits": route_logits, # [B, K, N+1] }
def trajectory_energy_score( pred_xyz: torch.Tensor, true_xyz: torch.Tensor, mask: torch.Tensor, beta: float = 1.0,) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Strictly proper Energy Score (multivariate CRPS) over K stochastic trajectories.
ES(P, y) = E_P[||X - y||^beta] - 0.5 * E_{P,P}[||X - X'||^beta]
Uniquely minimized iff P == P_true (Gneiting & Raftery, 2007). Actively prevents MSE conditional-mean velocity shrinkage via the diversity term!
Args: pred_xyz: [B, K, T, N, D] true_xyz: [B, T, N, D] mask: [B, T, N] bool (post-cut present objects) """ B, K, T, N, D = pred_xyz.shape m = mask.float() # [B, T, N] denom = m.sum(dim=(1, 2)).clamp_min(1.0) # [B]
# Term 1: accuracy E[||X_k - y||] normalized per valid object-frame diff_gt = pred_xyz - true_xyz.unsqueeze(1) # [B, K, T, N, D] dist_gt = torch.sqrt((diff_gt * diff_gt).sum(dim=-1) + 1e-8) # [B, K, T, N] per_k_err = (dist_gt * m.unsqueeze(1)).sum(dim=(2, 3)) / denom.unsqueeze(1) # [B, K] if beta != 1.0: per_k_err = per_k_err.pow(beta) acc_term = per_k_err.mean(dim=1) # [B]
# Term 2: pairwise dispersion 0.5 * E[||X_k - X_k'||] if K > 1: # Compute pairwise L2 over flattened masked coordinates: [B, K, K] # Per-object-frame Euclidean distance averaged over valid (t, n) (exact frame-wise CRPS!) # Memory-friendly vectorized computation over K pair_sum = torch.zeros(B, device=pred_xyz.device, dtype=pred_xyz.dtype) for k1 in range(K): d_pair = pred_xyz[:, k1:k1 + 1] - pred_xyz[:, k1 + 1:] # [B, K-1-k1, T, N, D] if d_pair.shape[1] == 0: continue l2 = torch.sqrt((d_pair * d_pair).sum(dim=-1) + 1e-8) avg_l2 = (l2 * m.unsqueeze(1)).sum(dim=(2, 3)) / denom.unsqueeze(1) if beta != 1.0: avg_l2 = avg_l2.pow(beta) pair_sum = pair_sum + 2.0 * avg_l2.sum(dim=1) spread_term = pair_sum / (K * (K - 1)) else: spread_term = torch.zeros_like(acc_term)
es = acc_term - 0.5 * spread_term return es.mean(), acc_term.mean(), spread_term.mean()
def gaussian_kl( mu_q: torch.Tensor, log_std_q: torch.Tensor, mu_p: torch.Tensor, log_std_p: torch.Tensor, obj_mask: torch.Tensor,) -> torch.Tensor: """Per-node KL(N(mu_q, std_q^2) || N(mu_p, std_p^2)) masked over valid objects.""" var_q = torch.exp(2.0 * log_std_q) var_p = torch.exp(2.0 * log_std_p) kl = (log_std_p - log_std_q) + (var_q + (mu_q - mu_p) ** 2) / (2.0 * var_p) - 0.5 kl_node = kl.sum(dim=-1) # [B, N] return (kl_node * obj_mask.float()).sum() / obj_mask.float().sum().clamp_min(1.0)
def paired_probabilistic_loss( model: ProbContactAttentionPropagator, batch: dict[str, torch.Tensor], *, K_prior: int = 8, tau: float = 0.5, kl_weight: float = 0.02, effect_weight: float = 0.6, contact_weight: float = 0.25, route_weight: float = 0.15, post_weight: float = 0.5,) -> tuple[torch.Tensor, dict[str, float]]: """Compute Paired Structural Variational + Strictly Proper Energy Score loss.
CRITICAL PROPERTIES: - Zero ground-truth mass labels used anywhere (`attrs` is NEVER accessed!). - Same latent physics Z is shared across factual (apply_edit=False) and counterfactual (apply_edit=True) branches (Pearl structural invariance). - Optimizes BOTH the amortized posterior reconstruction AND the prospective prefix-only predictive distribution (Energy Score on trajectory & paired intervention effect + contact Brier/BCE). """ state_f = batch["state_f"] # [B, 48, N, 13] state_cf = batch["state_cf"] # [B, 48, N, 13] contact_cf = batch["contact_cf"] # [B, 47, N, N] bool present_cf = batch["present_cf"] # [B, 48, N] bool present_f = batch["present_f"] # [B, 48, N] bool static = batch["static"] # [B, N, 8] obj_mask = batch["obj_mask"] # [B, N] bool subject = batch["subject"] # [B] heading = batch["heading"] # [B] step = batch["step"] # [B] cut = (step - 1) // 10 # [B]
B, T, N, _ = state_f.shape device = state_f.device max_cut = int(cut.max().item()) prefix = state_f[:, : max_cut + 1] prefix_len = cut + 1
# Mask strictly post-cut valid object-frames t_grid = torch.arange(T, device=device).view(1, T, 1) post_mask_cf = (t_grid > cut.view(B, 1, 1)) & present_cf & obj_mask.view(B, 1, N) post_mask_both = post_mask_cf & present_f
# 1. Prefix-only Prior p_theta(Z | prefix) & Amortized Posterior q_psi(Z | state_cf) mu_p, lstd_p = model.prior(prefix, static, prefix_len) mu_q, lstd_q = model.posterior(state_cf, static, obj_mask, present_cf) loss_kl = gaussian_kl(mu_q, lstd_q, mu_p, lstd_p, obj_mask)
# 2 & 3. Fused Single-Call Rollout: [cf, f] along batch (2*B) x [z_post, z_prior] along K (1+K_prior)! # Mathematically identical to 4 separate rollout calls, ~4x faster on GPU. z_post = model.sample_latents(mu_q, lstd_q, K=1) z_prior = model.sample_latents(mu_p, lstd_p, K=K_prior) z_all = torch.cat([z_post, z_prior], dim=1) # [B, 1+K_prior, N, z_dim]
prefix_2 = torch.cat([prefix, prefix], dim=0) static_2 = torch.cat([static, static], dim=0) mask_2 = torch.cat([obj_mask, obj_mask], dim=0) subj_2 = torch.cat([subject, subject], dim=0) head_2 = torch.cat([heading, torch.zeros_like(heading)], dim=0) step_2 = torch.cat([step, step], dim=0) cut_2 = torch.cat([cut, cut], dim=0) z_2 = torch.cat([z_all, z_all], dim=0)
out_all = model.rollout( prefix_2, static_2, mask_2, subj_2, head_2, step_2, cut_2, z_2, apply_edit=True, tau=tau, stochastic_gates=True, paired_batch=True, )
xyz_cf_all = out_all["xyz"][:B] # [B, 1+K_prior, 48, N, 3] xyz_f_all = out_all["xyz"][B:] vel_cf_all = out_all["vel"][:B] imp_cf_pr = out_all["impulse"][:B, 1:] gate_cf_pr = out_all["contact_prob"][:B, 1:] rlog_cf_pr = out_all["route_logits"][:B, 1:]
# Posterior Reconstruction Path (index 0): teaches exact latent-mass contact dynamics! diff_post = xyz_cf_all[:, 0, :, :, :2] - state_cf[:, :, :, :2] loss_post_pos = (F.smooth_l1_loss(diff_post, torch.zeros_like(diff_post), beta=0.05, reduction="none").sum(-1) * post_mask_cf.float()).sum() / post_mask_cf.float().sum().clamp_min(1.0) diff_post_v = vel_cf_all[:, 0] - state_cf[:, :, :, 7:9] loss_post_vel = (F.smooth_l1_loss(diff_post_v, torch.zeros_like(diff_post_v), beta=0.15, reduction="none").sum(-1) * post_mask_cf.float()).sum() / post_mask_cf.float().sum().clamp_min(1.0) diff_post_f = xyz_f_all[:, 0, :, :, :2] - state_f[:, :, :, :2] loss_post_f = (F.smooth_l1_loss(diff_post_f, torch.zeros_like(diff_post_f), beta=0.05, reduction="none").sum(-1) * post_mask_both.float()).sum() / post_mask_both.float().sum().clamp_min(1.0) loss_post = loss_post_pos + 0.35 * loss_post_vel + 0.4 * loss_post_f
# Prospective Prior Path (indices 1..K_prior): Strictly Proper Energy Score on BOTH # (a) Counterfactual Trajectory S_cf and (b) Paired Intervention Effect (S_cf - S_f)! xyz_cf_pr = xyz_cf_all[:, 1:] xyz_f_pr = xyz_f_all[:, 1:] vel_cf_pr = vel_cf_all[:, 1:]
loss_es_pos, acc_pos, spr_pos = trajectory_energy_score( xyz_cf_pr[..., :2], state_cf[..., :2], post_mask_cf ) loss_es_vel, _, _ = trajectory_energy_score( vel_cf_pr, state_cf[..., 7:9], post_mask_cf )
pred_eff = xyz_cf_pr[..., :2] - xyz_f_pr[..., :2] true_eff = state_cf[..., :2] - state_f[..., :2] loss_es_eff, acc_eff, spr_eff = trajectory_energy_score(pred_eff, true_eff, post_mask_both)
# 4. Distributional Contact-Event Proper Scoring Rule (Brier on marginal contact probs) gt_ct = contact_cf.float() # [B, 47, N, N] pred_ct_prob = gate_cf_pr[:, :, 1:].mean(dim=1) # [B, 47, N, N] imp_prob = torch.sigmoid((imp_cf_pr[:, :, 1:] - model.cfg.impact_threshold) / 0.05).mean(dim=1) marg_ct = 0.5 * (pred_ct_prob + imp_prob) eye = torch.eye(N, device=device, dtype=torch.bool).view(1, 1, N, N) ct_tmask = (torch.arange(1, T, device=device).view(1, T - 1, 1, 1) > cut.view(B, 1, 1, 1)) ct_valid = ct_tmask & obj_mask.view(B, 1, N, 1) & obj_mask.view(B, 1, 1, N) & (~eye) gt_ct_sym = torch.maximum(gt_ct, gt_ct.transpose(-1, -2)) pos_w = torch.where(gt_ct_sym > 0.5, torch.full_like(gt_ct_sym, 12.0), torch.ones_like(gt_ct_sym)) brier_ct = ((marg_ct - gt_ct_sym) ** 2 * pos_w * ct_valid.float()).sum() / ct_valid.float().sum().clamp_min(1.0)
# 5. Global First-Recipient Probabilistic Attention NLL (Cross-Entropy) first_targets = torch.full((B,), N, device=device, dtype=torch.long) # default = null class N for b_i in range(B): si = int(subject[b_i].item()) c_i = int(cut[b_i].item()) ct_sub = contact_cf[b_i, c_i:, si, :].clone() # [47-c_i, N] ct_sub[:, si] = False hits = torch.nonzero(ct_sub.any(dim=-1), as_tuple=False) if len(hits) > 0: f0 = int(hits[0].item()) recs = torch.nonzero(ct_sub[f0], as_tuple=False).flatten() if len(recs) == 1: first_targets[b_i] = int(recs[0].item()) r_logits = rlog_cf_pr.mean(dim=1) # [B, N+1] loss_route = F.cross_entropy(r_logits, first_targets)
total = ( loss_es_pos + 0.25 * loss_es_vel + effect_weight * loss_es_eff + post_weight * loss_post + kl_weight * loss_kl + contact_weight * brier_ct + route_weight * loss_route )
metrics = { "total": float(total.detach()), "es_pos": float(loss_es_pos.detach()), "es_acc": float(acc_pos.detach()), "es_spread": float(spr_pos.detach()), "es_eff": float(loss_es_eff.detach()), "post_pos": float(loss_post_pos.detach()), "kl": float(loss_kl.detach()), "ct_brier": float(brier_ct.detach()), "route_ce": float(loss_route.detach()), } return total, metrics12345678910111213141516171819202122232425"""Load the prospective epoch-11 model and its secondary-contact impulse correction."""import hashlibfrom pathlib import Path
import torchfrom importlib import import_module
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def load_corrected(base_checkpoint, adapter_checkpoint, device, variant=None): base = torch.load(base_checkpoint, map_location="cpu", weights_only=False) fit = None if adapter_checkpoint is None else torch.load(adapter_checkpoint,map_location="cpu",weights_only=False) variant = fit.get("variant","values") if fit is not None else (variant or "values") if variant not in ("values","direction_speed"):raise ValueError(variant) mod=import_module("transfer_dynamics" if variant=="values" else "transfer_direction_dynamics") model = mod.ProbContactAttentionPropagator(mod.ProbContactConfig(**base["config"])) missing, extra = model.load_state_dict(base["state_dict"], strict=False) assert set(missing) == {"contact_attn.transfer_head.weight","contact_attn.transfer_head.bias"} and not extra model.requires_grad_(False) if fit is not None: if fit["base_sha256"] != digest(base_checkpoint): raise ValueError("Velocity-transfer adapter was fit against different base weights") model.contact_attn.transfer_head.load_state_dict(fit["head"],strict=True) return model.to(device).eval()1234567891011121314151617181920212223242526272829"""Validate the selected checkpoint’s H1/H2 sender-mass fractions on eligible validation branches."""import argparse,jsonfrom pathlib import Pathimport numpy as npimport torchfrom train_transfer import examples,save_jsonfrom mass_transfer import load_correctedfrom transfer_model import digest
@torch.no_grad()def main(): p=argparse.ArgumentParser() for name in ('root','base','data'):p.add_argument('--'+name,type=Path,required=True) a=p.parse_args();d=a.root/'candidates/prefix_mass';lock=json.loads((d/'model_lock.json').read_bytes());assert digest(d/'best.pt')==lock['checkpoint_sha256'] m=load_corrected(a.base,d/'best.pt','cuda');data=torch.load(a.data,weights_only=False,mmap=True,map_location='cpu') ids=json.loads((a.root/'splits.json').read_bytes())['catalog']['val'];ix={s:i for i,s in enumerate(data['scene_ids'])} va=examples(data,ids,ix); vals={k:{t:[] for t in ('sim','frozen','corrected')} for k in ('A_into_B','B_into_C')} for start in range(0,len(va),100): b=torch.as_tensor(va[start:start+100]);j=b[:,0];cut=(data['step'][j].cuda()-1)//10;stat=data['static'][j].cuda() prefix=data['state_f'][j,:int(cut.max())+1].cuda();prefix=prefix.masked_fill((torch.arange(prefix.size(1),device='cuda')[None,:]>cut[:,None])[:,:,None,None],0.) lo,_=m.prior.original(prefix,stat,cut+1);lc,_=m.prior(prefix,stat,cut+1);attrs=data['attrs'][j,:,0];clip=m.cfg.log_mass_clip for k,sender,target in [('A_into_B',data['subject'][j],b[:,2]),('B_into_C',b[:,2],b[:,3])]: for name,q in [('sim',attrs),('frozen',lo[...,0].clamp(-clip,clip).cpu()),('corrected',lc[...,0].clamp(-clip,clip).cpu())]: index=torch.arange(len(b));share=(q[index,sender]-q[index,target]).sigmoid();vals[k][name].extend(share.tolist()) def summary(row): t=np.asarray(row['sim']);return {k:{'mean':float(np.mean(y)),'abs_error':float(np.abs(np.asarray(y)-t).mean()),'signed_error':float((np.asarray(y)-t).mean())} for k,y in row.items()} save_json(d/'validation_mass_shares.json',{'subset':'All 1069 train-selection validation branches with eligible H2, factual or edited; latent prior mean world only; labels for scoring, no resets', 'branches':len(va),'distinct_scenes':len(set(va[:,0])),'checkpoint_sha256':digest(d/'best.pt'),'sender_fraction':{k:summary(v) for k,v in vals.items()}})if __name__=='__main__':main()1234567{ "variant": "direction_speed", "changed": "bounded rotation of symmetric contact impulse basis up to 15 degrees and bounded restitution/friction residual on all predicted path first touches including H1", "trigger": "before any corrected test predictions, motivated by source audit of historical 29. H1 B speed also underestimated", "supervision": "0.5 original vector/path losses plus .45 C magnitude, .30 C magnitude among H3-positive training paths, .30 B magnitude at first hit; asymmetric Huber underprediction weight 1.5", "selection": "same registered original validation score; 6 epochs; frozen gate and positive inferred latent masses; identity and secondary-only fit both retained; publish best trained and disclose if identity wins"}12345678910111213141516171819202122232425262728293031{ "learned_parameters": 27, "finite_weights_and_gradients": true, "verification_gradient_norm": 0.48160088062286377, "latent_mass_preserved": true, "restitution_range": [ 0, 0.92 ], "friction_range": [ 0, 0.6 ], "maximum_direction_adjustment_degrees": 15, "base_sha256": "26b50b3a87dc61fe92e71007b5e35467a6761fef96bab0c474448424a5272187", "adapter_sha": "ce300934b2534be05320c15941acd737d9984db78870c2fbc0093ee9e52e427a", "frozen_parameter_max_diff": 0.0, "no_op_max": { "xyz": 0.0, "vel": 0.0, "impulse": 0.0, "contact_prob": 0.0, "route_logits": 0.0 }, "first_events_equal": 228, "first_event_equality_checked_worlds": 228, "positions_before_first_impact_max_diff_m": 0.0, "synthetic_two_body_impacts": 50, "net_impulse_max_abs": 4.76837158203125e-07, "max_planar_kinetic_energy_gain": -0.24796515703201294}attention_secondary_motion_transfer_20261202/candidates/direction_speed/best.ptAdded+3
attention_secondary_motion_transfer_20261202/candidates/direction_speed/finished.jsonAdded+36
attention_secondary_motion_transfer_20261202/candidates/direction_speed/history.jsonAdded+119
attention_secondary_motion_transfer_20261202/candidates/direction_speed/identity.ptAdded+3
attention_secondary_motion_transfer_20261202/candidates/direction_speed/last.ptAdded+3
attention_secondary_motion_transfer_20261202/candidates/direction_speed/registration.jsonAdded+23
attention_secondary_motion_transfer_20261202/candidates/prefix_mass/best.ptAdded+3
attention_secondary_motion_transfer_20261202/candidates/prefix_mass/history.jsonAdded+77
attention_secondary_motion_transfer_20261202/candidates/prefix_mass/model_lock.jsonAdded+53
attention_secondary_motion_transfer_20261202/candidates/prefix_mass/protocol.jsonAdded+10
attention_secondary_motion_transfer_20261202/candidates/prefix_mass/validation_mass_shares.jsonAdded+42
attention_secondary_motion_transfer_20261202/candidates/provenance.jsonAdded+187
attention_secondary_motion_transfer_20261202/candidates/values/best.ptAdded+3
attention_secondary_motion_transfer_20261202/candidates/values/finished.jsonAdded+36
attention_secondary_motion_transfer_20261202/candidates/values/history.jsonAdded+119
attention_secondary_motion_transfer_20261202/candidates/values/identity.ptAdded+3
attention_secondary_motion_transfer_20261202/candidates/values/last.ptAdded+3
attention_secondary_motion_transfer_20261202/candidates/values/registration.jsonAdded+22
attention_secondary_motion_transfer_20261202/code/build_transfer.pyAdded+86
attention_secondary_motion_transfer_20261202/code/check_transfer.pyAdded+89
attention_secondary_motion_transfer_20261202/code/finalize_transfer.pyAdded+38
attention_secondary_motion_transfer_20261202/code/mass_transfer.pyAdded+49
attention_secondary_motion_transfer_20261202/code/run_training.pyAdded+32
attention_secondary_motion_transfer_20261202/code/train_mass_transfer.pyAdded+90
attention_secondary_motion_transfer_20261202/code/train_transfer.pyAdded+273
attention_secondary_motion_transfer_20261202/code/transfer_direction_dynamics.pyAdded+1238
attention_secondary_motion_transfer_20261202/code/transfer_dynamics.pyAdded+1229
attention_secondary_motion_transfer_20261202/code/transfer_model.pyAdded+25
attention_secondary_motion_transfer_20261202/code/verify_mass_shares.pyAdded+29
attention_secondary_motion_transfer_20261202/direction_registration.jsonAdded+7
attention_secondary_motion_transfer_20261202/train/verification.jsonAdded+31