Release joint_mix40 VAE weights, training and GT neighborhood sampling code
Browse filesFiles changed (23)
- DATA_FORMAT.mdAdded+65
- README.mdAdded+158
- SHA256SUMSAdded+22
- augment.pyAdded+150
- bimanual_vae.pyAdded+32
- config.jsonAdded+47
- example.pyAdded+45
- hand_vae.pyAdded+38
- joint_mix40.ptAdded+3
- load_model.pyAdded+16
- mano_compat.pyAdded+26
- model.safetensorsAdded+3
- provenance.jsonAdded+53
- requirements-training.txtAdded+4
- requirements.txtAdded+4
- train.pyAdded+68
- training/README.mdAdded+24
- training/history.jsonAdded+340
- training/original_common.pyAdded+14
- training/original_prepare_data.pyAdded+54
- training/original_train_pair.pyAdded+44
- training_config.jsonAdded+19
- validation.jsonAdded+29
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# Numeric NPZ schemas
All NPZ files are loaded with `allow_pickle=False`. Rotations and positions usefloat32; split, recording, frame, and dataset indices are integers.
## Training cache and query poses
| Array | Shape | Meaning ||---|---|---|| `pose_aa` | N × 2 × 15 × 3 | Full native MANO local finger axis angles, radians; left/right || `relative_rotation` | N × 3 × 3 | `R_left.T @ R_right` || `relative_wrist_m` | N × 3 | `R_left.T @ (wrist_right - wrist_left)`, meters || `dataset` | N | 0=ARCTIC, 1=H2O, 2=GRAB in the original cache || `sequence` | N | Recording identifier, consistent within each source; required for training/pool encoding || `split` | N | 0=train, 1=validation, 2=test || `frame_ids` | N | Optional original frame identifier |
Only real, same-frame valid hand pairs belong in these inputs. Do not construct apair by combining unrelated single-hand examples. Do not add a hand mean twice.The original cache also has `anchor_rotation` and `anchor_wrist_m`; the trainingand portable augmentation scripts do not need them because they model relativecoordinates. Query files use the same pose fields; `sequence` is not required.
The encoder selects only training rows. The sampler uses only train/validationqueries and finds centers and neighbors in the training pool, restricted to thequery's source dataset. For an EgoRenderer query based on GRAB motion, use thesource-motion dataset ID `2`.
## Encoded training pool
`mu` and `logvar` are N × 40. `source_row` points back into the original trainingcache. `sequence`, `dataset`, `split`, optional `frame_ids`, and the cache`source_sha256` preserve provenance. Every pool row must have `split=0`.
## Synthetic rendering parameters
Let Q be query count, T the number of scales, and D the directions per scale.The output has S=Q×T×D samples ordered query, scale, direction.
| Array | Shape | Meaning ||---|---|---|| `z` | S × 40 | Sampled latent || `mano_rotation_matrices` | S × 2 × 16 × 3 × 3 | Wrist root followed by 15 native local finger rotations || `mano_pose_axis_angle` | S × 2 × 16 × 3 | The same full rotations as axis angles in radians || `wrist_positions_m` | S × 2 × 3 | Actual joint-zero positions in meters || `mano_shape` | S × 2 × 10 | Neutral shape, all zeros || `query_index` | S | Query row index || `train_pool_row`, `train_source_row` | S | Center in encoded pool / original cache || `train_sequence`, `train_dataset` | S | Center recording and dataset IDs || `temperature` | S | Interpolation fraction tau, despite the historical field name || `draw` | S | Direction index || `anchor_pool_rows` | Q | Retrieved training centers || `neighbor_pool_rows` | Q × K | Neighbor rows from distinct other training recordings || `endpoint_neighbor_indices` | Q × D × 2 | Pair indices into that query's neighbor list || `endpoint_weights` | Q × D | Convex endpoint weight w |
The canonical left wrist is at zero with identity rotation. Right-wrist placementcomes from the decoded relative pose. Apply the same chosen scene transform toboth wrists and both root orientations. Local finger rotations remain local.
To decode meshes, use MANO with full poses (no additional pose-mean addition),then translate each hand so its actual wrist joint matches `wrist_positions_m`.Do not pass actual wrist positions directly as MANO `transl` unless your MANOimplementation explicitly uses a wrist-centered template. Mesh generation is aseparate operation and is not required to encode/sample the VAE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158---library_name: pytorchlanguage:- en- zhtags:- hand-pose- bimanual- vae- mano- pose-generation- data-augmentation---
# Bimanual Pose VAE — joint_mix40
双手姿态 VAE 的代码与权重:学习双手局部姿态、相对腕朝向和相对腕位置,可用于姿态先验,以及从训练 GT 的 latent 邻域生成渲染增广候选。
This is the **exact joint_mix40 checkpoint** used by the[VAE Pose Atlas visualization](https://huggingface.co/spaces/WhynotGPT/vae-pose-atlas).The framewise model encodes 30 local finger rotations, one relative wrist rotation,and a relative wrist position into a **40-dimensional latent**. It uses a width-384MLP and a 189-dimensional input with row-based 6D rotation representations.Shared global rotation and translation are removed by expressing the wrist relationin the left wrist frame. RGB, camera parameters, hand shape, and temporal dynamicsare outside the model.
## Download and run
Python 3.11 is the tested environment. Download the repository, then run from its root:
```bashpip install huggingface_hubpython -c "from huggingface_hub import snapshot_download; snapshot_download('WhynotGPT/bimanual-pose-vae', local_dir='bimanual-pose-vae')"cd bimanual-pose-vaepip install -r requirements.txtpython example.py --device cpusha256sum -c SHA256SUMS```
The example uses synthetic inputs to verify loading, reconstruction, and inputgradients through the frozen VAE. It does not measure accuracy.
```pythonimport torchfrom load_model import load_modelfrom bimanual_vae import pack
vae, metadata = load_model(device="cpu") # model.safetensors + config.json# local_rot: [B,2,15,3,3]; root_rot: [B,2,3,3]; wrist: [B,2,3]with torch.no_grad(): rot, pos = pack(local_rot, root_rot, wrist) mu, logvar = vae.encode(rot, pos) reconstructed_rot, reconstructed_pos = vae.decode(mu)```
Inputs use **left, right** ordering and each hand's native MANO convention. Localrotations represent the full pose, including the native hand mean where requiredby the source convention. Wrist positions are actual joint positions in meters,not necessarily the MANO `transl` parameter. Both hands must be valid.
Decoder rotations have shape `[B,31,3,3]`: left fingers `0:15`, right fingers`15:30`, and relative right-wrist orientation `30`. Position `[B,3]` is the rightwrist in the left wrist frame. To place a pose in a scene, choose a left-wristanchor `(R_L,t_L)`, then set `R_R=R_L @ rot[:,30]` and `t_R=t_L+R_L @ pos`.
The original API is also available:
```pythonfrom bimanual_vae import load_pairvae, metadata = load_pair("joint_mix40.pt", device="cpu")# Preserve gradients through the inputs when using a frozen prior:loss_prior = vae.energy(local_rot, root_rot, wrist).mean()```
## Generate augmentation poses from training GT
The portable sampler follows the train-GT neighborhood method used in the Atlas.It encodes only `split=0` rows, retrieves the nearest training pose in the samedataset as each query, and finds neighbors from 16 distinct other training recordings.Queries can be difficult training/validation GT poses; test queries are rejected.The caller selects difficult queries, for example using a model's validation PA error.
```bashpython augment.py encode --data /path/to/paired_motion.npz --output train_latents.npzpython augment.py sample --pool train_latents.npz --queries /path/to/difficult_gt.npz --output render_poses.npz```
For each retrieved center, the sampler draws eight neighbor pairs with weights`w` in `[0.2,0.8]` and reuses those endpoints at `tau = 0.25, 0.5, 1.0`:
```textendpoint = w * mu_neighbor_a + (1-w) * mu_neighbor_bz = (1-tau) * mu_train_center + tau * endpoint```
Each query yields **24 synthetic bimanual poses**. Output includes full MANO axisangles and rotation matrices, actual wrist positions, zero shape coefficients,latent values, and training-source indices. The left wrist is at the origin withidentity orientation. See [DATA_FORMAT.md](DATA_FORMAT.md) for all array conventions.
These outputs are pose labels for subsequent rendering. Geometry, scene placement,hand-object contact, and collision checks belong to the rendering pipeline. Themodel alone does not generate mesh vertices or guarantee physical plausibility.Augmentation gains on a downstream hand estimator have not been established bythis release. The portable script implements the same sampling rule; it does notrecreate the Atlas's source-specific query extraction or its exact random draw order.
## Training
The released checkpoint was selected at **epoch 50** of a 60-epoch run usingvalidation reconstruction metrics. Training uses 48 updates per epoch, batch 192,AdamW at 0.001, dataset/recording-balanced random sampling, rotation and skeletalFK reconstruction, relative-position reconstruction, and KL regularization.
| Source | Train paired frames | Validation paired frames | Test paired frames ||---|---:|---:|---:|| ARCTIC | 32,320 | 4,960 | 4,480 || H2O | 12,686 | 2,560 | 1,760 || GRAB | 104,825 | 10,460 | 11,834 |
ARCTIC/H2O use frozen recording splits with the experiment's benchmark recordingsexcluded. GRAB uses subjects s1–s8 / s9 / s10. Preparation retains at most 160paired frames per recording; GRAB is first downsampled from 120 fps to 10 fps.These are VAE training counts, separate from the main estimator's SFT clip counts.
```bashpip install -r requirements-training.txtpython train.py --data /path/to/paired_motion.npz \ --mano-dir /path/to/mano --output runs/joint_mix40 --device cuda```
`train.py` preserves the original training algorithm, adding configurable paths,device, and run lengths. It needs your prepared motion cache and MANO_LEFT.pkl /MANO_RIGHT.pkl for the native skeleton FK loss. Raw data, the motion cache, MANOmodel assets, and their derived mesh buffers are not distributed here. Obtainthose dependencies under their respective terms. The original experiment scriptsare archived in [training/](training/README.md); their historical absolute pathsand external preprocessing dependencies are documented there.
The repository includes only the **joint_mix40 trained weights**. Training codealso exposes the historical joint_ego40 and pose_mix40 variants.
## Files and verification
- `joint_mix40.pt`: byte-identical original checkpoint, with normalization and metadata.- `model.safetensors`, `config.json`: equivalent tensor-only weights and JSON metadata.- `bimanual_vae.py`, `hand_vae.py`: unchanged original model definitions and rotation helpers.- `load_model.py`, `example.py`: loading and differentiable-prior examples.- `train.py`, `training_config.json`, `training/`: training entry point and provenance.- `augment.py`, `DATA_FORMAT.md`: train-GT encoding and neighborhood sampling.- `validation.json`, `provenance.json`, `SHA256SUMS`: checks and file integrity records.
Original checkpoint SHA-256:`e27bd6bab2aee8780eafb3dbdf2a368ab328af526d2835f480819052cd53d096`.The original model and training work is from the MiroHand P3R4 bimanual VAEexperiment dated 2026-09-27; this package adds portable interfaces for release.12345678910111213141516171819202122c3f7f50702d94ae4e2e631818a595723fc417e17f1388f63e228ce725853afb2 DATA_FORMAT.md9bb029884f38a9b5d3e80197a03f158eae05e4adfc0273c23dede3ba90901720 README.mdea941357aa03afdce5b6608dac2965d44bf6347d9119efb5f832999ebbe89744 augment.py9e940527007fc2bf93809eba891bb18b76b75a9e30206a2ab0698704e431f3f6 bimanual_vae.py0e486bd7ef71d03f55b2f4de0d4bdb314e198d37380cdb366240789534ce2ed3 config.jsond81b092510f478f0e0c405553ac8238144239926087f3650ee4c07e48906999d example.py5ee21d9a48ce2d8094f28c2ff1ae56a57d5c55244125e18b3c3e50d1a588979c hand_vae.pye27bd6bab2aee8780eafb3dbdf2a368ab328af526d2835f480819052cd53d096 joint_mix40.pt11e94dbc58096fb2ce590af9749f4ab431cf1c27799f6fdeb2341f61453b0338 load_model.pyc4a0ccd48ebba2e8f03fc295be942e4520385f99521460de4c9915c1776e9da3 mano_compat.py6c4fe1b79138e4cd3b7ddccb45780479de2d25270be018e46be6696d78bd05f8 model.safetensorsf362e83ba1b3798744b94f3d5b79edbb7b0dfdd8c4d0cef328f361abe8cf17a3 provenance.jsoncd3b0fc323d507a9935a38187754f71a8b973f9d3ef32be9bfd29b3f0a521ebb requirements-training.txtefba809b61f64bbf0863e65c9c303800b8c2c6a28100c1739e2407964b24e276 requirements.txt5b7db63f51871d303c1abad15441c002693df8cdc68cab944905ab8dc146f3db train.py89ee9e8f6152ad58d42003119d5c6643d9242e511a35a8a6711a860d57fd082f training/README.mda83a1341b55522d329adbaab29937ba5a260f42091975098aacb116490ff9417 training/history.jsonf08a807e45d72cc2fe6de81f65b22db78075d16ac4dcfa390b32572ccc3e185e training/original_common.py1c2bb19eeaf58e2f80b76e6ec556af02cb92cbb2ebfeaf580b7ed00fc86bac4d training/original_prepare_data.py8c854506d4a084fcea9ce8988c7dc33fe628f22b8380832f7f45a54ffc8a716a training/original_train_pair.pye4163ef9cc4f8b7add9d4e4350a853a145c842e51bab851101dcabb3c550c4ff training_config.json2e072c6387f5c7765b8a45b66a3217f4b6c11cbc31c0426ed47fece4c3ecf025 validation.json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Encode training GT and sample distinct-recording latent neighborhoods.
Inputs are numeric NPZ arrays, described in DATA_FORMAT.md. Mesh generation isexternal; the output contains full MANO rotations and actual wrist positions."""import argparseimport hashlibfrom pathlib import Path
import numpy as npimport torch
from hand_vae import aa_to_matrix, matrix_to_aafrom load_model import load_model
def encode_pose(model, pose, relative_rotation, relative_wrist): local = aa_to_matrix(torch.as_tensor(pose, dtype=torch.float32)).reshape(-1, 30, 3, 3) rotations = torch.cat([local, torch.as_tensor(relative_rotation, dtype=torch.float32)[:, None]], 1) return model.encode(rotations, torch.as_tensor(relative_wrist, dtype=torch.float32))
@torch.inference_mode()def encode(data_path, output): model, _ = load_model() with np.load(data_path, allow_pickle=False) as data: rows = np.flatnonzero(data["split"] == 0) if not len(rows): raise ValueError("No split=0 training rows.") payload = {name: data[name][rows] for name in ("sequence", "dataset")} if "frame_ids" in data: payload["frame_ids"] = data["frame_ids"][rows] poses = {name: data[name][rows] for name in ("pose_aa", "relative_rotation", "relative_wrist_m")} means, logvars = [], [] for start in range(0, len(rows), 2048): ix = slice(start, start + 2048) mu, logvar = encode_pose(model, poses["pose_aa"][ix], poses["relative_rotation"][ix], poses["relative_wrist_m"][ix]) means.append(mu.numpy()) logvars.append(logvar.numpy()) with data_path.open("rb") as stream: source_hash = hashlib.file_digest(stream, "sha256").hexdigest() np.savez_compressed(output, mu=np.concatenate(means), logvar=np.concatenate(logvars), source_row=rows, split=np.zeros(len(rows), dtype=np.int8), source_sha256=np.array(source_hash), **payload) print(f"Encoded {len(rows)} training GT rows into {output}")
@torch.inference_mode()def sample(pool_path, query_path, output, neighbor_count, directions, scales, seed): model, _ = load_model() rng = np.random.default_rng(seed) with np.load(pool_path, allow_pickle=False) as data: pool = {key: data[key] for key in data.files} if not np.all(pool["split"] == 0): raise ValueError("The candidate pool must contain only training GT.") with np.load(query_path, allow_pickle=False) as queries: # Queries identify difficult GT regions; held-out test queries are excluded. if not np.isin(queries["split"], [0, 1]).all(): raise ValueError("Queries must use train/validation GT, never test rows.") query_datasets = queries["dataset"].copy() query_mu, _ = encode_pose(model, queries["pose_aa"], queries["relative_rotation"], queries["relative_wrist_m"]) query_mu = query_mu.numpy() if not len(query_mu): raise ValueError("The query file is empty.") if not np.isfinite(pool["mu"]).all() or not np.isfinite(query_mu).all(): raise ValueError("Latents must be finite.") if neighbor_count < 1 or directions < 1 or not len(scales) or np.any((scales < 0) | (scales > 1)) or not np.isfinite(scales).all(): raise ValueError("Use positive counts and finite interpolation scales in [0,1].") anchors, neighbors, pairs, weights, latent_batches = [], [], [], [], [] for query, dataset in zip(query_mu, query_datasets): ids = np.flatnonzero(pool["dataset"] == dataset) if not len(ids): raise ValueError(f"No training rows for dataset {dataset}.") anchor = int(ids[np.argmin(np.square(pool["mu"][ids] - query).sum(1))]) order = np.argsort(np.square(pool["mu"][ids] - pool["mu"][anchor]).sum(1)) seen = {int(pool["sequence"][anchor])} nearest = [] for row in ids[order]: sequence = int(pool["sequence"][row]) if sequence not in seen: nearest.append(int(row)) seen.add(sequence) if len(nearest) == neighbor_count: break if len(nearest) != neighbor_count: raise ValueError(f"Dataset {dataset} needs {neighbor_count + 1} distinct training recordings.") nearest = np.asarray(nearest) pair = rng.choice(neighbor_count, (directions, 2), replace=True) weight = rng.uniform(.2, .8, directions).astype(np.float32) endpoint = weight[:, None] * pool["mu"][nearest[pair[:, 0]]] + (1 - weight[:, None]) * pool["mu"][nearest[pair[:, 1]]] z = (1 - scales[:, None, None]) * pool["mu"][anchor] + scales[:, None, None] * endpoint[None] latent_batches.append(z.reshape(-1, model.latent_dim)) anchors.append(anchor) neighbors.append(nearest) pairs.append(pair) weights.append(weight) z = np.concatenate(latent_batches).astype(np.float32) rot, pos = model.decode(torch.from_numpy(z)) full = torch.zeros(len(z), 2, 16, 3, 3) full[:, 0, 0] = torch.eye(3) full[:, 1, 0] = rot[:, 30] full[:, :, 1:] = rot[:, :30].reshape(-1, 2, 15, 3, 3) wrist = torch.zeros(len(z), 2, 3) wrist[:, 1] = pos anchors = np.asarray(anchors) query_index = np.repeat(np.arange(len(anchors)), len(scales) * directions) np.savez_compressed( output, z=z, mano_rotation_matrices=full.numpy(), mano_pose_axis_angle=matrix_to_aa(full).numpy(), wrist_positions_m=wrist.numpy(), mano_shape=np.zeros((len(z), 2, 10), np.float32), query_index=query_index, train_pool_row=anchors[query_index], train_source_row=pool["source_row"][anchors[query_index]], train_sequence=pool["sequence"][anchors[query_index]], train_dataset=pool["dataset"][anchors[query_index]], temperature=np.tile(np.repeat(scales, directions), len(anchors)), draw=np.tile(np.arange(directions), len(anchors) * len(scales)), anchor_pool_rows=anchors, neighbor_pool_rows=np.asarray(neighbors), endpoint_neighbor_indices=np.asarray(pairs), endpoint_weights=np.asarray(weights), seed=np.array(seed), coordinate_system=np.array("left_wrist_local"), ) print(f"Saved {len(z)} synthetic bimanual pose candidates to {output}")
def main(): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) enc = commands.add_parser("encode") enc.add_argument("--data", type=Path, required=True) enc.add_argument("--output", type=Path, required=True) sam = commands.add_parser("sample") sam.add_argument("--pool", type=Path, required=True) sam.add_argument("--queries", type=Path, required=True) sam.add_argument("--output", type=Path, required=True) sam.add_argument("--neighbors", type=int, default=16) sam.add_argument("--directions", type=int, default=8) sam.add_argument("--scales", type=float, nargs="+", default=[.25, .5, 1.]) sam.add_argument("--seed", type=int, default=20261110) args = parser.parse_args() if args.output.exists(): parser.error("Output already exists; choose a new path.") args.output.parent.mkdir(parents=True, exist_ok=True) torch.set_num_threads(4) if args.command == "encode": encode(args.data, args.output) else: sample(args.pool, args.queries, args.output, args.neighbors, args.directions, np.asarray(args.scales, dtype=np.float32), args.seed)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132"""P3R4 paired-hand prior. Translation-invariant, common-rotation-invariant.Local finger rotations (2 x 15), right wrist orientation and translation inleft wrist frame. Inference uses camera-coordinate inputs; mocap needs no camera."""import torchfrom torch import nnfrom hand_vae import matrix_to_six,six_to_matrix,aa_to_matrixclass BimanualVAE(nn.Module): def __init__(self,latent_dim=40,width=384,pose_only=False): super().__init__();self.latent_dim=latent_dim;self.width=width;self.pose_only=pose_only;self.nrot=30 if pose_only else 31;self.dim=self.nrot*6+(0 if pose_only else 3) self.register_buffer('input_mean',torch.zeros(self.dim));self.register_buffer('input_std',torch.ones(self.dim)) self.encoder=nn.Sequential(nn.Linear(self.dim,width),nn.LeakyReLU(.2),nn.Linear(width,width),nn.LeakyReLU(.2));self.mu=nn.Linear(width,latent_dim);self.logvar=nn.Linear(width,latent_dim);nn.init.constant_(self.logvar.bias,-2) self.decoder=nn.Sequential(nn.Linear(latent_dim,width),nn.LeakyReLU(.2),nn.Linear(width,width),nn.LeakyReLU(.2),nn.Linear(width,self.dim)) def features(self,rot,pos): x=matrix_to_six(rot[...,:self.nrot,:,:]).flatten(-2) return x if self.pose_only else torch.cat([x,pos],-1) def encode(self,rot,pos): h=self.encoder((self.features(rot,pos)-self.input_mean)/self.input_std);return self.mu(h),self.logvar(h).clamp(-8,4) def decode(self,z): x=self.decoder(z)*self.input_std+self.input_mean;rot=six_to_matrix(x[...,:self.nrot*6].reshape(*x.shape[:-1],self.nrot,6));pos=torch.zeros((*x.shape[:-1],3),device=x.device,dtype=x.dtype) if self.pose_only else x[...,-3:];return rot,pos def forward(self,rot,pos): mu,lv=self.encode(rot,pos);z=mu+torch.randn_like(mu)*(.5*lv).exp() if self.training else mu;r,p=self.decode(z);return r,p,mu,lv def energy(self,local_rot,root_rot,wrist): rot,pos=pack(local_rot,root_rot,wrist);rr,pp,mu,lv=self(rot,pos) pose=(rr[:,:30]-rot[:,:30]).square().sum((-1,-2)).mean(-1) relation=pose*0 if self.pose_only else (rr[:,30]-rot[:,30]).square().sum((-1,-2))+((pp-pos)/.1).square().sum(-1) return pose+relation+.0005*mu.square().mean(-1)def pack(local_rot,root_rot,wrist): left=root_rot[...,0,:,:];rr=left.transpose(-1,-2)@root_rot[...,1,:,:];pos=(left.transpose(-1,-2)@(wrist[...,1,:]-wrist[...,0,:])[...,None]).squeeze(-1) return torch.cat([local_rot.flatten(-4,-3),rr.unsqueeze(-3)],-3),posdef load_pair(path,device='cuda'): c=torch.load(path,map_location=device,weights_only=False);m=BimanualVAE(**c['architecture']).to(device);m.load_state_dict(c['state_dict'],strict=True);m.eval();m.requires_grad_(False);return m,c1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{ "architecture": { "latent_dim": 40, "width": 384, "pose_only": false }, "config": { "variant": "joint_mix40", "seed": 20260927, "epochs": 60, "steps_per_epoch": 48, "batch": 192, "lr": 0.001, "kl_beta": 0.0005, "joint_weight": 0.25, "position_scale_m": 0.1, "balanced_dataset_and_sequence": true, "included_datasets": [ 0, 1, 2 ], "selection": "equal-dataset validation local FK mm + 0.25 relative position mm + relative rotation deg; test not used", "data_sha256": "456c2b8011b56552a0806836fdb2eb9fcdd397ca3693f390bb2cbb5f8ba0f06f" }, "epoch": 50, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 2.552030563354492, "relative_wrist_mm": 15.961709022521973, "relative_rotation_deg": 13.042522430419922 }, { "dataset": "H2O", "local_fk_mm": 1.722329020500183, "relative_wrist_mm": 7.883533000946045, "relative_rotation_deg": 8.399897575378418 }, { "dataset": "GRAB", "local_fk_mm": 2.7820262908935547, "relative_wrist_mm": 18.310850143432617, "relative_rotation_deg": 17.670961380004883 } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445"""CPU/GPU smoke example. Synthetic inputs only; not an accuracy evaluation."""import argparseimport jsonfrom pathlib import Pathimport torchfrom bimanual_vae import load_pair, packfrom hand_vae import aa_to_matrix
def main(): parser = argparse.ArgumentParser() parser.add_argument("--device", default="cpu") args = parser.parse_args() torch.manual_seed(0) vae, _ = load_pair(str(Path(__file__).resolve().parent / "joint_mix40.pt"), args.device) # Synthetic full MANO local axis angles, left hand first, right hand second. local_aa = torch.zeros(2, 2, 15, 3, device=args.device, requires_grad=True) root_aa = torch.zeros(2, 2, 3, device=args.device, requires_grad=True) wrist = torch.tensor([[[0., 0., .5], [.2, 0., .5]], [[0., 0., .6], [.2, .02, .6]]], device=args.device, requires_grad=True) local_rot, root_rot = aa_to_matrix(local_aa), aa_to_matrix(root_aa) energy = vae.energy(local_rot, root_rot, wrist) loss = 0.1 * energy.mean() loss.backward() for x in (local_aa, root_aa, wrist): assert x.grad is not None and torch.isfinite(x.grad).all() assert torch.isfinite(energy).all() assert all(not p.requires_grad and p.grad is None for p in vae.parameters()) with torch.no_grad(): rot, pos = pack(local_rot, root_rot, wrist) rot_rec, pos_rec, mu, logvar = vae(rot, pos) assert rot_rec.shape == (2, 31, 3, 3) assert pos_rec.shape == (2, 3) assert mu.shape == logvar.shape == (2, 40) print(json.dumps({"device": args.device, "torch": torch.__version__, "synthetic_inputs": True, "energy": energy.detach().cpu().tolist(), "rotation_shape": list(rot_rec.shape), "position_shape": list(pos_rec.shape), "latent_shape": list(mu.shape), "finite_input_gradients": True, "frozen_vae": True}, indent=2))
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738"""Hand-specific, side-conditioned VAE; 15 local rotations, no wrist/global/shape."""import torchfrom torch import nnfrom torch.nn import functional as F
def aa_to_matrix(x): theta=x.norm(dim=-1,keepdim=True);x0,x1,x2=x.unbind(-1);z=torch.zeros_like(x0) k=torch.stack([z,-x2,x1,x2,z,-x0,-x1,x0,z],-1).reshape(*x.shape[:-1],3,3) a=torch.sinc(theta/torch.pi)[...,None];b=(.5*torch.sinc(theta/(2*torch.pi)).square())[...,None] return torch.eye(3,device=x.device,dtype=x.dtype)+a*k+b*(k@k)
def matrix_to_aa(m): m00,m01,m02=m[...,0,0],m[...,0,1],m[...,0,2];m10,m11,m12=m[...,1,0],m[...,1,1],m[...,1,2];m20,m21,m22=m[...,2,0],m[...,2,1],m[...,2,2] qabs=torch.stack([1+m00+m11+m22,1+m00-m11-m22,1-m00+m11-m22,1-m00-m11+m22],-1).clamp_min(1e-8).sqrt() candidates=torch.stack([torch.stack([qabs[...,0]**2,m21-m12,m02-m20,m10-m01],-1),torch.stack([m21-m12,qabs[...,1]**2,m10+m01,m02+m20],-1),torch.stack([m02-m20,m10+m01,qabs[...,2]**2,m12+m21],-1),torch.stack([m10-m01,m20+m02,m21+m12,qabs[...,3]**2],-1)],-2)/(2*qabs[...,None].clamp_min(.1)) ix=qabs.argmax(-1);q=candidates.gather(-2,ix[...,None,None].expand(*ix.shape,1,4)).squeeze(-2);q=F.normalize(q,dim=-1);q=torch.where(q[...,:1]<0,-q,q) norm=q[...,1:].norm(dim=-1,keepdim=True);angle=2*torch.atan2(norm,q[...,:1]);scale=torch.where(norm>1e-6,angle/norm.clamp_min(1e-8),2+norm.square()/3) return q[...,1:]*scale
def matrix_to_six(m):return m[...,:2,:].reshape(*m.shape[:-2],6)def six_to_matrix(x): a,b=x[...,:3],x[...,3:];r0=F.normalize(a,dim=-1,eps=1e-7);r1=F.normalize(b-(r0*b).sum(-1,keepdim=True)*r0,dim=-1,eps=1e-7);r2=torch.cross(r0,r1,dim=-1);return torch.stack([r0,r1,r2],-2)class HandVAE(nn.Module): def __init__(self,latent_dim=20,width=256): super().__init__();self.latent_dim=latent_dim;self.width=width self.register_buffer('input_mean',torch.zeros(90));self.register_buffer('input_std',torch.ones(90)) self.encoder=nn.Sequential(nn.Linear(92,width),nn.LeakyReLU(.2),nn.Linear(width,width),nn.LeakyReLU(.2)) self.mu=nn.Linear(width,latent_dim);self.logvar=nn.Linear(width,latent_dim);nn.init.constant_(self.logvar.bias,-2) self.decoder=nn.Sequential(nn.Linear(latent_dim+2,width),nn.LeakyReLU(.2),nn.Linear(width,width),nn.LeakyReLU(.2),nn.Linear(width,90)) def encode(self,rot,side): x=(matrix_to_six(rot).flatten(-2)-self.input_mean)/self.input_std;h=self.encoder(torch.cat([x,F.one_hot(side.long(),2).to(x)],-1));return self.mu(h),self.logvar(h).clamp(-8,4) def decode(self,z,side): x=self.decoder(torch.cat([z,F.one_hot(side.long(),2).to(z)],-1))*self.input_std+self.input_mean;return six_to_matrix(x.reshape(*z.shape[:-1],15,6)) def forward(self,rot,side): mu,lv=self.encode(rot,side);z=mu+torch.randn_like(mu)*(.5*lv).exp() if self.training else mu;return self.decode(z,side),mu,lv
def load_vae(path,device='cuda'): ck=torch.load(path,map_location=device,weights_only=False);m=HandVAE(**ck['architecture']).to(device);m.load_state_dict(ck['state_dict'],strict=True);m.eval();m.requires_grad_(False);return m,ck123version https://git-lfs.github.com/spec/v1oid sha256:e27bd6bab2aee8780eafb3dbdf2a368ab328af526d2835f480819052cd53d096size 195967012345678910111213141516"""Load the released tensor-only weights and checkpoint metadata."""import jsonfrom pathlib import Path
from safetensors.torch import load_file
from bimanual_vae import BimanualVAE
def load_model(directory=None, device="cpu"): directory = Path(directory) if directory else Path(__file__).resolve().parent config = json.loads((directory / "config.json").read_text()) model = BimanualVAE(**config["architecture"]) model.load_state_dict(load_file(str(directory / "model.safetensors")), strict=True) model.to(device).eval().requires_grad_(False) return model, config1234567891011121314151617181920212223242526"""Compatibility shim for the licensed MANO files and legacy chumpy loader."""
from __future__ import annotations
import inspect
import numpy as np
def enable_legacy_mano_loading() -> None: """Restore names removed after the legacy MANO/chumpy release."""
if not hasattr(inspect, "getargspec"): inspect.getargspec = inspect.getfullargspec # type: ignore[attr-defined] aliases = { "bool": bool, "int": int, "float": float, "complex": complex, "object": object, "unicode": str, "str": str, } for name, value in aliases.items(): if name not in np.__dict__: setattr(np, name, value)123version https://git-lfs.github.com/spec/v1oid sha256:6c4fe1b79138e4cd3b7ddccb45780479de2d25270be018e46be6696d78bd05f8size 19546361234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{ "source_experiment": "MiroHand_P3R4_bimanual_VAE_20260927", "release_date": "2026-11-15", "unchanged_original_files": { "joint_mix40.pt": { "source_relative_path": "priors/joint_mix40.pt", "sha256": "e27bd6bab2aee8780eafb3dbdf2a368ab328af526d2835f480819052cd53d096" }, "bimanual_vae.py": { "source_relative_path": "code/bimanual_vae.py", "sha256": "9e940527007fc2bf93809eba891bb18b76b75a9e30206a2ab0698704e431f3f6" }, "hand_vae.py": { "source_relative_path": "code/hand_vae.py", "sha256": "5ee21d9a48ce2d8094f28c2ff1ae56a57d5c55244125e18b3c3e50d1a588979c" }, "training_config.json": { "source_relative_path": "priors/joint_mix40_config.json", "sha256": "e4163ef9cc4f8b7add9d4e4350a853a145c842e51bab851101dcabb3c550c4ff" }, "training/history.json": { "source_relative_path": "priors/joint_mix40_history.json", "sha256": "a83a1341b55522d329adbaab29937ba5a260f42091975098aacb116490ff9417" }, "training/original_train_pair.py": { "source_relative_path": "code/train_pair.py", "sha256": "8c854506d4a084fcea9ce8988c7dc33fe628f22b8380832f7f45a54ffc8a716a" }, "training/original_prepare_data.py": { "source_relative_path": "code/prepare_data.py", "sha256": "1c2bb19eeaf58e2f80b76e6ec556af02cb92cbb2ebfeaf580b7ed00fc86bac4d" }, "training/original_common.py": { "source_relative_path": "code/common.py", "sha256": "f08a807e45d72cc2fe6de81f65b22db78075d16ac4dcfa390b32572ccc3e185e" } }, "converted_weights": { "model.safetensors": "All checkpoint state_dict tensors, exactly equal; metadata in config.json" }, "adapted_files": { "train.py": "Original algorithm with CLI paths/device/run lengths and standalone compatibility helpers", "augment.py": "Portable training-GT neighborhood sampling; query extraction and mesh generation external" }, "trained_variant": "joint_mix40", "checkpoint_epoch": 50, "excluded_assets": [ "raw datasets", "training motion cache", "MANO model files", "derived MANO buffers" ]}1234-r requirements.txtsmplx==0.1.28chumpy==0.70scipy>=1.101234torch>=2.0numpy>=1.24safetensors>=0.4huggingface_hub>=0.251234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Training algorithm preserved from the original 2026-09-27 experiment.Only environment/path plumbing and optional smoke-run lengths are adapted."""from pathlib import Pathimport json, hashlibimport numpy as npfrom mano_compat import enable_legacy_mano_loadingenable_legacy_mano_loading()def sha(path): with Path(path).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()def write(path,value): Path(path).parent.mkdir(parents=True,exist_ok=True) Path(path).write_text(json.dumps(value,indent=2,allow_nan=False)+'\n')import torch,time,smplx,argparsefrom bimanual_vae import *torch.set_num_threads(2)def main(variant, data, mano_dir, output, device, epochs, steps_per_epoch): output.mkdir(parents=True,exist_ok=True) seed=20260927;torch.manual_seed(seed);rng=np.random.default_rng(seed);a=np.load(data,allow_pickle=False);local=aa_to_matrix(torch.tensor(a['pose_aa'],device=device)).reshape(-1,30,3,3);rot=torch.cat([local,torch.tensor(a['relative_rotation'],device=device)[:,None]],1);pos=torch.tensor(a['relative_wrist_m'],device=device);ds=a['dataset'];split=a['split'];seq=a['sequence'];included=[0,1] if variant=='joint_ego40' else [0,1,2];train=np.flatnonzero((split==0)&np.isin(ds,included));val=np.flatnonzero((split==1)&np.isin(ds,included));model=BimanualVAE(pose_only=variant=='pose_mix40').to(device);x=model.features(rot[train],pos[train]);model.input_mean.copy_(x.mean(0));model.input_std.copy_(x.std(0).clamp_min(.03));opt=torch.optim.AdamW(model.parameters(),lr=.001,weight_decay=1e-5) # Balance datasets, then recordings; long recordings cannot dominate. groups={d:{int(s):np.flatnonzero((split==0)&(ds==d)&(seq==s)) for s in np.unique(seq[(split==0)&(ds==d)])} for d in included} # Simple FK of native 16 MANO skeletal joints, differentiated without rendering meshes. offsets=[];parents=None for s in range(2): m=smplx.MANO(str(mano_dir),is_rhand=s==1,use_pca=False,flat_hand_mean=True);j=m.J_regressor@m.v_template;par=m.parents.numpy();off=j.clone();off[1:]-=j[par[1:]];off[0]=0;offsets.append(off);parents=par off=torch.stack(offsets).to(device) def fk(q): q=q[:,:30].reshape(-1,2,15,3,3);n=len(q);g=[torch.eye(3,device=device).expand(n,2,3,3)];j=[torch.zeros(n,2,3,device=device)] for k in range(1,16): p=int(parents[k]);j.append(j[p]+(g[p]@off[None,:,k,:,None]).squeeze(-1));g.append(g[p]@q[:,:,k-1]) return torch.stack(j,2) with torch.no_grad():ref=fk(rot) cfg=dict(variant=variant,seed=seed,epochs=epochs,steps_per_epoch=steps_per_epoch,batch=192,lr=.001,kl_beta=.0005,joint_weight=.25,position_scale_m=.1,balanced_dataset_and_sequence=True,included_datasets=included,selection='equal-dataset validation local FK mm + 0.25 relative position mm + relative rotation deg; test not used',data_sha256=sha(data)) write(output/f'{variant}_config.json',cfg);best=float('inf');hist=[];start=time.monotonic() for epoch in range(1,cfg['epochs']+1): model.train();sums=[] for step in range(cfg['steps_per_epoch']): ids=[] for d in included: keys=list(groups[d]);ss=rng.choice(keys,192//len(included));ids.extend(int(rng.choice(groups[d][int(s)])) for s in ss) ids=torch.tensor(ids,device=device);rr,pp,mu,lv=model(rot[ids],pos[ids]);rec=(rr-rot[ids,:model.nrot]).square().sum((-1,-2)).mean();jloss=((fk(rr)-ref[ids])/.02).square().sum(-1).mean();ploss=rec*0 if model.pose_only else ((pp-pos[ids])/.1).square().sum(-1).mean();kl=.5*(mu.square()+lv.exp()-lv-1).mean();loss=rec+.25*jloss+ploss+.0005*min(1,epoch/20)*kl;opt.zero_grad();loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),5);opt.step();sums.append(float(loss.detach())) if epoch==1 or epoch%5==0: model.eval();met=[] with torch.no_grad(): for d in included: ids=val[ds[val]==d];errs=[];pe=[];re=[] for t in range(0,len(ids),1024): ix=ids[t:t+1024];rr,pp,mu,lv=model(rot[ix],pos[ix]);errs.append((fk(rr)-ref[ix]).norm(dim=-1).mean((1,2))*1000) if not model.pose_only:pe.append((pp-pos[ix]).norm(dim=-1)*1000);rel=rr[:,30]@rot[ix,30].transpose(-1,-2);re.append(torch.acos(((rel.diagonal(dim1=-2,dim2=-1).sum(-1)-1)/2).clamp(-1+1e-7,1-1e-7))*180/torch.pi) met.append(dict(dataset=['ARCTIC','H2O','GRAB'][d],local_fk_mm=float(torch.cat(errs).mean()),relative_wrist_mm=float(torch.cat(pe).mean()) if pe else None,relative_rotation_deg=float(torch.cat(re).mean()) if re else None)) score=float(np.mean([v['local_fk_mm']+.25*(v['relative_wrist_mm'] or 0)+(v['relative_rotation_deg'] or 0) for v in met]));entry=dict(epoch=epoch,train_loss=float(np.mean(sums)),validation=met,selection_score=score,seconds=time.monotonic()-start);hist.append(entry);print(variant,json.dumps(entry),flush=True) if score<best: best=score;torch.save(dict(architecture=dict(latent_dim=40,width=384,pose_only=model.pose_only),state_dict=model.state_dict(),config=cfg,epoch=epoch,validation=met),output/f'{variant}.pt') write(output/f'{variant}_history.json',hist) print('COMPLETE',variant,sha(output/f'{variant}.pt'),flush=True)if __name__=='__main__': p=argparse.ArgumentParser(description='Original paired-hand VAE recipe with portable paths.') p.add_argument('--variant',choices=['joint_ego40','joint_mix40','pose_mix40'],default='joint_mix40') p.add_argument('--data',type=Path,required=True) p.add_argument('--mano-dir',type=Path,required=True) p.add_argument('--output',type=Path,required=True) p.add_argument('--device',default='cuda') p.add_argument('--epochs',type=int,default=60) p.add_argument('--steps-per-epoch',type=int,default=48) a=p.parse_args() if a.epochs<1 or a.steps_per_epoch<1:p.error('Training counts must be positive.') if (a.output/(a.variant+'.pt')).exists():p.error('Output checkpoint already exists; choose a new output folder.') main(a.variant,a.data,a.mano_dir,a.output,a.device,a.epochs,a.steps_per_epoch)123456789101112131415161718192021222324# Original training provenance
`original_train_pair.py`, `original_prepare_data.py`, and `original_common.py`are unchanged copies from the 2026-09-27 MiroHand P3R4 experiment. They record theexact model-training recipe and source-specific data preparation. `history.json`is the original joint_mix40 validation history. These archived scripts retainthe original machine paths and are for reference; use `../train.py` to runtraining with your own paths.
The original preparation depended on an earlier filtered ARCTIC/H2O manifest,native MANO files, raw GRAB motion, and experiment-specific benchmark exclusionlists. Those inputs are not bundled. `../DATA_FORMAT.md` defines the preparedcache that the portable trainer consumes. The original training cache SHA-256 isrecorded in `../training_config.json`.
The portable trainer changes only path/device arguments, configurable epoch/stepcounts, local JSON/hash utilities, and the MANO compatibility import. Dataset andrecording balancing, normalization, losses, optimizer, random seed, validationselection, and model code follow the original recipe. CPU smoke checks exerciseone training update and validation; they do not reproduce the full GPU run.
The original experiment trained three variants. Only joint_mix40 weights arereleased in this repository; the other variant names in the scripts are optionsfor training new models.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340[ { "epoch": 1, "train_loss": 9.445151468118032, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 12.87500286102295, "relative_wrist_mm": 163.0471954345703, "relative_rotation_deg": 51.87311553955078 }, { "dataset": "H2O", "local_fk_mm": 9.052749633789062, "relative_wrist_mm": 117.507080078125, "relative_rotation_deg": 38.650142669677734 }, { "dataset": "GRAB", "local_fk_mm": 8.72321891784668, "relative_wrist_mm": 189.7671661376953, "relative_rotation_deg": 58.388023376464844 } ], "selection_score": 99.0475378036499, "seconds": 0.3951757492031902 }, { "epoch": 5, "train_loss": 0.5073744927843412, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 7.015540599822998, "relative_wrist_mm": 60.61729431152344, "relative_rotation_deg": 38.23624038696289 }, { "dataset": "H2O", "local_fk_mm": 4.575192451477051, "relative_wrist_mm": 51.943145751953125, "relative_rotation_deg": 29.724584579467773 }, { "dataset": "GRAB", "local_fk_mm": 5.3200531005859375, "relative_wrist_mm": 54.36599349975586, "relative_rotation_deg": 44.823211669921875 } ], "selection_score": 57.14214372634888, "seconds": 1.4217542971018702 }, { "epoch": 10, "train_loss": 0.2648027865216136, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 5.106489181518555, "relative_wrist_mm": 33.648101806640625, "relative_rotation_deg": 31.729633331298828 }, { "dataset": "H2O", "local_fk_mm": 3.4149880409240723, "relative_wrist_mm": 25.74277114868164, "relative_rotation_deg": 23.669815063476562 }, { "dataset": "GRAB", "local_fk_mm": 4.339122295379639, "relative_wrist_mm": 38.02174758911133, "relative_rotation_deg": 43.17218017578125 } ], "selection_score": 45.26179440816244, "seconds": 2.826522510033101 }, { "epoch": 15, "train_loss": 0.16469275082151094, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 4.236188888549805, "relative_wrist_mm": 30.4024715423584, "relative_rotation_deg": 26.648405075073242 }, { "dataset": "H2O", "local_fk_mm": 2.940308094024658, "relative_wrist_mm": 34.45616149902344, "relative_rotation_deg": 16.92371940612793 }, { "dataset": "GRAB", "local_fk_mm": 3.87188458442688, "relative_wrist_mm": 43.58067321777344, "relative_rotation_deg": 35.69742202758789 } ], "selection_score": 39.14258488019308, "seconds": 4.37071700906381 }, { "epoch": 20, "train_loss": 0.14342589862644672, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 3.692901849746704, "relative_wrist_mm": 26.702104568481445, "relative_rotation_deg": 21.544221878051758 }, { "dataset": "H2O", "local_fk_mm": 2.599233627319336, "relative_wrist_mm": 25.14226722717285, "relative_rotation_deg": 13.099417686462402 }, { "dataset": "GRAB", "local_fk_mm": 3.521355390548706, "relative_wrist_mm": 24.10993003845215, "relative_rotation_deg": 26.255090713500977 } ], "selection_score": 29.90026553471883, "seconds": 5.522418719017878 }, { "epoch": 25, "train_loss": 0.12864494665215412, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 3.295466184616089, "relative_wrist_mm": 36.14392852783203, "relative_rotation_deg": 19.423234939575195 }, { "dataset": "H2O", "local_fk_mm": 2.3364412784576416, "relative_wrist_mm": 32.38401412963867, "relative_rotation_deg": 12.863519668579102 }, { "dataset": "GRAB", "local_fk_mm": 3.4695565700531006, "relative_wrist_mm": 37.982025146484375, "relative_rotation_deg": 25.931699752807617 } ], "selection_score": 31.315803448359173, "seconds": 6.841986288083717 }, { "epoch": 30, "train_loss": 0.08499159834658106, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 3.0357227325439453, "relative_wrist_mm": 20.172719955444336, "relative_rotation_deg": 17.05535125732422 }, { "dataset": "H2O", "local_fk_mm": 2.1297340393066406, "relative_wrist_mm": 12.941731452941895, "relative_rotation_deg": 10.320504188537598 }, { "dataset": "GRAB", "local_fk_mm": 3.1395211219787598, "relative_wrist_mm": 17.7632999420166, "relative_rotation_deg": 20.985870361328125 } ], "selection_score": 23.128713846206665, "seconds": 8.110679685138166 }, { "epoch": 35, "train_loss": 0.0695953315589577, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 2.890573740005493, "relative_wrist_mm": 18.770294189453125, "relative_rotation_deg": 16.014467239379883 }, { "dataset": "H2O", "local_fk_mm": 1.9951664209365845, "relative_wrist_mm": 11.237444877624512, "relative_rotation_deg": 9.762822151184082 }, { "dataset": "GRAB", "local_fk_mm": 2.955854654312134, "relative_wrist_mm": 16.69818878173828, "relative_rotation_deg": 19.13675308227539 } ], "selection_score": 21.477373083432514, "seconds": 9.64998462004587 }, { "epoch": 40, "train_loss": 0.07276629415961604, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 2.755661964416504, "relative_wrist_mm": 17.329029083251953, "relative_rotation_deg": 14.625399589538574 }, { "dataset": "H2O", "local_fk_mm": 1.9094189405441284, "relative_wrist_mm": 9.26237678527832, "relative_rotation_deg": 9.038466453552246 }, { "dataset": "GRAB", "local_fk_mm": 2.7325074672698975, "relative_wrist_mm": 16.747617721557617, "relative_rotation_deg": 20.136404037475586 } ], "selection_score": 20.67753811677297, "seconds": 10.801130139036104 }, { "epoch": 45, "train_loss": 0.05866521876305342, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 2.6570005416870117, "relative_wrist_mm": 16.533859252929688, "relative_rotation_deg": 13.954176902770996 }, { "dataset": "H2O", "local_fk_mm": 1.812648057937622, "relative_wrist_mm": 10.88892650604248, "relative_rotation_deg": 8.842887878417969 }, { "dataset": "GRAB", "local_fk_mm": 2.5590364933013916, "relative_wrist_mm": 19.327693939208984, "relative_rotation_deg": 18.18161964416504 } ], "selection_score": 19.898329814275105, "seconds": 12.013499305117875 }, { "epoch": 50, "train_loss": 0.05538660536209742, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 2.552030563354492, "relative_wrist_mm": 15.961709022521973, "relative_rotation_deg": 13.042522430419922 }, { "dataset": "H2O", "local_fk_mm": 1.722329020500183, "relative_wrist_mm": 7.883533000946045, "relative_rotation_deg": 8.399897575378418 }, { "dataset": "GRAB", "local_fk_mm": 2.7820262908935547, "relative_wrist_mm": 18.310850143432617, "relative_rotation_deg": 17.670961380004883 } ], "selection_score": 18.90293010075887, "seconds": 13.535741310101002 }, { "epoch": 55, "train_loss": 0.10357473092153668, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 2.5025906562805176, "relative_wrist_mm": 32.9027214050293, "relative_rotation_deg": 12.71257495880127 }, { "dataset": "H2O", "local_fk_mm": 1.7116860151290894, "relative_wrist_mm": 24.95145034790039, "relative_rotation_deg": 8.395352363586426 }, { "dataset": "GRAB", "local_fk_mm": 2.518946647644043, "relative_wrist_mm": 29.448965072631836, "relative_rotation_deg": 18.022743225097656 } ], "selection_score": 22.563226024309795, "seconds": 14.875219596084207 }, { "epoch": 60, "train_loss": 0.04643667683315774, "validation": [ { "dataset": "ARCTIC", "local_fk_mm": 2.3993451595306396, "relative_wrist_mm": 22.116172790527344, "relative_rotation_deg": 12.27881908416748 }, { "dataset": "H2O", "local_fk_mm": 1.6551059484481812, "relative_wrist_mm": 18.894102096557617, "relative_rotation_deg": 8.041049003601074 }, { "dataset": "GRAB", "local_fk_mm": 2.4477932453155518, "relative_wrist_mm": 16.990732192993164, "relative_rotation_deg": 16.812602996826172 } ], "selection_score": 19.37832240263621, "seconds": 16.251781224040315 }]1234567891011121314from pathlib import Pathimport sys,json,hashlib,inspectimport numpy as npR=Path('/SSD3/yangzijing/MiroHand_P3R4_bimanual_VAE_20260927')OLD=Path('/SSD3/yangzijing/FoundationHand-A2_P3R3_VAE_20260922')REPO=Path('/SSD2/yangzijing/egoview-v9-foundationhand-s9l10-20260901')MANO=Path('/SSD3/yangzijing/shared_dependencies/foundation_hand/pretrained/mano')sys.path.insert(0,str(REPO));inspect.getargspec=inspect.getfullargspecfrom pipeline.utils.numpy_compat import ensure_chumpy_numpy_compatensure_chumpy_numpy_compat()def read(p):return json.loads(Path(p).read_text())def write(p,x):Path(p).parent.mkdir(parents=True,exist_ok=True);Path(p).write_text(json.dumps(x,ensure_ascii=False,indent=2,allow_nan=False)+'\n')def sha(p): with Path(p).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354from common import *import collections,trimesh,smplx,torch,warningsfrom scipy.spatial.transform import Rotationwarnings.filterwarnings('ignore',category=DeprecationWarning);torch.set_num_threads(2)F=Path('/SSD3/yangzijing/ego_full_training_filter_visible_20260925');G=Path('/SSD1/wbr/datasets/GRAB_source/GRAB_unzipped')models=[smplx.MANO(str(MANO),is_rhand=s==1,use_pca=True,num_pca_comps=24,flat_hand_mean=False) for s in range(2)]ex=set(map(tuple,read(OLD/'priors/excluded_recordings.json')))for c in read('/SSD3/yangzijing/MiroHand_A6_benchmark_20260924/selection.json'):ex.add((c['dataset'],c['recording_id']))write(R/'audit/excluded_pipeline_recordings.json',sorted(ex))seqs=[];refs={};summary=collections.Counter();data=collections.defaultdict(list)def add(ds,seq,pose,rot,wrist,fids,source,split=None): pose=np.asarray(pose,np.float32).reshape(-1,2,15,3);rot=np.asarray(rot,np.float32).reshape(-1,2,3);wrist=np.asarray(wrist,np.float32);n=len(pose) good=np.isfinite(pose).all((1,2,3))&np.isfinite(rot).all((1,2))&np.isfinite(wrist).all((1,2));summary[ds+'_nonfinite_removed']+=int((~good).sum());pose,rot,wrist,fids=pose[good],rot[good],wrist[good],np.asarray(fids)[good] if not len(pose):return # Each recording contributes at most 160 evenly spaced real paired frames. ids=np.unique(np.linspace(0,len(pose)-1,min(160,len(pose))).astype(int));pose,rot,wrist,fids=pose[ids],rot[ids],wrist[ids],fids[ids] rr=Rotation.from_rotvec(rot.reshape(-1,3)).as_matrix().reshape(-1,2,3,3);relrot=rr[:,0].transpose(0,2,1)@rr[:,1];relpos=np.einsum('nji,nj->ni',rr[:,0],wrist[:,1]-wrist[:,0]);dist=np.linalg.norm(relpos,axis=-1);assert np.isfinite(relpos).all() and dist.max()<3,(ds,seq,dist.max()) # Invariant to shared camera/world rigid transform. Keep anchor for exact roundtrip. reconstructed=np.einsum('nij,nj->ni',rr[:,0],relpos)+wrist[:,0];assert np.max(abs(reconstructed-wrist[:,1]))<1e-5 if split is None: h=int(hashlib.sha256(('P3R4_20260927:'+ds+':'+seq).encode()).hexdigest()[:8],16)%10;split='test' if h==0 else 'validation' if h==1 else 'train' sid=len(seqs);seqs.append(dict(dataset=ds,recording=seq,split=split,frames=len(pose),source=source)) for k,v in dict(pose_aa=pose,relative_rotation=relrot.astype(np.float32),relative_wrist_m=relpos.astype(np.float32),anchor_rotation=rr[:,0].astype(np.float32),anchor_wrist_m=wrist[:,0],frame_ids=fids,sequence=np.full(len(pose),sid),dataset=np.full(len(pose),['ARCTIC','H2O','GRAB'].index(ds)),split=np.full(len(pose),['train','validation','test'].index(split))).items():data[k].append(v) summary[ds+'_'+split]+=len(pose)rows=[w for w in map(json.loads,(F/'unified/filtered_manifest.jsonl').open()) if w['dataset'] in ['ARCTIC','H2O'] and len(w['target_sides'])==2]groups=collections.defaultdict(list)for w in rows: rec=w['recording_id'];canonical=rec.removesuffix('/cam4') if (w['dataset'],rec) in ex or (w['dataset'],canonical) in ex:summary[w['dataset']+'_excluded_windows']+=1;continue groups[(w['dataset'],canonical)].append(w)for (ds,seq),ws in sorted(groups.items()): ar=collections.defaultdict(list);paths=[] for w in sorted(ws,key=lambda x:x['start']): p=Path(w['filtered_gt_path']);assert sha(p)==w['gt_sha256'];refs[str(p)]=w['gt_sha256'];z=np.load(p);ok=z['valid'].all(1) # Original local_pose includes the native MANO hand mean already. for k in ['local_pose_aa_rad','native_global_orient_aa_rad','joints_native_m','frame_ids']:ar[k].append(z[k][ok]) paths.append(str(p)) ar={k:np.concatenate(v) for k,v in ar.items()};add(ds,seq,ar['local_pose_aa_rad'],ar['native_global_orient_aa_rad'],ar['joints_native_m'][:,:,0],ar['frame_ids'],paths)print('EGO',dict(summary),flush=True)rootcache={};convertmax=0.for i,p in enumerate(sorted((G/'grab').glob('*/*.npz'))): a=np.load(p,allow_pickle=True);pose=[];rot=[];wrist=[];n=int(a['n_frames']);ids=np.arange(0,n,12) # 120fps to 10fps; no interpolation for s,key in enumerate(['lhand','rhand']): h=a[key].item();q=h['params'];m=models[s];local=q['hand_pose'][ids]@m.hand_components.numpy()+m.hand_mean.numpy();err=float(np.max(abs(local-(q['fullpose'][ids]+m.hand_mean.numpy()))));assert err<2e-5;convertmax=max(convertmax,err) template=G/h['vtemp'] if str(template) not in rootcache: vt=np.asarray(trimesh.load(template,process=False).vertices);assert vt.shape==(778,3);rootcache[str(template)]=m.J_regressor[0].numpy()@vt;refs[str(template)]=sha(template) pose.append(local);rot.append(q['global_orient'][ids]);wrist.append(q['transl'][ids]+rootcache[str(template)]) refs[str(p)]=sha(p);sub=p.parent.name;split='test' if sub=='s10' else 'validation' if sub=='s9' else 'train';add('GRAB',str(p.relative_to(G/'grab')).removesuffix('.npz'),np.stack(pose,1),np.stack(rot,1),np.stack(wrist,1),ids,[str(p)],split) if i%200==0:print('GRAB',i,dict(summary),flush=True)np.savez_compressed(R/'data/paired_motion.npz',**{k:np.concatenate(v) for k,v in data.items()});write(R/'data/sequences.json',seqs);write(R/'audit/source_hashes.json',refs)old=read(OLD/'priors/training_manifest_local_only.json');write(R/'audit/previous_single_vae_data.json',dict(counts=old['counts'],data_sha256=old['pose_data_sha256'],note='DexYCB and HO3D single-hand supervision is not converted into artificial paired samples'))write(R/'data/summary.json',dict(counts=dict(summary),sequences=len(seqs),paired_frames=sum(x['frames'] for x in seqs),data_sha256=sha(R/'data/paired_motion.npz'),grab_pca_fullpose_max_error_rad=convertmax,coordinate='left wrist MANO local frame; invert using anchor wrist pose in ego camera; no fake camera GT',schema='30 local SO3 rotations + relative wrist SO3 + relative wrist XYZ metres; 189D rotation6D input',sources_missing=['HIMO','Embody3D'],split='GRAB subject s1-s8 train, s9 validation, s10 test; ARCTIC/H2O deterministic sequence split 80/10/10; pipeline benchmark recordings excluded'))print('COMPLETE',read(R/'data/summary.json'),flush=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344from common import *import torch,time,smplx,argparsefrom bimanual_vae import *torch.set_num_threads(2)def main(variant): seed=20260927;torch.manual_seed(seed);rng=np.random.default_rng(seed);a=np.load(R/'data/paired_motion.npz');device='cuda';local=aa_to_matrix(torch.tensor(a['pose_aa'],device=device)).reshape(-1,30,3,3);rot=torch.cat([local,torch.tensor(a['relative_rotation'],device=device)[:,None]],1);pos=torch.tensor(a['relative_wrist_m'],device=device);ds=a['dataset'];split=a['split'];seq=a['sequence'];included=[0,1] if variant=='joint_ego40' else [0,1,2];train=np.flatnonzero((split==0)&np.isin(ds,included));val=np.flatnonzero((split==1)&np.isin(ds,included));model=BimanualVAE(pose_only=variant=='pose_mix40').to(device);x=model.features(rot[train],pos[train]);model.input_mean.copy_(x.mean(0));model.input_std.copy_(x.std(0).clamp_min(.03));opt=torch.optim.AdamW(model.parameters(),lr=.001,weight_decay=1e-5) # Balance datasets, then recordings; long recordings cannot dominate. groups={d:{int(s):np.flatnonzero((split==0)&(ds==d)&(seq==s)) for s in np.unique(seq[(split==0)&(ds==d)])} for d in included} # Simple FK of native 16 MANO skeletal joints, differentiated without rendering meshes. offsets=[];parents=None for s in range(2): m=smplx.MANO(str(MANO),is_rhand=s==1,use_pca=False,flat_hand_mean=True);j=m.J_regressor@m.v_template;par=m.parents.numpy();off=j.clone();off[1:]-=j[par[1:]];off[0]=0;offsets.append(off);parents=par off=torch.stack(offsets).to(device) def fk(q): q=q[:,:30].reshape(-1,2,15,3,3);n=len(q);g=[torch.eye(3,device=device).expand(n,2,3,3)];j=[torch.zeros(n,2,3,device=device)] for k in range(1,16): p=int(parents[k]);j.append(j[p]+(g[p]@off[None,:,k,:,None]).squeeze(-1));g.append(g[p]@q[:,:,k-1]) return torch.stack(j,2) with torch.no_grad():ref=fk(rot) cfg=dict(variant=variant,seed=seed,epochs=60,steps_per_epoch=48,batch=192,lr=.001,kl_beta=.0005,joint_weight=.25,position_scale_m=.1,balanced_dataset_and_sequence=True,included_datasets=included,selection='equal-dataset validation local FK mm + 0.25 relative position mm + relative rotation deg; test not used',data_sha256=sha(R/'data/paired_motion.npz')) write(R/'priors'/f'{variant}_config.json',cfg);best=float('inf');hist=[];start=time.monotonic() for epoch in range(1,cfg['epochs']+1): model.train();sums=[] for step in range(cfg['steps_per_epoch']): ids=[] for d in included: keys=list(groups[d]);ss=rng.choice(keys,192//len(included));ids.extend(int(rng.choice(groups[d][int(s)])) for s in ss) ids=torch.tensor(ids,device=device);rr,pp,mu,lv=model(rot[ids],pos[ids]);rec=(rr-rot[ids,:model.nrot]).square().sum((-1,-2)).mean();jloss=((fk(rr)-ref[ids])/.02).square().sum(-1).mean();ploss=rec*0 if model.pose_only else ((pp-pos[ids])/.1).square().sum(-1).mean();kl=.5*(mu.square()+lv.exp()-lv-1).mean();loss=rec+.25*jloss+ploss+.0005*min(1,epoch/20)*kl;opt.zero_grad();loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),5);opt.step();sums.append(float(loss.detach())) if epoch==1 or epoch%5==0: model.eval();met=[] with torch.no_grad(): for d in included: ids=val[ds[val]==d];errs=[];pe=[];re=[] for t in range(0,len(ids),1024): ix=ids[t:t+1024];rr,pp,mu,lv=model(rot[ix],pos[ix]);errs.append((fk(rr)-ref[ix]).norm(dim=-1).mean((1,2))*1000) if not model.pose_only:pe.append((pp-pos[ix]).norm(dim=-1)*1000);rel=rr[:,30]@rot[ix,30].transpose(-1,-2);re.append(torch.acos(((rel.diagonal(dim1=-2,dim2=-1).sum(-1)-1)/2).clamp(-1+1e-7,1-1e-7))*180/torch.pi) met.append(dict(dataset=['ARCTIC','H2O','GRAB'][d],local_fk_mm=float(torch.cat(errs).mean()),relative_wrist_mm=float(torch.cat(pe).mean()) if pe else None,relative_rotation_deg=float(torch.cat(re).mean()) if re else None)) score=float(np.mean([v['local_fk_mm']+.25*(v['relative_wrist_mm'] or 0)+(v['relative_rotation_deg'] or 0) for v in met]));entry=dict(epoch=epoch,train_loss=float(np.mean(sums)),validation=met,selection_score=score,seconds=time.monotonic()-start);hist.append(entry);print(variant,json.dumps(entry),flush=True) if score<best: best=score;torch.save(dict(architecture=dict(latent_dim=40,width=384,pose_only=model.pose_only),state_dict=model.state_dict(),config=cfg,epoch=epoch,validation=met),R/'priors'/f'{variant}.pt') write(R/'priors'/f'{variant}_history.json',hist) print('COMPLETE',variant,sha(R/'priors'/f'{variant}.pt'),flush=True)if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('variant',choices=['joint_ego40','joint_mix40','pose_mix40']);main(p.parse_args().variant)12345678910111213141516171819{ "variant": "joint_mix40", "seed": 20260927, "epochs": 60, "steps_per_epoch": 48, "batch": 192, "lr": 0.001, "kl_beta": 0.0005, "joint_weight": 0.25, "position_scale_m": 0.1, "balanced_dataset_and_sequence": true, "included_datasets": [ 0, 1, 2 ], "selection": "equal-dataset validation local FK mm + 0.25 relative position mm + relative rotation deg; test not used", "data_sha256": "456c2b8011b56552a0806836fdb2eb9fcdd397ca3693f390bb2cbb5f8ba0f06f"}1234567891011121314151617181920212223242526272829{ "passed": true, "torch": "2.6.0+cu124", "device": "cpu", "original_checkpoint_equals_safetensors": true, "original_and_safe_outputs_identical": true, "pack_rigid_transform_invariance": true, "train_only_encoding_rows": 120, "heldout_encoding_rows_excluded": 12, "augmentation_samples": 72, "distinct_recording_neighbors": 16, "latent_convex_formula_verified": true, "proper_rotation_matrices": true, "axis_angle_roundtrip": true, "test_queries_rejected": true, "original_cpu_example": { "finite_input_gradients": true, "frozen_vae": true }, "training_smoke": { "epochs": 1, "updates": 1, "batch_size": 192, "validation_completed": true, "checkpoint_saved_and_loaded": true, "finite_parameters": true, "full_retraining_performed": false }}DATA_FORMAT.mdAdded+65
README.mdAdded+158
SHA256SUMSAdded+22
augment.pyAdded+150
bimanual_vae.pyAdded+32
config.jsonAdded+47
example.pyAdded+45
hand_vae.pyAdded+38
joint_mix40.ptAdded+3
load_model.pyAdded+16
mano_compat.pyAdded+26
model.safetensorsAdded+3
provenance.jsonAdded+53
requirements-training.txtAdded+4
requirements.txtAdded+4
train.pyAdded+68
training/README.mdAdded+24
training/history.jsonAdded+340
training/original_common.pyAdded+14
training/original_prepare_data.pyAdded+54
training/original_train_pair.pyAdded+44
training_config.jsonAdded+19
validation.jsonAdded+29