diff --git a/model/tachin_paired30_cache_20260923/cache/bases/smolvla/test/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/test/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..17840486a74c040bab84a6c46ea8a10f231b84e5 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/test/complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "smolvla", + "split": "test", + "rows": 1169, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/smolvla/best.pt", + "checkpoint_sha256": "c427d2a44799d371f6c5c57cd008f5910ebc57580f404f8e68bec356793dab0c", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/smolvla_official/best.pt", + "initial_sha256": "cdb1acffa5ac98eb872d35cf654d551dcbabc68b95b6c1b7ddc7442bd6a6c0c1", + "initial_step": 18000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "smolvla", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 100284352, + "frozen_parameters": 350165184, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/smolvla/test/smoke_complete.json b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/test/smoke_complete.json new file mode 100644 index 0000000000000000000000000000000000000000..62f4cbfb9a6727fafa17a185bbf5137140db0d82 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/test/smoke_complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "smolvla", + "split": "test", + "rows": 2, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/smolvla/best.pt", + "checkpoint_sha256": "c427d2a44799d371f6c5c57cd008f5910ebc57580f404f8e68bec356793dab0c", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/smolvla_official/best.pt", + "initial_sha256": "cdb1acffa5ac98eb872d35cf654d551dcbabc68b95b6c1b7ddc7442bd6a6c0c1", + "initial_step": 18000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "smolvla", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 100284352, + "frozen_parameters": 350165184, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/smolvla/train/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/train/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..b846ca52e5f9d717448d7a845cd4ab1591cc58ee --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/train/complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "smolvla", + "split": "train", + "rows": 18208, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/smolvla/best.pt", + "checkpoint_sha256": "c427d2a44799d371f6c5c57cd008f5910ebc57580f404f8e68bec356793dab0c", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/smolvla_official/best.pt", + "initial_sha256": "cdb1acffa5ac98eb872d35cf654d551dcbabc68b95b6c1b7ddc7442bd6a6c0c1", + "initial_step": 18000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "smolvla", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 100284352, + "frozen_parameters": 350165184, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/smolvla/train/smoke_complete.json b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/train/smoke_complete.json new file mode 100644 index 0000000000000000000000000000000000000000..d19ddb9fb0a152e39538969300a910b42715b3e4 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/train/smoke_complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "smolvla", + "split": "train", + "rows": 2, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/smolvla/best.pt", + "checkpoint_sha256": "c427d2a44799d371f6c5c57cd008f5910ebc57580f404f8e68bec356793dab0c", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/smolvla_official/best.pt", + "initial_sha256": "cdb1acffa5ac98eb872d35cf654d551dcbabc68b95b6c1b7ddc7442bd6a6c0c1", + "initial_step": 18000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "smolvla", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 100284352, + "frozen_parameters": 350165184, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/smolvla/val/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/val/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..b31753e63666661147299615b11eb22bb38efc2d --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/val/complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "smolvla", + "split": "val", + "rows": 1006, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/smolvla/best.pt", + "checkpoint_sha256": "c427d2a44799d371f6c5c57cd008f5910ebc57580f404f8e68bec356793dab0c", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/smolvla_official/best.pt", + "initial_sha256": "cdb1acffa5ac98eb872d35cf654d551dcbabc68b95b6c1b7ddc7442bd6a6c0c1", + "initial_step": 18000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "smolvla", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 100284352, + "frozen_parameters": 350165184, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/smolvla/val/smoke_complete.json b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/val/smoke_complete.json new file mode 100644 index 0000000000000000000000000000000000000000..9fce48be2b46e3fdb3ead2bd32f98f0b5fb05a38 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/smolvla/val/smoke_complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "smolvla", + "split": "val", + "rows": 2, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/smolvla/best.pt", + "checkpoint_sha256": "c427d2a44799d371f6c5c57cd008f5910ebc57580f404f8e68bec356793dab0c", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/smolvla_official/best.pt", + "initial_sha256": "cdb1acffa5ac98eb872d35cf654d551dcbabc68b95b6c1b7ddc7442bd6a6c0c1", + "initial_step": 18000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "smolvla", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 100284352, + "frozen_parameters": 350165184, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..49659c4ddd21f2f95256dccc110757e9e30e546b --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "test", + "rows": 1169, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_00_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_00_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..160641bdf29a90f50aed5bee2f353527fb6e4b40 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_00_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "test", + "rows": 1169, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 293, + "shard": 0, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_01_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_01_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..68d83543762c144a93db80bde91205ba97f07685 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_01_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "test", + "rows": 1169, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 292, + "shard": 1, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_02_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_02_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..9c9bc6c60478e068b6d551944f571831f126158f --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_02_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "test", + "rows": 1169, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 292, + "shard": 2, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_03_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_03_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..4e0745abebab7be0da044c39a489733fe9b7512a --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/complete_shard_03_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "test", + "rows": 1169, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 292, + "shard": 3, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/test/smoke_complete.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/smoke_complete.json new file mode 100644 index 0000000000000000000000000000000000000000..0e50f04f7b7390a005358bed9c7c054052e027c5 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/test/smoke_complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "test", + "rows": 1, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..4844e7100958f2dbc49ef6472fa04a9be0ed7dcc --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "train", + "rows": 18208, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_00_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_00_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..342da29486599d0d858893d8dce74d7b8fa74833 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_00_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "train", + "rows": 18208, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 4552, + "shard": 0, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_01_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_01_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..a3789231ffc9d1aa8d711eaf9a73403a398a18d9 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_01_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "train", + "rows": 18208, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 4552, + "shard": 1, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_02_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_02_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..40aec184b1ff7edfc94ddd00ca6c4d37f79bf41f --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_02_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "train", + "rows": 18208, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 4552, + "shard": 2, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_03_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_03_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..8fd0eb07aea8773600190b545879d2cebd1a6bd8 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/complete_shard_03_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "train", + "rows": 18208, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 4552, + "shard": 3, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/train/smoke_complete.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/smoke_complete.json new file mode 100644 index 0000000000000000000000000000000000000000..82cfd4fb8195fb0329ca5e77788b9a9f12da7319 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/train/smoke_complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "train", + "rows": 1, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..ecbbcdd1ca197e844e03221b06876dbcc0229610 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "val", + "rows": 1006, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_00_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_00_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..88f8fee1d22d3f8b68e632c7c9ed0480377a0e3c --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_00_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "val", + "rows": 1006, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 252, + "shard": 0, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_01_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_01_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..238141fd60934ff65426e2288643c52665e5857e --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_01_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "val", + "rows": 1006, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 252, + "shard": 1, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_02_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_02_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..0e14c81ef89f982a6f159354b681647a863fd7f6 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_02_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "val", + "rows": 1006, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 251, + "shard": 2, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_03_of_04.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_03_of_04.json new file mode 100644 index 0000000000000000000000000000000000000000..1a4eb8fea27608fa6c8c7d77fce13ba4032df865 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/complete_shard_03_of_04.json @@ -0,0 +1,33 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "val", + "rows": 1006, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + }, + "assigned_rows": 251, + "shard": 3, + "shards": 4 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/trex/val/smoke_complete.json b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/smoke_complete.json new file mode 100644 index 0000000000000000000000000000000000000000..f71586e936d6b06c05ec15b71a0bf296c07ff699 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/trex/val/smoke_complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "trex", + "split": "val", + "rows": 1, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/trex/best.pt", + "checkpoint_sha256": "ad61d4665fcc29191b1e5f670540f33e8e83abaf20a19c4a60ca9a4b652fc478", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": null, + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/trex_runs/g3_lora/best.pt", + "initial_sha256": "a0bdf8b91a795c3746b293ba633a995da55226476bd45ca77e9880bb06efe717", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "trex", + "renamed_vision_wrapper_keys": 0, + "trainable_parameters": 22026432, + "frozen_parameters": 3541664768, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/twla/test/shard_00/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/twla/test/shard_00/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..e41e8fcb3c3557fd651c7f0d18858ef2dd472e8b --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/twla/test/shard_00/complete.json @@ -0,0 +1,22 @@ +{ + "schema": "tachin.table1.twla_w3_cache.v1", + "split": "test", + "shard": 0, + "shards": 2, + "rows": 585, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/runs/twla_tachin_common_adaptation_20260922/best.pt", + "checkpoint_sha256": "8df6c87fda2e5ec09d61686451744c37bdcc2d1b4d9d13b58893851be620db7d", + "checkpoint_step": 800, + "checkpoint_is_tachin_adapted": true, + "adaptation_protocol": "Tachin-only expert adaptation from T-WLA-110k", + "adaptation_initial_checkpoint": "checkpoints/v4d_ten_stageA/best.pt", + "adaptation_initial_sha256": "ccd65fcf845ec01c7de46bb76e9cf0fee33674dd848771e114ff23b2535f13d9", + "adaptation_common_complete_sha256": "1cffe026d12e556cc2f66fbda0b34a65a985f50d7aeb0a5adb50571e8437e740", + "memory_protocol": "up to eight available 10-Hz historical observations plus current", + "noise": "per-row torch seed 20260922 + zero-based common row index", + "world_checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/checkpoints/v4d_world_stage1/last.pt", + "world_checkpoint_sha256": "1ce7c8fad5fca3f5c19246f88d48ca53e75aee1402ad7ec743350ed3cbd534bb", + "max_common_target_difference": 0.19084084033966064, + "common_mask_mismatches": 0, + "seconds": 130.8162066936493 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/twla/test/shard_01/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/twla/test/shard_01/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..8c242a0e768d332094ea1f5e1b7f7481fa6a1e9c --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/twla/test/shard_01/complete.json @@ -0,0 +1,22 @@ +{ + "schema": "tachin.table1.twla_w3_cache.v1", + "split": "test", + "shard": 1, + "shards": 2, + "rows": 584, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/runs/twla_tachin_common_adaptation_20260922/best.pt", + "checkpoint_sha256": "8df6c87fda2e5ec09d61686451744c37bdcc2d1b4d9d13b58893851be620db7d", + "checkpoint_step": 800, + "checkpoint_is_tachin_adapted": true, + "adaptation_protocol": "Tachin-only expert adaptation from T-WLA-110k", + "adaptation_initial_checkpoint": "checkpoints/v4d_ten_stageA/best.pt", + "adaptation_initial_sha256": "ccd65fcf845ec01c7de46bb76e9cf0fee33674dd848771e114ff23b2535f13d9", + "adaptation_common_complete_sha256": "1cffe026d12e556cc2f66fbda0b34a65a985f50d7aeb0a5adb50571e8437e740", + "memory_protocol": "up to eight available 10-Hz historical observations plus current", + "noise": "per-row torch seed 20260922 + zero-based common row index", + "world_checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/checkpoints/v4d_world_stage1/last.pt", + "world_checkpoint_sha256": "1ce7c8fad5fca3f5c19246f88d48ca53e75aee1402ad7ec743350ed3cbd534bb", + "max_common_target_difference": 0.19073008000850677, + "common_mask_mismatches": 0, + "seconds": 101.12281584739685 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/twla/train/shard_00/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/twla/train/shard_00/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..4dda61af1e237bc67a0ac876d27331f2e862334a --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/twla/train/shard_00/complete.json @@ -0,0 +1,22 @@ +{ + "schema": "tachin.table1.twla_w3_cache.v1", + "split": "train", + "shard": 0, + "shards": 2, + "rows": 9104, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/runs/twla_tachin_common_adaptation_20260922/best.pt", + "checkpoint_sha256": "8df6c87fda2e5ec09d61686451744c37bdcc2d1b4d9d13b58893851be620db7d", + "checkpoint_step": 800, + "checkpoint_is_tachin_adapted": true, + "adaptation_protocol": "Tachin-only expert adaptation from T-WLA-110k", + "adaptation_initial_checkpoint": "checkpoints/v4d_ten_stageA/best.pt", + "adaptation_initial_sha256": "ccd65fcf845ec01c7de46bb76e9cf0fee33674dd848771e114ff23b2535f13d9", + "adaptation_common_complete_sha256": "1cffe026d12e556cc2f66fbda0b34a65a985f50d7aeb0a5adb50571e8437e740", + "memory_protocol": "up to eight available 10-Hz historical observations plus current", + "noise": "per-row torch seed 20260922 + zero-based common row index", + "world_checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/checkpoints/v4d_world_stage1/last.pt", + "world_checkpoint_sha256": "1ce7c8fad5fca3f5c19246f88d48ca53e75aee1402ad7ec743350ed3cbd534bb", + "max_common_target_difference": 0.3907139301300049, + "common_mask_mismatches": 414, + "seconds": 1011.7041006088257 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/twla/train/shard_01/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/twla/train/shard_01/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..bd4f70b72b44e56b07ee3cc943a41c563c7c2777 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/twla/train/shard_01/complete.json @@ -0,0 +1,22 @@ +{ + "schema": "tachin.table1.twla_w3_cache.v1", + "split": "train", + "shard": 1, + "shards": 2, + "rows": 9104, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/runs/twla_tachin_common_adaptation_20260922/best.pt", + "checkpoint_sha256": "8df6c87fda2e5ec09d61686451744c37bdcc2d1b4d9d13b58893851be620db7d", + "checkpoint_step": 800, + "checkpoint_is_tachin_adapted": true, + "adaptation_protocol": "Tachin-only expert adaptation from T-WLA-110k", + "adaptation_initial_checkpoint": "checkpoints/v4d_ten_stageA/best.pt", + "adaptation_initial_sha256": "ccd65fcf845ec01c7de46bb76e9cf0fee33674dd848771e114ff23b2535f13d9", + "adaptation_common_complete_sha256": "1cffe026d12e556cc2f66fbda0b34a65a985f50d7aeb0a5adb50571e8437e740", + "memory_protocol": "up to eight available 10-Hz historical observations plus current", + "noise": "per-row torch seed 20260922 + zero-based common row index", + "world_checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/checkpoints/v4d_world_stage1/last.pt", + "world_checkpoint_sha256": "1ce7c8fad5fca3f5c19246f88d48ca53e75aee1402ad7ec743350ed3cbd534bb", + "max_common_target_difference": 0.39840880036354065, + "common_mask_mismatches": 621, + "seconds": 881.0313642024994 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/twla/val/shard_00/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/twla/val/shard_00/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..38904e732d5fa4de91721a39d6bdbf44e105bb2b --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/twla/val/shard_00/complete.json @@ -0,0 +1,22 @@ +{ + "schema": "tachin.table1.twla_w3_cache.v1", + "split": "val", + "shard": 0, + "shards": 2, + "rows": 503, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/runs/twla_tachin_common_adaptation_20260922/best.pt", + "checkpoint_sha256": "8df6c87fda2e5ec09d61686451744c37bdcc2d1b4d9d13b58893851be620db7d", + "checkpoint_step": 800, + "checkpoint_is_tachin_adapted": true, + "adaptation_protocol": "Tachin-only expert adaptation from T-WLA-110k", + "adaptation_initial_checkpoint": "checkpoints/v4d_ten_stageA/best.pt", + "adaptation_initial_sha256": "ccd65fcf845ec01c7de46bb76e9cf0fee33674dd848771e114ff23b2535f13d9", + "adaptation_common_complete_sha256": "1cffe026d12e556cc2f66fbda0b34a65a985f50d7aeb0a5adb50571e8437e740", + "memory_protocol": "up to eight available 10-Hz historical observations plus current", + "noise": "per-row torch seed 20260922 + zero-based common row index", + "world_checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/checkpoints/v4d_world_stage1/last.pt", + "world_checkpoint_sha256": "1ce7c8fad5fca3f5c19246f88d48ca53e75aee1402ad7ec743350ed3cbd534bb", + "max_common_target_difference": 0.14446601271629333, + "common_mask_mismatches": 0, + "seconds": 127.37033939361572 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/twla/val/shard_01/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/twla/val/shard_01/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..cf68b1dbf9cfb45cad8f060899893464d8022747 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/twla/val/shard_01/complete.json @@ -0,0 +1,22 @@ +{ + "schema": "tachin.table1.twla_w3_cache.v1", + "split": "val", + "shard": 1, + "shards": 2, + "rows": 503, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/runs/twla_tachin_common_adaptation_20260922/best.pt", + "checkpoint_sha256": "8df6c87fda2e5ec09d61686451744c37bdcc2d1b4d9d13b58893851be620db7d", + "checkpoint_step": 800, + "checkpoint_is_tachin_adapted": true, + "adaptation_protocol": "Tachin-only expert adaptation from T-WLA-110k", + "adaptation_initial_checkpoint": "checkpoints/v4d_ten_stageA/best.pt", + "adaptation_initial_sha256": "ccd65fcf845ec01c7de46bb76e9cf0fee33674dd848771e114ff23b2535f13d9", + "adaptation_common_complete_sha256": "1cffe026d12e556cc2f66fbda0b34a65a985f50d7aeb0a5adb50571e8437e740", + "memory_protocol": "up to eight available 10-Hz historical observations plus current", + "noise": "per-row torch seed 20260922 + zero-based common row index", + "world_checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/checkpoints/v4d_world_stage1/last.pt", + "world_checkpoint_sha256": "1ce7c8fad5fca3f5c19246f88d48ca53e75aee1402ad7ec743350ed3cbd534bb", + "max_common_target_difference": 0.16731011867523193, + "common_mask_mismatches": 0, + "seconds": 65.5791323184967 +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/vitra/test/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/vitra/test/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..ca7df2a0fe0f8a7544d43ba2ba0a79e019a08948 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/vitra/test/complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "vitra", + "split": "test", + "rows": 1169, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/vitra/best.pt", + "checkpoint_sha256": "953d60fbf9b65b7a94ede70c82dd84def60da3cc20c8fce3868efaa30d29f4dc", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": "native MANO_LEFT/MANO_RIGHT", + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/vitra_original/best.pt", + "initial_sha256": "3c4765c0497ad0c7a702b26948683f9218283412d0aafa219de25dcd3bf077f7", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "vitra", + "renamed_vision_wrapper_keys": 437, + "trainable_parameters": 141907392, + "frozen_parameters": 3032242416, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/vitra/test/smoke_complete.json b/model/tachin_paired30_cache_20260923/cache/bases/vitra/test/smoke_complete.json new file mode 100644 index 0000000000000000000000000000000000000000..c7a65c349b570e04cb63da42999c472aa152b825 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/vitra/test/smoke_complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "vitra", + "split": "test", + "rows": 2, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/vitra/best.pt", + "checkpoint_sha256": "953d60fbf9b65b7a94ede70c82dd84def60da3cc20c8fce3868efaa30d29f4dc", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": "native MANO_LEFT/MANO_RIGHT", + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/vitra_original/best.pt", + "initial_sha256": "3c4765c0497ad0c7a702b26948683f9218283412d0aafa219de25dcd3bf077f7", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "vitra", + "renamed_vision_wrapper_keys": 437, + "trainable_parameters": 141907392, + "frozen_parameters": 3032242416, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/vitra/train/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/vitra/train/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..1fd2e1196740bd86f6f6c08e35e9c693c0a72764 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/vitra/train/complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "vitra", + "split": "train", + "rows": 18208, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/vitra/best.pt", + "checkpoint_sha256": "953d60fbf9b65b7a94ede70c82dd84def60da3cc20c8fce3868efaa30d29f4dc", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": "native MANO_LEFT/MANO_RIGHT", + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/vitra_original/best.pt", + "initial_sha256": "3c4765c0497ad0c7a702b26948683f9218283412d0aafa219de25dcd3bf077f7", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "vitra", + "renamed_vision_wrapper_keys": 437, + "trainable_parameters": 141907392, + "frozen_parameters": 3032242416, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/vitra/train/smoke_complete.json b/model/tachin_paired30_cache_20260923/cache/bases/vitra/train/smoke_complete.json new file mode 100644 index 0000000000000000000000000000000000000000..06b2ead8b57519c0293abc1cb8922d6abfe29720 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/vitra/train/smoke_complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "vitra", + "split": "train", + "rows": 2, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/vitra/best.pt", + "checkpoint_sha256": "953d60fbf9b65b7a94ede70c82dd84def60da3cc20c8fce3868efaa30d29f4dc", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": "native MANO_LEFT/MANO_RIGHT", + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/vitra_original/best.pt", + "initial_sha256": "3c4765c0497ad0c7a702b26948683f9218283412d0aafa219de25dcd3bf077f7", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "vitra", + "renamed_vision_wrapper_keys": 437, + "trainable_parameters": 141907392, + "frozen_parameters": 3032242416, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/vitra/val/complete.json b/model/tachin_paired30_cache_20260923/cache/bases/vitra/val/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..21b9711cb04084af16c3252c8c84386de630bea3 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/vitra/val/complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "vitra", + "split": "val", + "rows": 1006, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/vitra/best.pt", + "checkpoint_sha256": "953d60fbf9b65b7a94ede70c82dd84def60da3cc20c8fce3868efaa30d29f4dc", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": "native MANO_LEFT/MANO_RIGHT", + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/vitra_original/best.pt", + "initial_sha256": "3c4765c0497ad0c7a702b26948683f9218283412d0aafa219de25dcd3bf077f7", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "vitra", + "renamed_vision_wrapper_keys": 437, + "trainable_parameters": 141907392, + "frozen_parameters": 3032242416, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/bases/vitra/val/smoke_complete.json b/model/tachin_paired30_cache_20260923/cache/bases/vitra/val/smoke_complete.json new file mode 100644 index 0000000000000000000000000000000000000000..5d723b90704052bfd38c587dd96f45bbe0ee3aec --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/bases/vitra/val/smoke_complete.json @@ -0,0 +1,30 @@ +{ + "schema": "tachin.table1.frozen_base.v1", + "model": "vitra", + "split": "val", + "rows": 2, + "checkpoint": "/scratch/hannahyao24/VLA-tactile_paper/artifacts/huggingface/vla-hand-baselines/model/tachin_adaptation_20260922/vitra/best.pt", + "checkpoint_sha256": "953d60fbf9b65b7a94ede70c82dd84def60da3cc20c8fce3868efaa30d29f4dc", + "adaptation_step": 1000, + "noise": "per-row torch seed 20260922 + zero-based common row index", + "output": "physical canonical [16,192] keypoint action", + "vitra_fk": "native MANO_LEFT/MANO_RIGHT", + "audit": { + "initial_checkpoint": "/scratch/chonghej/VLA/checkpoints/vla-hand-baselines/vitra_original/best.pt", + "initial_sha256": "3c4765c0497ad0c7a702b26948683f9218283412d0aafa219de25dcd3bf077f7", + "initial_step": 10000, + "initial_training_sources": [ + "gigahands", + "oakink2", + "taco" + ], + "model": "vitra", + "renamed_vision_wrapper_keys": 437, + "trainable_parameters": 141907392, + "frozen_parameters": 3032242416, + "tactile_input": false, + "editor": false, + "world_model": false, + "normalization": "fresh Tachin train-only, installed after checkpoint weights" + } +} diff --git a/model/tachin_paired30_cache_20260923/cache/shared/test/complete.json b/model/tachin_paired30_cache_20260923/cache/shared/test/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..420d04a62ab24d79b6a746ddfc9b00b7ebd8de5a --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/shared/test/complete.json @@ -0,0 +1,22 @@ +{ + "schema": "tachin.table1.paired30.shared.v1", + "split": "test", + "plans": 1169, + "rows_sha256": "fe2df096077fb2264f3cd4aff08fc9278789e8f0177fb3c5aeff9670cc9de751", + "decision_ticks": [ + 0, + 1, + 2 + ], + "decision_hz": 30.0, + "action_hz": 80.0, + "first_editable_action": [ + 0, + 3, + 6 + ], + "touch_input": "8-frame causal windows ending at plan + decision_tick/30 s", + "w3_tactile_target": "decision-relative +100 ms (+3 frames)", + "base_plan_reused_across_decisions": true, + "gated": false +} diff --git a/model/tachin_paired30_cache_20260923/cache/shared/train/complete.json b/model/tachin_paired30_cache_20260923/cache/shared/train/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..55d2dd3d92f1d506e21efaa4d942d9f4e115cd09 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/shared/train/complete.json @@ -0,0 +1,22 @@ +{ + "schema": "tachin.table1.paired30.shared.v1", + "split": "train", + "plans": 18208, + "rows_sha256": "ab63b0ad309dffdba1dc97560c51bf4c3d6ca1caf91bea5c856003ca4794cfef", + "decision_ticks": [ + 0, + 1, + 2 + ], + "decision_hz": 30.0, + "action_hz": 80.0, + "first_editable_action": [ + 0, + 3, + 6 + ], + "touch_input": "8-frame causal windows ending at plan + decision_tick/30 s", + "w3_tactile_target": "decision-relative +100 ms (+3 frames)", + "base_plan_reused_across_decisions": true, + "gated": false +} diff --git a/model/tachin_paired30_cache_20260923/cache/shared/val/complete.json b/model/tachin_paired30_cache_20260923/cache/shared/val/complete.json new file mode 100644 index 0000000000000000000000000000000000000000..26e885a38de5cc0ea7a7a3727cc042a06917b3e2 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/cache/shared/val/complete.json @@ -0,0 +1,22 @@ +{ + "schema": "tachin.table1.paired30.shared.v1", + "split": "val", + "plans": 1006, + "rows_sha256": "d29b089a609c293c8cb2b5f05e6fa96b0924be82016304dba6c55aa7fd73bb87", + "decision_ticks": [ + 0, + 1, + 2 + ], + "decision_hz": 30.0, + "action_hz": 80.0, + "first_editable_action": [ + 0, + 3, + 6 + ], + "touch_input": "8-frame causal windows ending at plan + decision_tick/30 s", + "w3_tactile_target": "decision-relative +100 ms (+3 frames)", + "base_plan_reused_across_decisions": true, + "gated": false +} diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/__init__.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..580a239db14cfeb706a2302c4db7e5cf2bd3e841 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/__init__.py @@ -0,0 +1,181 @@ +"""Method D + EgoTouch tactile integration framework.""" + +from .config import ( + EditorConfig, + EncoderConfig, + FusionConfig, + RuntimeConfig, + RuntimeMode, + TrainMode, + Variant, +) +from .action_layout import ( + ACTION_DIM, + ARTICULATION_GROUPS, + DEFAULT_ACTION_LAYOUT, + FULL_ACTION_GROUPS, + FULL_HAND_GROUPS, + ActionLayout, + ActionNormalizer, +) +from .action_output import NormalizedActionOutput +from .table1_protocol import MODEL_SPECS, protocol_metadata, validate_action_contract, validate_mask +from .editor_interface import BaseActionContext, EditorOutput, TactileEditorBackend +from .editor_backends import ( + MemoryFreeTactileEditor, + MemoryW0W3Editor, + NativeFinalActionEditor, + TactileEditorRouter, +) +from .model_adapters import ( + AdapterSpec, + MemoryVLAAdapter, + ModelAdapter, + SmolVLAAdapter, + TRexAdapter, + TWLAAdapter, + VITRAAdapter, +) +from .checkpoint_loaders import ( + load_v4d_checkpoint, official_memoryvla_contract, trex_action_contract, + vitra_action_contract, +) +from .direct_residual import ( + DIRECT_INPUT_MODES, + DirectTactileResidualEditor, + DirectTactileTrunk, +) +from .table1_editor_cache import Table1EditorCache +from .encoder import ( + DualHandTactileEncoder, + TouchFeatures, + initialize_random_t2p_encoder, + load_formal_t2p_encoder, + load_huggingface_encoder, +) +from .fusion import CenteredArticulationTouchEditor +from .model import TactileMethodD, component_report +from .offline_data import CachedPlan, EpisodeTouch, OfflineV1Dataset, collate_v1_samples +from .real_data import ( + RealEgoTouchEpisode, + load_pinned_egotouch_episode, + operate_real_data_replay, +) +from .runtime import ( + ActionPlan, + InferenceRequest, + PipelinedController, + ScheduledActionPlan, + TactileRingBuffer, + next_action_boundary, +) +from .trainability import configure_trainable_components +from .training import ( + V1TrainingBatch, + build_future_action_mask, + nominal_revision_times, + v1_residual_objective, +) +from .single_stage_world import ( + SingleStageWorldTactileEditor, + TactileTargetCodec, + gather_action_window, + ramp_world_weight, +) +from .rgb_world_editor import ( + FrozenRGBWorldResidual, + RGBWorldRegularizedTactileEditor, + TactileMemoryConditionModulator, + roi_weighted_world_loss, +) +from .world_regularized_data import ( + ShardedWorldEditorDataset, + WORLD_ARRAY_NAMES, + future_tactile_targets, +) +from .unified_cache import UnifiedWorldCache +from .unified_world import UnifiedWorldTactileEditor, WorldMode + +__all__ = [ + "ActionPlan", + "ACTION_DIM", + "ActionLayout", + "ActionNormalizer", + "NormalizedActionOutput", + "MODEL_SPECS", + "protocol_metadata", + "validate_action_contract", + "validate_mask", + "BaseActionContext", + "EditorOutput", + "TactileEditorBackend", + "MemoryFreeTactileEditor", + "MemoryW0W3Editor", + "NativeFinalActionEditor", + "TactileEditorRouter", + "AdapterSpec", + "ModelAdapter", + "MemoryVLAAdapter", + "SmolVLAAdapter", + "VITRAAdapter", + "TRexAdapter", + "TWLAAdapter", + "load_v4d_checkpoint", + "vitra_action_contract", + "trex_action_contract", + "official_memoryvla_contract", + "ARTICULATION_GROUPS", + "CachedPlan", + "CenteredArticulationTouchEditor", + "EpisodeTouch", + "OfflineV1Dataset", + "collate_v1_samples", + "DualHandTactileEncoder", + "DIRECT_INPUT_MODES", + "DirectTactileResidualEditor", + "DirectTactileTrunk", + "Table1EditorCache", + "EditorConfig", + "EncoderConfig", + "FusionConfig", + "FULL_ACTION_GROUPS", + "FULL_HAND_GROUPS", + "InferenceRequest", + "PipelinedController", + "RealEgoTouchEpisode", + "RuntimeConfig", + "RuntimeMode", + "DEFAULT_ACTION_LAYOUT", + "ScheduledActionPlan", + "TactileMethodD", + "TactileRingBuffer", + "TouchFeatures", + "TrainMode", + "Variant", + "V1TrainingBatch", + "build_future_action_mask", + "component_report", + "configure_trainable_components", + "load_huggingface_encoder", + "load_formal_t2p_encoder", + "initialize_random_t2p_encoder", + "load_pinned_egotouch_episode", + "next_action_boundary", + "nominal_revision_times", + "operate_real_data_replay", + "v1_residual_objective", + "SingleStageWorldTactileEditor", + "TactileTargetCodec", + "ShardedWorldEditorDataset", + "WORLD_ARRAY_NAMES", + "future_tactile_targets", + "gather_action_window", + "ramp_world_weight", + "FrozenRGBWorldResidual", + "RGBWorldRegularizedTactileEditor", + "TactileMemoryConditionModulator", + "roi_weighted_world_loss", + "UnifiedWorldCache", + "UnifiedWorldTactileEditor", + "WorldMode", +] diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/__init__.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..153721b58a0c3fc0344916077386c86c4cbc55c8 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/__init__.py @@ -0,0 +1 @@ +"""Pinned model runtimes from VLA-HAND/Kai_final.""" diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/provenance.json b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..7711fff84a44f055495dc1627e052d3b8f341fe1 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/provenance.json @@ -0,0 +1,71 @@ +{ + "repository": "https://github.com/kaichen-z/VLA-HAND", + "commit": "6597491add7acf92343e7a78ade66c529c5eb5b4", + "files": { + "smolvla_official/config.py": "ca4af48d152030f4741068308f9b0faac63af18178eefd8c9cbf2efe2b776f34", + "smolvla_official/model.py": "8ebfec996d6c1841adcc68f5d491ba4b68dc70b5519e46c7ca043207fd63f2ad", + "smolvla_official/flow.py": "8ec960f681de59fc47bcc9dc0a048b5f6f095ee83259e4ced6b85d2196c414fd", + "smolvla_official/smolvlm_with_expert.py": "8b17d09c5ab9b68e324e1b4f5011ab21e8d66165d8c955f3d36c19469229619e", + "smolvla_official/vla_utils.py": "689fea725369aba4f7bb5eb72112eb7f96911061bbde225113793626d7b687b2", + "smolvla_official/group_loss.py": "f8f26dc7af38af10db0d012d527a53c77493a034d96c0fda4e7462d2f6af0164", + "vitra_original/config.py": "306ce5d342acbe665c9160771b4c3711463a70598fddbc39a41df5362d7bdbc7", + "vitra_original/model.py": "edaaf0ce60a97459594f034a53a8edf9b1b07d2354cecf829ac74e957848bdc7", + "vitra_original/vlm.py": "f8e4f6c753f660201398a544d2b8f32bb94b573573acb21037221a341cb68807", + "vitra_original/dit.py": "7448464d79b9bbda800688798ba825e1864f9240502d2a5f6848e5d650074b73", + "vitra_original/diffusion.py": "5f7101f06653e57c2bec1ee03b6eaba473974ba0a475779d2baf0f91c9ec6ba1", + "vitra_original/prompt.py": "b0816ec6cd3f66e61bbd5ebd77b393a794a847fa0e801ca6a174b82ba6876fc7", + "vitra_original/group_loss.py": "bb021ee4c9d8f38db633f1f60fc8f9ffc6c4b963f442850233f794c42a79524a", + "memoryvla_official/config.py": "9ebb0bb52c5e2b28531c14f19efb982efd9d749308253b2ee4960d6b1bc123cc", + "memoryvla_official/model.py": "a53100dc812eaedc50e548839128ac9e83971354da3bb0427e57d6a8131d3c8a", + "memoryvla_official/upstream/action_model/__init__.py": "a250b824623704828544e600495214eed3595f37d3426d3b1c6cc6c73eebd2ba", + "memoryvla_official/upstream/action_model/action_model.py": "ea8df2900e9b3135937b01545efefcc3807c931c9199324f5ca4474c3012f407", + "memoryvla_official/upstream/action_model/diffusion_utils.py": "b18704df849ab6ef01fe5ffcd050762b24700b0c78a26d35eae9ad92e725f5ef", + "memoryvla_official/upstream/action_model/gaussian_diffusion.py": "e41926edcb562fa12f73c052295a04c965506e02a9f524f6e3dd52c95bf49180", + "memoryvla_official/upstream/action_model/models.py": "1ca165d31d7a607f793669b0d5a33c19d771cebedc08dce755df212917841486", + "memoryvla_official/upstream/action_model/respace.py": "e1cdca3da8b4ae828b79b37b76432881d10248aa85044861a3e1cbb874e5d26b", + "memoryvla_official/upstream/memory_vla.py": "998070d35cba0c57e7be85259c680aeee0120942545f04ad3bcd0bf5036d6f9a", + "memoryvla_official/upstream/prismatic/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "memoryvla_official/upstream/prismatic/models/__init__.py": "5c8c5740fe21de0a59de08aabfc9fdf7d519094030f4824b4b78d7c9ac0d20dd", + "memoryvla_official/upstream/prismatic/models/backbones/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "memoryvla_official/upstream/prismatic/models/backbones/llm/__init__.py": "94c49353334c38c67f9555d39915ba83e4b712420dfd4bc98cbde10ab20b5897", + "memoryvla_official/upstream/prismatic/models/backbones/llm/base_llm.py": "8f6b06fdd1af22c0d3d8fdbeb6a6bd490f0f3fafa97e9514994d24053453321a", + "memoryvla_official/upstream/prismatic/models/backbones/llm/llama2.py": "587e88dec921271a2b8d1de3867d6bf9584a70196176ecf54cf43b14ccfceeb5", + "memoryvla_official/upstream/prismatic/models/backbones/llm/mistral.py": "e72025a82d56ded938b6a119d98c81eea8cbf956c8d9f6b2f3bbe9b628fd71e1", + "memoryvla_official/upstream/prismatic/models/backbones/llm/phi.py": "e9ff83d1934c9e588b1ebcb8c755bbd20543125767d261f5eb75cbd07ed7c416", + "memoryvla_official/upstream/prismatic/models/backbones/llm/prompting/__init__.py": "6f532ea1f274096e32a5b4bf9b98648f3e0521f1f7e30599487a3230663d7b92", + "memoryvla_official/upstream/prismatic/models/backbones/llm/prompting/base_prompter.py": "d98922038a2607e21bd94fcd8a14451162ebded5e190c3b9869515ffcc28e2a5", + "memoryvla_official/upstream/prismatic/models/backbones/llm/prompting/llama2_chat_prompter.py": "85c7c39fe6f625b05d6b8becc4c1f670373d61f4c0414fc79f63591452306579", + "memoryvla_official/upstream/prismatic/models/backbones/llm/prompting/mistral_instruct_prompter.py": "3d5f57db4028ef84f8d09fb83e07f2049985c90a74cec471c764e353fe0fc617", + "memoryvla_official/upstream/prismatic/models/backbones/llm/prompting/phi_prompter.py": "0cba9b7821d43102ab7c0e53273033d0c53691df44efd10d91ebb037136bb29f", + "memoryvla_official/upstream/prismatic/models/backbones/llm/prompting/vicuna_v15_prompter.py": "0a9967daf1ca2e7796fc9cd8830f73b91996b573cf6bb3e0e3a5af1dfa93be39", + "memoryvla_official/upstream/prismatic/models/backbones/vision/__init__.py": "6e2d34cf72a18596dad8e18c3c6e9983588526ec1ee58a49516be88a91d03e17", + "memoryvla_official/upstream/prismatic/models/backbones/vision/base_vision.py": "80aa3fe577d3f23641077eaf358859683dde29fed9a2a8ec373c0cec2896579d", + "memoryvla_official/upstream/prismatic/models/backbones/vision/clip_vit.py": "ff8347d818230940059b47a58b997ea6d21f92a9b826b9e1cc50277ecd6dcaa6", + "memoryvla_official/upstream/prismatic/models/backbones/vision/dinoclip_vit.py": "05afd1bc7c0bb1fa6d4a5ee16948422375861b80cece854b56086eb81604b213", + "memoryvla_official/upstream/prismatic/models/backbones/vision/dinosiglip_vit.py": "8143262f1b62c1f83739a9142a8feb0c755025ce0751a476a22eb69fe5808131", + "memoryvla_official/upstream/prismatic/models/backbones/vision/dinov2_vit.py": "1b967fe1cba0d585f78ebfc21c904ac412c61fb7464c03c77131cf7a770a0791", + "memoryvla_official/upstream/prismatic/models/backbones/vision/in1k_vit.py": "a53de7f6ba1f82ae5976741740deefc25062901b88ffe5adf890b349720a7a41", + "memoryvla_official/upstream/prismatic/models/backbones/vision/siglip_vit.py": "c1f3500eaabe361457cb4110e404676587d231a0a0e1d29c1c8a41111ef3c3ec", + "memoryvla_official/upstream/prismatic/models/materialize.py": "b3fca60a822b4765644a1bbbe8402b6a6537f642de43d089faa560658cbb6e49", + "memoryvla_official/upstream/prismatic/models/registry.py": "eacdeb9201cd9fd1828d7ad7ffe2133f89e0de872c31f76b0038838b8a7dd493", + "memoryvla_official/upstream/prismatic/models/vlms/__init__.py": "bf58ab5c127b6df35f5d881357ec5aa24e0b46f2916c527612af484b95c7c448", + "memoryvla_official/upstream/prismatic/models/vlms/base_vlm.py": "ea291ec87810abfc4be2c4fcd942708c33a47b0601aa50ffa9e581a736dcd38c", + "memoryvla_official/upstream/prismatic/models/vlms/prismatic.py": "760d56e73fcdef9d5a4d260d00aba7fb6bfec048aa2b2ea3d319edef9c402137", + "memoryvla_official/upstream/prismatic/overwatch/__init__.py": "bd036db0376e394f189a420f798d0fa0b93637b72004419ccaaf316b8b5e757d", + "memoryvla_official/upstream/prismatic/overwatch/overwatch.py": "3f2342cd90dec06655e599975eb1a037d96602b453f6b720557125f311b15c8d", + "memoryvla_official/upstream/prismatic/util/__init__.py": "8ab7190ed1f1bd087966fcc59f35f9a7b4b315dd7b17f68a6a7ed6e335fc7380", + "memoryvla_official/upstream/prismatic/util/batching_utils.py": "a41d58f7baa40ccefe92be2727c19963a720a41feeada301a09cf01c8b261feb", + "memoryvla_official/upstream/prismatic/util/data_utils.py": "794742041f8da269ec2c185428e705984d29142be2a6febd53ba8ff1ac24de3f", + "memoryvla_official/upstream/prismatic/util/nn_utils.py": "7aa0562eab374f0585bb53639b861f06b6c44b82384e938dda9cd32d844bc0d0", + "memoryvla_official/upstream/prismatic/util/torch_utils.py": "a70e3b8d7e24b15a5d8abfa94f1c596ea70a9a85c86b50e8d8f963af51ff3304" + }, + "changes": [ + "SmolVLA group_loss uses a relative import, without sys.path modification.", + "VITRA diffusion imports its packaged group_loss by relative import.", + "MemoryVLA runtime uses package-qualified imports; the integration changes are documented in doc/memoryvla_integration.md.", + "MemoryVLA restores native memory modules strictly and resets runtime memory on failed windows.", + "MemoryVLA skips temporary LLM initialization before strict loading; embedding resize uses mean_resizing=False.", + "MemoryVLA vision unpacking accepts both list and tuple features from timm.", + "Trailing whitespace in the vendored MemoryVLA runtime was removed." + ] +} diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/__init__.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/config.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1c5ebe8617808ca9397e8f81e76ffe41ca70464a --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/config.py @@ -0,0 +1,410 @@ +"""Every knob for the SmolVLA-official baseline. Nothing is defaulted elsewhere. + +Values are transcribed from two places and each field says which: + + * `lerobot/smolvla_base`'s own `config.json` -- what the released checkpoint was trained + with. This is the authority wherever it and the dataclass default disagree. + * `src/lerobot/policies/smolvla/configuration_smolvla.py` @ 22bd7a2 -- the dataclass + defaults, for the fields the release does not record. + +Sections `vlm`, `image`, `action`, `data` and `train` carry the field names V4's dataloader +and `baselines/train.py` read. That is a hard interface, not a style choice: the loader is +shared so that the data reaching this baseline and the data reaching V4 are the same data. + +**Three fields differ from upstream and all three are forced by our action space:** + + max_action_dim 32 -> 192 (2 hands x 69, of which 138 are real) + max_state_dim 32 -> 212 + chunk_size 50 -> 16 (16 actions at 80 Hz = 0.2 s, V4's horizon) + +Everything else is upstream's, deliberately -- the baseline is "their model on our data", +so the recipe stays theirs (user, 2026-09-10). +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, fields, is_dataclass +from typing import Any + + +# --------------------------------------------------------------------------- VLM + +@dataclass +class VLMConfig: + """SmolVLM2-500M plus the action expert built beside it. + + The expert is NOT a copy of the VLM: `SmolVLMWithExpertModel` builds it from a + deep-copied text config with `hidden_size * expert_width_multiplier`, so 960 -> 720, + and always `AutoModel.from_config(...)` -- **never pretrained**. That is upstream's + own behaviour, not a choice made here: even loading `smolvla_base` through LeRobot + constructs the expert from scratch and then overwrites it from the policy state dict. + """ + + # ** Raw SmolVLM2-500M, the SAME starting weights V4 uses. ** User, 2026-09-11, + # revising an earlier choice of `lerobot/smolvla_base`'s VLM. + # + # The reasoning: whichever checkpoint is named, the part that makes `smolvla_base` + # *SmolVLA* is discarded anyway -- its `action_in_proj` is [720, 32] and + # `action_out_proj` [32, 720], neither of which can carry 192 channels, so the expert + # and both projections are rebuilt from scratch. What is left to choose is only which + # VLM weights, and choosing V4's removes a confound for free: both models then start + # from bit-identical weights and any difference is architecture and recipe. + # + # ⚠ The cost is what this baseline answers. It is now "SmolVLA's architecture and + # recipe, from the same start as V4", not "the released SmolVLA". The VITRA baseline + # answers the latter -- its pretrained action head is what makes it VITRA, so there + # was no equivalent choice there. Say which is which when reporting. + # + # V4 chose the same way and wrote down why (`v4_d_fm_0/config.py:24`): "our data is + # egocentric human hands, so the appearance prior of a general video model is closer + # than that of a model fitted to table-top grippers". It keeps the other checkpoint as + # a commented ablation switch; so do we. + model_id: str = "HuggingFaceTB/SmolVLM2-500M-Video-Instruct" + # Ablation: set `init.pretrain_path` to smolvla_base's safetensors to start from the + # robot-pretrained VLM instead. `model.load_pretrained` takes only its 345 + # `model.vlm_with_expert.vlm.*` tensors. + pretrained_policy: str = "lerobot/smolvla_base" + + num_vlm_layers: int = 16 # first 16 layers of the text model are kept + num_expert_layers: int = 0 # <= 0 -> expert has as many layers as the VLM + expert_width_multiplier: float = 0.75 + self_attn_every_n_layers: int = 2 + attention_mode: str = "cross_attn" + + freeze_vision_encoder: bool = True + train_expert_only: bool = True # ⚠ the ENTIRE VLM is frozen, vision tower included + train_state_proj: bool = True + add_image_special_tokens: bool = False + prefix_length: int = 0 # 0 -> no padding of the prefix to a fixed length + + use_cache: bool = True # prefix K/V cached once per sampling call + + # Read by the dataloader, not by the model. 512 with aspect preserved and padding on + # the LEFT and TOP -- `_to_square` and upstream's `resize_with_pad` are the same + # geometry, so no image knob exists for this baseline (unlike the VITRA one, which + # needed PaliGemma's aspect-destroying squash). + image_size: int = 512 + + # `tokenizer_max_length` upstream. No image placeholders to count: SmolVLA embeds + # images separately and concatenates, rather than scattering into `input_ids`. + max_language_tokens: int = 48 + + gradient_checkpointing: bool = False + + +# --------------------------------------------------------------------------- image + +@dataclass +class ImageConfig: + """`pad`, and there is no second option worth offering. + + V4's `_to_square` pads LEFT and TOP at 512 with the aspect preserved, and its docstring + says outright that the geometry matches `vlm.resize_with_pad`. SmolVLA's + `resize_with_pad` is the same convention. So for this baseline the shared loader's + default path already IS upstream preprocessing. + """ + + mode: str = "pad" + + +# --------------------------------------------------------------------------- action + +@dataclass +class ActionConfig: + """The action and state vectors -- ours, not upstream's 32/32.""" + + chunk_size: int = 16 # upstream 50. 16 at 80 Hz = 0.2 s, matching V4. + dim: int = 192 # `max_action_dim` + state_dim: int = 212 # `max_state_dim` + + control_hz: float = 10.0 + action_hz: float = 80.0 + source_fps: float = 30.0 + + # `keypoints`, not `angle` (user, 2026-09-10). Unlike VITRA, nothing here is + # pretrained into a layout -- the expert and both projections start from scratch -- so + # the layout is free, and keypoints is V4's. That means the evaluation needs no MANO + # forward kinematics and carries none of the FK floor the VITRA baseline does. + action_type: str = "keypoints" + + dual_layout: bool = False # evaluation only; see dataloader/FORK.md + + +# --------------------------------------------------------------------------- flow + +@dataclass +class FlowConfig: + """Flow matching. `x_t = t*noise + (1-t)*a`, target `u_t = noise - a`, MSE. + + ⚠ Note what the target is: `noise - a`, a difference of two unit-variance quantities, + so a zero-output model scores **2.0**, not 1.0. VITRA's DDPM predicts epsilon and + starts at 1.0. The two baselines' loss curves are not comparable to each other, nor to + V4's -- only the physical test error is. + """ + + num_steps: int = 10 # Euler steps at sampling time + + # Timestep sampling: Beta(1.5, 1) * 0.999 + 0.001, openpi's convention. Weighted + # towards t near 1 (mostly noise), which is where the velocity field is hardest. + time_alpha: float = 1.5 + time_beta: float = 1.0 + time_scale: float = 0.999 + time_offset: float = 0.001 + + # Sine-cosine timestep embedding period range. + min_period: float = 4e-3 + max_period: float = 4.0 + + +# --------------------------------------------------------------------------- loss + +@dataclass +class LossConfig: + """Per-channel groups, for reporting AND for masking. + + ⚠ **Upstream's loss is not usable as-is.** `SmolVLAPolicy.forward` masks with + `action_is_pad`, which marks padded TIME STEPS; our padding is per CHANNEL -- 192 + slots of which 138 carry data and 54 are permanently zero. Taking the plain mean would + train the model to predict those 54 zeros and divide the real error by 192/138. It + would not raise, and the loss would look better than it is. `model.loss` masks by + `action_mask` instead; these groups are how the result is reported. + + Six groups, matching V4's split (each wrist block into translation and rotation) + rather than VITRA's four. SmolVLA has no group structure of its own to be faithful + to -- its loss is one undifferentiated mean -- so the reporting follows the model this + baseline is compared against. + """ + + groups: tuple[tuple[str, int, int, float], ...] = ( + ("left_translation", 0, 3, 1.0), + ("left_rotation", 3, 6, 1.0), + ("left_joints", 6, 69, 1.0), + ("right_translation", 69, 72, 1.0), + ("right_rotation", 72, 75, 1.0), + ("right_joints", 75, 138, 1.0), + ) + + +# --------------------------------------------------------------------------- data + +@dataclass +class DataConfig: + """Read by the shared dataloader. Field names are its interface, not ours.""" + + stride: int = 3 # source_fps / control_hz + interpolation: str = "pchip_bone_preserving" + geometric_augmentation: bool = False + random_paraphrase: bool = True + + sources: tuple[dict[str, Any], ...] = () + stats_path: str = "" + + +# --------------------------------------------------------------------------- train + +@dataclass +class TrainConfig: + # ** `max_seq_len` and `length_alpha` are the LOADER's interface, and both must match + # V4's or the two models see different distributions of episode position. ** 9 is + # V4's bank capacity 8 plus the supervised step; `length_alpha` weights the draw of L + # by `L ** alpha`. This model has no memory and reads only `steps[-1]`, but the window + # still decides WHERE in an episode the supervised anchor lands -- shortening it here + # would quietly train on a different slice of the data than V4 and the VITRA baseline. + max_seq_len: int = 9 + length_alpha: float = 1.0 + + use_only_last_step: bool = True # no memory: only the supervised anchor is consumed + seed: int = 0 + parallel: str = "ddp" # "fsdp" | "ddp" + + +@dataclass +class OptimConfig: + """Upstream's preset, verbatim (`get_optimizer_preset` / `get_scheduler_preset`). + + ⚠ `weight_decay = 1e-10` is not a typo and not our choice -- it is what SmolVLA ships. + Effectively no decay. VITRA uses 0.1. Both are their authors'. + """ + + lr: float = 1e-4 + + # ⚠ NOT upstream. `None` means one group at `lr` for everything, which is what + # upstream does and what stage A wants (the VLM is frozen, so there is no backbone in + # the trainable set). Stage B sets it: unfreezing the language model puts pretrained + # weights beside a still-learning expert, and upstream's single 1e-4 would hit both. + # 1e-5 is the rate both VITRA and V4 give their backbones -- a 10x split with + # precedent in this project rather than a number picked here. + vlm_lr: float | None = None + + betas: tuple[float, float] = (0.9, 0.95) + eps: float = 1e-8 + weight_decay: float = 1e-10 + grad_clip: float = 10.0 + grad_accum_steps: int = 1 + + # Cosine decay with warmup, upstream's schedule. + warmup_steps: int = 1_000 + decay_steps: int = 30_000 + decay_lr: float = 2.5e-6 + + +@dataclass +class InitConfig: + pretrain_path: str = "" # the smolvla_base safetensors, VLM part only + allow_partial_load: bool = False + + +# --------------------------------------------------------------------------- top + +@dataclass +class Config: + """The whole configuration for this baseline. `train.py` and `test.py` in this + package import it by name.""" + + vlm: VLMConfig = field(default_factory=VLMConfig) + image: ImageConfig = field(default_factory=ImageConfig) + action: ActionConfig = field(default_factory=ActionConfig) + flow: FlowConfig = field(default_factory=FlowConfig) + loss: LossConfig = field(default_factory=LossConfig) + data: DataConfig = field(default_factory=DataConfig) + train: TrainConfig = field(default_factory=TrainConfig) + optim: OptimConfig = field(default_factory=OptimConfig) + init: InitConfig = field(default_factory=InitConfig) + + # ** `None` = report the preflight numbers but do NOT gate on them. ** + # + # The gate's premise is a head that outputs zero: then the first-batch loss is + # `E[(0 - target)^2]` and any departure from it is a normalisation error. VITRA's DiT + # satisfies that -- adaLN-Zero puts `nn.init.constant_(..., 0)` on the final layer, so + # its output really is zero at init (adaLN-Zero clears the final layer). + # + # SmolVLA does not. `action_out_proj` is a plain `nn.Linear` with PyTorch's default + # init and `flow.py` contains no zero-initialisation at all, so `v_t` is a random + # projection's output. The first batch measures + # `E[(noise - a - v_t)^2] ~= 2 + E[v_t^2]`, where the second term differs per output + # channel -- which is why the six groups spread over 1.94 to 2.87 on a run whose + # statistics were fine. No constant repairs that; the test simply does not apply. + preflight_loss: float | None = None + + # ----------------------------------------------------------------- validation + + def validate(self) -> None: + v, a, f = self.vlm, self.action, self.flow + + if self.image.mode != "pad": + raise ValueError( + f"image.mode {self.image.mode!r}: SmolVLA's preprocessing IS the shared " + f"loader's `pad` path (512, aspect preserved, padded left and top). " + f"'squash' is PaliGemma's and belongs to the VITRA baseline.") + + if a.action_type != "keypoints": + raise ValueError( + f"action.action_type {a.action_type!r}: this baseline trains keypoints " + f"(user, 2026-09-10). Nothing here is pretrained into a layout, so there " + f"is no reason to take on `angle`'s MANO-FK conversion at evaluation.") + + if a.dim != 192 or a.state_dim != 212: + raise ValueError( + f"action.dim={a.dim}, state_dim={a.state_dim}: the normalisation " + f"statistics and the loss groups are tied to 192/212.") + + hi = max(h for _, _, h, _ in self.loss.groups) + if hi > a.dim: + raise ValueError(f"loss group ends at {hi}, past action dim {a.dim}") + if self.loss.groups[2][2] != 69: + raise ValueError( + "loss.groups do not carry the keypoints ranges. keypoints is " + "(0,3)/(3,6)/(6,69)/(69,72)/(72,75)/(75,138).") + + if v.attention_mode not in ("cross_attn", "self_attn"): + raise ValueError(f"vlm.attention_mode {v.attention_mode!r}") + if v.num_expert_layers > 0 and v.num_vlm_layers % v.num_expert_layers != 0: + raise ValueError( + f"num_vlm_layers {v.num_vlm_layers} is not a multiple of " + f"num_expert_layers {v.num_expert_layers}; `get_model_layers` divides them") + if not v.train_expert_only and not v.freeze_vision_encoder: + # Not an error upstream, but it changes what the baseline is. + pass + + if f.num_steps < 1: + raise ValueError("flow.num_steps must be >= 1") + + if self.train.parallel not in ("fsdp", "ddp"): + raise ValueError(f"train.parallel {self.train.parallel!r}") + if not self.train.use_only_last_step: + raise ValueError( + "use_only_last_step=False: this model has no memory and no way to consume " + "earlier steps.") + + if self.data.stride != int(round(a.source_fps / a.control_hz)): + raise ValueError( + f"data.stride {self.data.stride} != source_fps/control_hz = " + f"{a.source_fps}/{a.control_hz}") + if not self.data.stats_path: + raise ValueError( + "data.stats_path is empty. The baseline MUST use the same normalisation " + "statistics as V4 -- see 项目专项规则.md, '归一化器属数据管线'.") + + +class FlatConfig: + """What the forked `VLAFlowMatching` expects: one flat namespace. + + Upstream's `SmolVLAConfig` is flat; ours is sectioned, because `baselines/train.py` + and the shared loader read `cfg.action.chunk_size`, `cfg.vlm.image_size` and so on. + Rather than edit the forked maths to walk our sections -- an unmarked change to a file + whose whole value is being unmodified -- the model builds this view over it. + + Attribute names here are upstream's, spelled exactly as `flow.py` reads them. + """ + + def __init__(self, cfg: Config): + v, a, f = cfg.vlm, cfg.action, cfg.flow + self.vlm_model_name = v.model_id + self.freeze_vision_encoder = v.freeze_vision_encoder + self.train_expert_only = v.train_expert_only + self.train_state_proj = v.train_state_proj + self.load_vlm_weights = True # build the architecture from the Hub config + self.attention_mode = v.attention_mode + self.num_expert_layers = v.num_expert_layers + self.num_vlm_layers = v.num_vlm_layers + self.self_attn_every_n_layers = v.self_attn_every_n_layers + self.expert_width_multiplier = v.expert_width_multiplier + self.add_image_special_tokens = v.add_image_special_tokens + self.prefix_length = v.prefix_length + self.use_cache = v.use_cache + self.device = None + self.max_state_dim = a.state_dim + self.max_action_dim = a.dim + self.chunk_size = a.chunk_size + self.num_steps = f.num_steps + self.min_period = f.min_period + self.max_period = f.max_period + + +# --------------------------------------------------------------------------- json + +def apply_overrides(cfg: Any, overrides: dict[str, Any], path: str = "") -> None: + """Recursively overwrite dataclass fields from a parsed json. + + Unknown keys RAISE. A run json with a typo'd knob otherwise trains happily with the + default and the log says nothing; that failure is indistinguishable from the + experiment simply not working. + """ + known = {f.name: f for f in fields(cfg)} + for key, value in overrides.items(): + if key not in known: + raise KeyError(f"unknown config key {path}{key!r}; known here: {sorted(known)}") + current = getattr(cfg, key) + if is_dataclass(current) and isinstance(value, dict): + apply_overrides(current, value, f"{path}{key}.") + elif isinstance(current, tuple) and isinstance(value, list): + setattr(cfg, key, tuple(tuple(v) if isinstance(v, list) else v for v in value)) + else: + setattr(cfg, key, value) + + +def from_json(overrides: dict[str, Any]) -> Config: + cfg = Config() + apply_overrides(cfg, overrides) + cfg.validate() + return cfg diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/flow.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/flow.py new file mode 100644 index 0000000000000000000000000000000000000000..28ad69865f79eddad2cf59a7d77b6cac44b17fff --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/flow.py @@ -0,0 +1,396 @@ +"""SmolVLA's flow-matching policy, forked from LeRobot. See `FORK.md`. + +Source: `yuzhench/paper_code/smolvla_lerobot` @ 22bd7a2, +`src/lerobot/policies/smolvla/modeling_smolvla.py` -- `pad_tensor` and `VLAFlowMatching`. +`SmolVLAPolicy` is NOT forked: it is the LeRobot wrapper (queues, processor pipeline, Hub +mixin, RTC) and `model.py` here plays that role against this project's interfaces instead. + +**The maths is unchanged.** Four edits, each marked `** FORK EDIT **` in place: + + 1. real-time chunking removed -- `rtc_processor`, `_rtc_enabled`, and the four RTC + kwargs of `sample_actions`. RTC is an online-execution feature (it blends a new chunk + with the tail of the one still running); offline evaluation never reaches it. + 2. `euler_integrate` inlined. Upstream's helper is mostly RTC plumbing around four lines + -- `dt = -1/num_steps`, `time = 1 + step*dt`, `v_t = denoise(x_t, time)`, + `x_t += dt * v_t`. Written out so the sampler is readable without the RTC branches. + 3. `torch.compile` block dropped; this tree compiles nothing. + 4. the `state` argument of `embed_prefix` loses its `= None` default -- it is required + here and a silent `None` would reach `state_proj` as a shape error far from the cause. + +⚠ **`embed_prefix` puts the state in the PREFIX**, next to the image and language tokens, +and `att_masks` marks it `1` so images and language cannot attend to it. That is SmolVLA's +arrangement and it is one of the things this baseline exists to hold fixed. +""" + +from __future__ import annotations + +import math + +import torch +import torch.nn.functional as F # noqa: N812 +from torch import Tensor, nn + +from .config import Config +from .smolvlm_with_expert import SmolVLMWithExpertModel +from .vla_utils import ( + create_sinusoidal_pos_embedding, + make_att_2d_masks, + sample_noise, + sample_time_beta, +) + + +def pad_tensor(tensor, max_len, pad_value=0): + """ + Efficiently pads a tensor along sequence dimension to match max_len. + + Args: + tensor (torch.Tensor): Shape (B, L, ...) or (B, L). + max_len (int): Fixed sequence length. + pad_value (int/float): Value for padding. + + Returns: + torch.Tensor: Shape (B, max_len, ...) or (B, max_len). + """ + b, d = tensor.shape[:2] + + # Create a padded tensor of max_len and copy the existing values + padded_tensor = torch.full( + (b, max_len, *tensor.shape[2:]), pad_value, dtype=tensor.dtype, device=tensor.device + ) + padded_tensor[:, :d] = tensor # Efficient in-place copy + + return padded_tensor + + +class VLAFlowMatching(nn.Module): + """ + SmolVLA + + [Paper]() + + Designed by Hugging Face. + ┌──────────────────────────────┐ + │ actions │ + │ ▲ │ + │ ┌─────────┐ ┌─|────┐ │ + │ | │────► │ │ │ + │ | │ kv │ │ │ + │ | │────► │Action│ │ + │ | VLM │cache │Expert│ | + │ │ │────► | │ │ + │ │ │ │ │ │ + │ └▲──▲───▲─┘ └───▲──┘ | + │ │ | | │ | + │ | | | noise │ + │ │ │ state │ + │ │ language tokens │ + │ image(s) │ + └──────────────────────────────┘ + """ + + def __init__(self, config: Config): + # ** FORK EDIT 1 ** `rtc_processor` dropped; ** FORK EDIT 3 ** no torch.compile. + super().__init__() + self.config = config + + self.vlm_with_expert = SmolVLMWithExpertModel( + model_id=self.config.vlm_model_name, + freeze_vision_encoder=self.config.freeze_vision_encoder, + train_expert_only=self.config.train_expert_only, + load_vlm_weights=self.config.load_vlm_weights, + attention_mode=self.config.attention_mode, + num_expert_layers=self.config.num_expert_layers, + num_vlm_layers=self.config.num_vlm_layers, + self_attn_every_n_layers=self.config.self_attn_every_n_layers, + expert_width_multiplier=self.config.expert_width_multiplier, + device=self.config.device if self.config.device is not None else "auto", + ) + self.state_proj = nn.Linear( + self.config.max_state_dim, self.vlm_with_expert.config.text_config.hidden_size + ) + self.action_in_proj = nn.Linear(self.config.max_action_dim, self.vlm_with_expert.expert_hidden_size) + self.action_out_proj = nn.Linear(self.vlm_with_expert.expert_hidden_size, self.config.max_action_dim) + + self.action_time_mlp_in = nn.Linear( + self.vlm_with_expert.expert_hidden_size * 2, self.vlm_with_expert.expert_hidden_size + ) + self.action_time_mlp_out = nn.Linear( + self.vlm_with_expert.expert_hidden_size, self.vlm_with_expert.expert_hidden_size + ) + + self.set_requires_grad() + self.fake_image_token = self.vlm_with_expert.processor.tokenizer.fake_image_token_id + self.global_image_token = self.vlm_with_expert.processor.tokenizer.global_image_token_id + self.global_image_start_token = torch.tensor( + [self.fake_image_token, self.global_image_token], dtype=torch.long + ) + + self.add_image_special_tokens = self.config.add_image_special_tokens + self.image_end_token = torch.tensor([self.fake_image_token], dtype=torch.long) + self.prefix_length = self.config.prefix_length + + def set_requires_grad(self): + for params in self.state_proj.parameters(): + params.requires_grad = self.config.train_state_proj + + def sample_noise(self, shape, device): + return sample_noise(shape, device) + + def sample_time(self, bsize, device): + return sample_time_beta(bsize, device, alpha=1.5, beta=1.0, scale=0.999, offset=0.001) + + def embed_prefix( + self, images, img_masks, lang_tokens, lang_masks, state: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + # ** FORK EDIT 4 ** `state` is required; upstream defaults it to None. + """Embed images with SigLIP and language tokens with embedding layer to prepare + for SmolVLM transformer processing. + """ + embs = [] + pad_masks = [] + att_masks = [] + for _img_idx, ( + img, + img_mask, + ) in enumerate(zip(images, img_masks, strict=False)): + if self.add_image_special_tokens: + image_start_token = ( + self.vlm_with_expert.embed_language_tokens( + self.global_image_start_token.to(device=self.vlm_with_expert.vlm.device) + ) + .unsqueeze(0) + .expand(img.shape[0], -1, -1) + ) + image_start_mask = torch.ones_like( + image_start_token[:, :, 0], dtype=torch.bool, device=image_start_token.device + ) + att_masks += [0] * (image_start_mask.shape[-1]) + embs.append(image_start_token) + pad_masks.append(image_start_mask) + + img_emb = self.vlm_with_expert.embed_image(img) + img_emb = img_emb + + # Normalize image embeddings + img_emb_dim = img_emb.shape[-1] + img_emb = img_emb * torch.tensor(img_emb_dim**0.5, dtype=img_emb.dtype, device=img_emb.device) + + bsize, num_img_embs = img_emb.shape[:2] + img_mask = img_mask[:, None].expand(bsize, num_img_embs) + + embs.append(img_emb) + pad_masks.append(img_mask) + + att_masks += [0] * (num_img_embs) + if self.add_image_special_tokens: + image_end_token = ( + self.vlm_with_expert.embed_language_tokens( + self.image_end_token.to(device=self.vlm_with_expert.vlm.device) + ) + .unsqueeze(0) + .expand(img.shape[0], -1, -1) + ) + image_end_mask = torch.ones_like( + image_end_token[:, :, 0], dtype=torch.bool, device=image_end_token.device + ) + embs.append(image_end_token) + pad_masks.append(image_end_mask) + att_masks += [0] * (image_end_mask.shape[1]) + lang_emb = self.vlm_with_expert.embed_language_tokens(lang_tokens) + # Normalize language embeddings + lang_emb_dim = lang_emb.shape[-1] + lang_emb = lang_emb * math.sqrt(lang_emb_dim) + + embs.append(lang_emb) + pad_masks.append(lang_masks) + + num_lang_embs = lang_emb.shape[1] + att_masks += [0] * num_lang_embs + + state_emb = self.state_proj(state) + state_emb = state_emb[:, None, :] if state_emb.ndim == 2 else state_emb + embs.append(state_emb) + bsize = state_emb.shape[0] + device = state_emb.device + + states_seq_len = state_emb.shape[1] + state_mask = torch.ones(bsize, states_seq_len, dtype=torch.bool, device=device) + pad_masks.append(state_mask) + + # Set attention masks so that image and language inputs do not attend to state or actions + att_masks += [1] * (states_seq_len) + embs = torch.cat(embs, dim=1) + pad_masks = torch.cat(pad_masks, dim=1) + att_masks = torch.tensor(att_masks, dtype=torch.bool, device=pad_masks.device) + att_masks = att_masks[None, :] + + seq_len = pad_masks.shape[1] + if seq_len < self.prefix_length: + embs = pad_tensor(embs, self.prefix_length, pad_value=0) + pad_masks = pad_tensor(pad_masks, self.prefix_length, pad_value=0) + att_masks = pad_tensor(att_masks, self.prefix_length, pad_value=0) + + att_masks = att_masks.expand(bsize, -1) + + return embs, pad_masks, att_masks + + def embed_suffix(self, noisy_actions, timestep): + """Embed state, noisy_actions, timestep to prepare for Expert Gemma processing.""" + embs = [] + pad_masks = [] + att_masks = [] + + # Fuse timestep + action information using an MLP + action_emb = self.action_in_proj(noisy_actions) + device = action_emb.device + bsize = action_emb.shape[0] + dtype = action_emb.dtype + # Embed timestep using sine-cosine positional encoding with sensitivity in the range [0, 1] + time_emb = create_sinusoidal_pos_embedding( + timestep, + self.vlm_with_expert.expert_hidden_size, + self.config.min_period, + self.config.max_period, + device=device, + ) + time_emb = time_emb.type(dtype=dtype) + + time_emb = time_emb[:, None, :].expand_as(action_emb) + action_time_emb = torch.cat([action_emb, time_emb], dim=2) + + action_time_emb = self.action_time_mlp_in(action_time_emb) + action_time_emb = F.silu(action_time_emb) # swish == silu + action_time_emb = self.action_time_mlp_out(action_time_emb) + + # Add to input tokens + embs.append(action_time_emb) + + bsize, action_time_dim = action_time_emb.shape[:2] + action_time_mask = torch.ones(bsize, action_time_dim, dtype=torch.bool, device=device) + pad_masks.append(action_time_mask) + + # Set attention masks so that image, language and state inputs do not attend to action tokens + att_masks += [1] * self.config.chunk_size + embs = torch.cat(embs, dim=1) + pad_masks = torch.cat(pad_masks, dim=1) + att_masks = torch.tensor(att_masks, dtype=embs.dtype, device=embs.device) + att_masks = att_masks[None, :].expand(bsize, len(att_masks)) + return embs, pad_masks, att_masks + + def forward( + self, images, img_masks, lang_tokens, lang_masks, state, actions, noise=None, time=None + ) -> Tensor: + """Do a full training forward pass and compute the loss (batch_size x num_steps x num_motors)""" + if noise is None: + noise = self.sample_noise(actions.shape, actions.device) + + if time is None: + time = self.sample_time(actions.shape[0], actions.device) + + time_expanded = time[:, None, None] + x_t = time_expanded * noise + (1 - time_expanded) * actions + u_t = noise - actions + prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix( + images, img_masks, lang_tokens, lang_masks, state=state + ) + suffix_embs, suffix_pad_masks, suffix_att_masks = self.embed_suffix(x_t, time) + + pad_masks = torch.cat([prefix_pad_masks, suffix_pad_masks], dim=1) + att_masks = torch.cat([prefix_att_masks, suffix_att_masks], dim=1) + + att_2d_masks = make_att_2d_masks(pad_masks, att_masks) + position_ids = torch.cumsum(pad_masks, dim=1) - 1 + (_, suffix_out), _ = self.vlm_with_expert.forward( + attention_mask=att_2d_masks, + position_ids=position_ids, + past_key_values=None, + inputs_embeds=[prefix_embs, suffix_embs], + use_cache=False, + ) + suffix_out = suffix_out[:, -self.config.chunk_size :] + # Original openpi code, upcast attention output + suffix_out = suffix_out.to(dtype=torch.float32) + v_t = self.action_out_proj(suffix_out) + losses = F.mse_loss(u_t, v_t, reduction="none") + return losses + + def sample_actions(self, images, img_masks, lang_tokens, lang_masks, state, + noise=None) -> Tensor: + # ** FORK EDIT 1 ** the four RTC kwargs are gone. + """Do a full inference forward and compute the action (batch_size x num_steps x num_motors)""" + bsize = state.shape[0] + device = state.device + + if noise is None: + actions_shape = (bsize, self.config.chunk_size, self.config.max_action_dim) + noise = self.sample_noise(actions_shape, device) + + prefix_embs, prefix_pad_masks, prefix_att_masks = self.embed_prefix( + images, img_masks, lang_tokens, lang_masks, state=state + ) + prefix_att_2d_masks = make_att_2d_masks(prefix_pad_masks, prefix_att_masks) + prefix_position_ids = torch.cumsum(prefix_pad_masks, dim=1) - 1 + # Compute image and language key value cache + _, past_key_values = self.vlm_with_expert.forward( + attention_mask=prefix_att_2d_masks, + position_ids=prefix_position_ids, + past_key_values=None, + inputs_embeds=[prefix_embs, None], + use_cache=self.config.use_cache, + ) + # ** FORK EDIT 2 ** `euler_integrate` inlined. Upstream's helper is these four + # lines wrapped in RTC branches; identical arithmetic, including that `time` + # starts at exactly 1.0 and the last step lands on 1/num_steps, not 0. + num_steps = self.config.num_steps + dt = -1.0 / num_steps + x_t = noise + for step in range(num_steps): + time = 1.0 + step * dt + time_tensor = torch.tensor(time, dtype=torch.float32, + device=device).expand(bsize) + v_t = self.denoise_step( + x_t=x_t, + prefix_pad_masks=prefix_pad_masks, + past_key_values=past_key_values, + timestep=time_tensor, + ) + x_t = x_t + dt * v_t + return x_t + + def denoise_step( + self, + prefix_pad_masks, + past_key_values, + x_t, + timestep, + ): + """Apply one denoising step of the noise `x_t` at a given timestep.""" + suffix_embs, suffix_pad_masks, suffix_att_masks = self.embed_suffix(x_t, timestep) + + suffix_len = suffix_pad_masks.shape[1] + batch_size = prefix_pad_masks.shape[0] + prefix_len = prefix_pad_masks.shape[1] + prefix_pad_2d_masks = prefix_pad_masks[:, None, :].expand(batch_size, suffix_len, prefix_len) + + suffix_att_2d_masks = make_att_2d_masks(suffix_pad_masks, suffix_att_masks) + + full_att_2d_masks = torch.cat([prefix_pad_2d_masks, suffix_att_2d_masks], dim=2) + prefix_offsets = torch.sum(prefix_pad_masks, dim=-1)[:, None] + position_ids = prefix_offsets + torch.cumsum(suffix_pad_masks, dim=1) - 1 + + outputs_embeds, _ = self.vlm_with_expert.forward( + attention_mask=full_att_2d_masks, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=[None, suffix_embs], + use_cache=self.config.use_cache, + ) + if past_key_values is not None: + # Self-attention layers append suffix K/V in place; restore the prefix for the next step. + past_key_values.crop(prefix_len) + suffix_out = outputs_embeds[1] + suffix_out = suffix_out[:, -self.config.chunk_size :] + suffix_out = suffix_out.to(dtype=torch.float32) + v_t = self.action_out_proj(suffix_out) + return v_t diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/group_loss.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/group_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6c34d305a821617d07b77bbcb5caa1babe031e --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/group_loss.py @@ -0,0 +1,92 @@ +"""The per-channel masked group loss, shared by both baselines. + +The group table is an argument rather than a constant: this baseline reports six groups +(each wrist block split into translation and rotation, matching V4), and the same +arithmetic serves any table. + +**Why a masked group loss at all, for a model whose upstream has none.** SmolVLA's own +loss is `F.mse_loss(u_t, v_t)` reduced by a mean over everything, with `action_is_pad` +masking padded TIME STEPS. Our padding is per CHANNEL: 192 slots of which 138 carry data +and 54 are permanently zero, and which 138 depends on the sample (an episode annotates one +hand). Taking upstream's plain mean would + + * train the model to predict 54 constant zeros, and + * divide the real error by 192 instead of by the number of live channels, + +so the reported loss would sit below the true one by a factor that varies with how many +hands the batch happens to contain. Nothing raises. That is not a faithfulness question -- +upstream never met this layout -- it is a correctness one. + +The group WEIGHTING is where the two baselines legitimately differ, and the caller owns it: +VITRA uses four groups (a 6-D wrist block per hand), V4 and this project's SmolVLA baseline +use six (translation and rotation split). Those belong to the objective each model is +trained under, not to this function. +""" + +from __future__ import annotations + +import torch + + +def masked_group_loss(pred: torch.Tensor, target: torch.Tensor, + action_mask: torch.Tensor, + groups, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """VITRA's `DiffusionPolicy.loss`, term for term, over `groups`. + + Per group: the masked mean of the squared error over that channel range, times the + group's weight. Those are then combined weighted by `count`, where count is the number + of (sample, step) pairs for which the group's FIRST channel is unmasked. Our cut writes + one hand per episode, so a group is either wholly present or wholly absent for a given + sample; the count is therefore "how many rows this group had", and the combination is + a mean over present groups rather than over channels. + + `groups` is an iterable of `(name, lo, hi, weight)`. + + The `total_count == 0` branch is upstream's: it returns `square_delta[0,0,0]`, a real + element of the graph, so the backward pass still has something to traverse and DDP + does not hang waiting for a rank that produced no gradient. + """ + return masked_group_loss_sq((pred - target) ** 2, action_mask, groups) + + +def masked_group_loss_sq(square: torch.Tensor, action_mask: torch.Tensor, groups + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Same, entered from an already-computed per-element squared error. + + SmolVLA's `VLAFlowMatching.forward` returns `F.mse_loss(u_t, v_t, reduction="none")` + and never exposes `v_t`, so the baseline cannot hand over a (pred, target) pair + without re-implementing that forward pass. Entering here instead keeps upstream's + file unmodified and the aggregation shared. + """ + m = action_mask.to(square.dtype) + square_delta = square * m + + parts: dict[str, torch.Tensor] = {} + counts: dict[str, torch.Tensor] = {} + dens: dict[str, torch.Tensor] = {} + for name, lo, hi, weight in groups: + n = m[:, :, lo:hi].sum() + val = square_delta[:, :, lo:hi].sum() / n if n > 0 else square_delta.new_zeros(()) + parts[name] = val * weight + counts[name] = m[:, :, lo].sum() + dens[name] = n + + total = sum(counts.values()) + if float(total) == 0.0: + loss = square_delta[0, 0, 0] + else: + loss = sum(parts[k] * counts[k] for k in counts) / total + + logged = {k: v.detach() for k, v in parts.items()} + # Two different counts, and they are not interchangeable: + # `_n` the FIRST channel's unmasked count. This is what upstream weights the + # groups by when it combines them -- effectively "how many rows had this + # group at all", since our cut turns a whole hand on or off together. + # `_den` the mean's actual denominator, over every channel in the range. + # Averaging per-batch means over a validation set needs `_den`; reproducing the + # training objective's group weighting needs `_n`. Using one for the other silently + # rescales the wrist against the fingers by the ratio of their channel counts (3 vs 63). + logged.update({f"{k}_n": v.detach() for k, v in counts.items()}) + logged.update({f"{k}_den": v.detach() for k, v in dens.items()}) + return loss, logged diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/model.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c44508d333155492b061361be3c87b4d0f439f86 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/model.py @@ -0,0 +1,341 @@ +"""The SmolVLA-official baseline, wired to this project's interfaces. + + Observation --> SmolVLM2-500M (frozen) --prefix K/V--> action expert --> v_t + state ----------^ (in the PREFIX) noise ---------^ + +This file plays the part LeRobot's `SmolVLAPolicy` plays upstream -- it owns the batch +shape, the normalisation and the optimiser groups -- while `flow.py` and +`smolvlm_with_expert.py` hold upstream's model, forked unmodified. The split is deliberate: +everything that could change the model's behaviour is in the forked files and pinned; this +file only adapts calling conventions. + +`Observation` carries exactly the fields this package's `to_observations` fills -- the +loader's contract, so the batches are V4's batches. + +**This model has no memory.** `loss` and `predict_from_noise` take the same +`steps: list[Observation]` V4's do and use only `steps[-1]`; the earlier steps exist so the +supervised anchor lands on the distribution of episode positions V4 trains on. + +**Three things here are NOT upstream, and each is forced rather than chosen:** + +1. **the loss is masked per channel** (`group_loss.py`). Upstream reduces with a plain + mean and masks only padded time steps; our 192 slots carry 138 real channels and which + ones depends on the sample. See that module for what the unmasked mean would do. +2. **normalisation comes from our statistics file**, installed as buffers, not from + LeRobot's processor pipeline -- 项目专项规则.md: the normaliser belongs to the data + pipeline, and MSE across two normalisers is not comparable. +3. **only the VLM is loaded from `smolvla_base`.** Its `action_in_proj` is [720, 32] and + `action_out_proj` [32, 720]; our action space is 192-wide, so the expert and both + projections start fresh. (User, 2026-09-10.) +""" + +from __future__ import annotations + +import os +import sys +from dataclasses import dataclass + +import torch +import torch.nn as nn + +from .config import Config, FlatConfig +from .flow import VLAFlowMatching +from .vla_utils import sample_noise, sample_time_beta + +from .group_loss import masked_group_loss_sq + + +@dataclass +class Observation: + """One control step. Field names and shapes are the shared loader's contract.""" + + images: torch.Tensor # [B, N, 3, H, W] float, already in [-1, 1] + lang_ids: torch.Tensor # [B, L] int + lang_mask: torch.Tensor # [B, L] bool + state: torch.Tensor # [B, 212] ** RAW ** -- the model normalises it + state_mask: torch.Tensor # [B, 212] bool + fov: torch.Tensor # [B, N, 2] ⚠ unused: SmolVLA has no FoV token + + +class SmolVLAOfficialModel(nn.Module): + def __init__(self, cfg: Config, *, load_weights: bool = True, + dtype: torch.dtype = torch.float32): + super().__init__() + cfg.validate() + self.cfg = cfg + # `load_weights` controls whether the Hub is read for the ARCHITECTURE's weights. + # Evaluation passes False: every parameter is about to be overwritten by a + # checkpoint, so reading 865 MB first is waste. Training passes True and then + # `load_pretrained` replaces the VLM with smolvla_base's. + flat = FlatConfig(cfg) + flat.load_vlm_weights = bool(load_weights) + self.flow = VLAFlowMatching(flat) + if dtype == torch.float32: + # `AutoModelForImageTextToText.from_pretrained(..., torch_dtype="bfloat16")` is + # hard-coded upstream, so the VLM arrives in bf16 whatever we ask for. Training + # in fp32 with bf16 autocast around the VLM forward is what the rest of this + # tree does; a silently-bf16 backbone is the bug the VITRA baseline hit on + # 2026-09-09 (3.03 B parameters in bf16 while `config.dtype` read float32). + self.flow = self.flow.to(torch.float32) + + d, s = cfg.action.dim, cfg.action.state_dim + for name, n in (("action_mean", d), ("action_std", d), + ("state_mean", s), ("state_std", s)): + self.register_buffer(name, torch.zeros(n) if name.endswith("mean") + else torch.ones(n)) + self.register_buffer("stats_loaded", torch.zeros((), dtype=torch.bool)) + + bad = [(n, p.dtype) for n, p in self.named_parameters() if p.dtype != dtype] + if bad: + raise RuntimeError( + f"{len(bad)} parameters are not {dtype} after construction, e.g. " + f"{bad[:3]}. A guard on the requested dtype is not enough here -- " + f"upstream pins the VLM's dtype inside `from_pretrained`.") + + # ------------------------------------------------------------------ statistics + + def set_normalisation(self, *, action_mean, action_std, state_mean, state_std, + eps: float = 1e-6) -> None: + """Install the dataset statistics. Must be called before training or inference. + + A sigma of exactly ZERO is ordinary and must not raise: MANO joint 0 sits at the + palm origin by construction, so its three coordinates have zero variance in every + domain, and the padding dimensions are the same case. Clamping keeps them an + identity transform; left alone they normalise to +-inf. + """ + for name, v, n in (("action_mean", action_mean, self.cfg.action.dim), + ("action_std", action_std, self.cfg.action.dim), + ("state_mean", state_mean, self.cfg.action.state_dim), + ("state_std", state_std, self.cfg.action.state_dim)): + t = torch.as_tensor(v, dtype=torch.float32).reshape(-1) + if t.numel() != n: + raise ValueError(f"{name} must have {n} entries, got {t.numel()}") + if not bool(torch.isfinite(t).all()): + raise ValueError( + f"{name} has {int((~torch.isfinite(t)).sum())} non-finite entries. " + f"Nothing downstream checks for this: the first `(a - mean) / std` " + f"turns the loss into NaN several thousand steps from here.") + if name.endswith("_std"): + if bool((t < 0).any()): + raise ValueError( + f"{name} has negative entries (min {float(t.min()):.3e}); a " + f"standard deviation cannot be negative, so the file is corrupt.") + t = t.clamp_min(eps) + getattr(self, name).copy_(t.to(getattr(self, name).device)) + self.stats_loaded.fill_(True) + + def _require_stats(self) -> None: + if not bool(self.stats_loaded): + raise RuntimeError( + "normalisation statistics were never installed. Call set_normalisation() " + "with values measured on THIS dataset at the 80 Hz action convention.") + + def normalise_action(self, a: torch.Tensor) -> torch.Tensor: + return (a - self.action_mean) / self.action_std + + def unnormalise_action(self, a: torch.Tensor) -> torch.Tensor: + return a * self.action_std + self.action_mean + + # ------------------------------------------------------------------ parameters + + def trainable_params_setup(self) -> None: + """Upstream's `set_requires_grad`, called once. + + ⚠ With `train_expert_only=True` -- SmolVLA's own default and what `smolvla_base` + was trained with -- the WHOLE VLM is frozen, vision tower included. What trains is + the action expert, `state_proj`, the two action projections and the time MLP. + """ + self.flow.vlm_with_expert.set_requires_grad() + self.flow.set_requires_grad() + + def param_groups(self) -> list[dict]: + """One group while the VLM is frozen; two once it is not. + + Upstream has only ever needed one: `get_optim_params` returns `self.parameters()` + and `AdamWConfig` gives every tensor the same rate. With `train_expert_only=True` + that is exactly right -- there is no backbone in the trainable set, and with + `weight_decay = 1e-10` there is no decay to exempt anything from. + + ** Stage B is different, and upstream never ran it. ** Unfreezing the language + model puts pretrained weights into the trainable set beside an action expert that + is still learning. Upstream's single 1e-4 would then hit a pretrained backbone at + the rate its randomly-initialised head needs. Both reference models in this project + split them by exactly 10x -- VITRA is action head 1e-4 / backbone 1e-5, V4 the same + -- so `optim.vlm_lr` follows that precedent rather than inventing a ratio. + + Setting `optim.vlm_lr` to `None` restores upstream's single group, whatever the + freeze setting: the deviation is a knob, not a hard-coded opinion. + """ + o = self.cfg.optim + trainable = [(n, p) for n, p in self.named_parameters() if p.requires_grad] + vlm = [p for n, p in trainable if "vlm_with_expert.vlm" in n] + rest = [p for n, p in trainable if "vlm_with_expert.vlm" not in n] + if o.vlm_lr is None or not vlm: + return [{"name": "all", "params": [p for _n, p in trainable], "lr": o.lr, + "weight_decay": o.weight_decay, "is_backbone": False}] + return [ + {"name": "expert", "params": rest, "lr": o.lr, + "weight_decay": o.weight_decay, "is_backbone": False}, + {"name": "vlm", "params": vlm, "lr": o.vlm_lr, + "weight_decay": o.weight_decay, "is_backbone": True}, + ] + + # ------------------------------------------------------------------ adaptation + + def _inputs(self, obs: Observation): + """Our `Observation` -> the five positional arguments `flow` takes. + + `images` is a LIST of `[B, 3, H, W]`, one per camera, because `embed_prefix` + iterates cameras and appends each one's embeddings to the prefix. Ours arrives + stacked as `[B, N, 3, H, W]` already in [-1, 1], which is the range SigLIP wants + and exactly what upstream's `prepare_images` produces -- so the conversion is a + split, with no resizing or rescaling left to do. + + `obs.fov` is dropped. SmolVLA has no field-of-view token; V4 added one. Passing it + would be inventing an architecture that is neither model's. + """ + self._require_stats() + imgs = obs.images + images = [imgs[:, i] for i in range(imgs.shape[1])] + ones = torch.ones(imgs.shape[0], dtype=torch.bool, device=imgs.device) + img_masks = [ones for _ in images] + state = (obs.state - self.state_mean) / self.state_std + return images, img_masks, obs.lang_ids, obs.lang_mask, state + + # ------------------------------------------------------------------ training + + def forward(self, steps: list[Observation], step_valid: torch.Tensor, + actions: torch.Tensor, action_mask: torch.Tensor): + return self.loss(steps, step_valid, actions, action_mask) + + def loss(self, steps: list[Observation], step_valid: torch.Tensor, + actions: torch.Tensor, action_mask: torch.Tensor, + generator: torch.Generator | None = None): + """-> (scalar loss, dict of per-group values for logging). + + `step_valid` is accepted and ignored: only `steps[-1]` is read, and the collate + left-pads so that index is the supervised step for every item in the batch. + + The noise and timestep are drawn HERE rather than left to `flow.forward`'s + defaults, so that a `generator` can make a run reproducible. The draws are + upstream's own functions with upstream's Beta parameters, so an unseeded call is + distributed identically to letting `flow.forward` do it. + """ + del step_valid + obs = steps[-1] + images, img_masks, lang_ids, lang_mask, state = self._inputs(obs) + + # RAW actions from the loader; normalise with the buffers a checkpoint carries. + a = self.normalise_action(actions.to(state.dtype)) + f = self.cfg.flow + noise = (sample_noise(a.shape, a.device) if generator is None else + torch.randn(a.shape, device=a.device, dtype=a.dtype, generator=generator)) + time = sample_time_beta(a.shape[0], a.device, alpha=f.time_alpha, + beta=f.time_beta, scale=f.time_scale, offset=f.time_offset) + + # `flow.forward` returns the per-element squared error, [B, chunk, 192]. + square = self.flow.forward(images, img_masks, lang_ids, lang_mask, state, a, + noise=noise, time=time) + return masked_group_loss_sq(square, action_mask, self.cfg.loss.groups) + + # ------------------------------------------------------------------ inference + + @torch.no_grad() + def predict_from_noise(self, steps: list[Observation], noise: torch.Tensor + ) -> torch.Tensor: + """-> [B, chunk, 192] in the NORMALISED domain, integrated from a GIVEN noise. + + The noise is passed in rather than drawn: the test protocol pairs one test frame + across conditions and the starting noise must be held fixed, so a `select_action` + that draws its own is unusable there. + """ + obs = steps[-1] + images, img_masks, lang_ids, lang_mask, state = self._inputs(obs) + return self.flow.sample_actions(images, img_masks, lang_ids, lang_mask, state, + noise=noise.to(state.dtype)) + + # ------------------------------------------------------------------ weights + + def load_pretrained(self, path: str) -> dict[str, list[str]]: + """Load ONLY the VLM out of `smolvla_base`. Returns {missing, unexpected, loaded}. + + The release stores a whole `SmolVLAPolicy`: 345 `model.vlm_with_expert.vlm.*` + tensors, 145 `model.vlm_with_expert.lm_expert.*`, and five projections sized for a + 32-dimensional action space. Only the first group is taken. + + ⚠ **The expert is deliberately left at its fresh initialisation.** It could be + loaded -- it is architecturally identical -- but it was trained to drive + `action_out_proj` [32, 720] into 32 robot joint targets, and ours emits 192 hand + channels through a randomly initialised head. An expert tuned to a head that no + longer exists is not a warm start; the first VITRA run was voided for the same + class of mismatch (its released head was `angle`-pretrained and we loaded it into + a keypoints layout). + + The count is asserted, not trusted: a silently-empty remap would leave the VLM at + its Hub initialisation and the run would look like a bad baseline rather than a + broken load. + """ + from safetensors.torch import load_file + + raw = load_file(path) if path.endswith(".safetensors") else torch.load( + path, map_location="cpu", weights_only=False) + # Our own checkpoints wrap the state dict under "model" alongside "step"; a + # LeRobot release is the state dict itself. Unwrap only when the inner value is + # a dict of tensors, so a release whose top level happens to hold a "model" key + # is not mistaken for one of ours. + if isinstance(raw, dict) and isinstance(raw.get("model"), dict): + raw = raw["model"] + + # ** Two kinds of checkpoint reach this method, and they are not interchangeable. ** + # + # a LeRobot release keys under `model.vlm_with_expert.vlm.` -- take the VLM, + # leave the expert and projections fresh (see above). + # one of OUR OWN keys are this model's own, e.g. `flow.action_in_proj.*` + # and the normalisation buffers. Stage B starts from stage + # A's `last.pt`, which is exactly this. Taking only the VLM + # there would throw away everything stage A trained and + # restart the expert from noise -- silently, because the VLM + # tensors would all match. + own_keys = set(self.state_dict()) + if any(k in own_keys for k in raw): + report = self.load_state_dict(raw, strict=False) + if report.missing_keys or report.unexpected_keys: + raise RuntimeError( + f"{path} is one of ours but does not match this model: " + f"{len(report.missing_keys)} missing, " + f"{len(report.unexpected_keys)} unexpected, e.g. " + f"{(report.missing_keys + report.unexpected_keys)[:3]}. Resuming " + f"across a config change would train a different model than the " + f"checkpoint describes.") + return {"loaded": sorted(raw), "missing": [], "unexpected": [], + "kind": "resume"} + + prefix = "model.vlm_with_expert.vlm." + remapped = {"vlm_with_expert.vlm." + k[len(prefix):]: v + for k, v in raw.items() if k.startswith(prefix)} + if not remapped: + raise RuntimeError( + f"{path} holds neither this model's own keys nor anything under " + f"{prefix!r}; keys look like {sorted(raw)[:3]}. Loading nothing would " + f"leave the VLM at its Hub initialisation and the baseline would be " + f"measuring the wrong model.") + + own = dict(self.flow.named_parameters()) + own.update(dict(self.flow.named_buffers())) + bad = [k for k, v in remapped.items() + if k in own and tuple(own[k].shape) != tuple(v.shape)] + if bad: + raise RuntimeError(f"shape mismatch on {len(bad)} VLM tensors, e.g. {bad[:3]}") + + report = self.flow.load_state_dict(remapped, strict=False) + missing_vlm = [k for k in report.missing_keys if k.startswith("vlm_with_expert.vlm.")] + if missing_vlm: + raise RuntimeError( + f"{len(missing_vlm)} VLM parameters were not covered by the checkpoint, " + f"e.g. {missing_vlm[:3]}. A partially loaded backbone trains without " + f"complaint.") + return {"loaded": sorted(remapped), "missing": list(report.missing_keys), + "unexpected": list(report.unexpected_keys), "kind": "vlm-only"} + + +Model = SmolVLAOfficialModel diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/smolvlm_with_expert.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/smolvlm_with_expert.py new file mode 100644 index 0000000000000000000000000000000000000000..4d646f10dbaff5e8e7c68bb06e71a5f5e2bf0ea4 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/smolvlm_with_expert.py @@ -0,0 +1,559 @@ +"""SmolVLA's VLM + action-expert stack, forked verbatim from LeRobot. See `FORK.md`. + +Source: `yuzhench/paper_code/smolvla_lerobot` @ 22bd7a2, +`src/lerobot/policies/smolvla/smolvlm_with_expert.py`, from `def apply_rope` to the end. +**Not one character of the model maths is changed.** Only the module header differs: the +upstream one guards the `transformers` imports behind LeRobot's `require_package` +machinery, which exists to give a nice error when an extra is missing. Here transformers +is a hard dependency, so the imports are plain. + +This is the file that holds what the user called "他们内部的信息交互方式" -- the part that +is genuinely NOT ours: + + * `forward_attn_layer` joint self-attention over [prefix | suffix] + * `forward_cross_attn_layer` the expert projects the VLM's hidden states through its OWN + k_proj / v_proj, i.e. real cross-attention rather than a + shared K/V cache + * `forward` alternates the two: layer index divisible by + `self_attn_every_n_layers` (2) does self-attention, the rest + cross-attend. The prefill pass forces self-attention on + every layer so the cache is complete. + +V4 variant A calls itself "the upstream SmolVLA arrangement", but it is a re-implementation +inside V4's own tree and it carries V4's memory bank, FoV token and state handling. This +file is the actual upstream, which is the point of the baseline. +""" + +import copy + +import torch +from torch import nn +from transformers import ( + AutoConfig, + AutoModel, + AutoModelForImageTextToText, + AutoProcessor, + DynamicCache, + SmolVLMForConditionalGeneration, +) + + +def apply_rope(x, positions, max_wavelength=10_000): + """ + Applies RoPE positions [B, L] to x [B, L, H, D]. + """ + d_half = x.shape[-1] // 2 + device = x.device + dtype = x.dtype + x = x.to(torch.float32) + + freq_exponents = (2.0 / x.shape[-1]) * torch.arange(d_half, dtype=torch.float32, device=device) + timescale = max_wavelength**freq_exponents + radians = positions[..., None].to(torch.float32) / timescale[None, None, :].to(torch.float32) + + radians = radians[..., None, :] + + sin = torch.sin(radians) # .to(dtype=dtype) + cos = torch.cos(radians) # .to(dtype=dtype) + + x1, x2 = x.split(d_half, dim=-1) + res = torch.empty_like(x) + res[..., :d_half] = x1 * cos - x2 * sin + res[..., d_half:] = x2 * cos + x1 * sin + + return res.to(dtype) + + +def get_intermediate_size(hidden_dim, ffn_dim_multiplier=4, multiple_of=256): + hidden_dim = int(2 * hidden_dim / 3) + hidden_dim = int(ffn_dim_multiplier * hidden_dim) + hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of) + return hidden_dim + + +class SmolVLMWithExpertModel(nn.Module): + def __init__( + self, + model_id: str = "HuggingFaceTB/SmolVLM2-500M-Video-Instruct", + load_vlm_weights: bool = True, + train_expert_only: bool = True, + freeze_vision_encoder: bool = False, + attention_mode: str = "self_attn", + num_expert_layers: int = -1, + num_vlm_layers: int = -1, + self_attn_every_n_layers: int = -1, + expert_width_multiplier: float = 0.5, + device: str = "auto", + ): + super().__init__() + if load_vlm_weights: + print(f"Loading {model_id} weights ...") + self.vlm = AutoModelForImageTextToText.from_pretrained( + model_id, + torch_dtype="bfloat16", + low_cpu_mem_usage=True, + ) + config = self.vlm.config + else: + config = AutoConfig.from_pretrained(model_id) + self.vlm = SmolVLMForConditionalGeneration(config=config) + self.processor = AutoProcessor.from_pretrained(model_id) + if num_vlm_layers > 0: + print(f"Reducing the number of VLM layers to {num_vlm_layers} ...") + self.get_vlm_model().text_model.layers = self.get_vlm_model().text_model.layers[:num_vlm_layers] + self.num_vlm_layers = len(self.get_vlm_model().text_model.layers) + self.config = config + # Smaller lm expert + lm_expert_config = copy.deepcopy(config.text_config) + hidden_size = lm_expert_config.hidden_size + lm_expert_config.hidden_size = int(hidden_size * expert_width_multiplier) # hidden_size // 2 + lm_expert_config.intermediate_size = get_intermediate_size(int(hidden_size * expert_width_multiplier)) + lm_expert_config.num_hidden_layers = self.num_vlm_layers + if num_expert_layers > 0: + assert len(self.get_vlm_model().text_model.layers) % num_expert_layers == 0, ( + f"Number of layers in the VLM {len(self.get_vlm_model().text_model.layers)} are not multiple of num_expert_layers {num_expert_layers}" + ) + lm_expert_config.num_hidden_layers = num_expert_layers + self.lm_expert = AutoModel.from_config(lm_expert_config) + + self.num_expert_layers = len(self.lm_expert.layers) + self.self_attn_every_n_layers = self_attn_every_n_layers + if "cross" in attention_mode: + # Reshape qkv projections to have the same input dimension as the vlm + for layer_idx in range(len(self.lm_expert.layers)): + if self.self_attn_every_n_layers > 0 and layer_idx % self.self_attn_every_n_layers == 0: + continue + self.lm_expert.layers[layer_idx].self_attn.k_proj = nn.Linear( + config.text_config.num_key_value_heads * config.text_config.head_dim, + lm_expert_config.num_key_value_heads * lm_expert_config.head_dim, + bias=lm_expert_config.attention_bias, + ) + self.lm_expert.layers[layer_idx].self_attn.v_proj = nn.Linear( + config.text_config.num_key_value_heads * config.text_config.head_dim, + lm_expert_config.num_key_value_heads * lm_expert_config.head_dim, + bias=lm_expert_config.attention_bias, + ) + # Remove unused embed_tokens + self.lm_expert.embed_tokens = None + + self.num_attention_heads = self.config.text_config.num_attention_heads + self.num_key_value_heads = self.config.text_config.num_key_value_heads + + self.freeze_vision_encoder = freeze_vision_encoder + self.train_expert_only = train_expert_only + self.attention_mode = attention_mode + self.expert_hidden_size = lm_expert_config.hidden_size + self.set_requires_grad() + + def get_vlm_model(self): + return self.vlm.model + + def set_requires_grad(self): + if self.freeze_vision_encoder: + self.get_vlm_model().vision_model.eval() + for params in self.get_vlm_model().vision_model.parameters(): + params.requires_grad = False + if self.train_expert_only: + self.vlm.eval() + for params in self.vlm.parameters(): + params.requires_grad = False + else: + # To avoid unused params issue with distributed training + last_layers = [self.num_vlm_layers - 1] + if ( + self.num_vlm_layers != self.num_expert_layers + and self.num_vlm_layers % self.num_expert_layers == 0 + ): + last_layers.append(self.num_vlm_layers - 2) + frozen_layers = [ + "lm_head", + "text_model.norm.weight", + ] + for layer in last_layers: + frozen_layers.append(f"text_model.layers.{layer}.") + + unmatched_patterns = set(frozen_layers) + for name, params in self.vlm.named_parameters(): + matched_patterns = [k for k in frozen_layers if k in name] + if matched_patterns: + params.requires_grad = False + unmatched_patterns.difference_update(matched_patterns) + if unmatched_patterns: + raise RuntimeError( + "Some frozen layer patterns matched no VLM parameters, so the corresponding layers " + "would silently remain trainable (parameter naming may have changed in transformers): " + f"{sorted(unmatched_patterns)}" + ) + # To avoid unused params issue with distributed training + for name, params in self.lm_expert.named_parameters(): + if "lm_head" in name: + params.requires_grad = False + + def train(self, mode: bool = True): + super().train(mode) + + if self.freeze_vision_encoder: + self.get_vlm_model().vision_model.eval() + + if self.train_expert_only: + self.vlm.eval() + + def embed_image(self, image: torch.Tensor): + patch_attention_mask = None + # Get sequence from the vision encoder + image_hidden_states = ( + self.get_vlm_model() + .vision_model( + pixel_values=image.to(dtype=self.get_vlm_model().vision_model.dtype), + patch_attention_mask=patch_attention_mask, + ) + .last_hidden_state + ) + # Modality projection & resampling + image_hidden_states = self.get_vlm_model().connector(image_hidden_states) + return image_hidden_states + + def embed_language_tokens(self, tokens: torch.Tensor): + return self.get_vlm_model().text_model.get_input_embeddings()(tokens) + + def forward_attn_layer( + self, + model_layers, + inputs_embeds, + layer_idx, + position_ids, + attention_mask, + batch_size, + head_dim, + use_cache: bool = True, + past_key_values: "DynamicCache | None" = None, + ) -> "tuple[list[torch.Tensor], DynamicCache | None]": + query_states = [] + key_states = [] + value_states = [] + for i, hidden_states in enumerate(inputs_embeds): + layer = model_layers[i][layer_idx] + if hidden_states is None or layer is None: + continue + hidden_states = layer.input_layernorm(hidden_states) + + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, layer.self_attn.head_dim) + + hidden_states = hidden_states.to(dtype=layer.self_attn.q_proj.weight.dtype) + query_state = layer.self_attn.q_proj(hidden_states).view(hidden_shape) + key_state = layer.self_attn.k_proj(hidden_states).view(hidden_shape) + value_state = layer.self_attn.v_proj(hidden_states).view(hidden_shape) + + query_states.append(query_state) + key_states.append(key_state) + value_states.append(value_state) + + # B,L,H,D with L sequence length, H number of heads, D head dim + # concatenate on the number of embeddings/tokens + query_states = torch.cat(query_states, dim=1) + key_states = torch.cat(key_states, dim=1) + value_states = torch.cat(value_states, dim=1) + seq_len = query_states.shape[1] + if seq_len < position_ids.shape[1]: + _position_ids = position_ids[:, :seq_len] + _attention_mask = attention_mask[:, :seq_len, :seq_len] + else: + _position_ids = position_ids + _attention_mask = attention_mask + + attention_mask_ = _attention_mask + position_ids_ = _position_ids + + query_states = apply_rope(query_states, position_ids_) + key_states = apply_rope(key_states, position_ids_) + + if use_cache: + # `DynamicCache` stores tensors as [batch, heads, seq, head_dim]; this module works with + # [batch, seq, heads, head_dim]. During prefix prefill this stores the (post-RoPE) K/V and + # returns them unchanged; during denoising it appends the suffix K/V and returns + # [prefix; suffix], exactly like the previous hand-rolled dict cache. + key_states, value_states = past_key_values.update( + key_states.transpose(1, 2), value_states.transpose(1, 2), layer_idx + ) + key_states = key_states.transpose(1, 2) + value_states = value_states.transpose(1, 2) + + attention_interface = self.get_attention_interface() + + att_output = attention_interface( + attention_mask_, batch_size, head_dim, query_states, key_states, value_states + ) + return [att_output], past_key_values + + def forward_cross_attn_layer( + self, + model_layers, + inputs_embeds, + layer_idx, + position_ids, + attention_mask, + batch_size, + head_dim, + use_cache: bool = True, + past_key_values: "DynamicCache | None" = None, + ) -> "tuple[list[torch.Tensor], DynamicCache | None]": + attention_interface = self.get_attention_interface() + + att_outputs = [] + assert len(inputs_embeds) == 2 or (use_cache and past_key_values is not None), ( + f"Both len(inputs_embeds) == {len(inputs_embeds)} and past_key_values is {past_key_values}" + ) + + if len(inputs_embeds) == 2 and not past_key_values: + # Prefix attention + seq_len = inputs_embeds[0].shape[1] + position_id, expert_position_id = position_ids[:, :seq_len], position_ids[:, seq_len:] + prefix_attention_mask = attention_mask[:, :seq_len, :seq_len] + + layer = model_layers[0][layer_idx] + + hidden_states = layer.input_layernorm(inputs_embeds[0]) + + input_shape = hidden_states.shape[:-1] + hidden_shape = (*input_shape, -1, layer.self_attn.head_dim) + + hidden_states = hidden_states.to(dtype=layer.self_attn.q_proj.weight.dtype) + query_state = layer.self_attn.q_proj(hidden_states).view(hidden_shape) + key_state = layer.self_attn.k_proj(hidden_states).view(hidden_shape) + value_states = layer.self_attn.v_proj(hidden_states).view(hidden_shape) + + # B,L,H,D with L sequence length, H number of heads, D head dim + query_states = apply_rope(query_state, position_id) + key_states = apply_rope(key_state, position_id) + + att_output = attention_interface( + prefix_attention_mask, batch_size, head_dim, query_states, key_states, value_states + ) + att_outputs.append(att_output) + else: + expert_position_id = position_ids + + if use_cache and past_key_values is not None: + # Cross-attention layers never fill the cache themselves: during the prefix prefill every + # layer goes through `forward_attn_layer`, which stores the (post-RoPE) VLM K/V for this + # layer index. Here we only read them back (no concatenation: the expert cross-attends to + # the fixed prefix). `DynamicCache` stores [batch, heads, seq, head_dim]; transpose back. + key_states = past_key_values.layers[layer_idx].keys.transpose(1, 2) + value_states = past_key_values.layers[layer_idx].values.transpose(1, 2) + + # Expert + expert_layer = model_layers[1][layer_idx] + if expert_layer is not None: + expert_hidden_states = expert_layer.input_layernorm(inputs_embeds[1]) + + expert_input_shape = expert_hidden_states.shape[:-1] + expert_hidden_shape = (*expert_input_shape, -1, expert_layer.self_attn.head_dim) + + expert_hidden_states = expert_hidden_states.to(dtype=expert_layer.self_attn.q_proj.weight.dtype) + expert_query_state = expert_layer.self_attn.q_proj(expert_hidden_states).view(expert_hidden_shape) + + # reshape (not view): K/V read back from the cache are transposed, hence non-contiguous + _key_states = key_states.to(dtype=expert_layer.self_attn.k_proj.weight.dtype).reshape( + *key_states.shape[:2], -1 + ) + expert_key_states = expert_layer.self_attn.k_proj(_key_states).view( + *_key_states.shape[:-1], -1, expert_layer.self_attn.head_dim + ) # k_proj should have same dim as kv + + _value_states = value_states.to(dtype=expert_layer.self_attn.v_proj.weight.dtype).reshape( + *value_states.shape[:2], -1 + ) + expert_value_states = expert_layer.self_attn.v_proj(_value_states).view( + *_value_states.shape[:-1], -1, expert_layer.self_attn.head_dim + ) + + expert_position_id = ( + expert_position_id - torch.min(expert_position_id, dim=1, keepdim=True).values + ) # start from 0 + expert_attention_mask = attention_mask[ + :, -inputs_embeds[1].shape[1] :, : expert_key_states.shape[1] : + ] # take into account kv + + expert_query_states = apply_rope(expert_query_state, expert_position_id) + + att_output = attention_interface( + expert_attention_mask, + batch_size, + head_dim, + expert_query_states, + expert_key_states, + expert_value_states, + ) + att_outputs.append(att_output) + else: + att_outputs.append(None) + + # att_output = att_output.to(dtype=models[i].dtype) + return att_outputs, past_key_values + + def get_model_layers(self, models: list) -> list: + vlm_layers = [] + expert_layers = [] + multiple_of = self.num_vlm_layers // self.num_expert_layers + for i in range(self.num_vlm_layers): + if multiple_of > 0 and i > 0 and i % multiple_of != 0: + expert_layer = None + else: + expert_layer_index = i // multiple_of if multiple_of > 0 else i + expert_layer = models[1].layers[expert_layer_index] + vlm_layers.append(models[0].layers[i]) + expert_layers.append(expert_layer) + return [vlm_layers, expert_layers] + + def forward( + self, + attention_mask: torch.Tensor | None = None, + position_ids: torch.LongTensor | None = None, + past_key_values: "DynamicCache | None" = None, + inputs_embeds: list[torch.FloatTensor] = None, + use_cache: bool | None = None, + ): + models = [self.get_vlm_model().text_model, self.lm_expert] + model_layers = self.get_model_layers(models) + for hidden_states in inputs_embeds: + # TODO this is very inefficient + # dtype is always the same, batch size too (if > 1 len) + # device could be trickier in multi gpu edge cases but that's it + if hidden_states is None: + continue + batch_size = hidden_states.shape[0] + + # Prefix prefill: no cache was passed, so create one and fill it (every layer runs + # self-attention over the prefix). When a filled cache is passed (denoising), layers + # read from it instead. + fill_kv_cache = use_cache and past_key_values is None + if fill_kv_cache: + past_key_values = DynamicCache() + + # RMSNorm + num_layers = self.num_vlm_layers + head_dim = self.vlm.config.text_config.head_dim + for layer_idx in range(num_layers): + if ( + fill_kv_cache + or "cross" not in self.attention_mode + or (self.self_attn_every_n_layers > 0 and layer_idx % self.self_attn_every_n_layers == 0) + ): + att_outputs, past_key_values = self.forward_attn_layer( + model_layers, + inputs_embeds, + layer_idx, + position_ids, + attention_mask, + batch_size, + head_dim, + use_cache=use_cache, + past_key_values=past_key_values, + ) + else: + att_outputs, past_key_values = self.forward_cross_attn_layer( + model_layers, + inputs_embeds, + layer_idx, + position_ids, + attention_mask, + batch_size, + head_dim, + use_cache=use_cache, + past_key_values=past_key_values, + ) + outputs_embeds = [] + start = 0 + for i, hidden_states in enumerate(inputs_embeds): + layer = model_layers[i][layer_idx] + att_output = ( + att_outputs[i] if i < len(att_outputs) else att_outputs[0] + ) # in case of self_attn + if hidden_states is not None: + if layer is None: + outputs_embeds.append(hidden_states) + continue + end = start + hidden_states.shape[1] + + if att_output.dtype != layer.self_attn.o_proj.weight.dtype: + att_output = att_output.to(layer.self_attn.o_proj.weight.dtype) + att_out = att_output[:, start:end] + out_emb = layer.self_attn.o_proj(att_out) + + out_emb += hidden_states + after_first_residual = out_emb.clone() + + out_emb = layer.post_attention_layernorm(out_emb) + out_emb = layer.mlp(out_emb) + + out_emb += after_first_residual + + outputs_embeds.append(out_emb) + + start = end if len(att_outputs) == 1 else 0 + else: + outputs_embeds.append(None) + + inputs_embeds = outputs_embeds + + # final norm + outputs_embeds = [] + for i, hidden_states in enumerate(inputs_embeds): + if hidden_states is not None: + out_emb = models[i].norm(hidden_states) + outputs_embeds.append(out_emb) + else: + outputs_embeds.append(None) + return outputs_embeds, past_key_values + + def get_attention_interface(self): + attention_interface = self.eager_attention_forward + return attention_interface + + def eager_attention_forward( + self, attention_mask, batch_size, head_dim, query_states, key_states, value_states + ): + num_att_heads = self.num_attention_heads + num_key_value_heads = self.num_key_value_heads + num_key_value_groups = num_att_heads // num_key_value_heads + + sequence_length = key_states.shape[1] + + key_states = key_states[:, :, :, None, :].expand( + batch_size, sequence_length, num_key_value_heads, num_key_value_groups, head_dim + ) + key_states = key_states.reshape( + batch_size, sequence_length, num_key_value_heads * num_key_value_groups, head_dim + ) + + value_states = value_states[:, :, :, None, :].expand( + batch_size, sequence_length, num_key_value_heads, num_key_value_groups, head_dim + ) + value_states = value_states.reshape( + batch_size, sequence_length, num_key_value_heads * num_key_value_groups, head_dim + ) + + # Attention here is upcasted to float32 to match the original eager implementation. + query_states = query_states.to(dtype=torch.float32) + key_states = key_states.to(dtype=torch.float32) + + query_states = query_states.transpose(1, 2) + key_states = key_states.transpose(1, 2) + + att_weights = torch.matmul(query_states, key_states.transpose(2, 3)) + att_weights *= head_dim**-0.5 + + att_weights = att_weights.to(dtype=torch.float32) + big_neg = torch.finfo(att_weights.dtype).min # -2.3819763e38 # See gemma/modules.py + masked_att_weights = torch.where(attention_mask[:, None, :, :], att_weights, big_neg) + probs = nn.functional.softmax(masked_att_weights, dim=-1) + probs = probs.to(dtype=value_states.dtype) + + att_output = torch.matmul(probs, value_states.permute(0, 2, 1, 3)) + + att_output = att_output.permute(0, 2, 1, 3) + # we use -1 because sequence length can change + att_output = att_output.reshape(batch_size, -1, num_key_value_heads * num_key_value_groups * head_dim) + + return att_output diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/vla_utils.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/vla_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa3c20dcc92110f9763ce059444558391f8a2c04 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/smolvla_official/vla_utils.py @@ -0,0 +1,169 @@ +"""SmolVLA's helper functions, forked verbatim from LeRobot. See `FORK.md`. + +Source: `yuzhench/paper_code/smolvla_lerobot` @ 22bd7a2 + * `src/lerobot/policies/common/flow_matching.py` -- sample_beta / sample_noise / + sample_time_beta + * `src/lerobot/policies/common/vla_utils.py` -- create_sinusoidal_pos_embedding / + make_att_2d_masks / pad_vector + +Forked rather than imported because LeRobot is a whole application -- draccus configs, +gymnasium envs, a processor pipeline, a Hub mixin -- and this baseline needs the model +maths, not the framework. Importing it would put all of that in the Modal image for the +sake of five functions. + +`euler_integrate` is NOT forked: its signature is half real-time-chunking parameters that +have no meaning here, and the loop it wraps is four lines. `flow.py` writes them out and +records the equivalence there. +""" + + +from __future__ import annotations + + +import logging # ** FORK EDIT ** upstream utils/device_utils.py:17. The fork took + # `get_safe_dtype` without the imports its own file carried, so its two + # `logging.warning` lines were NameErrors waiting for a device that + # cannot do float64. Latent on CUDA; found 2026-09-11 by an AST scan. +import math + + +import torch +import torch.nn.functional as F # noqa: N812 + # ** FORK EDIT ** upstream policies/common/vla_utils.py:28, same cause + # -- `pad_vector` uses `F.pad`. No caller in this tree today. + +from torch import Tensor + + + +# ---- flow_matching.py ------------------------------------------------------- + +def sample_beta(alpha: float, beta: float, bsize: int, device) -> Tensor: # see openpi (exact copy) + # Beta sampling uses _sample_dirichlet which isn't implemented for MPS, so sample on CPU + alpha_t = torch.tensor(alpha, dtype=torch.float32) + beta_t = torch.tensor(beta, dtype=torch.float32) + dist = torch.distributions.Beta(alpha_t, beta_t) + return dist.sample((bsize,)).to(device) + +def sample_noise(shape, device) -> Tensor: + """Standard-normal float32 noise, the flow-matching x_1 sample.""" + return torch.normal( + mean=0.0, + std=1.0, + size=shape, + dtype=torch.float32, + device=device, + ) + +def sample_time_beta(bsize: int, device, *, alpha: float, beta: float, scale: float, offset: float) -> Tensor: + """Beta-distributed flow-matching timesteps: ``Beta(alpha, beta) * scale + offset`` (openpi convention).""" + time_beta = sample_beta(alpha, beta, bsize, device) + time = time_beta * scale + offset + return time.to(dtype=torch.float32, device=device) + + +# ---- utils/device_utils.py --------------------------------------------------- +# Used by `create_sinusoidal_pos_embedding`; MPS has no float64, so the period grid falls +# back to float32 there. Kept so the embedding is bit-identical to upstream's. + +def get_safe_dtype(dtype: torch.dtype, device: str | torch.device): + """ + mps is currently not compatible with float64 + """ + if isinstance(device, torch.device): + device = device.type + if device == "mps" and dtype == torch.float64: + return torch.float32 + if device == "xpu" and dtype == torch.float64: + if hasattr(torch.xpu, "get_device_capability"): + device_capability = torch.xpu.get_device_capability() + # NOTE: Some Intel XPU devices do not support double precision (FP64). + # The `has_fp64` flag is returned by `torch.xpu.get_device_capability()` + # when available; if False, we fall back to float32 for compatibility. + if not device_capability.get("has_fp64", False): + logging.warning(f"Device {device} does not support float64, using float32 instead.") + return torch.float32 + else: + logging.warning( + f"Device {device} capability check failed. Assuming no support for float64, using float32 instead." + ) + return torch.float32 + return dtype + else: + return dtype + +# ---- vla_utils.py ----------------------------------------------------------- + +def create_sinusoidal_pos_embedding( # see openpi `create_sinusoidal_pos_embedding` (exact copy) + time: torch.Tensor, dimension: int, min_period: float, max_period: float, device="cpu" +) -> Tensor: + """Computes sine-cosine positional embedding vectors for scalar positions.""" + if dimension % 2 != 0: + raise ValueError(f"dimension ({dimension}) must be divisible by 2") + + if time.ndim != 1: + raise ValueError("The time tensor is expected to be of shape `(batch_size, )`.") + + dtype = get_safe_dtype(torch.float64, device.type) + fraction = torch.linspace(0.0, 1.0, dimension // 2, dtype=dtype, device=device) + period = min_period * (max_period / min_period) ** fraction + + # Compute the outer product + scaling_factor = 1.0 / period * 2 * math.pi + sin_input = scaling_factor[None, :] * time[:, None] + return torch.cat([torch.sin(sin_input), torch.cos(sin_input)], dim=1) + +def make_att_2d_masks(pad_masks: Tensor, att_masks: Tensor) -> Tensor: # see openpi (exact copy) + """Copied from big_vision. + + Tokens can attend to valid inputs tokens which have a cumulative mask_ar + smaller or equal to theirs. This way `mask_ar` int[B, N] can be used to + setup several types of attention, for example: + + [[1 1 1 1 1 1]]: pure causal attention. + + [[0 0 0 1 1 1]]: prefix-lm attention. The first 3 tokens can attend between + themselves and the last 3 tokens have a causal attention. The first + entry could also be a 1 without changing behaviour. + + [[1 0 1 0 1 0 0 1 0 0]]: causal attention between 4 blocks. Tokens of a + block can attend all previous blocks and all tokens on the same block. + + Args: + input_mask: bool[B, N] true if its part of the input, false if padding. + mask_ar: int32[B, N] mask that's 1 where previous tokens cannot depend on + it and 0 where it shares the same attention mask as the previous token. + """ + if att_masks.ndim != 2: + raise ValueError(att_masks.ndim) + if pad_masks.ndim != 2: + raise ValueError(pad_masks.ndim) + + cumsum = torch.cumsum(att_masks, dim=1) + att_2d_masks = cumsum[:, None, :] <= cumsum[:, :, None] + pad_2d_masks = pad_masks[:, None, :] * pad_masks[:, :, None] + return att_2d_masks & pad_2d_masks + +def pad_vector(vector: Tensor, new_dim: int, *, truncate: bool = False) -> Tensor: + """Pad the last dimension of a vector to new_dim with zeros. + + Can be (batch_size x sequence_length x features_dimension) + or (batch_size x features_dimension) + + With ``truncate=False`` (openpi behavior), vectors whose last dimension is already + >= new_dim are returned unchanged. With ``truncate=True`` (xVLA behavior), the last + dimension is truncated to exactly ``new_dim`` (which may be 0). + """ + if vector.shape[-1] == new_dim: + return vector + if not truncate: + if vector.shape[-1] >= new_dim: + return vector + return F.pad(vector, (0, new_dim - vector.shape[-1])) + shape = list(vector.shape) + current_dim = shape[-1] + shape[-1] = new_dim + new_vector = vector.new_zeros(*shape) + length = min(current_dim, new_dim) + new_vector[..., :length] = vector[..., :length] + return new_vector diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/__init__.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/config.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a2fb947d144cabc5d405a481d18e16190a24a696 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/config.py @@ -0,0 +1,509 @@ +"""Every knob for the VITRA-original baseline. Nothing is defaulted elsewhere. + +The values below are transcribed from VITRA's own training config, +`VLA-distillation/vitra/configs/human_pretrain_gigahands_real_all_cam0_keypoints_mano_vitra3b_linked.json`, +and from the code paths that config actually reaches. Where the json and the code +disagree, the CODE wins and the discrepancy is written down next to the field -- +a baseline that silently uses a number its reference never used is not a baseline. + +Sections `vlm`, `action`, `data` and `train` carry the field names V4's `dataloader` +package reads (`cfg.vlm.image_size`, `cfg.action.chunk_size`, ...). That is a hard +interface, not a style choice: the loader is shared so that the data reaching this +baseline and the data reaching V4 are the same data. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, fields, is_dataclass +from typing import Any + + +# --------------------------------------------------------------------------- VLM + +@dataclass +class VLMConfig: + """PaliGemma2-3B, VITRA's backbone. + + `google/paligemma2-3b-mix-224` is what VITRA's config names. The `-224` is + load-bearing: it fixes `image_size` at 224 and the number of image tokens at 256 + (224/14 = 16, 16x16 patches, no pixel shuffle). Pointing this at a `-448` checkpoint + without also changing `image_tokens` produces a masked_scatter size mismatch, which + at least fails loudly. + """ + + model_id: str = "google/paligemma2-3b-mix-224" + hidden_size: int = 2304 # PaliGemma2-3B text width; VITRA's json calls it + # `action_model.token_size` and passes it to the DiT + image_size: int = 224 + image_tokens: int = 256 # (224/14)^2 + num_cameras: int = 1 # VITRA's `post_transform` builds a one-image prompt and + # the comment there ("can be modified to multiple") is + # unexecuted code. One camera is what it was trained with. + + # `make_collate` pads the instruction to exactly this many tokens. It counts the 256 + # image tokens and the BOS/newline the PaliGemma prompt format adds, because those + # live in the same `input_ids`. + max_language_tokens: int = 256 + 1 + 48 + 1 # image | | text | \n + + # VITRA's `train_setup.freeze_option`. Three values exist upstream + # ("full_finetune", "only_head_and_token", "freeze_vision_encoder"); its config uses + # the third. NOTE the upstream `trainable_params_setup` tests all three with `==` + # against a DIFFERENT default each time, so more than one branch runs. Ours does not + # reproduce that bug -- see `model.trainable_params_setup`. + freeze_option: str = "freeze_vision_encoder" + + # `trainer.llm_freeze_step`: the language model trains only after this step. + llm_freeze_step: int = 5_000 + + cognition_token_id: int = 10 # an unused token id, VITRA's default + untied_cognition_token: bool = True # a separate learned embedding, initialised from + # the word embedding of `cognition_token_id` + cognition_token_init_id: int | None = None # None -> use `cognition_token_id` + + use_fov: bool = True + use_state: str = "DiT" # "DiT" | "VLM". + # ** "VLM" IS BROKEN UPSTREAM **: vitra_paligemma.py:320 + # calls `self.state_encoder`, but `_init_state_encoder` + # assigns `self.vlm_state_encoder` (:63) and no + # `state_encoder` attribute is ever defined. VITRA's own + # config uses "DiT", so nothing ever hit it. We implement + # "DiT" only and reject "VLM" rather than guess what the + # missing path was meant to be. + + use_bf16: bool = True # `use_bf16` in VITRA's config; autocast, not weights + gradient_checkpointing: bool = True # `trainer.enable_gradient_checkpointing` + + +# --------------------------------------------------------------------------- image + +@dataclass +class ImageConfig: + """How a frame becomes 224x224. + + **`squash` is VITRA's own behaviour and the project decision (2026-09-08, user).** + `PaliGemmaProcessor` resizes to a square without preserving the aspect ratio; V4 + instead scales the long side and pads the left and top. The two hand different + pictures to the vision tower, and which one this baseline uses decides what the + comparison against V4 means. Recorded here rather than left implicit. + + We do the resize ourselves instead of calling `PaliGemmaProcessor`, because the frames + arrive from V4's JPEG store as uint8 arrays and round-tripping them through PIL for + the processor costs a copy per frame per worker for nothing. The arithmetic the + processor applies is `x/255 * 2 - 1` (SigLIP, mean = std = 0.5), which is exactly what + V4's `to_observations` already does -- so only the geometry differs, and that is this + knob. + """ + + mode: str = "squash" # "squash" (VITRA/PaliGemma) | "pad" (V4/SmolVLA) + + # The store's frames have their LONG SIDE at the size they were packed with, so a + # squash to 224 resamples an already-downscaled frame rather than the 1080p original. + # Geometrically identical; a second resampling pass in quality terms. + # ⚠ UNVERIFIED: the packed size of the ten-domain store. Check on first run. + interpolation: str = "area" # cv2.INTER_AREA when downscaling + + +# --------------------------------------------------------------------------- action + +@dataclass +class ActionConfig: + """The action and state vectors. Identical to V4's, and not by coincidence -- + V4's dataloader vendors VITRA's geometry, so this is VITRA's own parameterisation.""" + + chunk_size: int = 16 # VITRA `fwd_pred_next_n`; the DiT is built with + # future_action_window_size = chunk_size - 1 = 15 + dim: int = 192 # `action_model.action_dim` + state_dim: int = 212 # `state_encoder.state_dim` + + control_hz: float = 10.0 # one VLM forward per 0.1 s + action_hz: float = 80.0 # the rate the statistics file must declare + source_fps: float = 30.0 + + # ** VITRA's released checkpoint is `angle`-pretrained ** -- its own config.json says + # `"action_type": "angle"`. The two layouts share only channels 0:6 (the left wrist): + # + # angle per hand 51 = dt(3) + dR(3) + pose_rel(45) right hand at 51:102 + # keypoints per hand 69 = dt(3) + dR(3) + joints(63) right hand at 69:138 + # + # Loading that head into the keypoints layout is semantically scrambled -- measured + # 2026-09-09, zero-adaptation: 100.65 cm / 103.08 deg / 47.80 cm. + action_type: str = "angle" + + # Evaluation only. Makes the loader emit the OTHER layout alongside this one, so one + # sample can serve a model trained on `angle` AND a metric scored against the data's + # own `joints_manospace`. `eval_baseline.py` sets it; training leaves it False and the + # samples are then byte-identical to what they were before this field existed. + dual_layout: bool = False + + state_mask_prob: float = 0.0 # VITRA's config sets 0.0 in the dataset AND the model + # default is 0.1; the dataset value is the one its runs + # used, so state is never dropped. + + +# --------------------------------------------------------------------------- DiT + +@dataclass +class DiTConfig: + """VITRA's diffusion-policy head. + + ⚠ `action_model.hidden_size = 1024` in VITRA's json is DEAD CONFIG. `_init_act_model` + (vitra_paligemma.py:115) never forwards it, and `DiT_B` hard-codes + `hidden_size=768, depth=12, num_heads=12`. The runs that config produced used 768. + Transcribing 1024 here would silently build a different model than the reference. + """ + + model_type: str = "DiT-B" # depth 12, width 768, 12 heads + depth: int = 12 + hidden_size: int = 768 + num_heads: int = 12 + mlp_ratio: float = 4.0 + + # The action token carries `[x_t ; action_mask]`, so the embedder's input is 2 x 192. + # This is not cosmetic: the 54 permanent padding slots contribute 108 input features + # that are identically zero at training time, and feeding a different mask at + # inference multiplies untrained weight columns by a non-zero vector. + concat_mask_to_input: bool = True + + learn_sigma: bool = False # VITRA passes `learn_sigma=False` (sigma_small=True) + class_dropout_prob: float = 0.1 # CFG: the fraction of samples whose condition is + # replaced by the learned `uncondition` vector + + # The sequence is [z | state | actions...]; +3 positions when state is in, +2 when not. + causal_attention: bool = True # VITRA masks the WHOLE sequence causally, including + # the condition and state tokens (dit.py:180-184). + # Kept, because it is what the reference does. + + +# --------------------------------------------------------------------------- diffusion + +@dataclass +class DiffusionConfig: + """DDPM training, DDIM sampling. `create_diffusion(...)` in `diffusion_policy.py`. + + ⚠ `diffusion_steps = 100`, NOT 1000. `DiffusionPolicy.__init__` defaults to 100 and + VITRA never overrides it. The DiT/ADM lineage this code came from uses 1000, so 1000 + is the number a reader expects; it is wrong here. + """ + + num_train_steps: int = 100 + schedule: str = "squaredcos_cap_v2" + num_inference_steps: int = 10 # `num_ddim_steps` + ddim_eta: float = 0.0 # deterministic + + # `repeated_diffusion_steps` in VITRA's config: each encoded condition is reused for K + # independent (noise, timestep) draws. K correlated views of one condition -- report + # them separately from the number of distinct episode timesteps. + repeated_diffusion_steps: int = 8 + + # `_forward_act_model`'s default. cfg_scale <= 1.0 disables CFG and halves the + # sampling cost. ⚠ This is an INFERENCE knob that changes reported numbers; it must be + # stated alongside any result. + cfg_scale: float = 5.0 + + # `ActionFeature.get_loss_components("angle")` -- FOUR groups, all weight 1.0, read off + # `HUMAN_LEFT_6D`/`HUMAN_LEFT_JOINTS`/... in `vitra_core/dataset_utils.py:22-27`. + # V4 uses SIX (it splits each 6-D wrist block into translation and rotation), which + # gives the wrist 4/6 of the loss where VITRA gives it 2/4. That difference belongs to + # the models being compared; it is not ours to harmonise away. + # + # ⚠ These ranges are `action_type`-dependent and `validate()` cross-checks them. The + # keypoints layout would be (0,6)/(6,69)/(69,75)/(75,138). + loss_groups: tuple[tuple[str, int, int, float], ...] = ( + ("left_6d", 0, 6, 1.0), + ("left_joints", 6, 51, 1.0), + ("right_6d", 51, 57, 1.0), + ("right_joints", 57, 102, 1.0), + ) + + +# --------------------------------------------------------------------------- data + +@dataclass +class DataConfig: + """Read by V4's dataloader. Field names are its interface, not ours.""" + + stride: int = 3 # source_fps / control_hz + interpolation: str = "pchip_bone_preserving" + geometric_augmentation: bool = False # VITRA `train_dataset.augmentation = False` + random_paraphrase: bool = True + + sources: tuple[dict[str, Any], ...] = () # filled from the run json + stats_path: str = "" # splits/ten_v3/stats_80hz.json + + +# --------------------------------------------------------------------------- train + +@dataclass +class TrainConfig: + """Sampling and the training loop. + + `max_seq_len` deserves a paragraph. V4 draws a window of L control steps and + supervises the LAST one, so the supervised anchor index is `s + L - 1` and larger L + pushes it later in the episode. This baseline has no memory and needs only that last + step -- but if it drew L = 1 the supervised anchors would be uniform over the episode + while V4's are skewed late, and the two models would then be measured on different + distributions of episode position. + + So the default KEEPS V4's draw and discards `steps[:-1]`. The cost is reading ~3.9 + frames per sample instead of 1, about 1.4 ms against a 3B forward pass -- negligible. + Set it to 1 only for a deliberate ablation, and say so when reporting. + """ + + # How the ranks are combined. Not a preference -- it follows from the card. + # + # "fsdp" shard-grad-op (ZeRO-2). Needed on a 48 GiB A6000: fp32 weights 11.8 + + # grads 11.8 + AdamW m,v 23.6 = 47.3 GiB leaves nothing for activations. + # This is also what VITRA's own config runs. + # "ddp" plain replication. On a 180 GiB B200 the whole 47.3 GiB fits with room to + # spare (batch 128 adds ~28 GiB of activations), so sharding buys nothing + # and costs an all-gather per forward. + # + # The MODEL is identical either way; only where the optimiser state lives changes. + parallel: str = "fsdp" + + max_seq_len: int = 9 # = V4's. bank_capacity 8 + 1 + length_alpha: float = 1.0 # P(L) proportional to L**alpha + use_only_last_step: bool = True # this model is memoryless; burn-in steps are dropped + + batch_size: int = 64 + max_steps: int = 65_000 # VITRA `trainer.max_steps` + seed: int = 42 # VITRA `seed` + + num_workers: int = 8 + prefetch_factor: int = 2 + + +# --------------------------------------------------------------------------- optim + +@dataclass +class OptimConfig: + """`trainer.lr_scheduler_type = "backbone-freeze-warmup"`, read off `fsdp.py`. + + ** THERE IS NO WARMUP. ** The name is misleading. `get_constant_schedule_with_freeze_warmup` + (`vitra/training/fsdp.py:68`) is three lines: the multiplier is `0.0` while + `step < llm_freeze_step` and `1.0` after. So the backbone's LR steps from 0 straight to + `backbone_lr` at step 5000, and the action head runs at a CONSTANT `action_model_lr` + from step 0 -- no warmup, no decay, on either group. + + ** "Freezing" is LR = 0, not `requires_grad = False`. ** Two consequences, and the + second is the reason to keep it: + + * gradients and Adam state exist for the whole backbone from step 0, so the frozen + phase costs the same memory as the rest of the run -- which is why VITRA needs + FSDP and why more GPUs alone would not fix a DDP OOM; + * AdamW at lr=0 updates nothing and decays nothing (both terms are multiplied by + lr), but `exp_avg` and `exp_avg_sq` keep accumulating. By step 5000 the optimiser + already holds 5000 steps of second-moment statistics, so the first real update is + correctly scaled. Freezing with `requires_grad` would start that state cold. + """ + + backbone_lr: float = 1e-5 # `trainer.learning_rate` + action_model_lr: float = 1e-4 # `trainer.action_model_learning_rate` + + # `fsdp.py:184`: `action_model_weight_decay` falls back to `weight_decay` when unset, + # and VITRA's config sets only the latter. So both groups decay at 0.1. + weight_decay: float = 0.1 # `trainer.weight_decay` + action_model_weight_decay: float | None = None + + # `split_modality_collator` (`fsdp.py:100-130`): a parameter is exempt from decay when + # `param.ndim <= 1 or name.endswith(".bias")` -- norms, biases, scalars. The cognition + # token is exempt by its own flag as well, though at 1-D it would be exempt anyway. + cognition_token_weight_decay: bool = False + + grad_clip: float = 1.0 # `trainer.gradient_clip_val` / `max_grad_norm` + betas: tuple[float, float] = (0.9, 0.999) # `fsdp.py:162`, an explicit default + eps: float = 1e-8 + grad_accum_steps: int = 1 + + +# --------------------------------------------------------------------------- weights + +@dataclass +class InitConfig: + """Where the parameters come from. + + VITRA's config: `pretrain_path = ./checkpoints/vitra-vla-3b.pt`. That is the project + decision for this baseline (2026-09-08, user): start from VITRA's pretrained VLA, not + from a bare PaliGemma2 backbone. + + ⚠ THE CHECKPOINT WAS SAVED UNDER `transformers==4.47.1` AND WE RUN 5.x. The module + tree beneath `PaliGemmaForConditionalGeneration` was reorganised between those + versions, so some keys will not match by name. `load_pretrained` therefore reports + every missing and unexpected key and refuses to continue unless the run json opts in + explicitly -- a `strict=False` that swallows a renamed backbone loads a randomly + initialised 3B model and trains it without a word. + """ + + pretrain_path: str = "" # vitra-vla-3b.pt + allow_partial_load: bool = False + + # Read off the real file on grace (2026-09-09, 899 keys, 3.767 B parameters). Longest + # prefix first: `backbone.language_model.model.` must be tested before any shorter + # `backbone.language_model.` would be, since the first match wins. + key_remap: tuple[tuple[str, str], ...] = ( + # transformers 4.47 -> 5.x: the tower, the projector and the text model all moved + # under `model`, and `lm_head` moved OUT from under `language_model`. + # transformers 4.47 nested the tower as `vision_tower.vision_model.*`; 5.x drops + # that level. Measured 2026-09-09: with the old spelling all 437 vision-tower + # parameters came back as "missing" and the guard stopped the run. + ("backbone.vision_tower.vision_model.", "vlm.pg.model.vision_tower."), + ("backbone.multi_modal_projector.", "vlm.pg.model.multi_modal_projector."), + ("backbone.language_model.model.", "vlm.pg.model.language_model."), + ("backbone.language_model.lm_head.", "vlm.pg.lm_head."), + # VITRA's own tree -> ours. + ("act_model.net.", "dit."), + ("fov_encoder.", "vlm.fov_encoder."), + ("cognition_token", "vlm.cognition_token"), + ) + + +# --------------------------------------------------------------------------- root + +@dataclass +class Config: + """The name is `Config`, not `V4XConfig`. + + V4's `train.load_variant` derives class names as `V4{KEY}Config`; that convention + describes V4 variants and this is not one. Until `eval_test.py` grows a fixed-name + lookup -- a change to a file this tree does not own -- this package is loaded by + `baselines/train.py`, which imports it directly. + """ + + vlm: VLMConfig = field(default_factory=VLMConfig) + image: ImageConfig = field(default_factory=ImageConfig) + action: ActionConfig = field(default_factory=ActionConfig) + dit: DiTConfig = field(default_factory=DiTConfig) + diffusion: DiffusionConfig = field(default_factory=DiffusionConfig) + data: DataConfig = field(default_factory=DataConfig) + train: TrainConfig = field(default_factory=TrainConfig) + optim: OptimConfig = field(default_factory=OptimConfig) + init: InitConfig = field(default_factory=InitConfig) + + # What `--preflight` must see from a head that outputs zero: DDPM predicts epsilon, so a zero-output head scores `E[eps^2] = 1`. + # Declared here so `train.py` does not have to know which model it is + # driving; hard-coding one baseline's value failed the other's first + # launch on numbers that were correct. + preflight_loss: float = 1.0 + + # ----------------------------------------------------------------- validation + + def validate(self) -> None: + """Everything that would otherwise fail late, expensively, or silently.""" + v, a, d, f = self.vlm, self.action, self.dit, self.diffusion + + if v.use_state != "DiT": + raise ValueError( + f"use_state={v.use_state!r}: only 'DiT' is implemented. The upstream 'VLM' " + f"path is broken (vitra_paligemma.py:320 calls self.state_encoder, which " + f"is never assigned), so there is no reference behaviour to reproduce.") + + if v.image_size % 14 != 0: + raise ValueError(f"image_size {v.image_size} is not a multiple of SigLIP's " + f"patch size 14") + expect_tokens = (v.image_size // 14) ** 2 + if v.image_tokens != expect_tokens: + raise ValueError( + f"image_tokens {v.image_tokens} != (image_size/14)^2 = {expect_tokens}. " + f"These must agree or masked_scatter fails on the first batch.") + + if self.image.mode not in ("squash", "pad"): + raise ValueError(f"image.mode {self.image.mode!r} must be 'squash' or 'pad'") + + if a.action_type not in ("angle", "keypoints"): + raise ValueError(f"action.action_type {a.action_type!r} must be 'angle' or " + f"'keypoints'") + if a.action_type == "angle" and f.loss_groups[1][2] != 51: + raise ValueError( + "action_type='angle' but diffusion.loss_groups still carry the keypoints " + "ranges. angle is (0,6)/(6,51)/(51,57)/(57,102); keypoints is " + "(0,6)/(6,69)/(69,75)/(75,138). Mixing them silently trains on the wrong " + "channels.") + + if a.dim != 192 or a.state_dim != 212: + raise ValueError( + f"action.dim={a.dim}, state_dim={a.state_dim}: the normalisation " + f"statistics and the loss groups are tied to 192/212.") + + hi = max(h for _, _, h, _ in f.loss_groups) + if hi > a.dim: + raise ValueError(f"loss group ends at {hi}, past action dim {a.dim}") + + if d.hidden_size % d.num_heads != 0: + raise ValueError(f"DiT hidden {d.hidden_size} not divisible by " + f"{d.num_heads} heads") + if d.model_type == "DiT-B" and (d.depth, d.hidden_size, d.num_heads) != (12, 768, 12): + raise ValueError( + f"model_type 'DiT-B' means depth 12 / width 768 / 12 heads upstream, got " + f"{d.depth}/{d.hidden_size}/{d.num_heads}. Rename the type or fix the " + f"numbers -- do not ship a 'DiT-B' that is not one.") + + if f.num_inference_steps > f.num_train_steps: + raise ValueError(f"num_inference_steps {f.num_inference_steps} exceeds " + f"num_train_steps {f.num_train_steps}") + if f.num_train_steps % f.num_inference_steps != 0: + # `range(0, T, T // N)` must land on exactly N points. T=100, N=10 -> stride 10. + raise ValueError( + f"num_train_steps {f.num_train_steps} is not a multiple of " + f"num_inference_steps {f.num_inference_steps}; the DDIM grid would be " + f"ragged. See diffusion.ddim_sample for why the grid matters.") + if f.repeated_diffusion_steps < 1: + raise ValueError("repeated_diffusion_steps must be >= 1") + + if v.llm_freeze_step < 0: + raise ValueError("llm_freeze_step must be >= 0") + + if self.train.parallel not in ("fsdp", "ddp"): + raise ValueError(f"train.parallel {self.train.parallel!r} must be 'fsdp' or " + f"'ddp'") + + if self.train.max_seq_len < 1: + raise ValueError("train.max_seq_len must be >= 1") + if not self.train.use_only_last_step: + raise ValueError( + "use_only_last_step=False: this model has no memory and no way to consume " + "earlier steps. Set it to True, or use a model that has one.") + + if self.data.stride != int(round(a.source_fps / a.control_hz)): + raise ValueError( + f"data.stride {self.data.stride} != source_fps/control_hz = " + f"{a.source_fps}/{a.control_hz}") + + if not self.data.stats_path: + raise ValueError( + "data.stats_path is empty. The baseline MUST use the same normalisation " + "statistics as V4 -- see 项目专项规则.md, '归一化器属数据管线'.") + + if self.init.pretrain_path and self.init.allow_partial_load: + # Not an error, but it must be a deliberate, visible choice. + pass + + +# --------------------------------------------------------------------------- json + +def apply_overrides(cfg: Any, overrides: dict[str, Any], path: str = "") -> None: + """Recursively overwrite dataclass fields from a parsed json. + + Unknown keys RAISE. A run json with a typo'd knob otherwise trains happily with the + default and the log says nothing; that failure is indistinguishable from the + experiment simply not working. + """ + known = {f.name: f for f in fields(cfg)} + for key, value in overrides.items(): + if key not in known: + where = f"{path}{key}" + raise KeyError(f"unknown config key {where!r}; known here: " + f"{sorted(known)}") + current = getattr(cfg, key) + if is_dataclass(current) and isinstance(value, dict): + apply_overrides(current, value, f"{path}{key}.") + elif isinstance(current, tuple) and isinstance(value, list): + setattr(cfg, key, tuple(tuple(v) if isinstance(v, list) else v for v in value)) + else: + setattr(cfg, key, value) + + +def from_json(overrides: dict[str, Any]) -> Config: + cfg = Config() + apply_overrides(cfg, overrides) + cfg.validate() + return cfg diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/diffusion.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..c663bf95e48dbf89d6dfec610f67d5877084e69c --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/diffusion.py @@ -0,0 +1,178 @@ +"""DDPM training and DDIM sampling, as VITRA configures them. + +Rewritten from `vitra/models/action_model/gaussian_diffusion.py` + `respace.py` + +`diffusion_policy.py`, keeping only the path VITRA's config reaches: + + create_diffusion(timestep_respacing="", noise_schedule="squaredcos_cap_v2", + diffusion_steps=100, sigma_small=True, learn_sigma=False) + +That selects: epsilon prediction, a fixed (not learned) variance, a plain MSE on the +noise, and -- at sampling -- `create_ddim(ddim_step=10)` with `clip_denoised=False, +eta=0.0`. Everything the 42 KB upstream file offers beyond that (learned sigma, VLB +terms, ancestral p_sample, importance-sampled timesteps) is unreachable from that call +and is not reproduced here. + +Two numbers a reader will expect to be different: + + * **T = 100, not 1000.** `DiffusionPolicy.__init__` defaults `diffusion_steps=100` and + VITRA never overrides it. The DiT/ADM lineage this came from uses 1000. + * **the beta clamp is real.** `betas_for_alpha_bar` caps each beta at 0.999, so + `alpha_bar` does NOT equal `f(t)/f(0)` at the tail. At T=100 the cosine's last entry + is exactly zero, which would make the last beta exactly 1; the clamp is what keeps + `alpha_bar[99]` at ~1e-3 rather than 0. Recomputing alpha_bar directly from the + cosine, as one naturally would, gives a different schedule. +""" + +from __future__ import annotations + +import math + +import torch + +from .config import Config + + +# --------------------------------------------------------------------------- schedule + +def betas_for_alpha_bar(num_steps: int, max_beta: float = 0.999) -> torch.Tensor: + """`squaredcos_cap_v2`, exactly as `get_named_beta_schedule` builds it. + + `alpha_bar(u) = cos((u + 0.008) / 1.008 * pi/2) ** 2` sampled at `i/T` and + `(i+1)/T`; each beta is `1 - abar(t2)/abar(t1)`, capped. + """ + def alpha_bar(u: float) -> float: + return math.cos((u + 0.008) / 1.008 * math.pi / 2) ** 2 + + betas = [] + for i in range(num_steps): + t1, t2 = i / num_steps, (i + 1) / num_steps + betas.append(min(1.0 - alpha_bar(t2) / alpha_bar(t1), max_beta)) + return torch.tensor(betas, dtype=torch.float64) + + +def alpha_bar_table(cfg: Config) -> torch.Tensor: + """Cumulative signal retention, length `num_train_steps`, float32. + + Kept as a buffer on the model so a checkpoint carries the schedule it was trained + with. A schedule silently changing between training and evaluation is not visible in + any loss curve. + """ + d = cfg.diffusion + if d.schedule != "squaredcos_cap_v2": + raise ValueError(f"schedule {d.schedule!r}: only 'squaredcos_cap_v2' is " + f"implemented, which is the one VITRA uses") + betas = betas_for_alpha_bar(d.num_train_steps) + return torch.cumprod(1.0 - betas, dim=0).float() + + +def ddim_grid(cfg: Config) -> list[int]: + """The timesteps DDIM visits, in the order it visits them (high to low). + + `space_timesteps(T, "ddimN")` searches for the stride `i` with + `len(range(0, T, i)) == N` and returns `set(range(0, T, i))`. For T=100, N=10 that is + {0, 10, ..., 90}. + + **This is not `linspace(T-1, 0, N)`, and the difference is not cosmetic.** x0 is + recovered as `(x - sqrt(1-abar)*eps) / sqrt(abar)`, so `1/sqrt(abar)` is the factor by + which the network's epsilon error is amplified on the first step. Starting at the top + of the schedule instead of at the top of the grid multiplies it by orders of + magnitude; the V4 side measured a wrist error of 7,916 cm against a 2 cm baseline + from exactly this mistake (2026-09-03, `v4_d_dp_0/diffusion.py`). + """ + T, n = cfg.diffusion.num_train_steps, cfg.diffusion.num_inference_steps + for stride in range(1, T + 1): + if len(range(0, T, stride)) == n: + return list(range(0, T, stride))[::-1] + raise ValueError(f"cannot space {T} steps into {n} for DDIM") + + +# --------------------------------------------------------------------------- masks + +def component_action_mask(batch: int, chunk: int, dim: int, cfg: Config, + device: torch.device) -> torch.Tensor: + """The mask inference must use: True on the loss groups, False on the padding. + + Of 192 slots only 0:138 mean anything; 138:192 are permanent padding. The mask is + CONCATENATED into the DiT's input, so those 54 slots and their 54 mask flags are 108 + input features that are identically zero at every training step -- their weight + columns never receive gradient. Passing an all-ones mask at inference multiplies + untrained columns by a non-zero vector and corrupts all 138 real predictions. + + Both hands are switched on even though our cut annotates only one hand per episode, + so the mask here is not the mask training saw for the absent hand. That is V4's choice + too (`eval_test.py` builds its mask from the config, not from the batch), and matching + it is the point: the two models must meet the test set the same way. + """ + mask = torch.zeros(batch, chunk, dim, dtype=torch.bool, device=device) + for _, lo, hi, _ in cfg.diffusion.loss_groups: + mask[..., lo:hi] = True + return mask + + +# --------------------------------------------------------------------------- training + +def sample_timesteps(batch: int, cfg: Config, device: torch.device, + generator: torch.Generator | None = None) -> torch.Tensor: + """Uniform over the full (unspaced) schedule -- `torch.randint(0, T, (B,))`.""" + return torch.randint(0, cfg.diffusion.num_train_steps, (batch,), device=device, + generator=generator) + + +def q_sample(x0: torch.Tensor, t: torch.Tensor, noise: torch.Tensor, + alpha_bar: torch.Tensor) -> torch.Tensor: + ab = alpha_bar.to(x0.device)[t].view(-1, *([1] * (x0.dim() - 1))) + return ab.sqrt() * x0 + (1.0 - ab).sqrt() * noise + + +def masked_group_loss(pred: torch.Tensor, target: torch.Tensor, + action_mask: torch.Tensor, cfg: Config, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """VITRA's four-group masked loss. + + ** The arithmetic moved to `baselines/group_loss.py` on 2026-09-10 ** so the SmolVLA + baseline could run the same computation over its own six-group table. This wrapper + keeps VITRA's call site and its group source (`cfg.diffusion.loss_groups`, four groups, + a 6-D wrist block per hand -- V4 and the SmolVLA baseline split that into translation + and rotation, which gives the wrist 4/6 of the loss where this gives it 2/4). + + Behaviour is unchanged: the extraction was a move, not a rewrite, and the run that + produced `vitra_orig_egotouch_r1` used the identical arithmetic. + """ + import sys, os + _here = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + if _here not in sys.path: + sys.path.insert(0, _here) + from .group_loss import masked_group_loss as _shared + + return _shared(pred, target, action_mask, cfg.diffusion.loss_groups) + + +# --------------------------------------------------------------------------- sampling + +@torch.no_grad() +def ddim_sample(eps_fn, noise: torch.Tensor, alpha_bar: torch.Tensor, + grid: list[int], eta: float = 0.0) -> torch.Tensor: + """DDIM from `noise` back to data. `eta = 0` is deterministic. + + `eps_fn(x_t, t) -> eps` is called once per grid point against a condition the caller + prepared. `clip_denoised=False`, matching VITRA's `ddim_sample_loop` call -- with the + correct grid the amplification is small and clipping is not what keeps it stable. + + The final step targets `alpha_bar_prev = 1`, which is `x = pred_x0`. Upstream reaches + the same place through `alphas_cumprod_prev[0] = 1.0`. + """ + ab = alpha_bar.to(noise.device) + x = noise + for i, t in enumerate(grid): + a_t = ab[t].view(1, 1, 1) + eps = eps_fn(x, torch.full((x.shape[0],), t, device=x.device, dtype=torch.long)) + x0 = (x - (1 - a_t).sqrt() * eps) / a_t.sqrt().clamp_min(1e-8) + if i + 1 == len(grid): + return x0 + a_prev = ab[grid[i + 1]].view(1, 1, 1) + sigma = (eta * ((1 - a_prev) / (1 - a_t)).clamp_min(0).sqrt() + * (1 - a_t / a_prev).clamp_min(0).sqrt()) + x = a_prev.sqrt() * x0 + (1 - a_prev - sigma ** 2).clamp_min(0).sqrt() * eps + if eta > 0: + x = x + sigma * torch.randn_like(x) + raise AssertionError("unreachable: the loop returns on its last iteration") diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/dit.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/dit.py new file mode 100644 index 0000000000000000000000000000000000000000..d2bb73002507dee90b4b3f1e6cf6b76ef111fc27 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/dit.py @@ -0,0 +1,351 @@ +"""VITRA's diffusion-policy head: a DiT stack with adaLN-Zero conditioning. + +Rewritten from `VLA-distillation/vitra/models/action_model/dit.py`, which is itself +Meta's DiT with the patch embedder replaced by an action embedder. Rewritten rather than +imported for two reasons: that tree pins `transformers==4.47.1` and cannot be installed +alongside V4's `>=5.13.0`, and it pulls `timm` for three small modules (`Attention`, +`Mlp`, `RmsNorm`) that are thirty lines each. + +**Everything here is behaviour-preserving with respect to the reference.** Where the +reference does something surprising, it is reproduced and the surprise is documented -- +this is a baseline, and "we fixed it while porting" makes the number mean something else. +Two such places: + + * the attention mask is causal over the WHOLE sequence, condition and state tokens + included, so the condition token attends to nothing but itself (dit.py:180-184); + * `initialize_weights` runs a generic Xavier pass and then overwrites specific modules, + so the order matters and the zeroed adaLN layers must be zeroed LAST. + +The sequence the blocks see: + + [ z | state | a_0 ... a_15 ] 18 positions when state is in the sequence + ^ ^ ^ + | | the noised action chunk, each token [x_t ; action_mask] = 384 features + | the current state, [state ; state_mask] = 424 features + the VLM's cognition token, projected + + c = z + t one vector per sample, drives every adaLN +""" + +from __future__ import annotations + +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .config import Config + + +def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor) -> torch.Tensor: + return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1) + + +class RMSNorm(nn.Module): + """timm's `RmsNorm` with its defaults: affine, eps 1e-6, computed in float32. + + Applied per attention head over `head_dim`, not over the model width. + """ + + def __init__(self, dim: int, eps: float = 1e-6): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + dt = x.dtype + x = x.float() + x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) + return (x * self.weight.float()).to(dt) + + +class Mlp(nn.Module): + """timm's `Mlp` as DiT configures it: tanh-approximated GELU, no dropout.""" + + def __init__(self, dim: int, hidden: int): + super().__init__() + self.fc1 = nn.Linear(dim, hidden, bias=True) + self.act = nn.GELU(approximate="tanh") + self.fc2 = nn.Linear(hidden, dim, bias=True) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.fc2(self.act(self.fc1(x))) + + +class Attention(nn.Module): + """timm's `Attention` with `qkv_bias=True, qk_norm=True, norm_layer=RmsNorm`. + + `attn_mask` is an additive float mask ([0, -inf]) shaped [T, T], broadcast over batch + and heads -- the form `scaled_dot_product_attention` takes for a float mask. + """ + + def __init__(self, dim: int, num_heads: int): + super().__init__() + if dim % num_heads: + raise ValueError(f"dim {dim} not divisible by {num_heads} heads") + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.qkv = nn.Linear(dim, dim * 3, bias=True) + self.q_norm = RMSNorm(self.head_dim) + self.k_norm = RMSNorm(self.head_dim) + self.proj = nn.Linear(dim, dim, bias=True) + + def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None = None + ) -> torch.Tensor: + B, N, C = x.shape + qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim) + q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0) # each [B, H, N, hd] + q, k = self.q_norm(q), self.k_norm(k) + x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask) + return self.proj(x.transpose(1, 2).reshape(B, N, C)) + + +class TimestepEmbedder(nn.Module): + """Sinusoidal embedding of the DISCRETE diffusion step, then a 2-layer MLP. + + `max_period` is 10000 and `frequency_embedding_size` 256, both upstream defaults. The + timestep is an integer index into a 100-step schedule, not a continuous tau. + """ + + def __init__(self, hidden_size: int, frequency_embedding_size: int = 256): + super().__init__() + self.frequency_embedding_size = frequency_embedding_size + self.mlp = nn.Sequential( + nn.Linear(frequency_embedding_size, hidden_size, bias=True), + nn.SiLU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + + @staticmethod + def timestep_embedding(t: torch.Tensor, dim: int, max_period: int = 10000 + ) -> torch.Tensor: + half = dim // 2 + freqs = torch.exp(-math.log(max_period) + * torch.arange(half, dtype=torch.float32, device=t.device) / half) + args = t[:, None].float() * freqs[None] + # cos FIRST, then sin -- upstream's order. Swapping them is a different (learnable, + # so ultimately harmless) basis, but it would break loading a reference checkpoint. + emb = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + emb = torch.cat([emb, torch.zeros_like(emb[:, :1])], dim=-1) + return emb + + def forward(self, t: torch.Tensor) -> torch.Tensor: + freq = self.timestep_embedding(t, self.frequency_embedding_size) + return self.mlp(freq.to(next(self.mlp.parameters()).dtype)) + + +class ActionEmbedder(nn.Module): + """`[x_t ; action_mask]` -> hidden. Linear-GELU-Linear.""" + + def __init__(self, action_size: int, hidden_size: int): + super().__init__() + self.projector = nn.Sequential( + nn.Linear(action_size, hidden_size, bias=True), + nn.GELU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.projector(x) + + +class StateEmbedder(nn.Module): + """`[state*mask ; mask]` -> hidden. Deeper and wider than the action embedder + (2*state -> 4*hidden -> hidden -> hidden), which is upstream's shape.""" + + def __init__(self, state_size: int, hidden_size: int): + super().__init__() + self.projector = nn.Sequential( + nn.Linear(2 * state_size, 4 * hidden_size, bias=True), + nn.GELU(), + nn.Linear(4 * hidden_size, hidden_size, bias=True), + nn.GELU(), + nn.Linear(hidden_size, hidden_size, bias=True), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.projector(x) + + +class LabelEmbedder(nn.Module): + """The cognition token, plus classifier-free-guidance dropout. + + During training a `dropout_prob` fraction of samples have their condition replaced by + the learned `uncondition` vector; at sampling, `uncondition` is what the unconditional + branch is fed. Dropping the condition AFTER projection would give the unconditional + branch a vector the projection never saw, so the replacement happens before `linear`. + """ + + def __init__(self, in_size: int, hidden_size: int, dropout_prob: float = 0.1): + super().__init__() + self.dropout_prob = dropout_prob + self.linear = nn.Linear(in_size, hidden_size) + if dropout_prob > 0: + # Shape [1, in_size]: one token wide, matching the [B, 1, D] condition. + self.uncondition = nn.Parameter(torch.empty(1, in_size)) + + def token_drop(self, conditions: torch.Tensor, + generator: torch.Generator | None = None) -> torch.Tensor: + drop = torch.rand(conditions.shape[0], device=conditions.device, + generator=generator) < self.dropout_prob + return torch.where(drop[:, None, None], self.uncondition.to(conditions.dtype), + conditions) + + def forward(self, conditions: torch.Tensor, train: bool, + generator: torch.Generator | None = None) -> torch.Tensor: + if train and self.dropout_prob > 0: + conditions = self.token_drop(conditions, generator) + return self.linear(conditions) + + +class DiTBlock(nn.Module): + """adaLN-Zero. `c` is one vector per sample and drives shift/scale/gate for both + sub-layers, broadcast across every sequence position.""" + + def __init__(self, hidden_size: int, num_heads: int, mlp_ratio: float = 4.0): + super().__init__() + self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.attn = Attention(hidden_size, num_heads) + self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.mlp = Mlp(hidden_size, int(hidden_size * mlp_ratio)) + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), nn.Linear(hidden_size, 6 * hidden_size, bias=True)) + + def forward(self, x: torch.Tensor, c: torch.Tensor, + attn_mask: torch.Tensor | None) -> torch.Tensor: + sh1, sc1, g1, sh2, sc2, g2 = self.adaLN_modulation(c).chunk(6, dim=1) + x = x + g1.unsqueeze(1) * self.attn(modulate(self.norm1(x), sh1, sc1), attn_mask) + x = x + g2.unsqueeze(1) * self.mlp(modulate(self.norm2(x), sh2, sc2)) + return x + + +class FinalLayer(nn.Module): + def __init__(self, hidden_size: int, out_channels: int): + super().__init__() + self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) + self.linear = nn.Linear(hidden_size, out_channels, bias=True) + self.adaLN_modulation = nn.Sequential( + nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True)) + + def forward(self, x: torch.Tensor, c: torch.Tensor) -> torch.Tensor: + shift, scale = self.adaLN_modulation(c).chunk(2, dim=1) + return self.linear(modulate(self.norm_final(x), shift, scale)) + + +class DiT(nn.Module): + """VITRA's `DiT`, specialised to what its config actually builds. + + Dropped relative to upstream: `past_action_window_size` (always 0 in every VITRA + config and in our data), `learn_sigma` (always False), and the 2-D sin-cos position + helpers (dead code -- the action positions use a learned table). + """ + + def __init__(self, cfg: Config): + super().__init__() + d, a, v = cfg.dit, cfg.action, cfg.vlm + self.cfg = cfg + self.chunk_size = a.chunk_size + self.in_channels = a.dim * (2 if d.concat_mask_to_input else 1) + self.out_channels = a.dim + self.use_state = v.use_state == "DiT" + + self.x_embedder = ActionEmbedder(self.in_channels, d.hidden_size) + self.t_embedder = TimestepEmbedder(d.hidden_size) + self.z_embedder = LabelEmbedder(v.hidden_size, d.hidden_size, d.class_dropout_prob) + if self.use_state: + self.state_embedder = StateEmbedder(a.state_dim, d.hidden_size) + + # z (+ state) + the chunk. Learned, not sinusoidal, and added to the whole + # sequence including the condition token -- upstream's `x + positional_embedding`. + self.seq_len = a.chunk_size + (2 if self.use_state else 1) + self.positional_embedding = nn.Parameter( + d.hidden_size ** -0.5 * torch.randn(self.seq_len, d.hidden_size)) + + self.blocks = nn.ModuleList( + [DiTBlock(d.hidden_size, d.num_heads, d.mlp_ratio) for _ in range(d.depth)]) + self.final_layer = FinalLayer(d.hidden_size, self.out_channels) + self.initialize_weights() + + # ------------------------------------------------------------------ init + + def initialize_weights(self) -> None: + """Upstream's order, which matters: a generic Xavier pass over every Linear, then + specific overwrites, and the adaLN / output zeroing LAST. Reordering these leaves + adaLN-Zero not zero, and the model then starts far from the identity.""" + + def basic(m: nn.Module) -> None: + if isinstance(m, nn.Linear): + nn.init.xavier_uniform_(m.weight) + if m.bias is not None: + nn.init.constant_(m.bias, 0) + + self.apply(basic) + + for mod in (self.x_embedder, *( [self.state_embedder] if self.use_state else [] )): + for layer in mod.projector: + if isinstance(layer, nn.Linear): + nn.init.normal_(layer.weight, std=0.02) + nn.init.constant_(layer.bias, 0) + + if self.z_embedder.dropout_prob > 0: + nn.init.normal_(self.z_embedder.uncondition, std=0.02) + nn.init.normal_(self.z_embedder.linear.weight, std=0.02) + nn.init.constant_(self.z_embedder.linear.bias, 0) + + nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02) + nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02) + + for block in self.blocks: + nn.init.constant_(block.adaLN_modulation[-1].weight, 0) + nn.init.constant_(block.adaLN_modulation[-1].bias, 0) + nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0) + nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0) + nn.init.constant_(self.final_layer.linear.weight, 0) + nn.init.constant_(self.final_layer.linear.bias, 0) + + # ------------------------------------------------------------------ mask + + def _attn_mask(self, device, dtype) -> torch.Tensor | None: + """Causal over the whole sequence, as upstream. + + This means the condition token at position 0 sees only itself and the state token + sees only the condition and itself. That is unusual -- one would expect the + conditioning to be visible to everything and only the actions to be ordered -- but + it is what the reference does, and adaLN carries the condition to every position + anyway, so the token path is not the only route. Reproduced deliberately. + """ + if not self.cfg.dit.causal_attention: + return None + n = self.seq_len + m = torch.triu(torch.ones(n, n, device=device, dtype=torch.float32), 1) + return m.masked_fill(m == 1, float("-inf")).to(dtype) + + # ------------------------------------------------------------------ forward + + def forward(self, x: torch.Tensor, t: torch.Tensor, z: torch.Tensor, + state: torch.Tensor | None = None, + state_mask: torch.Tensor | None = None, + generator: torch.Generator | None = None) -> torch.Tensor: + """`x` [B, T, 2*A] already carries the mask; `z` is [B, 1, vlm_hidden].""" + seq = [self.z_embedder(z, self.training, generator)] # [B, 1, D] + if self.use_state: + if state is None or state_mask is None: + raise ValueError("use_state='DiT' but no state was passed") + sm = state_mask.to(state.dtype) + seq.append(self.state_embedder(torch.cat([state * sm, sm], dim=-1))) + seq.append(self.x_embedder(x)) + + h = torch.cat(seq, dim=1) + if h.shape[1] != self.seq_len: + raise ValueError(f"sequence is {h.shape[1]} long, positions table has " + f"{self.seq_len}") + h = h + self.positional_embedding + + c = seq[0].squeeze(1) + self.t_embedder(t) # [B, D] + mask = self._attn_mask(h.device, h.dtype) + for block in self.blocks: + h = block(h, c, mask) + h = self.final_layer(h, c) + return h[:, -self.chunk_size:, :] diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/group_loss.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/group_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..bc74991a373533e32aefb5524849ec33891cd6cf --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/group_loss.py @@ -0,0 +1,81 @@ +"""The per-channel masked group loss for this baseline. + +Per group: the masked mean of the squared error over that channel range, weighted by how +many rows carried the group at all. Four groups here -- a 6-D wrist block per hand, as +VITRA's `ActionFeature.get_loss_components` defines them. V4 uses six, splitting each +wrist block into translation and rotation, which gives the wrist 4/6 of the loss where +this gives it 2/4. That difference belongs to the objective each model was designed with +and is not something to harmonise away. + +**Why masked at all.** Of 192 action slots only 102 carry data, and which ones depends on +the sample -- an episode annotates one hand. An unmasked mean would train the model to +predict 90 constant zeros and divide the real error by 192, silently. +""" + +from __future__ import annotations + +import torch + + +def masked_group_loss(pred: torch.Tensor, target: torch.Tensor, + action_mask: torch.Tensor, + groups, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """VITRA's `DiffusionPolicy.loss`, term for term, over `groups`. + + Per group: the masked mean of the squared error over that channel range, times the + group's weight. Those are then combined weighted by `count`, where count is the number + of (sample, step) pairs for which the group's FIRST channel is unmasked. Our cut writes + one hand per episode, so a group is either wholly present or wholly absent for a given + sample; the count is therefore "how many rows this group had", and the combination is + a mean over present groups rather than over channels. + + `groups` is an iterable of `(name, lo, hi, weight)`. + + The `total_count == 0` branch is upstream's: it returns `square_delta[0,0,0]`, a real + element of the graph, so the backward pass still has something to traverse and DDP + does not hang waiting for a rank that produced no gradient. + """ + return masked_group_loss_sq((pred - target) ** 2, action_mask, groups) + + +def masked_group_loss_sq(square: torch.Tensor, action_mask: torch.Tensor, groups + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + """Same, entered from an already-computed per-element squared error. + + SmolVLA's `VLAFlowMatching.forward` returns `F.mse_loss(u_t, v_t, reduction="none")` + and never exposes `v_t`, so the baseline cannot hand over a (pred, target) pair + without re-implementing that forward pass. Entering here instead keeps upstream's + file unmodified and the aggregation shared. + """ + m = action_mask.to(square.dtype) + square_delta = square * m + + parts: dict[str, torch.Tensor] = {} + counts: dict[str, torch.Tensor] = {} + dens: dict[str, torch.Tensor] = {} + for name, lo, hi, weight in groups: + n = m[:, :, lo:hi].sum() + val = square_delta[:, :, lo:hi].sum() / n if n > 0 else square_delta.new_zeros(()) + parts[name] = val * weight + counts[name] = m[:, :, lo].sum() + dens[name] = n + + total = sum(counts.values()) + if float(total) == 0.0: + loss = square_delta[0, 0, 0] + else: + loss = sum(parts[k] * counts[k] for k in counts) / total + + logged = {k: v.detach() for k, v in parts.items()} + # Two different counts, and they are not interchangeable: + # `_n` the FIRST channel's unmasked count. This is what upstream weights the + # groups by when it combines them -- effectively "how many rows had this + # group at all", since our cut turns a whole hand on or off together. + # `_den` the mean's actual denominator, over every channel in the range. + # Averaging per-batch means over a validation set needs `_den`; reproducing the + # training objective's group weighting needs `_n`. Using one for the other silently + # rescales the wrist against the fingers by the ratio of their channel counts (3 vs 63). + logged.update({f"{k}_n": v.detach() for k, v in counts.items()}) + logged.update({f"{k}_den": v.detach() for k, v in dens.items()}) + return loss, logged diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/model.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/model.py new file mode 100644 index 0000000000000000000000000000000000000000..ddcc63ba411fc855ba34191d4f2653fa1830db46 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/model.py @@ -0,0 +1,424 @@ +"""The VITRA-original baseline: PaliGemma2-3B -> cognition token -> DiT/DDPM chunk. + + Observation --> PaliGemmaVLM --> z [B, 1, 2304] --+ + |--> DiT --> eps --> DDIM --> a + state [B, 424] -------------------------------------+ + +`Observation` carries exactly the fields V4's `to_observations` fills, so the data side is +shared with V4 and the comparison is between models rather than between pipelines. + +**This model has no memory.** `loss` and `predict_from_noise` take the same +`steps: list[Observation]` that V4's do and use only `steps[-1]`; the earlier steps exist +so that the supervised anchor lands on the same distribution of episode positions that V4 +trains on (see `TrainConfig.max_seq_len`). Discarding them here rather than shortening the +window keeps that distribution identical and costs ~1.4 ms of JPEG reads per sample. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import torch +import torch.nn as nn + +from . import diffusion as dfn +from .config import Config +from .dit import DiT +from .vlm import PaliGemmaVLM + + +@dataclass +class Observation: + """One control step. Field names and shapes are V4's `to_observations` contract.""" + + images: torch.Tensor # [B, N, 3, H, W] float, already in [-1, 1] + lang_ids: torch.Tensor # [B, L] int + lang_mask: torch.Tensor # [B, L] bool + state: torch.Tensor # [B, 212] ** RAW ** -- the model normalises it + state_mask: torch.Tensor # [B, 212] bool + fov: torch.Tensor # [B, N, 2] + + +# Buffers this model owns that no VITRA checkpoint can contain: the normalisation +# statistics (V4's convention -- they live in the model, not the loader) and the diffusion +# schedule. `load_pretrained` must not count these as a failed load, or every run would +# refuse to start. +_OURS_NOT_THEIRS = ("alpha_bar", "action_mean", "action_std", "state_mean", "state_std", + "stats_loaded") + +# Segments that FSDP, DDP, activation checkpointing and torch.compile splice into +# parameter names. `param_groups` splits on the name, so a wrapped backbone parameter that +# stopped matching `vlm.pg.` would land in the action head's group at 10x the learning +# rate -- silently. +_WRAPPER_SEGMENTS = ("_fsdp_wrapped_module.", "_checkpoint_wrapped_module.", "_orig_mod.") + + +def _strip_wrappers(name: str) -> str: + for seg in _WRAPPER_SEGMENTS: + name = name.replace(seg, "") + # DDP's prefix is just `module.`, which is too generic to replace everywhere -- a + # legitimate submodule could be called that. Only the leading one is DDP's. + return name[len("module."):] if name.startswith("module.") else name + + +class VitraOriginalModel(nn.Module): + def __init__(self, cfg: Config, *, load_weights: bool = True, + dtype: torch.dtype = torch.float32): + """`load_weights` and `dtype` exist to match how V4's `eval_test.py` constructs a + model (`Model(cfg, load_weights=False, dtype=torch.float32)`), so that file needs + no change to build this one. + + `dtype` is accepted and must be float32: VITRA keeps parameters, gradients and the + all-reduce in fp32 and puts bf16 only inside the VLM forward via autocast + (`enable_mixed_precision_training: false`). Silently honouring a bf16 request would + be a different recipe, so it raises instead. + """ + super().__init__() + if dtype is not torch.float32: + raise ValueError( + f"dtype={dtype}: this baseline holds fp32 parameters and uses bf16 only " + f"inside the VLM forward, which is VITRA's configuration. Casting the " + f"parameters would be a different recipe.") + cfg.validate() + self.cfg = cfg + self.vlm = PaliGemmaVLM(cfg, load_weights=load_weights) + self.dit = DiT(cfg) + # A buffer, not a recomputation: a checkpoint then carries the schedule it was + # trained under. A schedule that changes between training and evaluation is + # invisible in every loss curve. + self.register_buffer("alpha_bar", dfn.alpha_bar_table(cfg), persistent=True) + self._ddim_grid = dfn.ddim_grid(cfg) + + # ** The loader emits RAW actions and state. ** `dataloader.py:410`: "Pad to + # 192 / 212 but do NOT normalise: mu and sigma live in the model as buffers." + # That boundary is V4's and we keep it, so a checkpoint carries the statistics it + # was trained under and cannot be evaluated against a different normaliser by + # accident. VITRA's own loader normalised instead (`train_dataset.normalization = + # true`), so this is the one place the port moves work from the data side to the + # model side -- the arithmetic is identical, the ownership is not. + self.register_buffer("action_mean", torch.zeros(cfg.action.dim)) + self.register_buffer("action_std", torch.ones(cfg.action.dim)) + self.register_buffer("state_mean", torch.zeros(cfg.action.state_dim)) + self.register_buffer("state_std", torch.ones(cfg.action.state_dim)) + self.register_buffer("stats_loaded", torch.zeros((), dtype=torch.bool)) + + # ** Recorded HERE, before FSDP. ** The rule is upstream's -- a parameter is exempt + # from weight decay when `p.ndim <= 1 or name.endswith(".bias")` -- but FSDP + # flattens every parameter into a 1-D shard, so asking `p.ndim` after the wrap + # answers "1" for all of them and the whole model comes out exempt. Measured + # 2026-09-09 on 6 ranks: two groups instead of four, 438 M "backbone_no_decay", + # weight decay silently 0 everywhere. Nothing raises; the run just is not the + # recipe. Names are stable across the wrap, shapes are not. + # Every parameter, not just the exempt ones: a name that is missing from this map + # is then a KeyError in `param_groups` rather than a silent "it decays". + self._no_decay = {n: (p.ndim <= 1 or n.endswith(".bias")) + for n, p in self.named_parameters()} + + # Guard the OUTCOME, not the request. The `dtype` check at the top of __init__ + # only reads the argument, and on 2026-09-09 that let a bf16 backbone through: + # `PaliGemmaForConditionalGeneration(config)` built its submodules from + # `text_config.dtype`, which is bf16, while `config.dtype` said float32. Loading + # the fp32 checkpoint into it downcast every backbone weight without a word. + wrong = {} + for n, prm in self.named_parameters(): + if prm.dtype is not torch.float32: + wrong[str(prm.dtype)] = wrong.get(str(prm.dtype), 0) + prm.numel() + if wrong: + raise RuntimeError( + f"parameters are not all fp32 after construction: {wrong}. VITRA holds " + f"fp32 weights and uses bf16 only inside the VLM forward via autocast.") + + # ------------------------------------------------------------ normalisation + + def set_normalisation(self, *, action_mean, action_std, state_mean, state_std, + eps: float = 1e-6) -> None: + """Install the dataset statistics. Must be called before training or inference. + + The three checks are V4's, and they guard files we did not write -- our own + `compute_stats.py` cannot produce a non-finite or negative sigma, but VITRA's + shipped statistics, a hand-edited json or a truncated copy can. + + A sigma of exactly ZERO is ordinary and must not raise: MANO joint 0 sits at the + palm origin by construction, so its three coordinates have zero variance in every + domain, and the padding dimensions are the same case. Clamping keeps them an + identity transform; left alone they normalise to +-inf. + """ + for name, v, n in (("action_mean", action_mean, self.cfg.action.dim), + ("action_std", action_std, self.cfg.action.dim), + ("state_mean", state_mean, self.cfg.action.state_dim), + ("state_std", state_std, self.cfg.action.state_dim)): + t = torch.as_tensor(v, dtype=torch.float32).reshape(-1) + if t.numel() != n: + raise ValueError(f"{name} must have {n} entries, got {t.numel()}") + if not bool(torch.isfinite(t).all()): + raise ValueError( + f"{name} has {int((~torch.isfinite(t)).sum())} non-finite entries. " + f"Nothing downstream checks for this: the first `(a - mean) / std` " + f"turns the loss into NaN several thousand steps from here.") + if name.endswith("_std"): + if bool((t < 0).any()): + raise ValueError( + f"{name} has negative entries (min {float(t.min()):.3e}); a " + f"standard deviation cannot be negative, so the file is corrupt.") + t = t.clamp_min(eps) + getattr(self, name).copy_(t.to(getattr(self, name).device)) + self.stats_loaded.fill_(True) + + def _require_stats(self) -> None: + if not bool(self.stats_loaded): + raise RuntimeError( + "normalisation statistics were never installed. Call set_normalisation() " + "with values measured on THIS dataset at the 80 Hz action convention -- " + "VITRA's shipped per-domain statistics are measured at the SOURCE rate " + "and are off by 8/3 on the wrist channels, which raises nothing.") + + def normalise_action(self, a: torch.Tensor) -> torch.Tensor: + return (a - self.action_mean) / self.action_std + + def unnormalise_action(self, a: torch.Tensor) -> torch.Tensor: + return a * self.action_std + self.action_mean + + # ------------------------------------------------------------------ pieces + + def trainable_params_setup(self) -> None: + """Called once. The trainable set does not change during a run -- `llm_freeze_step` + is a learning rate of zero, not a frozen parameter. See `OptimConfig`.""" + self.vlm.trainable_params_setup() + self.dit.requires_grad_(True) + + def param_groups(self) -> list[dict]: + """Four groups, as `split_modality_collator` builds them (`fsdp.py:82-131`). + + Two axes. **Backbone or not:** upstream tests `"backbone" in name`, and in its tree + only the PaliGemma is called `backbone` -- so `fov_encoder`, `cognition_token` and + the action head all fall on the other side and run at `action_model_lr`. Ours is + `vlm.pg`, and the same three land outside it. Putting the FoV projector and the + cognition token on the backbone's 1e-5 would be a 10x change to two modules that + VITRA trains at 1e-4. + + **Decay or not:** `param.ndim <= 1 or name.endswith(".bias")` -- norms, biases and + scalars are exempt. Decaying a LayerNorm gain toward zero is not regularisation, + it erases the layer. + + The `lr_scale` key is what `train.py` multiplies by 0 during the frozen phase; it + marks the two backbone groups so the schedule does not have to re-derive them. + """ + o = self.cfg.optim + wd_action = (o.weight_decay if o.action_model_weight_decay is None + else o.action_model_weight_decay) + + buckets: dict[tuple[bool, bool], list] = {(b, d): [] for b in (True, False) + for d in (True, False)} + for name, p in self.named_parameters(): + if not p.requires_grad: + continue + # FSDP and activation checkpointing splice their own segments into parameter + # names. The split below is on the name, so strip them -- otherwise a wrapped + # backbone parameter stops matching `vlm.pg.` and silently lands in the action + # head's group at 10x the learning rate. + clean = _strip_wrappers(name) + no_decay = self._no_decay[clean] + if "cognition_token" in clean: + no_decay = not o.cognition_token_weight_decay + buckets[(clean.startswith("vlm.pg."), no_decay)].append(p) + + groups = [ + ("backbone_decay", True, False, o.backbone_lr, o.weight_decay), + ("backbone_no_decay", True, True, o.backbone_lr, 0.0), + ("action_decay", False, False, o.action_model_lr, wd_action), + ("action_no_decay", False, True, o.action_model_lr, 0.0), + ] + out = [] + for gname, is_backbone, no_decay, lr, wd in groups: + params = buckets[(is_backbone, no_decay)] + if not params: + continue + out.append({"params": params, "lr": lr, "weight_decay": wd, + "name": gname, "is_backbone": is_backbone}) + return out + + def encode(self, obs: Observation) -> torch.Tensor: + """-> z [B, 1, hidden].""" + return self.vlm(obs.images, obs.lang_ids, obs.lang_mask, obs.fov).unsqueeze(1) + + def _state_pair(self, obs: Observation) -> tuple[torch.Tensor, torch.Tensor]: + """[B, 1, 212] NORMALISED value and its mask -- what the DiT's state embedder + wants. The embedder itself does the `state * mask` gating and the concatenation, + which is where VITRA does it, so only the normalisation moves here.""" + self._require_stats() + z = (obs.state - self.state_mean) / self.state_std + return z.unsqueeze(1), obs.state_mask.to(z.dtype).unsqueeze(1) + + def _eps(self, x_t: torch.Tensor, t: torch.Tensor, z: torch.Tensor, + mask_f: torch.Tensor, state: torch.Tensor, state_mask: torch.Tensor, + generator: torch.Generator | None = None) -> torch.Tensor: + """One network call. The action token is `[x_t * mask ; mask]`. + + The multiply before the concatenation is upstream's and is not redundant with the + mask channel: it keeps the padded slots' VALUES at exactly zero instead of at + whatever noise was drawn there, so the 108 dead input features are dead in both + halves. + """ + xin = torch.cat([x_t * mask_f, mask_f], dim=2) + return self.dit(xin, t, z, state, state_mask, generator) + + # ------------------------------------------------------------------ training + + def forward(self, steps: list[Observation], step_valid: torch.Tensor, + actions: torch.Tensor, action_mask: torch.Tensor): + return self.loss(steps, step_valid, actions, action_mask) + + def loss(self, steps: list[Observation], step_valid: torch.Tensor, + actions: torch.Tensor, action_mask: torch.Tensor, + generator: torch.Generator | None = None): + """-> (scalar loss, dict of per-group values for logging). + + `step_valid` is accepted and ignored: only `steps[-1]` is read, and the collate + left-pads so that index is the supervised step for every item in the batch. + """ + del step_valid + obs = steps[-1] + k = self.cfg.diffusion.repeated_diffusion_steps + + z = self.encode(obs) # [B, 1, D] + state, state_mask = self._state_pair(obs) + + # K independent (noise, t) draws share one VLM forward -- `repeated_diffusion_steps` + # in VITRA's config. They are K correlated views of one condition; when logging + # throughput, report the number of DISTINCT episode timesteps, not B*K. + if k > 1: + z = z.repeat_interleave(k, dim=0) + state = state.repeat_interleave(k, dim=0) + state_mask = state_mask.repeat_interleave(k, dim=0) + actions = actions.repeat_interleave(k, dim=0) + action_mask = action_mask.repeat_interleave(k, dim=0) + + # The loader hands over RAW actions; normalise here, with the buffers a checkpoint + # carries. Skipping this trains on centimetres and degrees, whose per-channel + # scales differ by two orders of magnitude -- the loss falls, and the fingers eat + # the wrist. + a = self.normalise_action(actions.to(z.dtype)) + mask_f = action_mask.to(z.dtype) + noise = torch.randn(a.shape, device=a.device, dtype=a.dtype, generator=generator) + t = dfn.sample_timesteps(a.shape[0], self.cfg, a.device, generator) + x_t = dfn.q_sample(a, t, noise, self.alpha_bar) + + eps = self._eps(x_t, t, z, mask_f, state, state_mask, generator) + return dfn.masked_group_loss(eps, noise, action_mask, self.cfg) + + # ------------------------------------------------------------------ inference + + @torch.no_grad() + def predict_from_noise(self, steps: list[Observation], noise: torch.Tensor + ) -> torch.Tensor: + """-> [B, chunk, 192] in the NORMALISED domain, integrated from a GIVEN noise. + + This is the seam V4's `eval_test.py` would need to drive this model. The noise is + passed in rather than drawn: the test protocol pairs one test + frame across conditions and the starting noise must be held fixed, so a + `select_action` that draws its own is unusable there. + + Classifier-free guidance runs the batch twice -- once on the cognition token, once + on the learned `uncondition` -- and combines the two epsilons. `cfg_scale <= 1` + skips the second branch entirely. + """ + obs = steps[-1] + b = obs.state.shape[0] + cfg = self.cfg + z = self.encode(obs) + state, state_mask = self._state_pair(obs) + + mask = dfn.component_action_mask(b, cfg.action.chunk_size, cfg.action.dim, + cfg, noise.device) + mask_f = mask.to(z.dtype) + x = noise.to(z.device, z.dtype).clone() + # Padding slots start at exactly zero, matching what `_eps` feeds the network at + # every training step. + x = x * mask_f + + scale = float(cfg.diffusion.cfg_scale) + if scale > 1.0: + if cfg.dit.class_dropout_prob <= 0: + raise ValueError("cfg_scale > 1 needs the learned `uncondition`, which " + "only exists when class_dropout_prob > 0") + uncond = self.dit.z_embedder.uncondition.to(z.dtype).expand(b, 1, -1) + z_pair = torch.cat([z, uncond], dim=0) + state_pair = torch.cat([state, state], dim=0) + smask_pair = torch.cat([state_mask, state_mask], dim=0) + mask_pair = torch.cat([mask_f, mask_f], dim=0) + + def eps_fn(x_t: torch.Tensor, t: torch.Tensor) -> torch.Tensor: + both = self._eps(torch.cat([x_t, x_t], 0), torch.cat([t, t], 0), + z_pair, mask_pair, state_pair, smask_pair) + cond_eps, uncond_eps = both.chunk(2, dim=0) + return uncond_eps + scale * (cond_eps - uncond_eps) + else: + def eps_fn(x_t: torch.Tensor, t: torch.Tensor) -> torch.Tensor: + return self._eps(x_t, t, z, mask_f, state, state_mask) + + out = dfn.ddim_sample(eps_fn, x, self.alpha_bar, self._ddim_grid, + cfg.diffusion.ddim_eta) + # The padding slots carry whatever the zeroed final layer produced; zero them so a + # caller that forgets the mask cannot read a number out of them. + return out * mask_f + + @torch.no_grad() + def select_action(self, steps: list[Observation], + generator: torch.Generator | None = None) -> torch.Tensor: + """Deployment path: draw the noise here, then integrate.""" + obs = steps[-1] + b = obs.state.shape[0] + shape = (b, self.cfg.action.chunk_size, self.cfg.action.dim) + noise = torch.randn(shape, device=obs.state.device, dtype=obs.state.dtype, + generator=generator) + return self.predict_from_noise(steps, noise) + + # ------------------------------------------------------------------ weights + + def load_pretrained(self, path: str) -> dict[str, list[str]]: + """Load `vitra-vla-3b.pt` and REPORT what did not match. + + ⚠ That checkpoint was written by code running `transformers==4.47.1`, and the + module tree under `PaliGemmaForConditionalGeneration` was reorganised before 5.x + (`language_model.*` moved under `model.*`, among others). Some keys will not match + by name, and our own tree differs from VITRA's anyway (`self.vlm.pg` where VITRA + has `self.backbone`, `self.dit` where it has `self.act_model.net`). + + So this does NOT call `load_state_dict(strict=False)` and move on. It applies the + configured prefix remaps, then refuses to continue if anything is missing unless + `init.allow_partial_load` is set. A silently partial load of a 3B backbone gives a + randomly initialised model that trains, logs a falling loss, and is not the + baseline anyone asked for. + + ⚠ UNVERIFIED: the exact remapping. It cannot be worked out without the file, which + lives on the server. Run this once with `allow_partial_load` off, read the report, + and put the pairs into `init.key_remap`. + """ + raw = torch.load(path, map_location="cpu", weights_only=True) + state = raw.get("state_dict", raw) if isinstance(raw, dict) else raw + + remapped = {} + for key, value in state.items(): + for old, new in self.cfg.init.key_remap: + if key.startswith(old): + key = new + key[len(old):] + break + remapped[key] = value + + incompatible = self.load_state_dict(remapped, strict=False) + # Buffers we own and no VITRA checkpoint could carry -- the normalisation + # statistics (installed by `set_normalisation`) and the diffusion schedule. They + # are legitimately absent, so counting them would make every load "fail". + # Filtered by exact name, not by prefix: a prefix match would also swallow a + # genuinely missing `action_mean_something` if one is ever added. + report = {"missing": [k for k in incompatible.missing_keys + if k not in _OURS_NOT_THEIRS], + "unexpected": list(incompatible.unexpected_keys)} + if report["missing"] and not self.cfg.init.allow_partial_load: + head = "\n ".join(report["missing"][:20]) + raise RuntimeError( + f"{len(report['missing'])} parameters were NOT found in {path} and keep " + f"their random initialisation. First few:\n {head}\n" + f"Fix `init.key_remap`, or set `init.allow_partial_load` if this is " + f"deliberate (say so in the run's log).") + return report diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/prompt.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/prompt.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd9210bda39ca2f066d5553dca1bfb507eb8606 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/prompt.py @@ -0,0 +1,104 @@ +"""The tokenizer object V4's `make_collate` expects, producing PaliGemma's prompt. + +`make_collate(cfg, tokenizer)` calls + + tokenizer(list_of_instructions, padding="max_length", truncation=True, + max_length=cfg.vlm.max_language_tokens, return_tensors="pt") + +and reads `input_ids` and `attention_mask`. Anything with that signature will do, which is +what makes the loader reusable across backbones without touching it. + +PaliGemma's prompt is fixed by `processing_paligemma.build_string_from_input`: + + "" * image_seq_len + + prompt + "\\n" + +We assemble the ids directly instead of formatting that string and handing it to +`PaliGemmaProcessor`. Two reasons, both about failure modes rather than speed: + + * truncation. The processor would tokenize the whole string and cut from the right, so a + long instruction silently eats the trailing "\\n" and then the tail of the image + block -- and a prompt with fewer than 256 image tokens fails much later, inside + `masked_scatter`, as a size mismatch with no hint of the cause. Here only the + instruction is truncated and the frame is structural. + * padding side. The pad has to end up AFTER the newline so `compact_left` in `vlm.py` + leaves the cognition token last. Building the row ourselves makes that explicit rather + than dependent on `tokenizer.padding_side`. +""" + +from __future__ import annotations + +import torch + +from .config import Config +from .vlm import resolve_model_dir + + +class PaliGemmaPromptTokenizer: + """Callable with the subset of the HF tokenizer signature `make_collate` uses.""" + + def __init__(self, cfg: Config): + from transformers import AutoProcessor + + self.cfg = cfg + proc = AutoProcessor.from_pretrained(resolve_model_dir(cfg.vlm.model_id)) + self.tokenizer = proc.tokenizer + self.image_token_id = proc.image_token_id + self.image_seq_len = int(proc.image_seq_length) + + if self.image_seq_len != cfg.vlm.image_tokens: + raise ValueError( + f"{cfg.vlm.model_id} uses {self.image_seq_len} image tokens but " + f"config.vlm.image_tokens is {cfg.vlm.image_tokens}. These must agree: " + f"the first is what the prompt reserves, the second is what the vision " + f"tower produces, and `masked_scatter` requires them equal.") + + self.bos_id = self.tokenizer.bos_token_id + if self.bos_id is None: + raise ValueError(f"{cfg.vlm.model_id}'s tokenizer has no bos_token_id") + nl = self.tokenizer("\n", add_special_tokens=False)["input_ids"] + if len(nl) != 1: + raise ValueError(f"'\\n' tokenizes to {len(nl)} ids, expected 1") + self.newline_id = nl[0] + self.pad_id = (self.tokenizer.pad_token_id + if self.tokenizer.pad_token_id is not None else 0) + + # image block + + at least one text token + "\n" + self.frame = self.image_seq_len + 2 + if cfg.vlm.max_language_tokens <= self.frame: + raise ValueError( + f"max_language_tokens {cfg.vlm.max_language_tokens} leaves no room for " + f"text: {self.image_seq_len} image tokens + + '\\n' already need " + f"{self.frame}.") + self.max_text = cfg.vlm.max_language_tokens - self.frame + + def __call__(self, texts, padding: str = "max_length", truncation: bool = True, + max_length: int | None = None, return_tensors: str = "pt"): + if padding != "max_length" or not truncation: + raise ValueError("this shim implements padding='max_length' with truncation, " + "which is what make_collate asks for") + total = max_length or self.cfg.vlm.max_language_tokens + max_text = total - self.frame + if max_text < 1: + raise ValueError(f"max_length {total} leaves no room for text") + + if isinstance(texts, str): + texts = [texts] + + ids = torch.full((len(texts), total), self.pad_id, dtype=torch.long) + mask = torch.zeros(len(texts), total, dtype=torch.long) + ids[:, :self.image_seq_len] = self.image_token_id + ids[:, self.image_seq_len] = self.bos_id + + encoded = self.tokenizer(list(texts), add_special_tokens=False)["input_ids"] + for i, text_ids in enumerate(encoded): + text_ids = text_ids[:max_text] + n = len(text_ids) + lo = self.image_seq_len + 1 + if n: + ids[i, lo:lo + n] = torch.tensor(text_ids, dtype=torch.long) + ids[i, lo + n] = self.newline_id + mask[i, :lo + n + 1] = 1 + + if return_tensors != "pt": + raise ValueError("only return_tensors='pt' is implemented") + return {"input_ids": ids, "attention_mask": mask} diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/vlm.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/vlm.py new file mode 100644 index 0000000000000000000000000000000000000000..8fdbd0755fce81d67a10b3a8aff156458b5982ee --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/_baselines/vitra_original/vlm.py @@ -0,0 +1,300 @@ +"""PaliGemma2-3B adapter: image + instruction + FoV -> one cognition vector. + +**Rewritten against transformers 5.x, not copied from VITRA.** VITRA pins +`transformers==4.47.1` and V4's dataloader needs `>=5.13.0`; they cannot share a process, +so the calls VITRA makes had to be re-expressed. What moved: + + 4.47 5.13 + model.language_model(...) model.model(...) -- PaliGemmaModel + config.image_token_index config.image_token_id + model._update_causal_mask(...) built inside PaliGemmaModel.forward + num_logits_to_keep=0 logits_to_keep (and unused here) + +The behaviour being reproduced, not the spelling: + + prefix [ x256 | | instruction | \\n | fov | cognition ] <- pad right + output the hidden state at the LAST valid position = the cognition token + +VITRA appends FoV and a cognition token as extra embeddings and points `input_ids` at a +placeholder id so the sequence lengths agree; then it compacts every valid token to the +left so the padding ends up at the back, which is what makes "the last valid position" +mean "the cognition token". Both steps are reproduced below. + +**State does not appear here.** `use_state='DiT'` sends it straight to the action head. +The `use_state='VLM'` alternative is unimplemented on purpose: it is broken upstream +(`vitra_paligemma.py:320` calls `self.state_encoder`, never assigned), so there is no +reference behaviour to match. `config.validate()` rejects it. +""" + +from __future__ import annotations + +import torch +import torch.nn as nn + +from .config import Config + + +def resolve_model_dir(model_id: str) -> str: + """Turn a Hub repo id into a local snapshot directory when one is already cached. + + Handing `from_pretrained` a DIRECTORY makes it take the purely local path: no revision + resolution, no HEAD request, and no lookup for optional files that the repo does not + contain. Handing it a repo id does the opposite, and both failure modes bit us on + 2026-09-09 with a complete cache: + + * online but flaky -> "does not appear to have files named + model-0000X-of-00002.safetensors", because the revision could not be resolved; + * `HF_HUB_OFFLINE=1` -> `LocalEntryNotFoundError` from `AutoProcessor`, because + offline turns "this optional file does not exist" into a hard error. + + Falls back to the id unchanged when nothing is cached, so a first run still downloads. + """ + import os + + if os.path.isdir(model_id): + return model_id + try: + from huggingface_hub import snapshot_download + return snapshot_download(model_id, local_files_only=True) + except Exception: + return model_id + + +class MLPProjector(nn.Module): + """VITRA's `MLPProjector`, `gelu-mlp`: Linear -> GELU -> Linear. + + Its init is unusual and reproduced: `normal_(std=0.02)` on the WEIGHTS **and the + biases** of both layers. Normal-initialised biases are not standard practice; they are + what the reference does. + """ + + def __init__(self, in_dim: int, out_dim: int): + super().__init__() + self.projector = nn.Sequential( + nn.Linear(in_dim, out_dim, bias=True), + nn.GELU(), + nn.Linear(out_dim, out_dim, bias=True), + ) + for layer in (self.projector[0], self.projector[2]): + nn.init.normal_(layer.weight, mean=0.0, std=0.02) + nn.init.normal_(layer.bias, mean=0.0, std=0.02) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.projector(x) + + +def compact_left(embeds: torch.Tensor, mask: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """Move every valid token to the front, order preserved; padding to the back. + + VITRA's `move_masked_to_left`. It matters twice. The tokenizer right-pads the + instruction, so without this the FoV and cognition embeddings would sit AFTER a run of + pad tokens; and `extract_cognition` reads the last valid position, which is only the + cognition token once the sequence is compact. + + A stable argsort on `~mask` is the whole operation: False sorts before True, and + stability keeps the valid tokens in their original order. + """ + order = torch.argsort((~mask).to(torch.uint8), dim=1, stable=True) + gathered = embeds.gather(1, order.unsqueeze(-1).expand(-1, -1, embeds.shape[-1])) + return gathered, mask.gather(1, order) + + +class PaliGemmaVLM(nn.Module): + """Wraps `PaliGemmaForConditionalGeneration` and returns the cognition vector.""" + + def __init__(self, cfg: Config, *, load_weights: bool = True): + super().__init__() + from transformers import (AutoConfig, PaliGemmaForConditionalGeneration) + + self.cfg = cfg + v = cfg.vlm + local = resolve_model_dir(v.model_id) + if load_weights: + self.pg = PaliGemmaForConditionalGeneration.from_pretrained( + local, dtype=torch.float32) + else: + # Architecture only. Every parameter is then overwritten by the checkpoint -- + # which is safe here precisely because `load_pretrained` verified 0 missing on + # `vitra-vla-3b.pt`, and because `eval_test.py` loads a full state_dict with + # `strict=True`. Skips reading 5.7 GB of base weights that are about to be + # replaced. `eval_test.py` passes `load_weights=False` for the same reason. + # `.to(torch.float32)` is the load-bearing part. Setting `dtype` on the TOP + # config does NOT propagate to `text_config` / `vision_config`, which carry + # their own bf16 from the checkpoint's config.json -- so the submodules get + # built in bf16 and an fp32 state_dict is then downcast into them silently. + # Measured 2026-09-09: 3,029,588,208 parameters in bf16, 144,561,600 in fp32, + # and `pg.config.dtype` reading float32 the whole time. + pg_cfg = AutoConfig.from_pretrained(local) + self.pg = PaliGemmaForConditionalGeneration(pg_cfg).to(torch.float32) + + text_cfg = self.pg.config.get_text_config() + if text_cfg.hidden_size != v.hidden_size: + raise ValueError( + f"config.vlm.hidden_size is {v.hidden_size} but {v.model_id} has " + f"{text_cfg.hidden_size}. This number is also the DiT's `token_size`; a " + f"mismatch would only surface as a shape error deep in the action head.") + + self.image_token_id = self.pg.config.image_token_id + + if v.use_fov: + self.fov_encoder = MLPProjector(2, v.hidden_size) + + # An embedding of its own rather than the word embedding row, initialised from + # that row. VITRA's `untied_cognition_token`: the token has a job no word has, and + # tying it would drag the embedding matrix along with it. + if not v.untied_cognition_token: + raise NotImplementedError( + "untied_cognition_token=False shares the word-embedding row and needs the " + "embedding matrix trainable; VITRA's configs all set True.") + init_id = v.cognition_token_init_id + init_id = v.cognition_token_id if init_id is None else init_id + with torch.no_grad(): + row = self.pg.get_input_embeddings().weight[init_id].detach().clone() + self.cognition_token = nn.Parameter(row) + + # Gradient checkpointing is NOT enabled here. `train.py` applies it after the FSDP + # wrap, with `apply_activation_checkpointing` + `CheckpointImpl.NO_REENTRANT` on + # the transformer layers. + # + # Not a preference -- VITRA says so in `fsdp.py:329-332`: "we cannot rely on the HF + # Transformers default `gradient_checkpointing_enable()` --> FSDP breaks + # semantics!" HF wraps each module's `forward`, and under FSDP the recomputation + # can run outside the all-gather that made the parameters available. + # + # `use_reentrant=False` matters for a second reason of our own: the reentrant + # checkpoint decides what to recompute from whether its INPUTS require grad, so + # while the backbone is at lr 0 it can silently produce no gradients at all -- and + # the loss would still fall, because the action head trains. + + # ------------------------------------------------------------------ freezing + + def trainable_params_setup(self) -> None: + """Apply `freeze_option`. Called ONCE, at construction. + + `llm_freeze_step` is NOT applied here. VITRA implements it as a learning rate of + zero for the backbone group, not as `requires_grad = False` + (`fsdp.py:68`), so the trainable set never changes during a run and this needs no + per-step call. See `OptimConfig`. + + Upstream's own `trainable_params_setup` compares + `get("freeze_option", ) == ` + three times in a row, so with the key present the FIRST test also passes: + `full_finetune` runs and is then overwritten by `freeze_vision_encoder`. The end + state is right only because the last branch wins. Written here as one dispatch. + """ + v = self.cfg.vlm + if v.freeze_option == "full_finetune": + self.pg.requires_grad_(True) + elif v.freeze_option == "freeze_vision_encoder": + self.pg.requires_grad_(True) + self.pg.model.vision_tower.requires_grad_(False) + elif v.freeze_option == "only_head_and_token": + self.pg.requires_grad_(False) + else: + raise ValueError(f"unknown freeze_option {v.freeze_option!r}") + + if v.use_fov: + self.fov_encoder.requires_grad_(True) + self.cognition_token.requires_grad_(True) + + # ------------------------------------------------------------------ forward + + def _autocast(self): + """bf16 for the VLM forward only. + + VITRA wraps `get_image_features` and the language model in + `torch.autocast(bfloat16, enabled=use_bf16)` and leaves everything downstream in + fp32: `_forward_act_model` casts the cognition vector to the action head's own + dtype and the diffusion loss runs outside any autocast region. Putting the + autocast around the whole step instead would run the DiT and the epsilon MSE in + bf16 -- about three decimal digits for a loss whose per-group differences we are + trying to read. + + Its FSDP is configured with `enable_mixed_precision_training: false` and + `reduce_in_full_precision: true`, so parameters, gradients and the all-reduce all + stay fp32; bf16 exists only inside these two calls. + """ + return torch.autocast("cuda", dtype=torch.bfloat16, + enabled=self.cfg.vlm.use_bf16 and torch.cuda.is_available()) + + def _image_features(self, images: torch.Tensor) -> torch.Tensor: + """`images` [B, N, 3, H, W] in [-1, 1] -> [B*N, image_tokens, hidden].""" + b, n = images.shape[:2] + with self._autocast(): + out = self.pg.model.get_image_features(images.flatten(0, 1)) + feats = out[0] if isinstance(out, tuple) else out.pooler_output + expect = (b * n, self.cfg.vlm.image_tokens, self.cfg.vlm.hidden_size) + if tuple(feats.shape) != expect: + raise ValueError(f"image features {tuple(feats.shape)} != expected {expect}") + return feats + + def forward(self, images: torch.Tensor, lang_ids: torch.Tensor, + lang_mask: torch.Tensor, fov: torch.Tensor) -> torch.Tensor: + """Returns the cognition vector, [B, hidden]. + + `images` [B, N, 3, H, W] already in [-1, 1] (V4's `to_observations`) + `lang_ids` [B, L] image placeholders + + text + \\n, right-padded + `lang_mask`[B, L] bool + `fov` [B, N, 2] + """ + b = lang_ids.shape[0] + dev = lang_ids.device + emb = self.pg.get_input_embeddings() + + # The image rows are placeholders; their embedding is overwritten below. Look them + # up as id 0 first, which is what the library does, so an image id outside the + # vocabulary cannot index out of bounds. + is_image = lang_ids == self.image_token_id + safe_ids = lang_ids.masked_fill(is_image, 0) + embeds = emb(safe_ids) + + feats = self._image_features(images).to(embeds.dtype) + n_slots = int(is_image.sum()) + if n_slots * embeds.shape[-1] != feats.numel(): + raise ValueError( + f"{n_slots} placeholders in the prompt but {feats.numel() // embeds.shape[-1]} " + f"image feature rows. The tokenizer shim and vlm.image_tokens disagree.") + embeds = embeds.masked_scatter(is_image.unsqueeze(-1), feats) + + extra, extra_mask = [], [] + if self.cfg.vlm.use_fov: + # One FoV per camera; with a single camera this is one token, as VITRA has. + extra.append(self.fov_encoder(fov[:, 0]).unsqueeze(1)) + extra_mask.append(torch.ones(b, 1, dtype=torch.bool, device=dev)) + extra.append(self.cognition_token.to(embeds.dtype).expand(b, 1, -1)) + extra_mask.append(torch.ones(b, 1, dtype=torch.bool, device=dev)) + + embeds = torch.cat([embeds, *extra], dim=1) + mask = torch.cat([lang_mask, *extra_mask], dim=1) + embeds, mask = compact_left(embeds, mask) + + # `token_type_ids` is left unset on purpose. PaliGemma was pretrained with a + # bidirectional prefix, and passing token_type_ids here would restore that. VITRA + # does not: it calls `_update_causal_mask(attention_mask, None, ...)` with + # `token_type_ids=None` and `is_training=False`, which in 4.47 yields a plain + # causal mask. So VITRA runs this backbone fully causally, and so do we -- + # matching the reference matters more than matching the pretraining recipe. + # `attention_mask` as 0/1 longs, HF's convention for a padding mask -- it is fed to + # `create_causal_mask`, not multiplied into the hidden states. + with self._autocast(): + out = self.pg.model( + inputs_embeds=embeds, + attention_mask=mask.long(), + use_cache=False, + ) + hidden = out.last_hidden_state + # Back to fp32 before the action head, as `_forward_act_model` does when it casts + # the cognition vector to the act_model's parameter dtype. + return self.extract_cognition(hidden, mask).float() + + @staticmethod + def extract_cognition(hidden: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: + """The hidden state at the last valid position, [B, D]. + + Correct only because `compact_left` ran: the cognition token is appended last, so + after compaction it is the final valid position of every row. + """ + last = mask.to(torch.int32).cumsum(1).argmax(1) # index of the last True + idx = last[:, None, None].expand(-1, 1, hidden.shape[-1]) + return hidden.gather(1, idx).squeeze(1) diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/checkpoint_loaders.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/checkpoint_loaders.py new file mode 100644 index 0000000000000000000000000000000000000000..951ff704cf85e11d698ff283d114effbac5506cb --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/checkpoint_loaders.py @@ -0,0 +1,95 @@ +"""Checkpoint loaders for the baseline adapter boundary. + +These loaders only construct/load the policy. Dataset-specific observation +preparation stays outside the editor package. +""" +from __future__ import annotations + +import copy +import dataclasses +import json +from pathlib import Path +from typing import Any + +import torch + + +def _apply_config(cfg: Any, saved: dict[str, Any]) -> None: + for section_name, values in saved.items(): + section = getattr(cfg, section_name, None) + if section is None or not dataclasses.is_dataclass(section): + continue + for name, value in values.items(): + if not hasattr(section, name): + raise ValueError(f"unknown checkpoint field {section_name}.{name}") + current = getattr(section, name) + if isinstance(current, tuple) and isinstance(value, list): + value = tuple(tuple(v) if isinstance(v, list) else v for v in value) + setattr(section, name, value) + + +def load_v4d_checkpoint( + checkpoint: str | Path, + *, + config_file: str | Path | None = None, + device: str | torch.device = "cpu", + dtype: torch.dtype = torch.bfloat16, +): + """Strict-load the local T-WLA/V4-D checkpoint used by Table 1.""" + checkpoint = Path(checkpoint) + payload = torch.load(checkpoint, map_location="cpu", weights_only=False, mmap=True) + if config_file is not None: + run = json.loads(Path(config_file).read_text()) + else: + run = {} + from v4_d_fm_0 import V4DConfig, V4DModel + + cfg = V4DConfig() + saved = payload.get("effective_config", run.get("effective_config", run.get("config", {}))) + _apply_config(cfg, copy.deepcopy(saved)) + cfg.validate() + model = V4DModel(cfg, load_weights=False, dtype=dtype) + incompatible = model.load_state_dict(payload["model"], strict=True) + if incompatible.missing_keys or incompatible.unexpected_keys: + raise RuntimeError(str(incompatible)) + if not bool(model.stats_loaded): + raise RuntimeError("checkpoint has no action/state normalization statistics") + return model.to(device).eval(), cfg + + +def vitra_action_contract() -> dict[str, Any]: + """Return the native VITRA human-action contract. + + The human MANO VITRA configs in this repository already use the canonical + 16 x 192 action chunk, so no dimensional padding or conversion is allowed. + """ + return {"horizon": 16, "action_dim": 192, "normalized": True, "memory": False} + + +def trex_action_contract() -> dict[str, Any]: + """Return the public T-Rex native contract.""" + return { + "horizons": (8, 16), + "action_dims": (29, 31, 58, 62), + "interface": "slow_fast_cascaded_flow", + "normalized": False, + "requires_native_to_mano_converter": True, + } + + +def official_memoryvla_contract() -> dict[str, Any]: + """Describe the official MemoryVLA checkpoint boundary. + + The public ``shihao1895/memvla-*`` checkpoints are robot-policy + checkpoints. Their action head is an end-effector/gripper policy and is + not a human MANO head. This metadata prevents accidentally labeling a + robot action vector as a Table 1 human prediction. + """ + return { + "checkpoint_family": "shihao1895/memvla-*", + "native_action": "robot_end_effector_and_gripper", + "native_memory": "internal_cognitive_and_perceptual_banks", + "canonical_action": False, + "requires_human_mano_head": True, + "requires_action_adapter": True, + } diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/frozen_stage1.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/frozen_stage1.py new file mode 100644 index 0000000000000000000000000000000000000000..d6e5812f2a269be95795892a24cc21fc9b420c62 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/frozen_stage1.py @@ -0,0 +1,93 @@ +"""Shared helpers for a frozen action-only Stage-1 anchor.""" + +from __future__ import annotations + +from pathlib import Path + +import torch + +from .architecture_ablation import cross_video_phase_matched_donors +from .config import FusionConfig +from .encoder import TouchFeatures +from .fusion import PosthocResidualEditor + + +def load_stage1(path: Path, device: torch.device) -> PosthocResidualEditor: + """Load and freeze an action-only Stage-1 checkpoint.""" + + payload = torch.load(path, map_location="cpu", weights_only=False) + configuration = payload.get("config", {}) + if configuration.get("mode") != "no_touch": + raise ValueError("Stage-1 checkpoint must be the action-only/no_touch control") + fusion = FusionConfig( + hidden_dim=720, + num_heads=8, + posthoc_edit_gate_bias=-2.0, + posthoc_touch_gate_init=0.2, + ) + model = PosthocResidualEditor(fusion).to(device) + model.load_state_dict(payload["editor"], strict=True) + model.requires_grad_(False).eval() + if float(model.touch_attention.gate) != 0.0: + raise ValueError("action-only Stage-1 touch-attention gate is not zero") + return model + + +@torch.no_grad() +def stage1_anchor( + model: PosthocResidualEditor, + base_action: torch.Tensor, + mask: torch.Tensor, +) -> torch.Tensor: + """Apply the frozen calibrator with its action-only condition.""" + + batch = len(base_action) + no_touch = TouchFeatures( + tokens=torch.zeros(batch, 2, 64, device=base_action.device), + valid=torch.ones(batch, 2, dtype=torch.bool, device=base_action.device), + ) + return model(base_action, no_touch, mask)[0] + + +def shuffle_donors( + recordings: list[str], + elapsed: torch.Tensor, + hand_valid: torch.Tensor, + *, + seed: int, +) -> tuple[torch.Tensor, str]: + """Build phase-matched cross-recording tactile donors.""" + + try: + return ( + cross_video_phase_matched_donors( + recordings, elapsed, hand_valid, seed=seed + ), + "one-to-one cross-recording permutation matched by phase and hand validity", + ) + except ValueError: + generator = torch.Generator().manual_seed(seed) + phases = torch.round(elapsed.float() * 30).long() + donors = torch.empty(len(recordings), dtype=torch.long) + for index, recording in enumerate(recordings): + candidates = torch.tensor( + [ + other + for other in range(len(recordings)) + if recordings[other] != recording + and phases[other] == phases[index] + and torch.equal(hand_valid[other], hand_valid[index]) + ], + dtype=torch.long, + ) + if not len(candidates): + raise ValueError( + "no different-recording donor with matching phase/hand validity" + ) + donors[index] = candidates[ + torch.randint(len(candidates), (), generator=generator) + ] + return ( + donors, + "cross-recording donors with replacement matched by phase and hand validity", + ) diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/human_baselines.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/human_baselines.py new file mode 100644 index 0000000000000000000000000000000000000000..7c83bef955350934145f3ba0aa4d15739c9b831b --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/human_baselines.py @@ -0,0 +1,208 @@ +"""Frozen human baseline loaders and explicit conversion into the editor space.""" +from __future__ import annotations + +import copy +import importlib +import os +from pathlib import Path + +import numpy as np +import torch +from torch import nn + +from .action_layout import ActionNormalizer, DEFAULT_ACTION_LAYOUT +from .editor_interface import BaseActionContext + +HF_REPO = "MIT-Media-Lab/vla-hand-baselines" +HF_REVISION = "09db16bb337fd4e15539eb84db9506cd4153015c" +PACKAGES = {"smolvla": "smolvla_official", "vitra": "vitra_original"} +BACKBONES = {"smolvla": "HuggingFaceTB/SmolVLM2-500M-Video-Instruct", + "vitra": "google/paligemma2-3b-mix-224"} + + +def download_human_checkpoint(model_id: str, directory: str | Path) -> Path: + from huggingface_hub import hf_hub_download + return Path(hf_hub_download(HF_REPO, f"{PACKAGES[model_id]}/best.pt", + revision=HF_REVISION, local_dir=str(directory))) + + +def load_human_baseline(model_id: str, checkpoint: str | Path, *, + device="cpu", backbone: str | None = None, + pretrained_checkpoint=None, llama_directory=None): + """Restore the complete human policy, including its original statistics. + + The source release stores weights under `model`, not `state_dict`. + No original robot action head or dataset statistics file is needed. + """ + if model_id == "memoryvla": + if pretrained_checkpoint is None or llama_directory is None: + raise ValueError("MemoryVLA requires its original frozen VLM checkpoint and Llama assets") + from .memoryvla_baseline import load_memoryvla_human_checkpoint + return load_memoryvla_human_checkpoint(checkpoint, pretrained_checkpoint=pretrained_checkpoint, + llama_directory=llama_directory, device=device) + package = PACKAGES[model_id] + config_mod = importlib.import_module(f"._baselines.{package}.config", __package__) + model_mod = importlib.import_module(f"._baselines.{package}.model", __package__) + payload = torch.load(checkpoint, map_location="cpu", mmap=True, weights_only=False) + run = payload["config"] + if run.get("model") != package: + raise ValueError(f"checkpoint is not a {package} human baseline") + overrides = copy.deepcopy(run.get("config", {})) + overrides.setdefault("data", {})["stats_path"] = "checkpoint://normalization-buffers" + overrides.setdefault("init", {})["pretrain_path"] = "" + original = os.path.expandvars(overrides.get("vlm", {}).get("model_id", "")) + overrides.setdefault("vlm", {})["model_id"] = ( + backbone or (original if Path(original).is_dir() and original else BACKBONES[model_id]) + ) + from huggingface_hub import snapshot_download + if not Path(overrides["vlm"]["model_id"]).is_dir(): + try: + overrides["vlm"]["model_id"] = snapshot_download( + overrides["vlm"]["model_id"], local_files_only=True) + except OSError: + pass + cfg = config_mod.from_json(overrides) + expected_layout = "angle" if model_id == "vitra" else "keypoints" + if cfg.action.action_type != expected_layout or (cfg.action.chunk_size, cfg.action.dim) != (16, 192): + raise ValueError("unsupported human checkpoint action convention") + cls = model_mod.VitraOriginalModel if model_id == "vitra" else model_mod.SmolVLAOfficialModel + model = cls(cfg, load_weights=False, dtype=torch.float32) + model.load_state_dict(payload["model"], strict=True) + if not bool(model.stats_loaded): + raise ValueError("checkpoint has no normalization buffers") + for kind, width in (("action", 192), ("state", 212)): + mean, std = getattr(model, kind + "_mean"), getattr(model, kind + "_std") + if mean.shape != (width,) or std.shape != (width,) or not torch.isfinite(mean).all() or not torch.isfinite(std).all() or (std <= 0).any(): + raise ValueError(f"invalid {kind} normalization") + for name in ("action_mean", "action_std"): + torch.testing.assert_close(getattr(model, name), torch.as_tensor(payload[name]), rtol=0, atol=0) + model.requires_grad_(False).eval().to(device) + return model, cfg, {"model_id": model_id, "checkpoint": str(Path(checkpoint).resolve()), + "step": int(payload["step"]), "layout": expected_layout, + "strict_load": True, "state_tensors": len(payload["model"])} + + +def prepare_observation(model_id, model, cfg, *, images, instructions, state, + state_mask, fov): + """Prepare one native observation from RGB uint8 [B,N,H,W,3]. + + State must already use the checkpoint's native representation. In particular, + VITRA requires angle state from annotations, never reshaped keypoints. + FoV is the source camera FoV in the training convention. + """ + import cv2 + from transformers import AutoTokenizer + device = next(model.parameters()).device + imgs = np.asarray(images) + if imgs.ndim != 5 or imgs.shape[-1] != 3 or imgs.dtype != np.uint8: + raise ValueError("images must be RGB uint8 [B,N,H,W,3]") + b, n, h, w, _ = imgs.shape + if model_id == "memoryvla" and n != 1: + raise ValueError("MemoryVLA requires one explicitly selected camera") + s = cfg.vlm.image_size + out = np.zeros((b, n, s, s, 3), np.uint8) + for i in range(b): + for j in range(n): + if model_id in ("vitra", "memoryvla"): + interpolation = cv2.INTER_AREA if h >= s and w >= s else cv2.INTER_LINEAR + out[i, j] = cv2.resize(imgs[i, j], (s, s), interpolation=interpolation) + else: + ratio = min(s / w, s / h) + nh, nw = max(1, int(h * ratio)), max(1, int(w * ratio)) + out[i, j, s - nh:, s - nw:] = cv2.resize(imgs[i, j], (nw, nh), interpolation=cv2.INTER_AREA) + if model_id == "vitra": + from ._baselines.vitra_original.model import Observation + from ._baselines.vitra_original.prompt import PaliGemmaPromptTokenizer + tokenizer = getattr(model, "_table1_tokenizer", None) + if tokenizer is None: + tokenizer = PaliGemmaPromptTokenizer(cfg) + model._table1_tokenizer = tokenizer + elif model_id == "memoryvla": + from ._baselines.memoryvla_official.model import Observation, build_tokenizer + tokenizer = getattr(model, "_table1_tokenizer", None) + if tokenizer is None: + tokenizer = build_tokenizer(cfg) + model._table1_tokenizer = tokenizer + elif model_id == "smolvla": + from ._baselines.smolvla_official.model import Observation + tokenizer = model.flow.vlm_with_expert.processor.tokenizer + elif model_id == "twla": + from v4_d_fm_0 import Observation + tokenizer = getattr(model, "_table1_tokenizer", None) + if tokenizer is None: + from huggingface_hub import snapshot_download + backbone = cfg.vlm.model_id + if not Path(backbone).is_dir(): + try: + backbone = snapshot_download(backbone, local_files_only=True) + except OSError: + pass + tokenizer = AutoTokenizer.from_pretrained(backbone) + model._table1_tokenizer = tokenizer + else: + raise ValueError(model_id) + if len(instructions) != b: + raise ValueError("one instruction is required for each batch row") + lang = tokenizer(list(instructions), padding="max_length", truncation=True, + max_length=cfg.vlm.max_language_tokens, return_tensors="pt") + state = torch.as_tensor(state, device=device, dtype=torch.float32) + state_mask = torch.as_tensor(state_mask, device=device, dtype=torch.bool) + if state.shape != (b, 212) or state_mask.shape != state.shape: + raise ValueError("native state and state_mask must be [B,212]") + if not torch.isfinite(state).all(): + raise ValueError("native state must be finite") + return Observation(torch.from_numpy(out).to(device).permute(0, 1, 4, 2, 3).float() / 127.5 - 1, + lang["input_ids"].to(device), lang["attention_mask"].to(device).bool(), + state, state_mask, torch.as_tensor(fov, device=device, dtype=torch.float32)) + + +class FrozenHumanPredictor(nn.Module): + """Keep a base frozen and re-normalize decoded predictions for one shared editor.""" + + def __init__(self, model, model_id: str, normalizer: ActionNormalizer, *, converter=None): + super().__init__() + if model_id not in ("smolvla", "vitra", "twla", "memoryvla"): + raise ValueError("unsupported shared-editor model") + if model_id == "vitra" and converter is None: + raise ValueError("VITRA requires an explicit MANO angle converter") + self.model = model.requires_grad_(False).eval() + self.model_id, self.normalizer, self.converter = model_id, normalizer, converter + + def train(self, mode=True): + super().train(mode) + self.model.eval() + return self + + @torch.no_grad() + def forward(self, observation, *, action_mask, noise=None, episode_id=None, + conversion=None, retain_memory=False, step_valid=None): + self.model.eval() + memory = None + if self.model_id == "twla": + if episode_id is None: + raise ValueError("T-WLA requires episode_id for memory reset") + out = self.model.select_action_context(observation, episode_id, noise=noise) + prediction = out["base_action"] + if retain_memory: + memory = out["memory_tokens"].detach() + else: + if noise is None: + raise ValueError("baseline inference requires explicit paired noise") + steps = observation if isinstance(observation, list) else [observation] + if self.model_id == "memoryvla": + prediction = self.model.predict_from_noise(steps, noise, step_valid=step_valid) + else: + prediction = self.model.predict_from_noise(steps, noise) + physical = self.model.unnormalise_action(prediction.float()) + if self.converter is not None: + physical = self.converter(physical, **(conversion or {})) + DEFAULT_ACTION_LAYOUT.validate(physical) + mask = action_mask.to(device=physical.device, dtype=torch.bool) + if mask.shape != physical.shape or mask[..., 138:].any(): + raise ValueError("action_mask must use the 138D keypoints layout") + # Invalid hands and padding never condition the common editor. + base = self.normalizer.normalize(physical).masked_fill(~mask, 0) + return BaseActionContext(base.detach(), mask, self.model_id, self.normalizer.identity, + memory_tokens=memory, + metadata={"native_memory_used_by_base": self.model_id in ("twla", "memoryvla"), + "human_action_trained": getattr(self.model, "_human_action_trained", True)}) diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/mano_action.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/mano_action.py new file mode 100644 index 0000000000000000000000000000000000000000..90b0325a4b431acff269eaf7bb8335c8b1837ebd --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/mano_action.py @@ -0,0 +1,92 @@ +"""Decode VITRA's absolute joint angles with explicit per-hand MANO conventions.""" +from __future__ import annotations + +import numpy as np +import torch +from scipy.spatial.transform import Rotation + +MANO2DATA = [0, 5, 6, 7, 9, 10, 11, 17, 18, 19, 13, 14, 15, 1, 2, 3] +TIP_DATA = [4, 8, 12, 16, 20] +TIP_VERTS = [744, 320, 443, 554, 671] + + +class ManoActionConverter: + """Convert denormalized [B,16,192] angle actions into keypoint actions. + + `conventions` is [B,2]: left = mirrored_right or mano_left, + right = mano_right. No sensor/dataset-name heuristic selects a hand model. + `betas` is [B,2,10], measured at the observation or fixed per subject. + """ + + def __init__(self, weights_dir, *, device="cpu"): + self.weights_dir, self.device = str(weights_dir), device + self.models = {} + + def _model(self, right): + if right not in self.models: + # chumpy 0.70, which is referenced by the official MANO pickle, + # still calls the alias removed in Python 3.11. + import inspect + if not hasattr(inspect, "getargspec"): + inspect.getargspec = inspect.getfullargspec + # The PyPI chumpy wheel also imports NumPy aliases removed in 1.24. + for name, value in { + "bool": np.bool_, "int": int, "float": float, + "complex": complex, "object": object, "unicode": str, "str": str, + }.items(): + if name not in np.__dict__: + setattr(np, name, value) + import smplx + self.models[right] = smplx.create( + self.weights_dir, "mano", is_rhand=right, use_pca=False, + flat_hand_mean=True, batch_size=1).to(self.device).eval().requires_grad_(False) + return self.models[right] + + @torch.no_grad() + def __call__(self, action, *, betas, conventions): + if action.ndim != 3 or action.shape[1:] != (16, 192): + raise ValueError("angle action must be [B,16,192]") + shape = np.asarray(torch.as_tensor(betas).cpu(), dtype=np.float32) + conventions = np.asarray(conventions) + if shape.shape != (len(action), 2, 10) or conventions.shape != (len(action), 2): + raise ValueError("betas must be [B,2,10]; conventions must be [B,2]") + if not np.isfinite(shape).all() or not torch.isfinite(action).all(): + raise ValueError("MANO inputs must be finite") + result = torch.zeros_like(action) + for side, (source, target) in enumerate(((0, 0), (51, 69))): + result[..., target:target + 6] = action[..., source:source + 6] + valid_names = {"mirrored_right", "mano_left"} if side == 0 else {"mano_right"} + if not set(conventions[:, side]).issubset(valid_names): + raise ValueError(f"invalid MANO convention for hand {side}") + for convention in sorted(set(conventions[:, side])): + rows = np.flatnonzero(conventions[:, side] == convention) + angles = action[rows, :, source + 6:source + 51].cpu().numpy() + aa = Rotation.from_euler("xyz", angles.reshape(-1, 3)).as_rotvec().reshape(-1, 45) + z = torch.zeros(len(rows) * 16, 3, device=self.device) + output = self._model(convention != "mano_left")( + betas=torch.as_tensor(np.repeat(shape[rows, side], 16, axis=0), device=self.device), + hand_pose=torch.as_tensor(aa, dtype=torch.float32, device=self.device), + global_orient=z, transl=z) + root = output.joints[:, :1] + kp = torch.empty(len(rows) * 16, 21, 3, device=self.device) + kp[:, MANO2DATA] = output.joints[:, :16] - root + kp[:, TIP_DATA] = output.vertices[:, TIP_VERTS] - root + if convention == "mirrored_right": + kp[..., 0] *= -1 + result[rows, :, target + 6:target + 69] = kp.reshape(len(rows), 16, 63).to(action) + return result + + def calibration_error_cm(self, angles, keypoints, mask, *, betas, conventions): + """Measure FK residual on ground-truth labels. This is not subtracted from scores.""" + decoded = self(angles, betas=betas, conventions=conventions) + errors = [] + for lo in (6, 75): + valid = mask[..., lo:lo + 63].bool().all(-1) + diff = (decoded[..., lo:lo + 63] - keypoints[..., lo:lo + 63]).reshape(-1, 21, 3) + distance = diff[:, 1:].norm(dim=-1).mean(-1).reshape(valid.shape) + errors.append(distance[valid]) + errors = torch.cat(errors) + if not errors.numel(): + raise ValueError("no valid hands for FK calibration") + return {"mean_cm": float(errors.mean() * 100), + "max_cm": float(errors.max() * 100), "valid_hand_frames": len(errors)} diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/mock.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/mock.py new file mode 100644 index 0000000000000000000000000000000000000000..aef4d65fa0898b4560c8af6f0f2f77ff93e2e982 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/mock.py @@ -0,0 +1,80 @@ +"""Small Method D fixture for contract tests and CI smoke runs.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import torch +from torch import nn + + +class MockSelectedEncoder(nn.Module): + """Keep the published encoder signature without external model files.""" + + def __init__(self, embedding_dim: int = 64) -> None: + super().__init__() + self.projection = nn.Linear(2, embedding_dim) + + def forward(self, touch: torch.Tensor, side: torch.Tensor) -> torch.Tensor: + stats = torch.stack( + (touch.mean(dim=(1, 2, 3)), touch.std(dim=(1, 2, 3))), dim=-1 + ) + result = self.projection(stats) + return torch.nn.functional.normalize(result, dim=-1) + + +class TinyMethodD(nn.Module): + """Use the real V4-D ActionExpert with small dimensions.""" + + def __init__( + self, + *, + hidden_dim: int = 64, + memory_dim: int = 32, + slots: int = 3, + chunk_size: int = 4, + action_dim: int = 12, + depth: int = 2, + num_heads: int = 4, + num_kv_heads: int = 2, + head_dim: int = 16, + ) -> None: + super().__init__() + from vla_hand_pose.v4_d_fm_0.action_expert import ActionExpert + from vla_hand_pose.v4_d_fm_0.config import ExpertConfig + + expert_cfg = ExpertConfig( + num_layers=depth, + hidden_size=hidden_dim, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + head_dim=head_dim, + self_attn_every_n_layers=2, + cond_proj_in=memory_dim, + expert_slot_embedding=False, + causal_actions=True, + ) + self.expert = ActionExpert(expert_cfg, chunk_size, action_dim, slots) + # V4-D zero-initializes this layer for training stability. A nonzero test + # layer makes adapter gradients observable in the smoke run. + nn.init.normal_(self.expert.action_out_proj.weight, std=0.02) + self.cfg = SimpleNamespace(flow=SimpleNamespace(num_inference_steps=2)) + + def unnormalise_action(self, action: torch.Tensor) -> torch.Tensor: + return action + + +def build_structural_method_d() -> TinyMethodD: + """Build the production V4-D expert shape without VLM weights.""" + + return TinyMethodD( + hidden_dim=720, + memory_dim=960, + slots=8, + chunk_size=16, + action_dim=192, + depth=16, + num_heads=15, + num_kv_heads=5, + head_dim=64, + ) diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/model.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/model.py new file mode 100644 index 0000000000000000000000000000000000000000..dac0190769fa2d85970a03e7fc2aa070c54aa7a0 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/model.py @@ -0,0 +1,286 @@ +"""Checkpoint-independent integration at Method D's memory/expert seam.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +import torch +from torch import nn + +from .config import EditorConfig, Variant +from .encoder import DualHandTactileEncoder, TouchFeatures +from .fusion import ( + ExpertFusionContext, + ExpertTouchFusion, + PosthocResidualEditor, + build_fusion, +) + + +@dataclass +class PreparedContext: + """Conditions that stay constant across all Euler integration steps.""" + + method_d: Any + touch: TouchFeatures | None + expert_fusion: ExpertFusionContext | None + + +class TactileMethodD(nn.Module): + """Compose an existing Method D object with one V0--V3 tactile variant. + + The wrapper deliberately starts at ``m_f`` rather than duplicating the VLM and + memory-bank code. A future Method D checkpoint can therefore be loaded into the + unchanged base object. ``sample_from_memory`` is the executable integration seam; + V4-D's observation path only has to supply its normal ``m_f`` tensor. + """ + + def __init__( + self, + method_d: nn.Module, + config: EditorConfig, + tactile_encoder: DualHandTactileEncoder | None = None, + ) -> None: + super().__init__() + self.method_d = method_d + self.config = config + self.tactile_encoder = tactile_encoder + self.fusion = build_fusion(config.variant, config.fusion) + self._validate_contract() + + @property + def variant(self) -> Variant: + return self.config.variant + + def train(self, mode: bool = True): + super().train(mode) + if not any(p.requires_grad for p in self.method_d.parameters()): + self.method_d.eval() + if self.tactile_encoder is not None and not any( + p.requires_grad for p in self.tactile_encoder.parameters() + ): + self.tactile_encoder.eval() + return self + + def _validate_contract(self) -> None: + if not hasattr(self.method_d, "expert"): + raise TypeError("method_d must expose its action expert as .expert") + expert = self.method_d.expert + expert_hidden = int(expert.cfg.hidden_size) + if expert_hidden != self.config.fusion.hidden_dim: + raise ValueError( + f"fusion hidden_dim={self.config.fusion.hidden_dim} but expert uses {expert_hidden}" + ) + if int(expert.chunk_size) != self.config.fusion.chunk_size: + raise ValueError("fusion chunk_size does not match the Method D expert") + if self.variant != Variant.V0_BASE and self.tactile_encoder is None: + raise ValueError(f"{self.variant.value} requires a tactile encoder") + if self.variant in {Variant.V2_EXPERT_TOUCH, Variant.V3_MEMORY_TOUCH}: + depth = len(expert.layers) + invalid = [i for i in self.config.fusion.injection_layers if i >= depth] + if invalid: + raise ValueError( + f"injection layers {invalid} exceed expert depth {depth}" + ) + + def encode_touch( + self, + pressure: torch.Tensor, + temporal_valid: torch.Tensor | None = None, + *, + canonicalized: bool = False, + ) -> TouchFeatures: + if self.tactile_encoder is None: + raise RuntimeError("V0 has no tactile encoder") + return self.tactile_encoder( + pressure, temporal_valid, canonicalized=canonicalized + ) + + def _prepare_context( + self, + m_f: torch.Tensor, + touch: TouchFeatures | None, + state_with_mask: torch.Tensor | None, + ) -> PreparedContext: + expert = self.method_d.expert + base_ctx = expert.prepare(m_f, state_with_mask) + if self.variant in {Variant.V0_BASE, Variant.V1_POSTHOC}: + return PreparedContext(base_ctx, touch, None) + + if touch is None: + raise ValueError(f"{self.variant.value} requires touch features") + if not isinstance(self.fusion, ExpertTouchFusion): + raise TypeError("expert variant was built with the wrong fusion module") + fusion_ctx = self.fusion.prepare(touch, base_ctx.mem) + return PreparedContext(base_ctx, touch, fusion_ctx) + + def _expert_velocity( + self, + prepared: PreparedContext, + noisy_actions: torch.Tensor, + action_mask: torch.Tensor, + tau: torch.Tensor, + ) -> torch.Tensor: + expert = self.method_d.expert + base_ctx = prepared.method_d + if self.variant in {Variant.V0_BASE, Variant.V1_POSTHOC}: + return expert.velocity(base_ctx, noisy_actions, action_mask, tau) + if ( + not isinstance(self.fusion, ExpertTouchFusion) + or prepared.expert_fusion is None + ): + raise TypeError("expert variant was built with the wrong fusion module") + hidden = expert.embed_actions(noisy_actions, action_mask, tau) + for layer_index, layer in enumerate(expert.layers): + mask = base_ctx.sa_mask if layer.is_self_attn else base_ctx.ca_mask + hidden = layer(hidden, base_ctx.mem, mask) + hidden = self.fusion(layer_index, hidden, prepared.expert_fusion) + return expert.action_out_proj(expert.norm_out(hidden)) + + def velocity_from_memory( + self, + m_f: torch.Tensor, + noisy_actions: torch.Tensor, + action_mask: torch.Tensor, + tau: torch.Tensor, + *, + touch_pressure: torch.Tensor | None = None, + touch_valid: torch.Tensor | None = None, + canonicalized_touch: bool = False, + state_with_mask: torch.Tensor | None = None, + ) -> torch.Tensor: + """Predict one flow velocity while preserving Method D's native objective.""" + + touch = None + if self.variant not in {Variant.V0_BASE, Variant.V1_POSTHOC}: + if touch_pressure is None: + raise ValueError(f"{self.variant.value} requires touch_pressure") + touch = self.encode_touch( + touch_pressure, touch_valid, canonicalized=canonicalized_touch + ) + prepared = self._prepare_context(m_f, touch, state_with_mask) + return self._expert_velocity(prepared, noisy_actions, action_mask, tau) + + def sample_from_memory( + self, + m_f: torch.Tensor, + action_mask: torch.Tensor, + *, + touch_pressure: torch.Tensor | None = None, + touch_valid: torch.Tensor | None = None, + canonicalized_touch: bool = False, + state_with_mask: torch.Tensor | None = None, + edit_mask: torch.Tensor | None = None, + noise: torch.Tensor | None = None, + num_steps: int | None = None, + return_normalized: bool = False, + apply_posthoc: bool = True, + ) -> torch.Tensor: + """Generate a full chunk. For a V1 runtime install, use apply_posthoc=False. + + The controller stores that unedited chunk and applies V1 at each decision. + The default keeps the one-shot V1 evaluation interface unchanged. + """ + + b = m_f.shape[0] + cfg = self.config.fusion + expected = (b, cfg.chunk_size, cfg.action_dim) + if tuple(action_mask.shape) != expected: + raise ValueError( + f"action_mask must be {expected}, got {tuple(action_mask.shape)}" + ) + touch = None + if self.variant != Variant.V0_BASE and not ( + self.variant == Variant.V1_POSTHOC and not apply_posthoc + ): + if touch_pressure is None: + raise ValueError(f"{self.variant.value} requires touch_pressure") + touch = self.encode_touch( + touch_pressure, touch_valid, canonicalized=canonicalized_touch + ) + + if noise is None: + noise = torch.randn(expected, device=m_f.device, dtype=m_f.dtype) + if tuple(noise.shape) != expected: + raise ValueError(f"noise must be {expected}, got {tuple(noise.shape)}") + x = noise.masked_fill(~action_mask, 0) + prepared = self._prepare_context(m_f, touch, state_with_mask) + steps = int( + self.method_d.cfg.flow.num_inference_steps + if num_steps is None + else num_steps + ) + if steps <= 0: + raise ValueError("num_steps must be positive") + dt = 1.0 / steps + for index in range(steps): + tau = torch.full((b,), 1.0 - index * dt, device=x.device, dtype=x.dtype) + velocity = self._expert_velocity(prepared, x, action_mask, tau) + x = x - dt * velocity + x = x.masked_fill(~action_mask, 0) + + if self.variant == Variant.V1_POSTHOC and apply_posthoc: + if not isinstance(self.fusion, PosthocResidualEditor) or touch is None: + raise TypeError("V1 was built with the wrong fusion module") + editable = action_mask if edit_mask is None else (action_mask & edit_mask) + x, _ = self.fusion(x, touch, editable) + + if return_normalized: + return x + if not hasattr(self.method_d, "unnormalise_action"): + raise TypeError( + "method_d must expose unnormalise_action for raw action output" + ) + return self.method_d.unnormalise_action(x.float()) + + def edit_existing_plan( + self, + normalized_action: torch.Tensor, + edit_mask: torch.Tensor, + touch_pressure: torch.Tensor, + touch_valid: torch.Tensor | None = None, + *, + canonicalized_touch: bool = False, + ) -> torch.Tensor: + """Predict from the ORIGINAL normalized VLA plan, never a prior revision.""" + + if self.variant != Variant.V1_POSTHOC or not isinstance( + self.fusion, PosthocResidualEditor + ): + raise RuntimeError("edit_existing_plan is available only for V1") + if self.config.fusion.posthoc_use_touch: + touch = self.encode_touch( + touch_pressure, touch_valid, canonicalized=canonicalized_touch + ) + else: + touch = TouchFeatures( + normalized_action.new_zeros(len(normalized_action), 2, 64), + normalized_action.new_zeros( + len(normalized_action), 2, dtype=torch.bool + ), + ) + edited, _ = self.fusion(normalized_action, touch, edit_mask) + return edited + + def extra_repr(self) -> str: + return ( + f"variant={self.variant.value}, train_mode={self.config.train_mode.value}" + ) + + +def count_parameters(module: nn.Module | None) -> dict[str, int]: + if module is None: + return {"total": 0, "trainable": 0} + return { + "total": sum(p.numel() for p in module.parameters()), + "trainable": sum(p.numel() for p in module.parameters() if p.requires_grad), + } + + +def component_report(model: TactileMethodD) -> dict[str, dict[str, int]]: + return { + "method_d": count_parameters(model.method_d), + "tactile_encoder": count_parameters(model.tactile_encoder), + "fusion": count_parameters(model.fusion), + } diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/offline_data.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/offline_data.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb48f0036a88c33a403763ebf7ee80e1e99bea6 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/offline_data.py @@ -0,0 +1,165 @@ +"""Offline V1 samples from immutable normalized VLA plans and episode touch.""" + +from __future__ import annotations + +from dataclasses import dataclass, fields +import math + +import torch +from torch.utils.data import Dataset + +from .training import V1TrainingBatch, nominal_revision_times + + +@dataclass(frozen=True) +class EpisodeTouch: + source_video_id: str + timestamps: torch.Tensor # [N], episode-relative seconds, float64 preferred + pressure: torch.Tensor # [N,2,21,21], raw, not mirrored or normalized + valid: torch.Tensor # [N,2] + + +@dataclass(frozen=True) +class CachedPlan: + episode_id: str + anchor_seconds: float + base_action: torch.Tensor # [16,192], unedited normalized VLA prediction + target_action: torch.Tensor # [16,192], same grid/frame/normalizer as base + action_mask: torch.Tensor # [16,192], missing hands and padding are false + normalization_id: str # SHA256 of frozen VLA statistics, or labelled smoke ID + backbone_id: str # checkpoint identity, or labelled smoke fixture + + +class OfflineV1Dataset(Dataset): + """Expand each plan into independent tactile decisions, without wall-clock time. + + ``split_by_video`` must come from the upstream VLA split manifest. All episodes + cut from one video inherit that split. This loader never resplits windows. + Cache generation must use causal VLA memory and the original action geometry. + """ + + def __init__( + self, + plans: list[CachedPlan], + episodes: dict[str, EpisodeTouch], + split_by_video: dict[str, str], + *, + split: str, + normalization_id: str, + backbone_id: str, + decision_times: tuple[float, ...] = nominal_revision_times(), + ) -> None: + if split not in {"train", "val", "test"}: + raise ValueError("split must be train, val, or test") + if not normalization_id or not backbone_id: + raise ValueError("normalization and backbone identities are required") + if ( + not decision_times + or any(not math.isfinite(t) or not 0 <= t < 0.1 for t in decision_times) + or tuple(sorted(set(decision_times))) != decision_times + ): + raise ValueError("decision_times must increase within [0, 0.1) seconds") + self.episodes = episodes + self.samples: list[tuple[CachedPlan, float]] = [] + for episode in episodes.values(): + n = len(episode.timestamps) + if n == 0 or episode.timestamps.shape != (n,): + raise ValueError("each episode needs a nonempty timestamp vector") + if ( + not torch.isfinite(episode.timestamps).all() + or not (episode.timestamps[1:] > episode.timestamps[:-1]).all() + ): + raise ValueError("episode timestamps must be finite and increasing") + if episode.pressure.shape != (n, 2, 21, 21) or episode.valid.shape != ( + n, + 2, + ): + raise ValueError("invalid dual-hand episode shapes") + if not torch.isfinite(episode.pressure).all(): + raise ValueError("remove nonsensor NaN values before loading touch") + if split_by_video.get(episode.source_video_id) not in { + "train", + "val", + "test", + }: + raise ValueError("every source video needs an explicit split") + seen: set[tuple[str, float]] = set() + for plan in plans: + if plan.episode_id not in episodes: + raise ValueError("plan references an unknown episode") + if ( + plan.normalization_id != normalization_id + or plan.backbone_id != backbone_id + ): + raise ValueError("mixed backbone or normalization identities") + if any( + x.shape != (16, 192) + for x in (plan.base_action, plan.target_action, plan.action_mask) + ): + raise ValueError("cached actions and mask must be [16,192]") + if plan.action_mask[..., 138:].any(): + raise ValueError("padded action dimensions must be invalid") + if ( + not torch.isfinite(plan.base_action).all() + or not torch.isfinite(plan.target_action[plan.action_mask.bool()]).all() + ): + raise ValueError("cached base and valid targets must be finite") + episode = episodes[plan.episode_id] + if not math.isfinite(plan.anchor_seconds) or plan.anchor_seconds < float( + episode.timestamps[0] + ): + raise ValueError("plan anchor precedes episode touch") + key = (plan.episode_id, plan.anchor_seconds) + if key in seen: + raise ValueError("duplicate cached plan") + seen.add(key) + if split_by_video[episode.source_video_id] != split: + continue + for decision in decision_times: + if ( + plan.anchor_seconds + decision + > float(episode.timestamps[-1]) + 1e-9 + ): + continue # No future episode data or hold beyond recording end. + self.samples.append((plan, decision)) + + def __len__(self) -> int: + return len(self.samples) + + def __getitem__(self, index: int) -> dict[str, torch.Tensor]: + plan, decision = self.samples[index] + episode = self.episodes[plan.episode_id] + now = plan.anchor_seconds + decision + targets = now - torch.arange(7, -1, -1, dtype=torch.float64) / 30.0 + # A tiny tolerance treats mathematically identical frame timestamps alike. + indices = ( + torch.searchsorted(episode.timestamps.double(), targets + 1e-9, right=True) + - 1 + ) + available = indices >= 0 + indices = indices.clamp_min(0) + valid = episode.valid[indices].bool() & available[:, None] + touch = ( + episode.pressure[indices].clone().masked_fill(~valid[..., None, None], 0) + ) + return { + "base_action": plan.base_action.detach().clone(), + "target_action": plan.target_action.detach().clone(), + "action_mask": plan.action_mask.bool().clone(), + "touch_pressure": touch, + "touch_valid": valid, + "decision_after_start_seconds": torch.tensor(decision, dtype=torch.float64), + } + + +def collate_v1_samples(samples: list[dict[str, torch.Tensor]]) -> V1TrainingBatch: + if not samples: + raise ValueError("cannot collate an empty batch") + batch = V1TrainingBatch( + **{ + field.name: torch.stack([sample[field.name] for sample in samples]) + for field in fields(V1TrainingBatch) + } + ) + batch.validate() + return batch diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/paired30_cache.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/paired30_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..92c31e1a032a6a3fbe9f8a1536beb800e42717b1 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/paired30_cache.py @@ -0,0 +1,128 @@ +"""One common (query, decision) row set for all six editor experiments.""" +from pathlib import Path +import json +import numpy as np +import torch +from torch.utils.data import Dataset + +from .contact_filter import contact_gate + +class Paired30Cache(Dataset): + def __init__(self,root,split,model,*,include_rgb=False,statistics=None,require_complete=True): + self.root=Path(root);self.split=split;self.model=model;self.include_rgb=include_rgb + common=self.root/'shared'/split + if require_complete and not (common/'complete.json').is_file():raise RuntimeError(f'incomplete common cache {common}') + self.common={p.stem:np.load(p,mmap_mode='r') for p in common.glob('*.npy')} + self.rows=np.argwhere(self.common['eligible']) + self.queries=dict(np.load(common/'queries.npz',allow_pickle=False)) + n=len(self.queries['episode_id']) + shapes={'target_action':(n,16,192),'action_mask':(n,16,192), + 'touch_sequence':(n,10,2,21,21),'touch_sequence_valid':(n,10,2), + 'future_touch_pressure':(n,3,2,21,21),'future_touch_valid':(n,3,2), + 'eligible':(n,3),'source_frame':(n,)} + for name,shape in shapes.items(): + if name not in self.common or self.common[name].shape!=shape: + raise ValueError(f'invalid common field {name}: expected {shape}') + self.stats=statistics + self.bases=[] + if model=='twla': + paths=sorted((self.root/'bases/twla'/split).glob('shard_*')) + for p in paths: + if require_complete and not (p/'complete.json').is_file():raise RuntimeError(f'incomplete predictions {p}') + names=['base_action','final_memory','query_index']+(['image_tokens','clean_latent','rgb_valid','future_roi'] if include_rgb else []) + self.bases.append({k:np.load(p/f'{k}.npy',mmap_mode='r') for k in names}) + n=len(self.common['target_action']);self.locations=np.full((n,2),-1,dtype=np.int64) + for si,b in enumerate(self.bases): + ids=b['query_index'] + if ids.ndim!=1 or not np.issubdtype(ids.dtype,np.integer): + raise ValueError('query indices must be a one-dimensional integer array') + if np.any(ids<0) or np.any(ids>=n) or len(np.unique(ids))!=len(ids): + raise ValueError('invalid or repeated query index within shard') + if any(len(value)!=len(ids) for value in b.values()): + raise ValueError('prediction arrays have different row counts') + if np.any(self.locations[ids,0]>=0):raise ValueError('duplicate query predictions') + self.locations[ids,0]=si;self.locations[ids,1]=np.arange(len(ids)) + if np.any(self.locations<0):raise ValueError('missing canonical predictions') + else: + self.bases=[{'base_action':np.load(self.root/'bases'/model/split/'base_action.npy',mmap_mode='r')}] + if self.bases[0]['base_action'].shape!=(n,16,192): + raise ValueError('baseline prediction shape does not match common queries') + self.identity=json.loads((common/'complete.json').read_text()) if (common/'complete.json').exists() else {} + + def __len__(self):return len(self.rows) + + def __getitem__(self,index): + qi,tick=map(int,self.rows[index]);c=self.common + if self.model=='twla':si,bi=self.locations[qi] + else:si,bi=0,qi + b=self.bases[si] + out={k:torch.from_numpy(np.array(v[bi],copy=True)) for k,v in b.items() if k!='query_index'} + out.update(target_action=torch.from_numpy(np.array(c['target_action'][qi],copy=True)),action_mask=torch.from_numpy(np.array(c['action_mask'][qi],copy=True)),touch_pressure=torch.from_numpy(np.array(c['touch_sequence'][qi,tick:tick+8],copy=True)).float(),touch_valid=torch.from_numpy(np.array(c['touch_sequence_valid'][qi,tick:tick+8],copy=True)),future_touch_pressure=torch.from_numpy(np.array(c['future_touch_pressure'][qi,tick],copy=True)).float(),future_touch_valid=torch.from_numpy(np.array(c['future_touch_valid'][qi,tick],copy=True)),decision_seconds=torch.tensor(tick/30,dtype=torch.float32),query_index=torch.tensor(qi),decision_tick=torch.tensor(tick)) + if self.stats is not None: + for k in ('base_action','target_action'):out[k]=(out[k].float()-self.stats['action_mean'])/self.stats['action_std'] + return out + + +class Paired30ContactCache(Dataset): + """Apply a precomputed pressure gate without changing paired row identity.""" + + def __init__(self, base, manifest_root, *, contact_only): + self.base = base + self.manifest_root = Path(manifest_root) + self.metadata = json.loads((self.manifest_root / "metadata.json").read_text()) + if self.metadata.get("split") != base.split: + raise ValueError("contact manifest split does not match the cache") + if self.metadata.get("query_sha256") != base.identity.get("query_sha256"): + raise ValueError("contact manifest query identity does not match the cache") + self.plan_gate = np.load(self.manifest_root / "plan_hand_gate.npy", mmap_mode="r") + if self.plan_gate.shape != (len(base.common["eligible"]), 3, 2): + raise ValueError("invalid plan_hand_gate shape") + row_gate = self.plan_gate[base.rows[:, 0], base.rows[:, 1]] + self.selected = np.flatnonzero(row_gate.any(1)) if contact_only else np.arange(len(base)) + expected = int(self.metadata["selected_rows"]) + if int(row_gate.any(1).sum()) != expected: + raise ValueError("contact manifest selected-row count does not match") + self.contact_only = bool(contact_only) + self.common = base.common + self.bases = base.bases + self.model = base.model + self.split = base.split + self.identity = { + **base.identity, + "contact_gate": { + "threshold": self.metadata["threshold"], + "comparator": self.metadata["comparator"], + "score": self.metadata["score"], + "selected_rows": expected, + "contact_only": self.contact_only, + }, + } + + def __len__(self): + return len(self.selected) + + def gate_for_queries(self, query_index, decision_tick): + return np.asarray(self.plan_gate[query_index, decision_tick], dtype=bool) + + def __getitem__(self, index): + base_index = int(self.selected[index]) + row = self.base[base_index] + query_index, decision_tick = map(int, self.base.rows[base_index]) + gate = torch.from_numpy( + np.array(self.plan_gate[query_index, decision_tick], copy=True) + ).bool() + row["contact_gate"] = gate + row["touch_valid"] &= gate[None] + row["future_touch_valid"] &= gate + row["action_mask"][:, :69] &= gate[0] + row["action_mask"][:, 69:138] &= gate[1] + return row + +def edit_mask(batch): + from .training import build_future_action_mask + mask=build_future_action_mask(batch['action_mask'],batch['decision_seconds']) + mask[...,138:]=False + latest=batch['touch_valid'][:,-1].bool() + mask[...,:69]&=latest[:,0,None,None] + mask[...,69:138]&=latest[:,1,None,None] + return mask diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/real_data.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/real_data.py new file mode 100644 index 0000000000000000000000000000000000000000..cc57b4a1701dc4ffd4ed2880f2c9885993c03812 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/real_data.py @@ -0,0 +1,439 @@ +"""Pinned real EgoTouch sample loading and deterministic multi-rate replay.""" + +from __future__ import annotations + +import hashlib +import io +import json +import math +import gc +import statistics +import tarfile +import time +import urllib.request +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +import torch + +from .config import EditorConfig, FusionConfig, Variant +from .encoder import DualHandTactileEncoder, load_huggingface_encoder +from .mock import build_structural_method_d +from .model import TactileMethodD, component_report +from .runtime import ActionPlan, PipelinedController +from .trainability import configure_trainable_components + + +SOURCE_REVISION = "11b1e07ecb5706fe309d7ae8d55de0eeb7f2bf3f" +SOURCE_REPOSITORY = "MIT-Media-Lab/egotouch-annotations-v1" +SOURCE_MEMBER = ( + "Annotation/egotouch/episodic_annotations/" + "egotouch_Home__arrange_pillow__20260412_101136_379_" + "ep_000000_c30_000000_left.npy" +) +SOURCE_MEMBER_SHA256 = ( + "5874a337b55b5b9d1172e92cc29e782f568f3d4a512a27dab97e135a2f10c423" +) +SOURCE_RANGE_BYTES = 1_048_576 +RAW_PRESSURE_CELLS_PER_HAND = 217 +SOURCE_URL = ( + f"https://huggingface.co/datasets/{SOURCE_REPOSITORY}/resolve/" + f"{SOURCE_REVISION}/egotouch.tar" +) + + +@dataclass(frozen=True) +class RealEgoTouchEpisode: + episode_id: str + pressure: torch.Tensor # [T,2,21,21], raw left/right glove coordinates + valid: torch.Tensor # [T,2] + frame_hz: float = 30.0 + + +def _decode_annotation(payload: bytes) -> RealEgoTouchEpisode: + digest = hashlib.sha256(payload).hexdigest() + if digest != SOURCE_MEMBER_SHA256: + raise ValueError(f"EgoTouch sample checksum mismatch: {digest}") + annotation = np.load(io.BytesIO(payload), allow_pickle=True).item() + tactile = annotation.get("tactile") + if not isinstance(tactile, dict) or set(tactile) != {"left", "right"}: + raise ValueError( + "the EgoTouch annotation must contain left and right tactile data" + ) + hands = [np.asarray(tactile[name], dtype=np.float32) for name in ("left", "right")] + if hands[0].shape != hands[1].shape or hands[0].ndim != 3: + raise ValueError( + "left and right tactile arrays must have the same [T,H,W] shape" + ) + if hands[0].shape[1:] != (21, 21): + raise ValueError(f"unexpected tactile grid shape: {hands[0].shape}") + pressure = np.stack(hands, axis=1) + # The raw 21 x 21 grid has NaN at positions that have no physical sensor. + # A valid glove frame has all 217 raw sensor values. The encoder later removes + # the 66 bend cells and retains the same 151 pressure cells used for training. + valid = np.isfinite(pressure).sum(axis=(2, 3)) == RAW_PRESSURE_CELLS_PER_HAND + pressure = np.nan_to_num(pressure, nan=0.0, posinf=0.0, neginf=0.0) + episode_id = Path(SOURCE_MEMBER).stem + return RealEgoTouchEpisode( + episode_id=episode_id, + pressure=torch.from_numpy(pressure), + valid=torch.from_numpy(valid), + ) + + +def load_pinned_egotouch_episode(cache_dir: str | Path) -> RealEgoTouchEpisode: + """Load one pinned, dual-hand sample without downloading the 21 GB archive.""" + + root = Path(cache_dir) + root.mkdir(parents=True, exist_ok=True) + target = root / f"{Path(SOURCE_MEMBER).stem}.npy" + if target.is_file(): + return _decode_annotation(target.read_bytes()) + + request = urllib.request.Request( + SOURCE_URL, + headers={"Range": f"bytes=0-{SOURCE_RANGE_BYTES - 1}"}, + ) + with urllib.request.urlopen(request, timeout=120) as response: + if response.status != 206: + raise RuntimeError( + f"the dataset server ignored the byte-range request: HTTP {response.status}" + ) + archive_prefix = response.read(SOURCE_RANGE_BYTES + 1) + if len(archive_prefix) > SOURCE_RANGE_BYTES: + raise RuntimeError("the EgoTouch archive prefix exceeded the download limit") + + with tarfile.open(fileobj=io.BytesIO(archive_prefix), mode="r:") as archive: + member = archive.next() + if member is None or member.name != SOURCE_MEMBER: + actual = None if member is None else member.name + raise RuntimeError(f"the pinned first tar member changed: {actual}") + extracted = archive.extractfile(member) + if extracted is None: + raise RuntimeError("the pinned EgoTouch tar member cannot be read") + payload = extracted.read() + episode = _decode_annotation(payload) + target.write_bytes(payload) + return episode + + +def _latency_summary(values: list[float]) -> dict[str, float]: + ordered = sorted(values) + p95_index = max(0, math.ceil(0.95 * len(ordered)) - 1) + return { + "mean_ms": statistics.fmean(ordered), + "p50_ms": statistics.median(ordered), + "p95_ms": ordered[p95_index], + "max_ms": ordered[-1], + } + + +def _sync(device: torch.device) -> None: + if device.type == "cuda": + torch.cuda.synchronize(device) + + +def _timed(device: torch.device, operation): + _sync(device) + start = time.perf_counter() + result = operation() + _sync(device) + return result, (time.perf_counter() - start) * 1_000.0 + + +def _condition( + plan_index: int, device: torch.device +) -> tuple[torch.Tensor, torch.Tensor]: + generator = torch.Generator(device="cpu").manual_seed(90_000 + plan_index) + memory = torch.randn(1, 8, 960, generator=generator) + noise = torch.randn(1, 16, 192, generator=generator) + return memory.to(device), noise.to(device) + + +def _make_model( + variant: Variant, + selected_encoder: torch.nn.Module, + device: torch.device, +) -> TactileMethodD: + torch.manual_seed(11) + method_d = build_structural_method_d() + frontend = None + if variant != Variant.V0_BASE: + frontend = DualHandTactileEncoder(selected_encoder, freeze=True) + model = TactileMethodD( + method_d, + EditorConfig(variant=variant, fusion=FusionConfig()), + frontend, + ).to(device) + configure_trainable_components(model) + return model.eval() + + +def _operate_variant( + variant: Variant, + episode: RealEgoTouchEpisode, + selected_encoder: torch.nn.Module, + device: torch.device, +) -> tuple[dict[str, object], torch.Tensor]: + model = _make_model(variant, selected_encoder, device) + controller = PipelinedController( + control_hz=10.0, + action_hz=80.0, + tactile_model_hz=30.0, + history_frames=8, + ) + action_mask = torch.zeros(1, 16, 192, dtype=torch.bool, device=device) + action_mask[..., :138] = True + vision_latencies: list[float] = [] + revision_latencies: list[float] = [] + emitted: list[torch.Tensor] = [] + touch_updates = 0 + plan_generations = 0 + revision_calls = 0 + max_committed_change = 0.0 + + def revise(base, edit_mask, pressure, valid): + nonlocal max_committed_change + before = base.detach().clone() + edited = model.edit_existing_plan( + base, + edit_mask, + pressure.to(device), + valid.to(device), + canonicalized_touch=False, + ) + protected = ~edit_mask + if bool(protected.any()): + change = (edited[protected] - before[protected]).abs().max().item() + max_committed_change = max(max_committed_change, change) + return edited + + last_tick = (len(episode.pressure) - 1) * 8 + with torch.inference_mode(): + for tick in range(last_tick + 1): + timestamp = tick / 240.0 + touch_event = tick % 8 == 0 + vision_event = tick % 24 == 0 + action_event = tick % 3 == 0 + + if touch_event: + frame = tick // 8 + touch_updates += 1 + if variant == Variant.V1_POSTHOC and not vision_event: + _, elapsed = _timed( + device, + lambda: controller.update_touch( + episode.pressure[frame], + timestamp=timestamp, + episode_id=episode.episode_id, + valid=episode.valid[frame], + revise=revise, + ), + ) + revision_latencies.append(elapsed) + revision_calls += 1 + else: + controller.update_touch( + episode.pressure[frame], + timestamp=timestamp, + episode_id=episode.episode_id, + valid=episode.valid[frame], + ) + + if vision_event: + request = controller.begin_inference( + captured_at=timestamp, episode_id=episode.episode_id + ) + window, window_valid = controller.touch.window(timestamp) + memory, noise = _condition(plan_generations, device) + plan, elapsed = _timed( + device, + lambda: model.sample_from_memory( + memory, + action_mask, + touch_pressure=( + window.to(device) if variant != Variant.V0_BASE else None + ), + touch_valid=( + window_valid.to(device) + if variant != Variant.V0_BASE + else None + ), + canonicalized_touch=False, + noise=noise, + num_steps=1, + return_normalized=True, + apply_posthoc=False, + ), + ) + vision_latencies.append(elapsed) + # This structural replay has no wall-clock latency model. The real + # checkpoint replay supplies measured ready timestamps. + scheduled = controller.complete_inference( + plan[0], + request_id=request.request_id, + ready_at=timestamp, + episode_id=episode.episode_id, + action_mask=action_mask[0], + ) + plan_generations += 1 + if variant == Variant.V1_POSTHOC: + # Install the original flow output; keep the initial revision + # separate so later updates cannot compound its residual. + initial, revision_elapsed = _timed( + device, lambda: revise(plan, action_mask, window, window_valid) + ) + revision_latencies.append(revision_elapsed) + scheduled.plan.apply_revision(initial[0], now=timestamp) + revision_calls += 1 + + if action_event: + action = controller.next_action(timestamp) + emitted.append(action.detach().float().cpu()) + + stale_guard = ActionPlan( + torch.zeros(16, 192), started_at=0.0, action_hz=80.0, plan_id=7 + ) + stale_rejected = False + try: + stale_guard.apply_revision(torch.ones(16, 192), now=0.05, expected_plan_id=6) + except RuntimeError: + stale_rejected = True + + controller.update_touch( + episode.pressure[0], + timestamp=(last_tick + 8) / 240.0, + episode_id=f"{episode.episode_id}:next", + valid=episode.valid[0], + ) + episode_reset = controller.plan is None and controller.touch.sample_count == 1 + actions = torch.stack(emitted) + result: dict[str, object] = { + "plan_generations_10hz": plan_generations, + "touch_updates_30hz": touch_updates, + "action_outputs_80hz": len(emitted), + "tactile_revision_calls": revision_calls, + "all_actions_finite": bool(torch.isfinite(actions).all()), + "max_committed_action_change": max_committed_change, + "stale_plan_rejected": stale_rejected, + "episode_reset_passed": episode_reset, + "vision_path_latency": _latency_summary(vision_latencies), + "revision_latency": ( + _latency_summary(revision_latencies) if revision_latencies else None + ), + "components": component_report(model), + } + return result, actions + + +def operate_real_data_replay( + *, + cache_dir: str | Path, + device: str | torch.device, +) -> dict[str, object]: + """Operate V0--V3 on one real dual-hand EgoTouch sequence without training.""" + + target = torch.device(device) + episode = load_pinned_egotouch_episode(cache_dir) + encoder = load_huggingface_encoder(cache_dir=cache_dir, device=target).eval() + outputs: dict[Variant, torch.Tensor] = {} + variants: dict[str, object] = {} + for variant in Variant: + result, actions = _operate_variant(variant, episode, encoder, target) + outputs[variant] = actions + variants[variant.value] = result + gc.collect() + if target.type == "cuda": + torch.cuda.empty_cache() + + baseline = outputs[Variant.V0_BASE] + for variant in Variant: + variants[variant.value]["max_abs_action_difference_from_v0"] = float( + (outputs[variant] - baseline).abs().max() + ) + + with torch.inference_mode(): + bridge = DualHandTactileEncoder(encoder, freeze=True).to(target).eval() + pressure = episode.pressure[-8:][None].to(target) + valid = episode.valid[-8:][None].to(target) + matched = bridge(pressure, valid, canonicalized=False).tokens + reversed_tokens = bridge( + pressure.flip(1), valid.flip(1), canonicalized=False + ).tokens + stale = bridge( + episode.pressure[:8][None].to(target), + episode.valid[:8][None].to(target), + canonicalized=False, + ).tokens + zero = bridge( + torch.zeros_like(pressure), + torch.zeros_like(valid), + canonicalized=False, + ).tokens + + cosine = torch.nn.functional.cosine_similarity + result = { + "scope": { + "trained_action_model": False, + "method_d_checkpoint": False, + "method_d_memory_source": "deterministic synthetic m_f", + "vlm_forward": False, + "flow_inference_steps": 1, + "production_flow_inference_steps": 10, + "latency_is_production_benchmark": False, + "tactile_encoder_checkpoint": True, + "real_dual_hand_tactile": True, + }, + "runtime": { + "device": str(target), + "torch": torch.__version__, + "cuda": torch.version.cuda, + "gpu": torch.cuda.get_device_name(target) + if target.type == "cuda" + else None, + }, + "source": { + "repository": SOURCE_REPOSITORY, + "revision": SOURCE_REVISION, + "member": SOURCE_MEMBER, + "member_sha256": SOURCE_MEMBER_SHA256, + "episode_id": episode.episode_id, + "frames": len(episode.pressure), + "frame_hz": episode.frame_hz, + "duration_seconds": (len(episode.pressure) - 1) / episode.frame_hz, + "pressure_shape": list(episode.pressure.shape), + "valid_frames_per_hand": episode.valid.sum(dim=0).tolist(), + }, + "action_contract": { + "chunk_shape": [16, 192], + "left_dimensions": [0, 69], + "right_dimensions": [69, 138], + "masked_padding_dimensions": [138, 192], + }, + "encoder_controls": { + "output_shape": list(matched.shape), + "raw_sensor_cells_per_hand": RAW_PRESSURE_CELLS_PER_HAND, + "encoder_pressure_cells_per_hand": encoder.pressure_masks.sum(dim=(1, 2)) + .cpu() + .tolist(), + "matched_norms": matched.norm(dim=-1).cpu().tolist(), + "zero_invalid_is_zero": bool(torch.count_nonzero(zero) == 0), + "matched_vs_reversed_cosine": cosine(matched, reversed_tokens, dim=-1) + .cpu() + .tolist(), + "matched_vs_stale_cosine": cosine(matched, stale, dim=-1).cpu().tolist(), + }, + "variants": variants, + "interpretation": ( + "All tactile adapters are untrained and start as the V0 identity path. " + "Equal action outputs are expected and do not measure tactile utility." + ), + } + return result + + +def save_replay_result(result: dict[str, object], path: str | Path) -> None: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/rgb_world_data.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/rgb_world_data.py new file mode 100644 index 0000000000000000000000000000000000000000..7e8ce597099f0bec7152226597b2c16cf3e55082 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/rgb_world_data.py @@ -0,0 +1,130 @@ +"""Geometry utilities for future-hand RGB-world supervision. + +EgoTouch images are 640x480. The V4 loader keeps aspect ratio, resizes the long +side to 512, and pads on the *top and left*. The helpers here apply that exact +pixel transform before rasterizing hand boxes onto the DC-AE latent grid. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np + + +@dataclass(frozen=True) +class ProjectedHandROI: + roi: np.ndarray + uv_source: np.ndarray + visible: np.ndarray + source_bbox: tuple[float, float, float, float] | None + square_bbox: tuple[float, float, float, float] | None + valid: bool + + +def square_resize_geometry( + source_hw: tuple[int, int], square_size: int +) -> tuple[float, int, int, int, int]: + """Return scale, top pad, left pad, resized height and resized width.""" + height, width = source_hw + if min(height, width, square_size) <= 0: + raise ValueError("image dimensions must be positive") + scale = min(square_size / width, square_size / height) + resized_height = max(1, int(height * scale)) + resized_width = max(1, int(width * scale)) + return ( + scale, + square_size - resized_height, + square_size - resized_width, + resized_height, + resized_width, + ) + + +def intrinsics_for_square( + intrinsics: np.ndarray, + source_hw: tuple[int, int], + square_size: int, +) -> np.ndarray: + """Transform source-pixel intrinsics to the V4 bottom-right square canvas.""" + scale, top, left, _, _ = square_resize_geometry(source_hw, square_size) + result = np.asarray(intrinsics, dtype=np.float64).copy() + if result.shape != (3, 3): + raise ValueError("intrinsics must be [3,3]") + result[0, :] *= scale + result[1, :] *= scale + result[0, 2] += left + result[1, 2] += top + result[2, :] = (0.0, 0.0, 1.0) + return result + + +def project_future_hand_roi( + joints_camspace: np.ndarray, + intrinsics: np.ndarray, + *, + source_hw: tuple[int, int] = (480, 640), + square_size: int = 512, + latent_hw: tuple[int, int] = (16, 16), + min_visible_joints: int = 10, + margin_fraction: float = 0.20, +) -> ProjectedHandROI: + """Project 21 camera-space joints and rasterize a padded latent-space box.""" + joints = np.asarray(joints_camspace, dtype=np.float64) + if joints.shape != (21, 3): + raise ValueError(f"joints_camspace must be [21,3], got {joints.shape}") + if not 0 <= margin_fraction <= 2: + raise ValueError("margin_fraction must be in [0,2]") + height, width = source_hw + finite = np.isfinite(joints).all(1) + positive = joints[:, 2] > 1e-6 + safe_z = np.where(positive, joints[:, 2], 1.0) + normalized = joints / safe_z[:, None] + projected = (np.asarray(intrinsics, np.float64) @ normalized.T).T + uv = projected[:, :2] + visible = ( + finite + & positive + & np.isfinite(uv).all(1) + & (uv[:, 0] >= 0) + & (uv[:, 0] < width) + & (uv[:, 1] >= 0) + & (uv[:, 1] < height) + ) + latent_h, latent_w = latent_hw + roi = np.zeros((latent_h, latent_w), dtype=bool) + if int(visible.sum()) < min_visible_joints: + return ProjectedHandROI(roi, uv, visible, None, None, False) + + selected = uv[visible] + x0, y0 = selected.min(0) + x1, y1 = selected.max(0) + margin = max(x1 - x0, y1 - y0, 1.0) * margin_fraction + x0, x1 = max(0.0, x0 - margin), min(float(width), x1 + margin) + y0, y1 = max(0.0, y0 - margin), min(float(height), y1 + margin) + + scale, top, left, _, _ = square_resize_geometry(source_hw, square_size) + sx0, sx1 = x0 * scale + left, x1 * scale + left + sy0, sy1 = y0 * scale + top, y1 * scale + top + lx0 = max(0, int(np.floor(sx0 / square_size * latent_w))) + lx1 = min(latent_w, int(np.ceil(sx1 / square_size * latent_w))) + ly0 = max(0, int(np.floor(sy0 / square_size * latent_h))) + ly1 = min(latent_h, int(np.ceil(sy1 / square_size * latent_h))) + if lx1 <= lx0 or ly1 <= ly0: + return ProjectedHandROI(roi, uv, visible, (x0, y0, x1, y1), None, False) + roi[ly0:ly1, lx0:lx1] = True + return ProjectedHandROI( + roi, + uv, + visible, + (x0, y0, x1, y1), + (sx0, sy0, sx1, sy1), + True, + ) + + +def exact_episode_row(source_frames: np.ndarray, source_frame: int) -> int | None: + """Return the episode-local row for an exact absolute source frame.""" + frames = np.asarray(source_frames, dtype=np.int64) + row = int(np.searchsorted(frames, source_frame)) + return row if row < len(frames) and int(frames[row]) == source_frame else None diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/single_stage_world.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/single_stage_world.py new file mode 100644 index 0000000000000000000000000000000000000000..d43f2e82cbffe8ad1d9f53af33e4359f8f70b623 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/single_stage_world.py @@ -0,0 +1,668 @@ +"""Single-stage memory/tactile action editing with a tactile world objective. + +The frozen Method-D VLA is outside this module. Its cached ``m_f`` and action +plan are immutable inputs. One tactile trunk is shared by two trainable heads: + +* the action head edits the frozen plan from ``m_f + a_base + z_touch``; +* the world head predicts tactile pressure 0.1 s later from + ``m_f + z_touch + stopgrad(a_edited)``. + +The world path follows Kai's VLA-WM training contract where it matters for +optimisation: a deterministic frozen target codec, rectified-flow supervision, +four trainable blocks, a faster condition adapter, and an explicit gradient +boundary at the frozen VLA. SANA itself is not reused because its 2-D latent +geometry and pretrained RGB decoder are specific to image latents, not the two +21x21 pressure grids used here. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math + +import torch +from torch import nn + +from .action_objectives import per_sample_action_loss +from .action_layout import ARTICULATION_GROUPS, FULL_ACTION_GROUPS +from .direct_residual import DirectTactileTrunk + + +def _validate_shape( + tensor: torch.Tensor, shape: tuple[int | None, ...], name: str +) -> None: + if tensor.ndim != len(shape): + raise ValueError( + f"{name} must have {len(shape)} dimensions, got {tuple(tensor.shape)}" + ) + for actual, expected in zip(tensor.shape, shape): + if expected is not None and actual != expected: + raise ValueError( + f"{name} must have shape {shape}, got {tuple(tensor.shape)}" + ) + + +def gather_action_window( + action: torch.Tensor, + decision_seconds: torch.Tensor, + *, + steps: int = 8, + action_hz: float = 80.0, +) -> tuple[torch.Tensor, torch.Tensor]: + """Gather the next plan-relative actions at each tactile decision. + + The first index uses the same float-tolerant ceil rule as + ``build_future_action_mask``. Windows near the plan end are zero padded and + accompanied by a validity mask. + """ + + _validate_shape(action, (None, None, None), "action") + if decision_seconds.shape != (len(action),): + raise ValueError("decision_seconds must be [B]") + if steps < 1 or not math.isfinite(action_hz) or action_hz <= 0: + raise ValueError("steps and action_hz must be positive") + seconds = decision_seconds.to(device=action.device, dtype=torch.float64) + if not torch.isfinite(seconds).all() or (seconds < 0).any(): + raise ValueError("decision_seconds must be finite and non-negative") + tolerance = 1e-6 if decision_seconds.dtype != torch.float64 else 1e-9 + start = torch.ceil(seconds * action_hz - tolerance).long() + offsets = torch.arange(steps, device=action.device)[None] + indices = start[:, None] + offsets + valid = indices < action.shape[1] + safe = indices.clamp(max=max(action.shape[1] - 1, 0)) + batch = torch.arange(len(action), device=action.device)[:, None] + window = action[batch, safe] + return window * valid[..., None].to(window.dtype), valid + + +class TactileTargetCodec(nn.Module): + """Frozen deterministic analogue of the RGB DC-AE target encoder. + + It canonicalises the left sensor, removes train-split means, and scales each + valid taxel by train-split standard deviation. There are deliberately no + trainable parameters, so the future target cannot collapse with the online + tactile encoder. + """ + + def __init__( + self, + pressure_masks: torch.Tensor, + reference_pressure: torch.Tensor, + pressure_scale: torch.Tensor, + ) -> None: + super().__init__() + if tuple(pressure_masks.shape) != (2, 21, 21): + raise ValueError("pressure_masks must be [2,21,21]") + if tuple(reference_pressure.shape) == (1, 8, 2, 21, 21): + reference_pressure = reference_pressure[0, -1] + if tuple(reference_pressure.shape) != (2, 21, 21): + raise ValueError("reference_pressure must be [2,21,21] or [1,8,2,21,21]") + if tuple(pressure_scale.shape) != (2, 21, 21): + raise ValueError("pressure_scale must be [2,21,21]") + # Statistics are stored in the dataset's raw sensor coordinates. The + # codec target is canonical, so transform its statistics identically. + reference_pressure = reference_pressure.float().clone() + pressure_scale = pressure_scale.float().clone() + reference_pressure[0] = reference_pressure[0].flip(-1) + pressure_scale[0] = pressure_scale[0].flip(-1) + self.register_buffer("pressure_masks", pressure_masks.bool(), persistent=True) + self.register_buffer("reference_pressure", reference_pressure, persistent=True) + self.register_buffer( + "pressure_scale", pressure_scale.clamp_min(1e-3), persistent=True + ) + + def encode( + self, pressure: torch.Tensor, hand_valid: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + _validate_shape(pressure, (None, 2, 21, 21), "future_pressure") + if hand_valid.shape != (len(pressure), 2): + raise ValueError("future_hand_valid must be [B,2]") + value = torch.nan_to_num(pressure.float()).clone() + value[:, 0] = value[:, 0].flip(-1) + spatial = hand_valid.bool()[..., None, None] & self.pressure_masks[None] + normalized = (value - self.reference_pressure) / self.pressure_scale + normalized = normalized * spatial.to(normalized.dtype) + return normalized.flatten(2), spatial.flatten(2) + + def decode(self, tokens: torch.Tensor) -> torch.Tensor: + _validate_shape(tokens, (None, 2, 441), "tactile_tokens") + value = ( + tokens.reshape(-1, 2, 21, 21) * self.pressure_scale + + self.reference_pressure + ) + value = value.clone() + value[:, 0] = value[:, 0].flip(-1) + return value + + +class MemoryConditionedActionBasis(nn.Module): + """Create residual bases from the frozen plan and explicit Method-D memory.""" + + def __init__( + self, + action_mean: torch.Tensor, + action_std: torch.Tensor, + *, + memory_dim: int = 960, + hidden_dim: int = 256, + residual_bases: int = 8, + num_layers: int = 2, + dropout: float = 0.1, + ) -> None: + super().__init__() + if tuple(action_mean.shape) != (192,) or tuple(action_std.shape) != (192,): + raise ValueError("action statistics must be [192]") + self.residual_bases = residual_bases + self.register_buffer("action_mean", action_mean.float(), persistent=True) + self.register_buffer( + "action_std", action_std.float().clamp_min(1e-3), persistent=True + ) + self.memory_norm = nn.RMSNorm(memory_dim) + self.memory_projection = nn.Linear(memory_dim, hidden_dim, bias=False) + self.action_projection = nn.Linear(192, hidden_dim) + self.memory_type = nn.Parameter(torch.zeros(1, 1, hidden_dim)) + self.action_type = nn.Parameter(torch.zeros(1, 1, hidden_dim)) + self.action_position = nn.Parameter(torch.randn(1, 16, hidden_dim) * 0.02) + self.elapsed_projection = nn.Linear(1, hidden_dim) + layer = nn.TransformerEncoderLayer( + hidden_dim, + nhead=8, + dim_feedforward=hidden_dim * 4, + dropout=dropout, + activation="gelu", + batch_first=True, + norm_first=True, + ) + self.blocks = nn.TransformerEncoder( + layer, num_layers=num_layers, enable_nested_tensor=False + ) + self.output = nn.Linear(hidden_dim, residual_bases * 192) + nn.init.zeros_(self.output.weight) + nn.init.zeros_(self.output.bias) + + def forward( + self, + base_action: torch.Tensor, + final_memory: torch.Tensor, + decision_seconds: torch.Tensor, + ) -> torch.Tensor: + _validate_shape(base_action, (None, 16, 192), "base_action") + _validate_shape(final_memory, (len(base_action), 8, None), "final_memory") + if decision_seconds.shape != (len(base_action),): + raise ValueError("decision_seconds must be [B]") + dtype = self.action_projection.weight.dtype + action = ( + base_action.detach().to(dtype) - self.action_mean.to(dtype) + ) / self.action_std.to(dtype) + action = ( + self.action_projection(action) + self.action_type + self.action_position + ) + action = action + self.elapsed_projection( + decision_seconds.to(dtype=dtype)[:, None, None] * 10.0 + ) + memory = self.memory_projection( + self.memory_norm(final_memory.detach().to(dtype)) + ) + memory = memory + self.memory_type + hidden = self.blocks(torch.cat((memory, action), dim=1))[:, memory.shape[1] :] + bases = self.output(hidden).reshape(len(action), 16, self.residual_bases, 192) + return bases.permute(0, 2, 1, 3) + + +class TactileWorldConditionAdapter(nn.Module): + """Map memory, shared tactile features, and an optional action window to WM tokens.""" + + def __init__( + self, + *, + memory_dim: int = 960, + tactile_dim: int = 128, + hidden_dim: int = 256, + action_tokens: int = 8, + ) -> None: + super().__init__() + self.action_tokens = action_tokens + self.memory_norm = nn.RMSNorm(memory_dim) + self.tactile_norm = nn.RMSNorm(tactile_dim) + self.memory_projection = nn.Linear(memory_dim, hidden_dim, bias=False) + self.tactile_projection = nn.Linear(tactile_dim, hidden_dim, bias=False) + self.action_projection = ( + nn.Linear(192, hidden_dim, bias=False) if action_tokens else None + ) + self.memory_type = nn.Parameter(torch.zeros(1, 1, hidden_dim)) + self.tactile_type = nn.Parameter(torch.zeros(1, 2, hidden_dim)) + self.action_type = nn.Parameter(torch.zeros(1, 1, hidden_dim)) + self.action_position = ( + nn.Parameter(torch.randn(1, action_tokens, hidden_dim) * 0.02) + if action_tokens + else None + ) + + def forward( + self, + final_memory: torch.Tensor, + tactile_features: torch.Tensor, + hand_valid: torch.Tensor, + action_window: torch.Tensor | None, + action_valid: torch.Tensor | None, + ) -> tuple[torch.Tensor, torch.Tensor]: + _validate_shape(final_memory, (None, 8, None), "final_memory") + _validate_shape( + tactile_features, (len(final_memory), 2, None), "tactile_features" + ) + if hand_valid.shape != (len(final_memory), 2): + raise ValueError("hand_valid must be [B,2]") + dtype = self.memory_projection.weight.dtype + memory = self.memory_projection( + self.memory_norm(final_memory.detach().to(dtype)) + ) + memory = memory + self.memory_type + tactile = self.tactile_projection(self.tactile_norm(tactile_features.to(dtype))) + tactile = (tactile + self.tactile_type) * hand_valid[..., None].to(dtype) + tokens = [memory, tactile] + padding = [ + torch.zeros( + len(memory), memory.shape[1], dtype=torch.bool, device=memory.device + ), + ~hand_valid.bool(), + ] + if self.action_projection is not None: + if action_window is None or action_valid is None: + raise ValueError("the configured world model requires an action window") + _validate_shape( + action_window, (len(memory), self.action_tokens, 192), "action_window" + ) + if action_valid.shape != (len(memory), self.action_tokens): + raise ValueError("action_valid has the wrong shape") + action = self.action_projection(action_window.detach().to(dtype)) + action = action + self.action_type + self.action_position + action = action * action_valid[..., None].to(dtype) + tokens.append(action) + padding.append(~action_valid.bool()) + return torch.cat(tokens, dim=1), torch.cat(padding, dim=1) + + +class TactileWorldModel(nn.Module): + """Four-block rectified-flow model for a future two-hand pressure state.""" + + def __init__( + self, + *, + memory_dim: int = 960, + tactile_dim: int = 128, + hidden_dim: int = 256, + num_layers: int = 4, + action_tokens: int = 8, + dropout: float = 0.1, + cells: int = 441, + ) -> None: + super().__init__() + if num_layers != 4: + raise ValueError( + "the Kai-aligned primary setup uses exactly four world blocks" + ) + self.adapter = TactileWorldConditionAdapter( + memory_dim=memory_dim, + tactile_dim=tactile_dim, + hidden_dim=hidden_dim, + action_tokens=action_tokens, + ) + if cells < 1: + raise ValueError("cells must be positive") + self.cells = int(cells) + self.target_projection = nn.Linear(self.cells, hidden_dim) + self.target_side = nn.Parameter(torch.randn(1, 2, hidden_dim) * 0.02) + self.time_mlp = nn.Sequential( + nn.Linear(hidden_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, hidden_dim), + ) + layer = nn.TransformerDecoderLayer( + hidden_dim, + nhead=8, + dim_feedforward=hidden_dim * 4, + dropout=dropout, + activation="gelu", + batch_first=True, + norm_first=True, + ) + self.blocks = nn.TransformerDecoder(layer, num_layers=num_layers) + self.norm_out = nn.RMSNorm(hidden_dim) + self.output = nn.Linear(hidden_dim, self.cells) + nn.init.zeros_(self.output.weight) + nn.init.zeros_(self.output.bias) + + @staticmethod + def _time_embedding(tau: torch.Tensor, dim: int) -> torch.Tensor: + half = dim // 2 + frequencies = torch.exp( + torch.linspace(math.log(0.25), math.log(250.0), half, device=tau.device) + ) + angles = tau.float()[:, None] * frequencies[None] * 2 * math.pi + value = torch.cat((angles.sin(), angles.cos()), dim=-1) + return value[:, :dim] + + def velocity( + self, + noisy_future: torch.Tensor, + tau: torch.Tensor, + *, + final_memory: torch.Tensor, + tactile_features: torch.Tensor, + hand_valid: torch.Tensor, + action_window: torch.Tensor | None, + action_valid: torch.Tensor | None, + ) -> torch.Tensor: + _validate_shape(noisy_future, (None, 2, self.cells), "noisy_future") + if tau.shape != (len(noisy_future),): + raise ValueError("tau must be [B]") + condition, condition_padding = self.adapter( + final_memory, + tactile_features, + hand_valid, + action_window, + action_valid, + ) + dtype = self.target_projection.weight.dtype + time = self.time_mlp(self._time_embedding(tau, condition.shape[-1]).to(dtype)) + target = ( + self.target_projection(noisy_future.to(dtype)) + + self.target_side + + time[:, None] + ) + hidden = self.blocks( + tgt=target, + memory=condition, + memory_key_padding_mask=condition_padding, + ) + return self.output(self.norm_out(hidden)) + + +def tactile_flow_pair( + clean: torch.Tensor, + valid: torch.Tensor, + tau: torch.Tensor, + noise: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor]: + """Kai/Method-D convention: tau=0 is data and tau=1 is noise.""" + + if clean.shape != noise.shape or valid.shape != clean.shape: + raise ValueError("clean, noise, and valid must have matching [B,2,441] shapes") + if tau.shape != (len(clean),): + raise ValueError("tau must be [B]") + weight = valid.to(clean.dtype) + clean = clean * weight + noise = noise * weight + t = tau.to(clean.dtype)[:, None, None] + return ((1.0 - t) * clean + t * noise) * weight, (noise - clean) * weight + + +def masked_tactile_flow_loss( + prediction: torch.Tensor, target: torch.Tensor, valid: torch.Tensor +) -> torch.Tensor: + if prediction.shape != target.shape or valid.shape != prediction.shape: + raise ValueError("world tensors must have matching shapes") + squared = (prediction.float() - target.float()).square().masked_fill(~valid, 0) + return squared.sum() / valid.sum().clamp_min(1) + + +@dataclass +class SingleStageWorldOutput: + final_action: torch.Tensor + delta_action: torch.Tensor + coefficients: torch.Tensor + tactile_features: torch.Tensor + tactile_history_features: torch.Tensor + hand_valid: torch.Tensor + allowed_mask: torch.Tensor + world_velocity: torch.Tensor | None + world_target: torch.Tensor | None + world_valid: torch.Tensor | None + + +class SingleStageWorldTactileEditor(nn.Module): + """Joint single-stage editor and future-tactile world model.""" + + def __init__( + self, + *, + action_mean: torch.Tensor, + action_std: torch.Tensor, + pressure_masks: torch.Tensor, + reference_pressure: torch.Tensor, + pressure_scale: torch.Tensor, + tactile_mode: str = "history_delta", + residual_bases: int = 8, + memory_dim: int = 960, + hidden_dim: int = 256, + condition_on_action: bool = True, + articulation_only: bool = False, + ) -> None: + super().__init__() + self.tactile = DirectTactileTrunk( + pressure_masks, + reference_pressure, + mode=tactile_mode, + residual_bases=residual_bases, + ) + self.action = MemoryConditionedActionBasis( + action_mean, + action_std, + memory_dim=memory_dim, + hidden_dim=hidden_dim, + residual_bases=residual_bases, + ) + self.world = TactileWorldModel( + memory_dim=memory_dim, + tactile_dim=128, + hidden_dim=hidden_dim, + action_tokens=8 if condition_on_action else 0, + ) + self.target_codec = TactileTargetCodec( + pressure_masks, reference_pressure, pressure_scale + ) + component_mask = torch.zeros(1, 1, 192, dtype=torch.bool) + groups = ARTICULATION_GROUPS if articulation_only else FULL_ACTION_GROUPS + for start, stop in groups: + component_mask[..., start:stop] = True + self.register_buffer("component_mask", component_mask, persistent=True) + self.residual_bases = residual_bases + self.condition_on_action = condition_on_action + self.articulation_only = articulation_only + + def forward( + self, + *, + base_action: torch.Tensor, + edit_mask: torch.Tensor, + pressure: torch.Tensor, + temporal_valid: torch.Tensor, + decision_seconds: torch.Tensor, + final_memory: torch.Tensor, + future_pressure: torch.Tensor | None = None, + future_valid: torch.Tensor | None = None, + tau: torch.Tensor | None = None, + noise: torch.Tensor | None = None, + ) -> SingleStageWorldOutput: + coefficients, hand_valid, tactile_features, tactile_history = self.tactile( + pressure, temporal_valid + ) + bases = self.action(base_action, final_memory, decision_seconds) + raw_delta = (coefficients[:, :, None, None] * bases).sum(1) / math.sqrt( + self.residual_bases + ) + allowed = edit_mask.bool() & self.component_mask + allowed = allowed.clone() + allowed[..., :69] &= hand_valid[:, 0, None, None] + allowed[..., 69:138] &= hand_valid[:, 1, None, None] + delta = raw_delta * allowed.to(raw_delta.dtype) + final_action = base_action.detach() + delta + + world_velocity = world_target = world_valid = None + supplied = [ + future_pressure is not None, + future_valid is not None, + tau is not None, + ] + if any(supplied) and not all(supplied): + raise ValueError( + "future_pressure, future_valid, and tau must be supplied together" + ) + if all(supplied): + assert ( + future_pressure is not None + and future_valid is not None + and tau is not None + ) + clean, world_valid = self.target_codec.encode(future_pressure, future_valid) + if noise is None: + noise = torch.randn_like(clean) + noisy, world_target = tactile_flow_pair(clean, world_valid, tau, noise) + if self.condition_on_action: + action_window, action_valid = gather_action_window( + final_action.detach(), decision_seconds, steps=8 + ) + else: + action_window = action_valid = None + world_velocity = self.world.velocity( + noisy, + tau, + final_memory=final_memory.detach(), + tactile_features=tactile_features, + hand_valid=hand_valid, + action_window=action_window, + action_valid=action_valid, + ) + return SingleStageWorldOutput( + final_action=final_action, + delta_action=delta, + coefficients=coefficients, + tactile_features=tactile_features, + tactile_history_features=tactile_history, + hand_valid=hand_valid, + allowed_mask=allowed, + world_velocity=world_velocity, + world_target=world_target, + world_valid=world_valid, + ) + + def objective( + self, + output: SingleStageWorldOutput, + target_action: torch.Tensor, + edit_mask: torch.Tensor, + *, + lambda_world: float, + lambda_delta: float = 1e-4, + lambda_coefficient: float = 1e-5, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + if lambda_world < 0 or lambda_delta < 0 or lambda_coefficient < 0: + raise ValueError("loss weights must be non-negative") + # Use the exact mask that produced the residual. In particular, do not + # charge an irreducible action loss for a hand whose latest touch frame + # is absent: that loss has no gradient but corrupts model selection. + mask = edit_mask.bool() & output.allowed_mask + present = mask.any((1, 2)) + if not present.any(): + raise ValueError("the batch contains no tactile-editable action target") + action_loss = per_sample_action_loss( + output.final_action[present], + target_action[present], + mask[present], + groups=(ARTICULATION_GROUPS if self.articulation_only else FULL_ACTION_GROUPS), + ).mean() + delta_l2 = output.delta_action.float().square().masked_fill(~mask, 0).sum() + delta_l2 = delta_l2 / mask.sum().clamp_min(1) + coefficient_l2 = output.coefficients.float().square().mean() + if output.world_velocity is None: + if lambda_world: + raise ValueError( + "world supervision is missing while lambda_world is nonzero" + ) + world_loss = action_loss.new_zeros(()) + else: + assert output.world_target is not None and output.world_valid is not None + world_loss = masked_tactile_flow_loss( + output.world_velocity, output.world_target, output.world_valid + ) + total = ( + action_loss + + lambda_world * world_loss + + lambda_delta * delta_l2 + + lambda_coefficient * coefficient_l2 + ) + return total, { + "loss": total.detach(), + "action_loss": action_loss.detach(), + "world_loss": world_loss.detach(), + "delta_l2": delta_l2.detach(), + "coefficient_l2": coefficient_l2.detach(), + } + + def optimizer_groups( + self, + *, + action_head_lr: float = 1e-4, + tactile_gru_lr: float = 1e-5, + tactile_cnn_lr: float = 3e-6, + world_adapter_lr: float = 1e-4, + world_block_lr: float = 1e-5, + ) -> list[dict]: + """Kai-style parameter groups with no frozen-VLA parameters.""" + + tactile_head = list(self.tactile.coefficient_head.parameters()) + tactile_gru = ( + list(self.tactile.temporal.parameters()) if self.tactile.temporal else [] + ) + groups = [ + { + "name": "action", + "params": list(self.action.parameters()) + tactile_head, + "lr": action_head_lr, + }, + { + "name": "tactile.cnn", + "params": list(self.tactile.frame_encoder.parameters()), + "lr": tactile_cnn_lr, + }, + { + "name": "world.adapter", + "params": list(self.world.adapter.parameters()), + "lr": world_adapter_lr, + }, + { + "name": "world.blocks", + "params": [ + *self.world.target_projection.parameters(), + self.world.target_side, + *self.world.time_mlp.parameters(), + *self.world.blocks.parameters(), + *self.world.norm_out.parameters(), + *self.world.output.parameters(), + ], + "lr": world_block_lr, + }, + ] + if tactile_gru: + groups.insert( + 2, {"name": "tactile.gru", "params": tactile_gru, "lr": tactile_gru_lr} + ) + parameters = [parameter for group in groups for parameter in group["params"]] + if len(parameters) != len({id(parameter) for parameter in parameters}): + raise RuntimeError("a parameter occurs in more than one optimizer group") + expected = { + id(parameter) for parameter in self.parameters() if parameter.requires_grad + } + if {id(parameter) for parameter in parameters} != expected: + raise RuntimeError( + "optimizer groups do not cover every trainable parameter" + ) + return groups + + +def ramp_world_weight(step: int, maximum: float, warmup_steps: int) -> float: + if step < 0 or maximum < 0 or warmup_steps < 0: + raise ValueError("step and world-weight settings must be non-negative") + if warmup_steps == 0: + return float(maximum) + return float(maximum) * min(1.0, step / warmup_steps) diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/smoke.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/smoke.py new file mode 100644 index 0000000000000000000000000000000000000000..73c0ae31dd40b92dd524454f75d50510b31e8a74 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/smoke.py @@ -0,0 +1,109 @@ +"""Operate all four variants without a Method D checkpoint.""" + +from __future__ import annotations + +import argparse +import gc +import json +from pathlib import Path + +import torch + +from .config import EditorConfig, FusionConfig, Variant +from .encoder import DualHandTactileEncoder, load_huggingface_encoder +from .mock import MockSelectedEncoder, TinyMethodD, build_structural_method_d +from .model import TactileMethodD, component_report +from .trainability import configure_trainable_components + + +def operate_smoke( + *, + encoder_source: str, + cache_dir: Path | None, + shape: str = "tiny", + device: str = "cpu", +) -> dict[str, object]: + torch.manual_seed(7) + selected = ( + load_huggingface_encoder(cache_dir=cache_dir, device=device) + if encoder_source == "hf" + else MockSelectedEncoder() + ) + selected = selected.to(device) + results: dict[str, object] = {} + for variant in Variant: + torch.manual_seed(11) + production_shape = shape == "v4d" + base = build_structural_method_d() if production_shape else TinyMethodD() + frontend = None + if variant != Variant.V0_BASE: + frontend = DualHandTactileEncoder(selected, freeze=True) + fusion = ( + FusionConfig() + if production_shape + else FusionConfig( + hidden_dim=64, + action_dim=12, + chunk_size=4, + num_heads=4, + injection_layers=(0, 1), + posthoc_hidden_dim=64, + posthoc_heads=4, + posthoc_layers=1, + ) + ) + config = EditorConfig(variant=variant, fusion=fusion) + model = TactileMethodD(base, config, frontend).to(device) + configure_trainable_components(model) + batch = 1 if production_shape else 2 + slots = 8 if production_shape else 3 + memory_dim = 960 if production_shape else 32 + memory = torch.randn(batch, slots, memory_dim, device=device) + action_mask = torch.ones( + batch, fusion.chunk_size, fusion.action_dim, dtype=torch.bool, device=device + ) + pressure = torch.randn(batch, 8, 2, 21, 21, device=device) + output = model.sample_from_memory( + memory, + action_mask, + touch_pressure=pressure if frontend is not None else None, + noise=torch.randn( + batch, fusion.chunk_size, fusion.action_dim, device=device + ), + num_steps=1 if production_shape else 2, + return_normalized=True, + ) + results[variant.value] = { + "output_shape": list(output.shape), + "finite": bool(torch.isfinite(output).all()), + "components": component_report(model), + } + del model, base, frontend, memory, action_mask, pressure, output + gc.collect() + if device.startswith("cuda"): + torch.cuda.empty_cache() + return results + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--encoder", choices=("mock", "hf"), default="mock") + parser.add_argument("--cache-dir", type=Path) + parser.add_argument("--shape", choices=("tiny", "v4d"), default="tiny") + parser.add_argument("--device", default="cpu") + args = parser.parse_args() + print( + json.dumps( + operate_smoke( + encoder_source=args.encoder, + cache_dir=args.cache_dir, + shape=args.shape, + device=args.device, + ), + indent=2, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/table1_editor_cache.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/table1_editor_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..cf86aa9109dfc61ecb13f28f73b846f51cf1cf19 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/table1_editor_cache.py @@ -0,0 +1,101 @@ +"""Strict reader for the memory-free Table-1 tactile editor cache.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import Dataset + + +ARRAYS = ( + "base_action", + "target_action", + "action_mask", + "touch_pressure", + "touch_valid", + "decision_seconds", + "recording", +) +EXPECTED_COUNTS = {"train": 415_624, "val": 23_571, "test": 23_950} + + +class Table1EditorCache(Dataset): + """Read a model-specific, canonical, memory-free editor cache. + + The cache is intentionally separate from the T-WLA cache. Each split is a + directory containing arrays and a metadata.json with canonical manifest and + checkpoint provenance. + """ + + def __init__(self, root: str | Path, split: str, *, model: str): + self.root = Path(root) + self.split = split + self.model = model + if split not in EXPECTED_COUNTS: + raise ValueError(f"unknown split: {split}") + split_root = self.root / split + metadata_path = split_root / "metadata.json" + if not metadata_path.is_file(): + raise FileNotFoundError( + f"missing Table-1 editor cache metadata: {metadata_path}; " + "refusing to use a legacy or T-WLA cache" + ) + self.metadata = json.loads(metadata_path.read_text()) + if self.metadata.get("cache_kind") != "table1_memory_free_editor": + raise ValueError(f"wrong cache kind at {split_root}") + if self.metadata.get("model") != model: + raise ValueError("cache model provenance does not match requested model") + if self.metadata.get("canonical_manifest") != "runs/table1_cache_relaxed_v1/manifests/canonical_table1_bundle.json": + raise ValueError("cache is not tied to the frozen canonical Table-1 bundle") + if self.metadata.get("history_frames") != 8: + raise ValueError("Table-1 editor requires exactly 8 causal history frames") + if self.metadata.get("decision_time_schema") != 2 or self.metadata.get("decision_seconds_reference") != "plan_start": + raise ValueError("Legacy/ambiguous decision times: repair the cache before training") + if self.metadata.get("decision_ticks") != [0]: + raise ValueError("This anchor-only cache requires decision_ticks=[0]") + self.count = int(self.metadata.get("count", -1)) + if self.count != EXPECTED_COUNTS[split]: + raise ValueError(f"{split} count {self.count} != {EXPECTED_COUNTS[split]}") + self.arrays = {} + for name in ARRAYS: + path = split_root / f"{name}.npy" + if not path.is_file(): + raise FileNotFoundError(f"missing {path}") + self.arrays[name] = np.load(path, mmap_mode="r") + if len(self.arrays[name]) != self.count: + raise ValueError(f"{path} length does not match metadata count") + if self.arrays["base_action"].shape[1:] != (16, 192): + raise ValueError("base_action must have shape [N,16,192]") + if self.arrays["target_action"].shape != self.arrays["base_action"].shape: + raise ValueError("target_action shape mismatch") + if self.arrays["action_mask"].shape != self.arrays["base_action"].shape: + raise ValueError("action_mask shape mismatch") + if self.arrays["touch_pressure"].shape[1:] != (8, 2, 21, 21): + raise ValueError("touch_pressure must be [N,8,2,21,21]") + if self.arrays["touch_valid"].shape[1:] != (8, 2): + raise ValueError("touch_valid must be [N,8,2]") + + decision = self.arrays["decision_seconds"] + if decision.shape != (self.count,) or not np.isfinite(decision).all() or np.any(decision != 0): + raise ValueError("Anchor-only cache decision_seconds must be finite and exactly zero") + + def __len__(self) -> int: + return self.count + + def __getitem__(self, index: int) -> dict[str, torch.Tensor]: + if index < 0: + index += self.count + if not 0 <= index < self.count: + raise IndexError(index) + result = {} + for name, array in self.arrays.items(): + value = np.array(array[index], copy=True) + if value.dtype.kind in "OUS": + result[name] = str(value) + else: + result[name] = torch.from_numpy(value) + result["index"] = torch.tensor(index, dtype=torch.long) + return result diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/table1_experiment.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/table1_experiment.py new file mode 100644 index 0000000000000000000000000000000000000000..25972cdc98a2195488c52f2e6cae73df6056b9f9 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/table1_experiment.py @@ -0,0 +1,286 @@ +"""Shared-editor experiment protocol, training cache validation, and physical scoring.""" +from __future__ import annotations + +import hashlib +import json +from dataclasses import asdict, dataclass + +import numpy as np +import torch +from scipy.spatial.transform import Rotation + +from .action_layout import ActionNormalizer, FULL_ACTION_GROUPS +from .direct_residual import DirectTactileResidualEditor +from .editor_backends import MemoryFreeTactileEditor, TactileEditorRouter + +MODELS = ("smolvla", "vitra", "twla") +OPTIONAL_MODELS = ("memoryvla",) + + +def cache_models(cache): + return tuple(name for name in (*MODELS, *OPTIONAL_MODELS) if name in cache["base_actions"]) + +METRICS = ("translation_cm", "rotation_deg", "joint_mpjpe_cm") + + +@dataclass(frozen=True) +class SharedEditorProtocol: + dataset: str + seed: int = 0 + batch_size: int = 64 + max_steps: int = 10000 + val_every: int = 250 + learning_rate: float = 1e-4 + primary_horizon: int = 8 + residual_bases: int = 8 + mode: str = "history_delta" + + def __post_init__(self): + if self.dataset not in ("egotouch", "tachin"): + raise ValueError("dataset must be egotouch or tachin") + if self.primary_horizon not in (8, 16): + raise ValueError("primary_horizon must be 8 or 16") + if min(self.batch_size, self.max_steps, self.val_every, self.residual_bases, self.learning_rate) <= 0: + raise ValueError("training budget and learning rate must be positive") + + def identity(self): + return hashlib.sha256(json.dumps(asdict(self), sort_keys=True).encode()).hexdigest() + + +def paired_noise(sample_ids, seed, *, device="cpu"): + """Stable noise independent of model, source ordering, and batch composition.""" + samples = [] + for key in sample_ids: + number = int.from_bytes(hashlib.sha256(f"{seed}:{key}".encode()).digest()[:8], "little") % (2**63) + samples.append(torch.randn(16, 192, generator=torch.Generator().manual_seed(number))) + return torch.stack(samples).to(device) + + +def validate_cache(cache): + """Reject data leakage, missing predictions, and unknown sensor conventions.""" + if cache.get("schema") != "table1.shared.v1": + raise ValueError("unsupported cache schema") + ids = cache["sample_id"] + n = len(ids) + if not n or len(set(ids)) != n: + raise ValueError("sample_id must be nonempty and unique") + shapes = {"target_action": (n, 16, 192), "action_mask": (n, 16, 192), + "pressure": (n, 8, 2, 21, 21), "temporal_valid": (n, 8, 2), + "pressure_seconds": (n, 8), "anchor_seconds": (n,), + "pressure_masks": (2, 21, 21)} + for key, shape in shapes.items(): + value = cache[key] + if not isinstance(value, torch.Tensor) or tuple(value.shape) != shape: + raise ValueError(f"{key} must be a tensor of shape {shape}") + if not torch.isfinite(value).all(): + raise ValueError(f"{key} contains non-finite values") + for key in ("action_mask", "temporal_valid", "pressure_masks"): + if cache[key].dtype != torch.bool: + raise ValueError(f"{key} must be boolean") + if cache["action_mask"][..., 138:].any(): + raise ValueError("padding cannot be valid") + if not cache["action_mask"].flatten(1).any(1).all(): + raise ValueError("every sample must contain a valid action target") + for start in (0, 69): + m = cache["action_mask"][..., start:start + 69] + if (m.any(-1) != m.all(-1)).any(): + raise ValueError("a hand must have a complete channel mask") + live = m.all(-1) + if (live[:, 1:] & ~live[:, :-1]).any(): + raise ValueError("valid action steps must form a prefix") + valid_touch = cache["temporal_valid"].any(-1) + if ((cache["pressure_seconds"] > cache["anchor_seconds"][:, None] + 1e-7) & valid_touch).any(): + raise ValueError("future tactile input leaks into the editor") + if (cache["pressure_seconds"][:, 1:] < cache["pressure_seconds"][:, :-1]).any(): + raise ValueError("tactile history must be ordered by time") + if cache["pressure_convention"] not in ("egotouch_raw", "canonical_right"): + raise ValueError("declare egotouch_raw or canonical_right pressure convention") + if cache["dataset"] == "tachin" and cache["pressure_convention"] != "canonical_right": + raise ValueError("Tachin requires a documented mapping to canonical_right grids") + if not cache.get("pressure_mapping_id"): + raise ValueError("pressure_mapping_id must identify the sensor preprocessing") + for key in ("sequence_id", "environment", "split"): + if len(cache[key]) != n: + raise ValueError(f"{key} must have one entry per sample") + if set(cache["split"]) != {"train", "val", "test"}: + raise ValueError("cache must contain train, val, and test") + seen = {} + for seq, split, env in zip(cache["sequence_id"], cache["split"], cache["environment"]): + if seq in seen and seen[seq] != (split, env): + raise ValueError("sequence crosses splits or environments") + seen[seq] = (split, env) + names = set(cache["base_actions"]) + if not set(MODELS).issubset(names) or names - set((*MODELS, *OPTIONAL_MODELS)): + raise ValueError("shared comparison requires predictions for all three models") + for model_id, action in cache["base_actions"].items(): + if tuple(action.shape) != (n, 16, 192) or not torch.isfinite(action).all(): + raise ValueError(f"invalid {model_id} physical keypoint predictions") + if not cache.get("provenance", {}).get(model_id): + raise ValueError(f"missing checkpoint provenance for {model_id}") + if cache["provenance"][model_id].get("human_action_trained") is False: + raise ValueError("untrained human action heads are smoke-only, not Table 1 predictions") + return cache + + +def cache_identity(cache): + """Hash data, splits, and prediction sources for checkpoint/evaluation matching.""" + h = hashlib.sha256() + for key in ("dataset", "sample_id", "sequence_id", "environment", "split", + "pressure_convention", "pressure_mapping_id", "provenance"): + h.update(json.dumps(cache[key], sort_keys=True).encode()) + for key in ("target_action", "action_mask", "pressure", "temporal_valid", + "pressure_seconds", "anchor_seconds", "pressure_masks"): + a = cache[key].detach().cpu().contiguous() + h.update(str(a.dtype).encode()); h.update(a.numpy().tobytes()) + for name in cache_models(cache): + h.update(cache["base_actions"][name].detach().cpu().float().contiguous().numpy().tobytes()) + return h.hexdigest() + + +def fit_normalizer(cache): + """One normalizer from training targets, never model predictions or held-out data.""" + train = torch.tensor([s == "train" for s in cache["split"]]) + x = cache["target_action"][train].float() + m = cache["action_mask"][train].bool() + count = m.sum((0, 1)) + mean = (x * m).sum((0, 1)) / count.clamp_min(1) + var = ((x - mean).square() * m).sum((0, 1)) / count.clamp_min(1) + std = var.sqrt() + std = torch.where(std > 1e-6, std, torch.ones_like(std)) + digest = hashlib.sha256(mean.numpy().tobytes() + std.numpy().tobytes()).hexdigest() + return ActionNormalizer(mean, std, "train-keypoints:" + digest) + + +def build_shared_editor(protocol, pressure_masks, pressure_convention): + # Inputs and targets are already normalized. Do not normalize a second time. + with torch.random.fork_rng(devices=[]): + torch.manual_seed(protocol.seed) + editor = DirectTactileResidualEditor( + torch.zeros(192), torch.ones(192), pressure_masks.cpu(), torch.zeros(1, 8, 2, 21, 21), + mode=protocol.mode, residual_bases=protocol.residual_bases, + articulation_only=False, flip_left=pressure_convention == "egotouch_raw") + return TactileEditorRouter(None, MemoryFreeTactileEditor(editor), route="shared") + + +def grouped_action_loss(pred, target, mask): + """Equal group weight, reduced over valid hand-steps. Padding contributes nothing.""" + total, count = pred.sum() * 0, 0 + for start, stop in FULL_ACTION_GROUPS: + live = mask[..., start:stop].all(-1) + square = (pred[..., start:stop] - target[..., start:stop]).square().mean(-1) + total = total + square[live].sum() + count = count + live.sum() + if int(count) == 0: + raise ValueError("no valid action targets") + return total / count + + +def physical_window_errors(pred, target, mask, *, horizon): + """Accumulated wrist motion and palm-local joints 1..20, in cm/degrees. + + A strict horizon excludes each hand whose valid prefix is too short. + Joint 0 is a fixed origin and is not re-subtracted from predicted local joints. + """ + if horizon not in (8, 16): + raise ValueError("horizon must be 8 or 16") + p, t, m = [np.asarray(x) for x in (pred, target, mask)] + if p.ndim != 3 or p.shape[1:] != (16, 192) or t.shape != p.shape or m.shape != p.shape: + raise ValueError("actions and mask must be [N,16,192]") + n = len(p) + sums, counts = np.zeros((n, 3)), np.zeros(n) + for lo in (0, 69): + valid = m[:, :horizon, lo:lo + 69].all((1, 2)) + if not valid.any(): + continue + a, b = p[valid, :horizon, lo:lo + 69], t[valid, :horizon, lo:lo + 69] + if not np.isfinite(a).all() or not np.isfinite(b).all(): + raise ValueError("non-finite prediction or target on valid frames") + trans = np.linalg.norm(np.cumsum(a[..., :3] - b[..., :3], axis=1), axis=-1) * 100 + rp = Rotation.from_euler("xyz", a[..., 3:6].reshape(-1, 3)).as_matrix().reshape(-1, horizon, 3, 3) + rt = Rotation.from_euler("xyz", b[..., 3:6].reshape(-1, 3)).as_matrix().reshape(-1, horizon, 3, 3) + ap = np.broadcast_to(np.eye(3), (len(a), 3, 3)).copy(); at = ap.copy() + rotation = np.empty((len(a), horizon)) + for k in range(horizon): + ap, at = rp[:, k] @ ap, rt[:, k] @ at + cosine = ((np.trace(np.swapaxes(ap, -1, -2) @ at, axis1=-2, axis2=-1) - 1) / 2).clip(-1, 1) + rotation[:, k] = np.degrees(np.arccos(cosine)) + fingers = np.linalg.norm((a[..., 6:] - b[..., 6:]).reshape(-1, horizon, 21, 3)[:, :, 1:], axis=-1).mean(-1) * 100 + sums[valid] += np.stack((trans.sum(1), rotation.sum(1), fingers.sum(1)), axis=-1) + counts[valid] += horizon + return sums, counts + + +def summarize_physical(pred, target, mask, sequence_id, environment, *, horizon, dataset): + sums, counts = physical_window_errors(pred, target, mask, horizon=horizon) + seqs, envs = np.asarray(sequence_id), np.asarray(environment) + per_seq, by_env = {}, {} + for seq in sorted(set(seqs)): + rows = seqs == seq + if counts[rows].sum() == 0: + continue + group = set(envs[rows]) + if len(group) != 1: + raise ValueError("sequence belongs to multiple environments") + value = sums[rows].sum(0) / counts[rows].sum() + per_seq[str(seq)] = dict(zip(METRICS, value.tolist())) + by_env.setdefault(str(next(iter(group))), []).append(value) + if not per_seq: + raise ValueError("no sequences have the requested horizon") + means = {name: np.mean(values, axis=0) for name, values in by_env.items()} + # EgoTouch environments have equal weight. Tachin sequences have equal weight. + overall = np.mean(list(means.values()), axis=0) if dataset == "egotouch" else np.mean( + [list(v.values()) for v in per_seq.values()], axis=0) + return {"overall": dict(zip(METRICS, overall.tolist())), + "environments": {k: dict(zip(METRICS, v.tolist())) for k, v in means.items()}, + "sequences": per_seq, "valid_sequences": len(per_seq), + "valid_hand_frames": int(counts.sum()), "horizon": horizon, + "complete_egotouch_environments": len(means) == 5 if dataset == "egotouch" else None} + + +def summarize_seeds(reports): + """Mean and sample standard deviation for one model on an unchanged test cache.""" + if not reports: + raise ValueError("at least one seed report is required") + first = reports[0] + expected = {k: v for k, v in first["protocol"].items() if k != "seed"} + seeds = [] + for report in reports: + protocol = {k: v for k, v in report["protocol"].items() if k != "seed"} + if report["model_id"] != first["model_id"] or report["cache_id"] != first["cache_id"] or protocol != expected: + raise ValueError("seed reports must use one model, cache, and protocol") + seeds.append(report["protocol"]["seed"]) + if len(set(seeds)) != len(seeds): + raise ValueError("seed reports contain duplicate seeds") + output = {"model_id": first["model_id"], "seeds": seeds, "views": {}} + def statistics(values): + return {"mean": float(np.mean(values)), + "std": float(np.std(values, ddof=1)) if len(values) > 1 else None} + for view in ("8", "16"): + rows = {} + for mode in ("base", "editor", "improvement"): + rows[mode] = {} + for metric in METRICS: + values = [r["views"][view][mode][metric] if mode == "improvement" + else r["views"][view][mode]["overall"][metric] for r in reports] + rows[mode][metric] = statistics(values) + environments = set(first["views"][view]["base"]["environments"]) + if any(set(r["views"][view][m]["environments"]) != environments + for r in reports for m in ("base", "editor")): + raise ValueError("seed reports have different environment coverage") + rows["environments"] = {} + for env in sorted(environments): + cell = {} + for mode in ("base", "editor", "improvement"): + cell[mode] = {} + for metric in METRICS: + values = [] + for r in reports: + v = r["views"][view] + if mode == "improvement": + values.append(v["base"]["environments"][env][metric] - v["editor"]["environments"][env][metric]) + else: + values.append(v[mode]["environments"][env][metric]) + cell[mode][metric] = statistics(values) + rows["environments"][env] = cell + output["views"][view] = rows + return output diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/table1_protocol.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/table1_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..70c504eb16fd343d389f2562b66ba753d3207311 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/table1_protocol.py @@ -0,0 +1,60 @@ +"""Frozen protocol and validation helpers for the Table 1 experiments.""" +from __future__ import annotations + +from dataclasses import dataclass +import hashlib, json +from pathlib import Path +import torch + +from .action_layout import ACTION_DIM, CHUNK_SIZE, VALID_ACTION_DIM, FULL_ACTION_GROUPS + +SOURCE_FPS = 30.0 +CONTROL_HZ = 10.0 +ACTION_HZ = 80.0 +STRIDE_SOURCE_FRAMES = 3 +EXECUTED_PREFIX = 8 +CONTACT_THRESHOLD = 0.25 + +@dataclass(frozen=True) +class Table1ModelSpec: + model_id: str + checkpoint: str + native_output: str + canonical_output: str = "[B,16,192]" + uses_mano_fk: bool = False + +MODEL_SPECS = { + "vitra": Table1ModelSpec("vitra", "MIT-Media-Lab/vla-hand-baselines/vitra_original/best.pt", "angles", uses_mano_fk=True), + "smolvla": Table1ModelSpec("smolvla", "MIT-Media-Lab/vla-hand-baselines/smolvla_official/best.pt", "keypoints"), + "twla": Table1ModelSpec("twla", "table1-trained", "canonical"), +} + +def validate_action_contract(action: torch.Tensor, *, name: str = "action") -> None: + if action.ndim < 2 or tuple(action.shape[-2:]) != (CHUNK_SIZE, ACTION_DIM): + raise ValueError(f"{name} must end in [16,192], got {tuple(action.shape)}") + if not torch.is_floating_point(action) or not torch.isfinite(action).all(): + raise ValueError(f"{name} must be finite floating point") + +def validate_mask(mask: torch.Tensor, *, name: str = "action_mask") -> None: + validate_action_contract(mask, name=name) + if mask[..., VALID_ACTION_DIM:].any(): + raise ValueError(f"{name} marks padding dimensions as valid") + +def sha256(path: str | Path) -> str: + h = hashlib.sha256() + with Path(path).open("rb") as f: + for block in iter(lambda: f.read(1 << 20), b""): h.update(block) + return h.hexdigest() + +def protocol_metadata() -> dict: + return { + "source_fps": SOURCE_FPS, "control_hz": CONTROL_HZ, "action_hz": ACTION_HZ, + "stride_source_frames": STRIDE_SOURCE_FRAMES, "action_chunk": CHUNK_SIZE, + "executed_prefix": EXECUTED_PREFIX, "action_dim": ACTION_DIM, + "editable_groups": [list(x) for x in FULL_ACTION_GROUPS], + "contact_threshold": CONTACT_THRESHOLD, + } + +def write_protocol(path: str | Path, **extra) -> None: + value = {"schema_version": 1, **protocol_metadata(), **extra} + Path(path).write_text(json.dumps(value, indent=2) + "\n") diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/unified_world.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/unified_world.py new file mode 100644 index 0000000000000000000000000000000000000000..e4b4ca8834cfb60b69dbe495d444da923024e627 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/unified_world.py @@ -0,0 +1,487 @@ +"""One tactile editor with optional RGB and tactile world objectives. + +The action architecture is identical in W0--W3. Only the auxiliary world +losses change: + +* W0: action only; +* W1: action + frozen RGB-world critic; +* W2: action + future-tactile world model; +* W3: action + both world objectives. + +The Method-D VLA is never owned by this module. Its cached final memory and +normalised base action are immutable inputs. This makes the four experiments +cheap, reproducible, and compatible with the ten-domain 110k checkpoint. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum + +import torch +from torch import nn + +from .action_objectives import per_sample_action_loss +from .action_layout import ARTICULATION_GROUPS, FULL_ACTION_GROUPS, FULL_HAND_GROUPS +from .encoder import DualHandTactileEncoder +from .rgb_world_editor import ( + FrozenRGBWorldResidual, + RGBWorldResidualOutput, + roi_weighted_world_loss, +) +from .single_stage_world import ( + TactileTargetCodec, + TactileWorldModel, + gather_action_window, + masked_tactile_flow_loss, + tactile_flow_pair, +) + + +class WorldMode(str, Enum): + W0 = "w0" + W1_RGB = "w1_rgb" + W2_TACTILE = "w2_tactile" + W3_BOTH = "w3_both" + + @property + def uses_rgb(self) -> bool: + return self in {WorldMode.W1_RGB, WorldMode.W3_BOTH} + + @property + def uses_tactile(self) -> bool: + return self in {WorldMode.W2_TACTILE, WorldMode.W3_BOTH} + + +class CenteredTactileFeatures(nn.Module): + """Return two reference-centred tokens from one shared P1 encoder.""" + + def __init__( + self, + encoder: DualHandTactileEncoder, + reference_pressure: torch.Tensor, + ) -> None: + super().__init__() + if tuple(reference_pressure.shape) == (1, 8, 2, 21, 21): + reference_pressure = reference_pressure[0] + if tuple(reference_pressure.shape) != (8, 2, 21, 21): + raise ValueError("reference_pressure must be [8,2,21,21]") + self.encoder = encoder + self.register_buffer( + "reference_pressure", reference_pressure.float(), persistent=True + ) + + def forward( + self, pressure: torch.Tensor, temporal_valid: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + if pressure.ndim != 5 or tuple(pressure.shape[1:]) != (8, 2, 21, 21): + raise ValueError("pressure must be [B,8,2,21,21]") + if temporal_valid.shape != pressure.shape[:3]: + raise ValueError("temporal_valid must be [B,8,2]") + batch = len(pressure) + reference = self.reference_pressure[None].expand(batch, -1, -1, -1, -1) + reference_valid = torch.ones_like(temporal_valid, dtype=torch.bool) + # One call keeps the actual/reference paths numerically symmetric. + features = self.encoder( + torch.cat((pressure, reference.to(pressure.dtype)), dim=0), + torch.cat((temporal_valid.bool(), reference_valid), dim=0), + ) + actual, baseline = features.tokens.split(batch, dim=0) + hand_valid = features.valid[:batch] & temporal_valid[:, -1].bool() + centered = (actual - baseline) * hand_valid[..., None].to(actual.dtype) + return centered, hand_valid + + +class DirectMemoryActionEditor(nn.Module): + """Predict a direct per-hand delta from ``m_f + a_base + z_touch``. + + Tactile tokens generate bias-free FiLM terms for action features. A zero + centered token contributes no tactile FiLM term. Reference behavior remains + a diagnostic because each sample also has a temporal-validity pattern. + """ + + def __init__( + self, + action_mean: torch.Tensor, + action_std: torch.Tensor, + *, + memory_dim: int = 960, + tactile_dim: int = 64, + hidden_dim: int = 256, + num_layers: int = 2, + articulation_only: bool = False, + ) -> None: + super().__init__() + if tuple(action_mean.shape) != (192,) or tuple(action_std.shape) != (192,): + raise ValueError("action statistics must be [192]") + self.register_buffer("action_mean", action_mean.float(), persistent=True) + self.register_buffer( + "action_std", action_std.float().clamp_min(1e-3), persistent=True + ) + self.memory_norm = nn.RMSNorm(memory_dim) + self.memory_projection = nn.Linear(memory_dim, hidden_dim, bias=False) + self.action_projection = nn.Linear(192, hidden_dim) + self.memory_type = nn.Parameter(torch.zeros(1, 1, hidden_dim)) + self.action_type = nn.Parameter(torch.zeros(1, 1, hidden_dim)) + self.action_position = nn.Parameter(torch.randn(1, 16, hidden_dim) * 0.02) + self.time_projection = nn.Linear(1, hidden_dim) + layer = nn.TransformerEncoderLayer( + hidden_dim, + nhead=8, + dim_feedforward=hidden_dim * 4, + dropout=0.0, + activation="gelu", + batch_first=True, + norm_first=True, + ) + self.blocks = nn.TransformerEncoder( + layer, num_layers=num_layers, enable_nested_tensor=False + ) + self.touch_film = nn.ModuleList( + nn.Linear(tactile_dim, 2 * hidden_dim, bias=False) for _ in range(2) + ) + self.output = nn.ModuleList( + nn.Linear(hidden_dim, 192, bias=False) for _ in range(2) + ) + # Start as the exact frozen Method-D plan while preserving a gradient to + # the tactile path after the first optimiser update. + for head in self.output: + nn.init.zeros_(head.weight) + component = torch.zeros(1, 2, 1, 192, dtype=torch.bool) + groups = ARTICULATION_GROUPS if articulation_only else FULL_HAND_GROUPS + for hand, (start, stop) in enumerate(groups): + component[:, hand, :, start:stop] = True + self.register_buffer("hand_component_mask", component, persistent=True) + + def forward( + self, + base_action: torch.Tensor, + final_memory: torch.Tensor, + tactile_features: torch.Tensor, + hand_valid: torch.Tensor, + decision_seconds: torch.Tensor, + edit_mask: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if tuple(base_action.shape[1:]) != (16, 192): + raise ValueError("base_action must be [B,16,192]") + if final_memory.shape[:2] != (len(base_action), 8): + raise ValueError("final_memory must be [B,8,D]") + if tactile_features.shape[:2] != (len(base_action), 2): + raise ValueError("tactile_features must be [B,2,D]") + if hand_valid.shape != (len(base_action), 2): + raise ValueError("hand_valid must be [B,2]") + dtype = self.action_projection.weight.dtype + action = (base_action.detach().to(dtype) - self.action_mean.to(dtype)) + action = action / self.action_std.to(dtype) + action = self.action_projection(action) + self.action_type + self.action_position + action = action + self.time_projection( + decision_seconds.to(dtype)[:, None, None] * 10.0 + ) + memory = self.memory_projection( + self.memory_norm(final_memory.detach().to(dtype)) + ) + self.memory_type + hidden = self.blocks(torch.cat((memory, action), dim=1))[:, memory.shape[1] :] + per_hand = [] + for hand in range(2): + scale, shift = self.touch_film[hand]( + tactile_features[:, hand].to(dtype) + ).chunk(2, dim=-1) + modulated = hidden * scale[:, None] + shift[:, None] + per_hand.append(self.output[hand](modulated)) + per_hand_delta = torch.stack(per_hand, dim=1) + allowed = edit_mask[:, None].bool() & self.hand_component_mask + allowed &= hand_valid[:, :, None, None] + delta = (per_hand_delta * allowed.to(per_hand_delta.dtype)).sum(1) + return base_action.detach() + delta, delta, allowed.any(1) + + +@dataclass +class UnifiedWorldOutput: + final_action: torch.Tensor + delta_action: torch.Tensor + tactile_features: torch.Tensor + hand_valid: torch.Tensor + allowed_mask: torch.Tensor + tactile_velocity: torch.Tensor | None = None + tactile_target: torch.Tensor | None = None + tactile_valid: torch.Tensor | None = None + rgb: RGBWorldResidualOutput | None = None + + +class UnifiedWorldTactileEditor(nn.Module): + """Shared W0--W3 implementation selected only by ``world_mode``.""" + + def __init__( + self, + tactile_encoder: DualHandTactileEncoder, + *, + world_mode: WorldMode | str, + action_mean: torch.Tensor, + action_std: torch.Tensor, + pressure_masks: torch.Tensor, + reference_pressure: torch.Tensor, + pressure_scale: torch.Tensor, + memory_dim: int = 960, + tactile_dim: int = 64, + hidden_dim: int = 256, + condition_on_action: bool = True, + world_condition_dim: int = 2304, + articulation_only: bool = False, + ) -> None: + super().__init__() + self.world_mode = WorldMode(world_mode) + self.tactile = CenteredTactileFeatures( + tactile_encoder, reference_pressure + ) + self.action = DirectMemoryActionEditor( + action_mean, + action_std, + memory_dim=memory_dim, + tactile_dim=tactile_dim, + hidden_dim=hidden_dim, + articulation_only=articulation_only, + ) + self.articulation_only = articulation_only + self.target_codec = TactileTargetCodec( + pressure_masks, reference_pressure, pressure_scale + ) + self.tactile_world = ( + TactileWorldModel( + memory_dim=memory_dim, + tactile_dim=tactile_dim, + hidden_dim=hidden_dim, + action_tokens=8 if condition_on_action else 0, + ) + if self.world_mode.uses_tactile + else None + ) + self.rgb_world = ( + FrozenRGBWorldResidual( + tactile_dim=tactile_dim, + memory_rows=8, + condition_dim=world_condition_dim, + hidden_dim=hidden_dim, + ) + if self.world_mode.uses_rgb + else None + ) + self.condition_on_action = condition_on_action + + def forward( + self, + *, + base_action: torch.Tensor, + edit_mask: torch.Tensor, + pressure: torch.Tensor, + temporal_valid: torch.Tensor, + decision_seconds: torch.Tensor, + final_memory: torch.Tensor, + future_pressure: torch.Tensor | None = None, + future_valid: torch.Tensor | None = None, + tactile_tau: torch.Tensor | None = None, + tactile_noise: torch.Tensor | None = None, + rgb_world_head=None, + image_tokens: torch.Tensor | None = None, + clean_latent: torch.Tensor | None = None, + rgb_valid: torch.Tensor | None = None, + rgb_tau: torch.Tensor | None = None, + rgb_noise: torch.Tensor | None = None, + compute_auxiliary: bool = True, + ) -> UnifiedWorldOutput: + tactile_features, hand_valid = self.tactile(pressure, temporal_valid) + final_action, delta, allowed = self.action( + base_action, + final_memory, + tactile_features, + hand_valid, + decision_seconds, + edit_mask, + ) + tactile_velocity = tactile_target = tactile_valid = None + if self.tactile_world is not None and compute_auxiliary: + if future_pressure is None or future_valid is None or tactile_tau is None: + raise ValueError("W2/W3 require future tactile targets and tau") + clean, tactile_valid = self.target_codec.encode( + future_pressure, future_valid + ) + if tactile_noise is None: + tactile_noise = torch.randn_like(clean) + noisy, tactile_target = tactile_flow_pair( + clean, tactile_valid, tactile_tau, tactile_noise + ) + if self.condition_on_action: + action_window, action_valid = gather_action_window( + final_action.detach(), decision_seconds, steps=8 + ) + else: + action_window = action_valid = None + tactile_velocity = self.tactile_world.velocity( + noisy, + tactile_tau, + final_memory=final_memory.detach(), + tactile_features=tactile_features, + hand_valid=hand_valid, + action_window=action_window, + action_valid=action_valid, + ) + + rgb = None + if self.rgb_world is not None and compute_auxiliary: + values = ( + rgb_world_head, + image_tokens, + clean_latent, + rgb_valid, + rgb_tau, + rgb_noise, + ) + if any(value is None for value in values): + raise ValueError("W1/W3 require all cached RGB-world inputs") + rgb = self.rgb_world( + world_head=rgb_world_head, + image_tokens=image_tokens, + final_memory=final_memory.detach(), + tactile_features=tactile_features, + hand_valid=hand_valid, + clean_latent=clean_latent, + world_valid=rgb_valid, + tau=rgb_tau, + noise=rgb_noise, + ) + return UnifiedWorldOutput( + final_action=final_action, + delta_action=delta, + tactile_features=tactile_features, + hand_valid=hand_valid, + allowed_mask=allowed, + tactile_velocity=tactile_velocity, + tactile_target=tactile_target, + tactile_valid=tactile_valid, + rgb=rgb, + ) + + def objective( + self, + output: UnifiedWorldOutput, + target_action: torch.Tensor, + edit_mask: torch.Tensor, + *, + rgb_roi: torch.Tensor | None, + lambda_rgb: float, + lambda_tactile: float, + lambda_delta: float = 1e-4, + rgb_background_weight: float = 0.1, + ) -> tuple[torch.Tensor, dict[str, torch.Tensor]]: + if min(lambda_rgb, lambda_tactile, lambda_delta) < 0: + raise ValueError("loss weights must be non-negative") + mask = edit_mask.bool() & output.allowed_mask + present = mask.any((1, 2)) + if not present.any(): + raise ValueError("batch has no tactile-editable action target") + action_loss = per_sample_action_loss( + output.final_action[present], + target_action[present], + mask[present], + groups=(ARTICULATION_GROUPS if self.articulation_only else FULL_ACTION_GROUPS), + ).mean() + delta_l2 = output.delta_action.float().square().masked_fill(~mask, 0).sum() + delta_l2 = delta_l2 / mask.sum().clamp_min(1) + zero = action_loss.new_zeros(()) + tactile_world_loss = zero + if output.tactile_velocity is not None: + assert output.tactile_target is not None and output.tactile_valid is not None + tactile_world_loss = masked_tactile_flow_loss( + output.tactile_velocity, + output.tactile_target, + output.tactile_valid, + ) + elif lambda_tactile: + raise ValueError("lambda_tactile is nonzero without a tactile WM") + rgb_world_loss = zero + if output.rgb is not None: + if rgb_roi is None: + raise ValueError("RGB world loss requires ROI") + rgb_world_loss = roi_weighted_world_loss( + output.rgb, rgb_roi, background_weight=rgb_background_weight + ) + elif lambda_rgb: + raise ValueError("lambda_rgb is nonzero without an RGB WM") + total = ( + action_loss + + lambda_rgb * rgb_world_loss + + lambda_tactile * tactile_world_loss + + lambda_delta * delta_l2 + ) + return total, { + "loss": total.detach(), + "action_loss": action_loss.detach(), + "rgb_world_loss": rgb_world_loss.detach(), + "tactile_world_loss": tactile_world_loss.detach(), + "delta_l2": delta_l2.detach(), + } + + def optimizer_groups( + self, + *, + action_lr: float = 1e-4, + encoder_lr: float = 1e-5, + world_adapter_lr: float = 1e-4, + world_block_lr: float = 1e-5, + ) -> list[dict]: + groups = [ + {"name": "action", "params": list(self.action.parameters()), "lr": action_lr}, + { + "name": "tactile.encoder", + "params": [ + parameter + for parameter in self.tactile.encoder.parameters() + if parameter.requires_grad + ], + "lr": encoder_lr, + }, + ] + if self.tactile_world is not None: + groups += [ + { + "name": "tactile_world.adapter", + "params": list(self.tactile_world.adapter.parameters()), + "lr": world_adapter_lr, + }, + { + "name": "tactile_world.blocks", + "params": [ + parameter + for name, parameter in self.tactile_world.named_parameters() + if not name.startswith("adapter.") + ], + "lr": world_block_lr, + }, + ] + if self.rgb_world is not None: + groups.append( + { + "name": "rgb_world.touch_adapter", + "params": list(self.rgb_world.parameters()), + "lr": world_adapter_lr, + } + ) + groups = [ + {**group, "params": [p for p in group["params"] if p.requires_grad]} + for group in groups + ] + groups = [group for group in groups if group["params"]] + ids = [id(p) for group in groups for p in group["params"]] + if len(ids) != len(set(ids)): + raise RuntimeError("optimizer parameter groups overlap") + expected = {id(p) for p in self.parameters() if p.requires_grad} + if set(ids) != expected: + raise RuntimeError("optimizer groups do not cover all trainable parameters") + return groups + + +def ramp_weight(step: int, maximum: float, warmup_steps: int) -> float: + if step < 0 or maximum < 0 or warmup_steps < 0: + raise ValueError("weight schedule arguments must be non-negative") + return float(maximum) if warmup_steps == 0 else float(maximum) * min( + 1.0, step / warmup_steps + ) diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/world_flow.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/world_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..b4baec56f423cdbd8a08e64c653a38180bc5e3b2 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/world_flow.py @@ -0,0 +1,258 @@ +"""Task-35 tactile-free future-RGB flow baseline. + +This is the executable counterpart of the Small-SANA contract in Task-34. The +source checkpoint is pinned, four blocks are constructed from the start, and +only tensors needed by those blocks are read from the safetensors file. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import json +from pathlib import Path + +import torch +from torch import nn + + +SANA_REPOSITORY = "SJTU-DENG-Lab/Sana_600M_512px_diffusers_64channels" +SANA_REVISION = "dccf14061e06994e999cceb17cce700dcc1b3c78" +DCAE_SCALE = 0.41407 +SOURCE_BLOCKS = (0, 9, 18, 27) + + +class WorldConditionAdapter(nn.Module): + """Map frozen V4 features and the decision-aligned action suffix to SANA.""" + + def __init__(self, input_width: int = 960, caption_width: int = 2304) -> None: + super().__init__() + self.image_norm = nn.RMSNorm(input_width, eps=1e-6) + self.memory_norm = nn.RMSNorm(input_width, eps=1e-6) + self.action_norm = nn.RMSNorm(input_width, eps=1e-6) + self.image_type = nn.Parameter(torch.zeros(1, 1, input_width)) + self.memory_type = nn.Parameter(torch.zeros(1, 1, input_width)) + self.action_type = nn.Parameter(torch.zeros(1, 1, input_width)) + self.elapsed_type = nn.Parameter(torch.zeros(1, 1, input_width)) + self.action_projection = nn.Linear(192, input_width) + self.action_position = nn.Parameter(torch.zeros(1, 8, input_width)) + self.elapsed_projection = nn.Linear(1, input_width) + self.caption_projection = nn.Linear(input_width, caption_width) + + def forward( + self, + image_tokens: torch.Tensor, + final_memory: torch.Tensor, + action_window: torch.Tensor, + decision_seconds: torch.Tensor, + ) -> torch.Tensor: + if tuple(image_tokens.shape[1:]) != (64, 960): + raise ValueError("image_tokens must be [B,64,960]") + if tuple(final_memory.shape[1:]) != (8, 960): + raise ValueError("final_memory must be [B,8,960]") + if tuple(action_window.shape[1:]) != (8, 192): + raise ValueError("action_window must be [B,8,192]") + if tuple(decision_seconds.shape) != (len(image_tokens),): + raise ValueError("decision_seconds must be [B]") + image = self.image_norm(image_tokens) + self.image_type + memory = self.memory_norm(final_memory) + self.memory_type + action = self.action_projection(action_window) + action = self.action_norm(action) + self.action_type + self.action_position + elapsed = self.elapsed_projection(decision_seconds[:, None])[:, None] + elapsed = elapsed + self.elapsed_type + # 64 current-image + 8 memory + 8 next-action + 1 elapsed = 81 tokens. + return self.caption_projection(torch.cat((image, memory, action, elapsed), dim=1)) + + +class SmallSanaWorldModel(nn.Module): + """Four-block SANA plus the Task-35 V4/action condition adapter.""" + + def __init__(self, sana: nn.Module) -> None: + super().__init__() + if len(sana.transformer_blocks) != 4: + raise ValueError("world model must contain exactly four SANA blocks") + self.adapter = WorldConditionAdapter() + self.sana = sana + + def condition( + self, + image_tokens: torch.Tensor, + final_memory: torch.Tensor, + action_window: torch.Tensor, + decision_seconds: torch.Tensor, + ) -> torch.Tensor: + return self.adapter(image_tokens, final_memory, action_window, decision_seconds) + + def velocity( + self, noisy_latent: torch.Tensor, tau: torch.Tensor, condition: torch.Tensor + ) -> torch.Tensor: + return self.sana( + hidden_states=noisy_latent, + timestep=1000.0 * tau, + encoder_hidden_states=condition, + return_dict=True, + ).sample + + +def _source_key(destination_key: str) -> str: + if not destination_key.startswith("transformer_blocks."): + return destination_key + fields = destination_key.split(".") + destination_block = int(fields[1]) + fields[1] = str(SOURCE_BLOCKS[destination_block]) + return ".".join(fields) + + +def construct_small_sana( + *, cache_dir: str | Path | None = None, dtype: torch.dtype = torch.bfloat16 +) -> SmallSanaWorldModel: + """Construct an uninitialized four-block model from the pinned configuration.""" + + from diffusers import SanaTransformer2DModel + from huggingface_hub import hf_hub_download + + config_path = hf_hub_download( + SANA_REPOSITORY, "transformer/config.json", revision=SANA_REVISION, + cache_dir=cache_dir, + ) + config = json.loads(Path(config_path).read_text()) + config["num_layers"] = 4 + sana = SanaTransformer2DModel.from_config(config).to(dtype=dtype) + # The adapter is constructed after SANA, so converting SANA alone leaves + # its Linear/RMSNorm parameters in fp32 while all cached conditions are + # bf16. Keep the complete trainable world model in one dtype. + return SmallSanaWorldModel(sana).to(dtype=dtype) + + +def initialize_small_sana( + *, cache_dir: str | Path | None = None, dtype: torch.dtype = torch.bfloat16 +) -> SmallSanaWorldModel: + """Construct four blocks and load pinned source tensors without a 28-block model.""" + + from huggingface_hub import hf_hub_download + from safetensors import safe_open + + model = construct_small_sana(cache_dir=cache_dir, dtype=dtype) + sana = model.sana + weights_path = hf_hub_download( + SANA_REPOSITORY, "transformer/diffusion_pytorch_model.safetensors", + revision=SANA_REVISION, cache_dir=cache_dir, + ) + destination = sana.state_dict() + loaded: dict[str, torch.Tensor] = {} + with safe_open(weights_path, framework="pt", device="cpu") as reader: + available = set(reader.keys()) + for key, expected in destination.items(): + source = _source_key(key) + if source not in available and f"transformer.{source}" in available: + source = f"transformer.{source}" + if source not in available: + raise KeyError(f"source SANA tensor missing: {source}") + value = reader.get_tensor(source) + if value.shape != expected.shape: + raise ValueError( + f"shape mismatch for {key}: {tuple(value.shape)} != {tuple(expected.shape)}" + ) + loaded[key] = value.to(dtype=dtype) + sana.load_state_dict(loaded, strict=True) + if len(model.sana.transformer_blocks) != 4: + raise AssertionError("SANA block count changed after initialization") + return model + + +def load_frozen_dcae( + *, cache_dir: str | Path | None = None, dtype: torch.dtype = torch.bfloat16 +) -> nn.Module: + """Load the pinned 32-channel DC-AE shipped with the pinned SANA snapshot.""" + + from diffusers import AutoencoderDC + + model = AutoencoderDC.from_pretrained( + SANA_REPOSITORY, subfolder="vae", revision=SANA_REVISION, + cache_dir=cache_dir, torch_dtype=dtype, + ) + model.requires_grad_(False).eval() + if int(model.config.latent_channels) != 32: + raise ValueError("Task-35 requires a 32-channel DC-AE") + if abs(float(model.config.scaling_factor) - DCAE_SCALE) > 1e-8: + raise ValueError("unexpected DC-AE scaling factor") + return model + + +def encode_future_rgb(dcae: nn.Module, images: torch.Tensor) -> torch.Tensor: + """Encode normalized [-1,1] 512px RGB into scaled [B,32,16,16] latents.""" + + with torch.no_grad(): + latent = dcae.encode(images).latent + return latent * DCAE_SCALE + + +def flow_training_pair( + clean_rgb_latent: torch.Tensor, + tau: torch.Tensor, + noise: torch.Tensor, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Return padded clean latent, z_tau, and GT velocity.""" + + if tuple(clean_rgb_latent.shape[1:]) != (32, 16, 16): + raise ValueError("clean_rgb_latent must be [B,32,16,16]") + clean = torch.cat((clean_rgb_latent, torch.zeros_like(clean_rgb_latent)), dim=1) + if noise.shape != clean.shape or tau.shape != (len(clean),): + raise ValueError("noise/tau shape mismatch") + t = tau[:, None, None, None].to(dtype=clean.dtype) + noisy = (1 - t) * clean + t * noise + return clean, noisy, noise - clean + + +def masked_rgb_flow_loss( + prediction: torch.Tensor, target: torch.Tensor, valid: torch.Tensor +) -> torch.Tensor: + """Mean flow MSE on the 32 real RGB latent channels only.""" + + if prediction.shape != target.shape or prediction.shape[1:] != (64, 16, 16): + raise ValueError("flow tensors must be matching [B,64,16,16]") + if valid.shape != (len(prediction),): + raise ValueError("valid must be [B]") + weights = valid[:, None, None, None].to(dtype=torch.float32) + squared = (prediction[:, :32].float() - target[:, :32].float()).square() + return (squared * weights).sum() / (weights.sum() * 32 * 16 * 16).clamp_min(1) + + +@dataclass(frozen=True) +class FlowProbeGrid: + tau: tuple[float, ...] = (0.25, 0.5, 0.75) + noise_draws: int = 4 + seed: int = 20260911 + + +@torch.no_grad() +def extract_visual_residual( + model: SmallSanaWorldModel, + clean_rgb_latent: torch.Tensor, + condition: torch.Tensor, + sample_ids: torch.Tensor, + grid: FlowProbeGrid = FlowProbeGrid(), +) -> torch.Tensor: + """Return noise-averaged W0 residuals, [B,len(tau),32,16,16].""" + + clean = torch.cat((clean_rgb_latent, torch.zeros_like(clean_rgb_latent)), dim=1) + results = [] + for tau_value in grid.tau: + draws = [] + for draw in range(grid.noise_draws): + noises = [] + for sample_id in sample_ids.detach().cpu().tolist(): + generator = torch.Generator(device=clean.device).manual_seed( + grid.seed + int(sample_id) * 1009 + draw * 9176 + ) + noises.append(torch.randn(clean.shape[1:], generator=generator, + device=clean.device, dtype=clean.dtype)) + noise = torch.stack(noises) + tau = torch.full((len(clean),), tau_value, device=clean.device, + dtype=clean.dtype) + t = tau[:, None, None, None] + noisy = (1 - t) * clean + t * noise + target = noise - clean + prediction = model.velocity(noisy, tau, condition) + draws.append(target[:, :32] - prediction[:, :32]) + results.append(torch.stack(draws).float().mean(0)) + return torch.stack(results, dim=1) diff --git a/model/tachin_paired30_cache_20260923/code/src/tactile_editor/world_regularized_data.py b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/world_regularized_data.py new file mode 100644 index 0000000000000000000000000000000000000000..bc85a2eabe7ac90f31da94755971d3da0570fe71 --- /dev/null +++ b/model/tachin_paired30_cache_20260923/code/src/tactile_editor/world_regularized_data.py @@ -0,0 +1,129 @@ +"""Data contract for joint action-editor and future-tactile training.""" + +from __future__ import annotations + +import bisect +import json +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import Dataset + + +WORLD_ARRAY_NAMES = ( + "base_action", + "target_action", + "action_mask", + "touch_pressure", + "touch_valid", + "decision_seconds", + "recording", + "final_memory", + "future_touch_pressure", + "future_touch_valid", + "future_source_frame", +) + + +def future_tactile_targets( + pressure: np.ndarray, + finite: np.ndarray, + source_frames: np.ndarray, + current_source_frame: int, + *, + decision_ticks: tuple[int, ...] = (0, 1, 2), + horizon_frames: int = 3, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Return exact same-episode targets at decision + horizon. + + EgoTouch is 30 Hz. The primary setting uses ``horizon_frames=3`` (0.1 s). + A missing source frame is invalid, never filled from a neighbouring frame. + """ + + if pressure.ndim != 4 or pressure.shape[1:] != (2, 21, 21): + raise ValueError("pressure must be [F,2,21,21]") + if finite.shape != pressure.shape[:2] or source_frames.shape != (len(pressure),): + raise ValueError("finite/source_frames do not match pressure") + if horizon_frames < 1: + raise ValueError("horizon_frames must be positive") + targets = np.zeros((len(decision_ticks), 2, 21, 21), dtype=np.float16) + valid = np.zeros((len(decision_ticks), 2), dtype=bool) + target_frames = np.asarray( + [current_source_frame + tick + horizon_frames for tick in decision_ticks], + dtype=np.int64, + ) + rows = np.searchsorted(source_frames, target_frames) + available = rows < len(source_frames) + exact = np.zeros_like(available) + exact[available] = source_frames[rows[available]] == target_frames[available] + for index in np.flatnonzero(exact): + targets[index] = pressure[rows[index]].astype(np.float16) + valid[index] = finite[rows[index]] + return targets, valid, target_frames + + +class ShardedWorldEditorDataset(Dataset): + """Memory-map the cache version required by the single-stage objective.""" + + def __init__(self, cache_root: str | Path, split: str, *, expected_shards: int = 8): + self.cache_root = Path(cache_root) + self.split = split + self.shards: list[tuple[int, dict[str, np.ndarray]]] = [] + self.ends: list[int] = [] + total = 0 + for root in sorted(self.cache_root.glob("shard_*")): + split_root = root / split + metadata_path = split_root / "metadata.json" + if not metadata_path.is_file(): + continue + missing = [ + name + for name in WORLD_ARRAY_NAMES + if not (split_root / f"{name}.npy").is_file() + ] + if missing: + raise RuntimeError( + f"legacy cache at {split_root}; rebuild it for Issue #9 " + f"(missing {', '.join(missing)})" + ) + metadata = json.loads(metadata_path.read_text()) + count = int(metadata["valid_samples"]) + arrays = { + name: np.load(split_root / f"{name}.npy", mmap_mode="r") + for name in WORLD_ARRAY_NAMES + } + if any(len(value) < count for value in arrays.values()): + raise ValueError(f"shard arrays shorter than metadata: {split_root}") + self.shards.append((count, arrays)) + total += count + self.ends.append(total) + if len(self.shards) != expected_shards: + raise RuntimeError( + f"expected {expected_shards} complete cache shards, found {len(self.shards)}" + ) + + def __len__(self) -> int: + return self.ends[-1] + + def __getitem__(self, index: int) -> dict[str, torch.Tensor]: + if index < 0: + index += len(self) + if not 0 <= index < len(self): + raise IndexError(index) + shard = bisect.bisect_right(self.ends, index) + start = 0 if shard == 0 else self.ends[shard - 1] + arrays = self.shards[shard][1] + result = { + name: torch.from_numpy(np.array(value[index - start], copy=True)) + for name, value in arrays.items() + } + result["index"] = torch.tensor(index, dtype=torch.long) + return result + + def read_column(self, name: str) -> np.ndarray: + if name not in WORLD_ARRAY_NAMES: + raise KeyError(name) + return np.concatenate( + [np.asarray(arrays[name][:count]) for count, arrays in self.shards], axis=0 + )