Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.
Python
Optimize FlowHMR attention and hands; add optional HaMeR refinement
toyxyzf9747bdecf43
diff --git a/README.md b/README.mdindex 9c5c98c..89443b2 100644--- a/README.md+++ b/README.md@@ -125,6 +125,7 @@ do not put passwords or account tokens in the agent chat.- Save side-by-side input video and the current 3D viewport as MP4 with **File > Export Preview...** (offline models).- Inspect source-video/bone alignment in Camera Preview and display saved cameras in 3D, with optional background rotation refinement for FlowHMR/ExMR.- Save projects with separate results for each AI model.+- Reduce FlowHMR memory use with query-batched attention and optional sparse hand sampling; optional HaMeR refines fingers. See [controls and trade-offs](docs/models/FLOWHMR.md#controls) and [measured time/memory comparisons](docs/PERFORMANCE.md#flowhmr-query-batches-and-four-frame-hands-2026-11-03).- Track webcam or video input in real time with PEAR's experimental body/finger bone preview; tracking and poses may be unstable.## How it worksdiff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.jsonindex 65ae292..b3eb64f 100644--- a/SOURCE_MANIFEST.json+++ b/SOURCE_MANIFEST.json@@ -26,8 +26,8 @@},{"path": "README.md",- "bytes": 12123,- "sha256": "3a69eb100ea5a0c85eef2f436713f26a09d5f87a3c4f0cbb7af44340e9f06355"+ "bytes": 12425,+ "sha256": "0085bb68c8ea6ae8c133d37bfa960fbbc32a090f5a170ef16fb5e2b98617d42b"},{"path": "RGBMoCap.cmd",@@ -96,8 +96,8 @@},{"path": "docs/AGENT_GUIDE.md",- "bytes": 64392,- "sha256": "88380a9503b24a012ef7c5e6bdaf81f31b88ecc900f1ae6f6242a1f1fe87c74d"+ "bytes": 68225,+ "sha256": "5ea3fc662da00e09b88ffb9f7153ce74887a13b72c836d87e670e4d3be802a97"},{"path": "docs/BUILD.md",@@ -121,18 +121,18 @@},{"path": "docs/PERFORMANCE.md",- "bytes": 19258,- "sha256": "da8996dc115a98b6fa2fa872fa52cf4fe63db7ee7c81c59985b43eeb6e2d7e05"+ "bytes": 23477,+ "sha256": "9a7930c96cde25c9d56ecfe1981ccd57b1099207e408aabced2961ad6cd6fce9"},{"path": "docs/USER_GUIDE.md",- "bytes": 62771,- "sha256": "a0bead1f7dfaf60d388248098fbc8115181f6d3d8c1d90890a86d2524ebbc51d"+ "bytes": 63738,+ "sha256": "56c928d6a05e882e24fd43773fd146d440f73387b325f532a4afca7939076f33"},{"path": "docs/VALIDATION.md",- "bytes": 131403,- "sha256": "ac15b4c4d59d27c03a026cf82245112adf3b7b8c3d0b4aab28d39c98dd0c8a6d"+ "bytes": 137180,+ "sha256": "bc42cbb32f6756739822483e2d3029933b9e8228e1470684f8e91d194fa05cdb"},{"path": "docs/images/exmr-interaction-contact.png",@@ -161,8 +161,8 @@},{"path": "docs/models/FLOWHMR.md",- "bytes": 13269,- "sha256": "db85a1f7fb46f960e0732a36cddcd93776fdf7268d28f1be85f4c2ddedb61253"+ "bytes": 18530,+ "sha256": "93dcb3323fa9dfc0f3fed8079c27ef9eef07fc727f900b346ea0ef5387f6aca4"},{"path": "docs/models/GVHMR.md",@@ -1311,8 +1311,8 @@},{"path": "mocap/flow_backend.py",- "bytes": 26391,- "sha256": "35a4308ee1908cd5eae7799ac5bba0b4ff13fd45c411b33ecbbe7d76e4b2046a"+ "bytes": 29439,+ "sha256": "27853e22ba019d260ee284cb464f06dfc249ea4e91be40f486d2f945cfeb8f6d"},{"path": "mocap/flow_camera.py",@@ -1331,28 +1331,43 @@},{"path": "mocap/flow_fast_sam.py",- "bytes": 3948,- "sha256": "dd4fabe790e4f5a021a5507adf372668931264fe4d57abd47ea820149a43fe6c"+ "bytes": 5480,+ "sha256": "f01b62a52011c3d4ce1f09280224e98ef420cf485af83d5ef9b7894d6b6ecae9"},{"path": "mocap/flow_floor.py","bytes": 2009,"sha256": "5c33de610d8acfaa38ea4142a83ca979ec899e02325fe799e3b6cbf30ecff29a"},+ {+ "path": "mocap/flow_hamer.py",+ "bytes": 11120,+ "sha256": "b82861ea8496949c3b7d914a4b6eecf6400e61dcc008a188e2b7504c317a3012"+ },+ {+ "path": "mocap/flow_hamer_entry.py",+ "bytes": 524,+ "sha256": "587c42743b11046575ddf18209f481293bd4f4bad5c0197c5fa58faf0f774538"+ },+ {+ "path": "mocap/flow_hand_sampling.py",+ "bytes": 1709,+ "sha256": "6e932ef90769a7043220f28dd0b228475caedc3c9b2b98e9a71fbce8f32ad7bf"+ },{"path": "mocap/flow_placement.py",- "bytes": 9795,- "sha256": "9dc0e4b89bc409e328b7c0c33fe0d1a590e9d421b3db722db458c838c334438c"+ "bytes": 10497,+ "sha256": "4d2df2dc65e8680fc4add9d750cdcabb1d7d09e9d87167cb340de5909777de23"},{"path": "mocap/flow_sam.py",- "bytes": 6582,- "sha256": "db6fd57ca78c6dfab27142b9e99db207fcc1021933f1c4cfeb599c5fdad321ed"+ "bytes": 6713,+ "sha256": "ac4bfaa4ce2ca1caed51e2a693a9c3c39f45dc07241ed9c0e2df7a127f52200f"},{"path": "mocap/flow_sam_batch.py",- "bytes": 3002,- "sha256": "e02e6a75f7aa4a8055ff2894f70e9db34e5aca02b05c76cb08247c2a03e196b3"+ "bytes": 3520,+ "sha256": "03f5c3521a2a3752d758076db0b5fb4aaf3674c37bbfe388e041dd6620950851"},{"path": "mocap/flow_scene.py",@@ -1381,8 +1396,8 @@},{"path": "mocap/gui.py",- "bytes": 106907,- "sha256": "e2d26a91298fbca7d427a8845d83ef3a7f28e35b634592c46f9b827837a2b09a"+ "bytes": 108365,+ "sha256": "d0cd184bc15a36c9e8c2f14c31a304bed2ed4e0e5f91c70fa13bdf334d365822"},{"path": "mocap/gvhmr_attention.py",@@ -1516,8 +1531,8 @@},{"path": "mocap/model_guide.py",- "bytes": 12589,- "sha256": "6b46a04d8023377ddc5460931fc1cf1c7030dae224828cf2b89591cbe9da2e1a"+ "bytes": 13352,+ "sha256": "eadbea53fe399296eeba27669dec0e4bf557f4944dec955e93dd274cf4c4d490"},{"path": "mocap/model_session.py",@@ -1776,8 +1791,8 @@},{"path": "mocap/project_workspace_ui.py",- "bytes": 10189,- "sha256": "0577f32e583c3667d6ebb638b7687045d0f487870d2f5abc1875b83ce4d4de64"+ "bytes": 10475,+ "sha256": "f1b65c1ad389874ccf150c583347b110de6928c4b35239df6ff63bc8a54efec0"},{"path": "mocap/prompthmr_cache.py",@@ -1999,6 +2014,11 @@"bytes": 10219,"sha256": "87642b11a7a50515c634968b60f35ceebf2ba929c538a287086120869338f2a4"},+ {+ "path": "mocap/sidebar_scroll.py",+ "bytes": 1840,+ "sha256": "0ff7ad062e89f746cc0c4816775e2f6f0e600331fb0a6ba7b38961035215e3ec"+ },{"path": "mocap/single_actor.py","bytes": 3842,@@ -2111,8 +2131,8 @@},{"path": "mocap/worker.py",- "bytes": 27801,- "sha256": "f1f4f58ddeb795b32f14b2ff51fdc011f25d41501c52144041bbd022f90ed6b4"+ "bytes": 28097,+ "sha256": "883d9dde808cf27c86611cb85f0e28ffcb3541639d417d2f68c4c7e1b2d00855"},{"path": "mocap/worker_progress.py",@@ -2121,8 +2141,8 @@},{"path": "mocap/workspace_ui.py",- "bytes": 38463,- "sha256": "cc5b4f7c0924f1ba4318cbc43a53f52b7cebf75da7425c85979ff997d1999da5"+ "bytes": 39524,+ "sha256": "938c78c65d486f5a60ca63ba3a513d17963b6697ceb040b69bd9c9d3aafe36a4"},{"path": "native_compat/LICENSE",@@ -5256,8 +5276,8 @@},{"path": "third_party/FlowHMR/RGB_MOCAP_PROVENANCE.json",- "bytes": 220,- "sha256": "d11a08c86cbc344a33048d383ffb5f8f2f9462b8f036347860eaa695d1365f90"+ "bytes": 582,+ "sha256": "9196421188a003a2cd3f7a91f871f51ab39145b22f8a01f62fc9e807a8d16438"},{"path": "third_party/FlowHMR/app.py",@@ -5621,8 +5641,8 @@},{"path": "third_party/FlowHMR/flowhmr/network/hymotion_mmdit_for_v2m.py",- "bytes": 44341,- "sha256": "b562a59fb6b22c0fdcd172db39578a564502afd9548f8c8443717abfe8a23dd4"+ "bytes": 46989,+ "sha256": "d68e2779c0385139492f7c93b99e520e5fae05e1154cc1dd7714cebade4f0c9a"},{"path": "third_party/FlowHMR/flowhmr/network/mmdit/__init__.py",@@ -5654,10 +5674,15 @@"bytes": 19543,"sha256": "838d58b8c420bccac58d791c38f4f2a0d7020270b1a1f65974ce8ab635db9f5e"},+ {+ "path": "third_party/FlowHMR/flowhmr/network/mmdit/query_batched_attention.py",+ "bytes": 11710,+ "sha256": "5c41357c393fe72bc0b80235212a7ca8de6d3f3e2c88c8fd6287cfda1d832392"+ },{"path": "third_party/FlowHMR/flowhmr/network/token_refiner.py",- "bytes": 7684,- "sha256": "b7acccec001cf4a1818eb8cc90023b6f5772e5bf3758ea24c792444e9eb98636"+ "bytes": 8639,+ "sha256": "76e1011d24394a95fa199f0c345c29c65134bbe302c4ec548542779e9e00527a"},{"path": "third_party/FlowHMR/flowhmr/pipeline/__init__.py",diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.mdindex 323f5cb..3922013 100644--- a/docs/AGENT_GUIDE.md+++ b/docs/AGENT_GUIDE.md@@ -41,6 +41,12 @@ cache. The two prepared batches are in addition to the batch being consumed.The 256 MiB prepared-storage estimate is not a hard cap on whole-process RAM;retain actual memory monitoring and deterministic producer cleanup.+For FlowHMR query-batch before/after time, allocated VRAM, worker RAM and+precision limits, use the [measured comparison table](PERFORMANCE.md#flowhmr-query-batches-and-four-frame-hands-2026-11-03).+Keep warm generator measurements separate from fresh feature jobs and the+additional HaMeR child pass. HaMeR is an optional finger-accuracy refinement,+not a guarantee of better results for every video.+## Models and model filesExMR's integrated v0.1.5 uses public `pipeline.hand_boxes`, `model_inputs` and@@ -392,6 +398,13 @@ runtime dependency, source motion or contact change is part of export.## Resources and performance+`sidebar_scroll.py` routes ordinary wheel events over closed combo boxes and+number inputs into the right settings scroll area. Do not let scrolling mutate+inference/correction options and trigger model checks or viewport repainting.+Preserve native high-resolution deltas, open popup scrolling, keyboard/text/button+edits and deliberate focused Ctrl+wheel. This is scoped UI input routing, not a+model/cache/precision change or an application-wide wheel filter.+**Resource Safety** defaults on below Resource Mode. Off skips the measuredRAM/commit-headroom stop and sets the PyTorch allocator fraction to 1 (no appVRAM cap). Keep adaptive batch/path selection, actual OOM backoff/recovery,@@ -448,9 +461,50 @@ not necessarily RAM; individual CPU-loaded models can add several GiB of hostworking set. Automatic selects a path per operation, not from a guaranteedwhole-job capacity prediction. FlowHMR's Low Memory SAM batch is one even whenthe saved Adaptive Batching box is on; its GPU Hand Crops selection is retained.-The two Fast SAM switches default on for new work, preserve saved off settings,+The three Fast SAM switches default on for new work, preserve saved off settings,and only apply with Fast SAM. See [their separate measurements and output differences](PERFORMANCE.md#flowhmr-fast-sam-switches).+FlowHMR additionally uses the reviewed 256-query attention implementation for+every clip length, with FP32, unchanged visibility/RoPE and full sequence context.+Do not substitute temporal chunking or change steps/precision. Network sources+are recorded in `third_party/FlowHMR/RGB_MOCAP_PROVENANCE.json` and motion receipts.+No runtime package changes or additional compilation are needed.++The default-on `sam_hand_stride4` setting controls **4-Frame Hand Sampling**.+It is distinct from the spatial `sam_batch4` key: body features stay per frame,+hands use indices 0,4,8,... plus the last frame, and bounded CPU linear feature+interpolation fills all output frames. Keep the same indices across OOM splits,+one-frame Low Memory batches and people/take jobs. `flow_hand_sampling.py` holds+the schedule/interpolation; `flow_fast_sam.py` also supports body-only sub-batches.+The body decoder provides the first placement hips without requiring hand fusion.+Saved off is respected; an absent setting defaults on for future reconstruction,+without automatically replacing cached motion. Include the option and sampling+code in feature identities; never alias this numerical change to an older cache.+Publish no partially interpolated tokens.+Tests measured 41–49% less warm SAM feature time and 5.43→4.21 GiB allocated VRAM+at batch 16, but body/wrist positions and contacts can change too. See+[the model guide](models/FLOWHMR.md#query-batched-motion-attention-and-sparse-hands).++FlowHMR's optional `hamer` flag defaults **false** and forces `fast_sam` and+`sam_hand_stride4` true. The UI locks those dependent switches while enabled.+SAM publishes per-frame body-derived hand boxes with its feature receipt.+`flow_hamer.py` runs `flow_hamer_entry.py` in the existing **ExMR** runtime, never+imports its incompatible packages into FlowHMR, and reuses shared HaMeR/MANO+assets. It applies ExMR crops/mirroring and Gaussian rotation smoothing to+direct HaMeR finger predictions; this is not ExMR's learned HandMR inference.+HaMeR itself uses every frame, eight hand crops per batch (one with CPU-first+loading in Low Memory), without another detector. Keep invalid-hand fallback,+bounded capture/prefetch, child cancellation and atomic cache receipts intact.+Release the parent GPU model before launching the child. Preserve+`flow_prediction.pt` as the untouched FlowHMR output; optional fingers go to+`flow_hamer_prediction.pt`. `flow_placement.py` selects the source recorded by+the committed generation, not a draft checkbox value. Preserve root/body/wrist,+shape, camera and native contact tensors exactly before subsequent correction.+HaMeR's local matrix predictions map directly to SMPL-H's 15 joints per side;+mirror the left local matrices but do not add/subtract a MANO/SMPL hand mean.+Do not promise better accuracy for every video or ExMR-equivalent temporal stability. See+[HaMeR details and requirements](models/FLOWHMR.md#optional-hamer-fingers).+FlowHMR's `flow_sam_batch.py` selects 1/2/4/8/16 frames from current allocationheadroom, free RAM and resolution after loading. Preserve the legacy`sam_batch4` boolean key so saved off values stay off. The 16-frame ceiling isdiff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.mdindex 04a7615..52b8eb9 100644--- a/docs/PERFORMANCE.md+++ b/docs/PERFORMANCE.md@@ -283,6 +283,71 @@ Compilation, TensorRT, model weights and installed dependencies areunchanged. The upstream A100 report compares against an unaccelerated originalbaseline, so its 5–10× claim must not be applied to this app's previous Fast path.+### FlowHMR query batches and four-frame hands (2026-11-03)++The app now uses the validated official 256-query attention implementation for+all FlowHMR motion lengths. FP32, full key visibility, RoPE, temporal context,+checkpoint and 20 ODE steps are retained. The before/after measurements below+use identical features on the test PC (RTX 5090 32 GB, Ryzen 9 9950X, 96 GB RAM):++| Motion length (30 fps) | Original time | Query-256 time | Original / query peak allocated VRAM | Original / query worker RAM (RSS) |+| --- | ---: | ---: | ---: | ---: |+| 60 frames / 2.0 s | 0.47 s | 0.55 s | 1.83 / 1.83 GiB | 4.97 / 4.97 GiB |+| 474 frames / 15.8 s | 0.77 s | 0.90 s | 2.04 / 1.93 GiB | 4.48 / 4.99 GiB |+| 999 frames / 33.3 s | 2.16 s | 1.82 s | 2.64 / 2.07 GiB | 5.03 / 5.01 GiB |+| 4,806 frames / 160.2 s | 25.45 s | 7.97 s | 17.41 / 3.06 GiB | 4.37 / 5.04 GiB |++At 4,806 frames, this is **3.19× throughput (68.7% less time)** and+**82.4% less allocated VRAM**, while worker RSS increases about **0.67 GiB**.+Short sequences can be slightly slower. These are warm motion-generator timings+reported as medians of three runs per case, excluding model load, warmup, SAM extraction,+camera estimation, correction and export. Allocated VRAM is the PyTorch allocation+peak, not total GPU/desktop usage; RSS is the worker working set, not all processes.+These are measured differences, not minimum requirements or whole-job speedups.+The source-motion comparison found joint differences below **0.001 mm**; a+separate downstream correction comparison reached **0.674 mm / 0.202°** maximum+disagreement with unchanged contact timing. Floating-point results are not+guaranteed bit-identical.++**4-Frame Hand Sampling** is a separate, default-on Fast SAM option. Body+features and output motion still use every frame. Hand features are sampled+every four frames plus the final endpoint, then interpolated on CPU. It works+with one-frame Low Memory batches and CPU or GPU hand crops. It is independent+of the number of spatial frames processed together. Disable it to retain+every-frame hand evidence. This option does not itself run HaMeR or add a runtime dependency.++On the test PC, a 327-frame 1080×1920 clip's fresh app feature jobs took+**54.05 s off / 43.21 s on**, including model loading and decoding. Allocated+VRAM peaks were **5.43 / 4.21 GiB**. Earlier warm extraction measurements were+**20.55 / 11.33 s**; these are different timing scopes. Neither is a universal+whole-job speedup. The app integration comparison retained all 327 frames.+Query versus original attention, using identical features, differed by at most+**0.00034 mm** across source joints. Sparse versus every-frame hands differed+by **22.26 mm mean / 85.24 mm maximum** across body/wrist joints in this+upper-body clip; the all-joint maximum was **167.85 mm**. These are disagreements,+not measured accuracy losses against ground truth. The hands condition the+whole motion model, so changes are not confined to fingers or contact timing.++See [FlowHMR controls and limits](models/FLOWHMR.md#controls) and the+[integration checks](VALIDATION.md#flowhmr-query-and-hand-sampling-integration-2026-11-03).++### Optional FlowHMR HaMeR fingers (2026-11-03)++The separate default-off HaMeR option uses the existing ExMR runtime and shared+HaMeR/MANO weights. It infers every frame with ExMR crop preparation, FP16 network+execution and Gaussian rotation smoothing. It is not ExMR's learned HandMR+temporal inference. It forces four-frame SAM hand conditioning on, but does not+reduce HaMeR's own temporal sampling. It replaces fingers only and may still+produce jitter or inaccurate poses. FlowHMR body/wrists/root/shape/native contacts+remain exact before downstream correction.++A 327-frame app check measured **26.67 s** for the fresh HaMeR child pass,+including its startup/model load and video read. Peak child allocated VRAM was+**5.14 GiB**, with peak child RAM working set **1.75 GiB**. These are child-worker+figures, not combined parent/desktop RAM peaks or universal requirements. The+parent releases its GPU model before the child starts. Warm timings from earlier+standalone FP32 crop experiments have a different scope and precision.+### MAMMAThe current MAMMA adapter uses exact-coordinate ROI preprocessing, CPU checkpointdiff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.mdindex c01efbc..2f08b54 100644--- a/docs/USER_GUIDE.md+++ b/docs/USER_GUIDE.md@@ -496,7 +496,8 @@ selected result is missing, reconstruct it; the app reports it as unavailable.| **ExMR → Camera** | Static Camera for a camera that stays still without zooming; Moving Camera / SimpleVO when it moves. || **ExMR → Smooth Motion** | Reduce small changes between frames. Off keeps the unsmoothed result. || **FlowHMR → Fast SAM** | Speed up body/hand image processing with the same model files. Small numerical differences can affect motion and automatic contacts. |-| **FlowHMR → Fast SAM Acceleration** | Two independent, default-on switches: **Adaptive Batching** and **GPU Hand Crops**. Automatic selects 1, 2, 4, 8 or 16 frames from memory headroom and image size; Low Memory or disabling batching uses one frame. Used only with Fast SAM, on Reconstruct 3D. Tooltips and the [FlowHMR guide](models/FLOWHMR.md#controls) explain speed, VRAM and output differences. Batch selection and OOM retry messages appear in Console and CMD. |+| **FlowHMR → Fast SAM Acceleration** | Three default-on switches: **Adaptive Batching**, **GPU Hand Crops** and **4-Frame Hand Sampling**. Automatic selects 1, 2, 4, 8 or 16 spatial frames; Low Memory or disabling batching uses one. Four-frame hand sampling interpolates intermediate hand features: faster with less VRAM, but finger accuracy, body/wrist motion and contacts can change. Off uses every hand frame. Used only with Fast SAM, on Reconstruct 3D. Tooltips and the [FlowHMR guide](models/FLOWHMR.md#controls) explain measurements and differences. Query size, hand interval, batch selection and OOM retries appear in Console and CMD. |+| **FlowHMR → HaMeR Finger Refinement** | Default off. Aims to improve finger tracking accuracy with every-frame HaMeR inference using ExMR crops and Gaussian rotation smoothing, preserving FlowHMR body/wrists/trajectory. Enables and locks Fast SAM and 4-Frame Hand Sampling while on. Slower and may still jitter; this is not ExMR learned HandMR inference. Prepare shared HaMeR/MANO files in Model Manager. Uses the existing ExMR runtime from install.cmd. Reconstruct 3D after changing it. || **FlowHMR → Camera / Sampling** | Start with Moving / Unknown - Auto for moving or uncertain cameras. Static Camera skips camera estimation for locked footage. Explicit frame intervals control camera analysis only; denser sampling uses more memory. || **GVHMR → HTD Refine** | Improve body-motion consistency over time. Runs before FootMR when both are enabled. || **GVHMR → FootMR** | Refine ankle angles from foot observations. Separate from foot contact locking. |@@ -512,6 +513,11 @@ selected result is missing, reconstruct it; the app reports it as unavailable.| **Prepare Preview** | Rebuild mesh/skeleton previews from existing motion without running the AI model again. Useful for older projects. || **Cancel Job** | Stop queued processing; completed results are kept. |+The mouse wheel scrolls the right settings panel even above a closed selection+list or number field, without changing its value. Click/type, use keyboard arrows+or the field's buttons to edit. A focused field also accepts Ctrl+wheel. Open+selection lists retain their own normal scrolling.+Processing shows the current step, progress and elapsed time. **Step left** estimatesthe current step; **Total left** estimates the queue when timing data is available.Use **Console** for details and errors. Loading or unmeasured work shows activitydiff --git a/docs/VALIDATION.md b/docs/VALIDATION.mdindex 7a06a4f..a3a442d 100644--- a/docs/VALIDATION.md+++ b/docs/VALIDATION.md@@ -1998,3 +1998,91 @@ AI worker and source-correction implementation stayed unchanged.No clean Windows installation, other-GPU verification, long-video stability orabsolute SLAM scale/accuracy claim follows from these checks. Tracking loss,zoom/cuts, poor texture and scale drift remain possible.++## FlowHMR query and hand-sampling integration (2026-11-03)++Validation used the installed Windows runtime on the test PC, with private+projects outside the source checkout. No user project, video or model weight+was published or replaced. This initial sampling/query check preceded the+optional HaMeR integration described below.++- A 327-frame app-backend comparison completed with sparse hands on and off,+ including camera receipt handling, SAM features, query-batched generation and+ native world placement. Every stage reused its verified cache on the second+ call. Changing only hand sampling invalidated feature identity while leaving+ the camera identity unchanged.+- A 117-case CPU FP32 attention check covered local/global masks, padding and+ fully masked rows. Maximum difference from original math attention was+ 4.77e-7. Actual app features generated a 327-frame motion with a maximum+ source-joint difference of 0.00034 mm against original attention.+- Sampling/interpolation checks covered 98 frame-length/batch combinations,+ including one frame, final endpoints, maximum context and simulated batch+ allocation backoff. Body slots and sampled anchors were preserved. Actual+ SAM calls checked CPU/GPU crops, batches without a hand sample and body-pelvis+ placement before/after hand fusion; placement differences stayed below+ 0.0004 mm. Every-frame output was within repeated baseline GPU variation,+ rather than bitwise identical across separate feature calls.+- App controls defaulted on, restored saved off values and supplied the on+ default for missing legacy settings. Switching tools/toggles did not start+ inference. The three controls and explanations were inspected using the+ application's theme in an offscreen Qt widget render.+- A separate nine-frame app project completed CPU hand crops with one-frame+ batches, explicit Low Memory block offloading, query generation, native+ correction, preview generation and FBX saving. Cancelling feature extraction+ left the previous tokens intact and marked the stage pending; a retry committed+ a complete generation and removed the marker. This was a controlled+ cancellation/backoff check, not a physically exhausted-GPU test.++Timing and quality differences are in [performance measurements](PERFORMANCE.md#flowhmr-query-batches-and-four-frame-hands-2026-11-03).+These checks do not establish other-GPU performance, universal motion accuracy+or absence of long-session resource leaks.++## Optional FlowHMR HaMeR integration (2026-11-03)++Private nine- and 327-frame app-backend projects completed per-frame SAM hand+box capture, four-frame SAM conditioning, query motion generation and the+independent ExMR-runtime HaMeR pass. The direct HaMeR finger output uses ExMR+crops/rotation smoothing, not its learned temporal HandMR network. Body/root,+wrist rotations, shape and native foot contacts were bit-exact to the same+FlowHMR prediction before hand replacement. The original FlowHMR tensor remained+separate. A nine-frame run completed correction, preview and FBX saving. Turning+HaMeR off and reconstructing restored the original SAM-conditioned prediction.+The nine-frame paired contact-correction check also retained identical corrected+body/wrist/root/shape/contact tensors; only fingers differed in that test.++- A nine-frame Low Memory run exercised SAM's one-frame CPU-crop/offload path+ and HaMeR's one-hand-crop CPU-first loader. Both finished and reused verified+ feature/motion caches on repeat calls. A separate 327-frame Automatic run+ used body batches of 16 and hand batches of eight. HaMeR child resource/time+ measurements are recorded in [performance](PERFORMANCE.md#optional-flowhmr-hamer-fingers-2026-11-03).+- Controlled OOM splits retained exactly one ordered hand-box row per source+ frame. Invalid-hand fallback retained original fingers exactly. Cancelling+ the actual child before model loading preserved the previous completed hand+ cache, left no partial output and reaped the process. A malformed hand cache+ entered recovery. These do not establish physically exhausted-GPU behavior+ or long-running child-process leak freedom.+- Themed offscreen Qt checks verified default off, missing legacy flag defaults,+ saved on/off restoration, automatic Fast SAM/four-frame activation and locking,+ additional Model Manager rows and no inference on toggles. Draft checkbox+ changes retained the committed source until reconstruction.++No new runtime package, model weight or test video was distributed. Other GPUs,+clean installation and universal accuracy/stability were not established.++## Right-sidebar wheel routing (2026-11-03)++A native Windows Qt/OpenGL test (150% scaling, 773×476 logical 3D viewport,+no loaded actor or playback) sent 72 wheel events per target. Previously,+hovering the preset combo changed its value 23 times and the numeric pelvis+field 72 times, consuming the wheel without scrolling. These triggered the same+number of model-readiness checks and 3D paints. After routing to the panel, both+targets scrolled with no value changes, readiness checks or 3D paints. Measured+event p95 changed 7.42→1.72 ms for the combo and 7.94→1.03 ms for the number+field; maxima changed 8.97→3.85 ms and 9.34→1.32 ms. These are synthetic wheel+event timings, not overall FPS or a heavy-scene playback benchmark.++Additional Qt checks preserved pixel-delta behavior, open popups, focused+Ctrl+wheel, text/keyboard edits, frame/camera and idle processing state. Six+offscreen create/close cycles retained 419 handles and 34 threads; the final+repeat's RSS ranged 81.56–84.43 MiB. This short trend does not establish long-session leak freedom.+Inference, correction, preview math and installed packages were unchanged.diff --git a/docs/models/FLOWHMR.md b/docs/models/FLOWHMR.mdindex 8d17905..36c26b8 100644--- a/docs/models/FLOWHMR.md+++ b/docs/models/FLOWHMR.md@@ -40,6 +40,8 @@ replace `config.yml`, change inference settings or invalidate existing motion.| **Fast SAM** | On | Speed up feature extraction using the same supported weights. Small numerical differences can affect motion or automatic contact timings. || **Fast SAM Acceleration > Adaptive Batching** | On | Automatic selects 1, 2, 4, 8 or 16 frames from current GPU allocation headroom, free RAM and image size. Short tests of 4 to 16 frames reduced warm feature time by 16–23%; allocated VRAM rose from 3.84 to 5.43 GiB. Off and Low Memory use one frame. Small numerical differences are possible. || **Fast SAM Acceleration > GPU Hand Crops** | On | Prepare hand crops on the GPU. Tests on top of 4-frame batching measured about 8–11% less feature time, with unchanged allocated VRAM at that batch size. Image interpolation differs from CPU crops, so the resulting motion can differ slightly. |+| **Fast SAM Acceleration > 4-Frame Hand Sampling** | On | Infer hand features every four frames and linearly interpolate the intermediate features. Reduces processing time and VRAM, but finger accuracy may decrease. Body/wrist motion and automatic contacts can also change. Off infers hands every frame. |+| **HaMeR Finger Refinement** | Off | Improve finger tracking accuracy with optional every-frame HaMeR inference, ExMR hand crops and Gaussian rotation smoothing. Accuracy varies by video. Enables and locks Fast SAM and 4-Frame Hand Sampling while selected. Slower; jitter and inaccurate fingers remain possible. Requires the shared HaMeR and MANO files. || **Camera / Sampling** | Moving / Unknown - Auto | Automatically choose camera-estimation sampling when the camera moves or its behavior is uncertain. || **Camera / Sampling > Static Camera** | Optional | Skip camera estimation for a fixed camera without zooming. This path does not require the VGGT weight. || **Camera / Sampling > Every ... Frames** | Optional | Analyze the camera every 1, 2, 5, 10 or 30 frames. Denser camera sampling uses more memory. It does not reduce motion frame count. |@@ -49,7 +51,7 @@ These options apply on **Reconstruct 3D**. Fast SAM is an extraction option,not MAMMA's SAM 2.1 masks, PromptHMR's SAM2 tiny tracker or the standaloneSAM 3.1 experiments. Those checkpoints are not interchangeable.-The two acceleration switches work independently and are saved with the project.+The three acceleration switches work independently while HaMeR is off and are saved with the project.They are used only while **Fast SAM** is on. They do not lower model precision,reduce image resolution or skip motion frames. In the short validation clips,GPU crops changed final joint positions by about 1 mm at the 95th percentile,@@ -58,6 +60,74 @@ accuracy against ground truth. Speed figures describe feature extraction afterwarm-up, not the whole reconstruction, and vary with the PC and video. CUDAmemory pressure can retry with Low Memory and a smaller batch.+4-Frame Hand Sampling keeps every body and output motion frame. Its interval is+independent of Adaptive Batching: it also works with one-frame Low Memory batches+and either CPU or GPU hand crops. The final frame is sampled as an endpoint.+Feature interpolation uses up to three future frames; this is an offline option.+Saved off values are retained. New work and projects without this setting default+on for their next reconstruction; opening a cached result does not rerun inference.++### Query-batched motion attention and sparse hands++The motion generator uses **256-query attention batches for all clip lengths**,+retaining FP32, the original attention visibility, RoPE and full temporal context.+This is not a shorter temporal window. No extra package, TensorRT or native build+is required. On the test PC, a real 4,806-frame sequence's warm generator time+changed **25.45 → 7.97 s** and peak allocated VRAM **17.41 → 3.06 GiB**.+Worker RAM RSS increased **4.37 → 5.04 GiB**. For that long sequence, time fell+**68.7% (3.19× throughput)** and allocated VRAM fell **82.4%**. Short clips can+be slightly slower; these are warm generator-only measurements, not whole-job+timings or requirements. See the [before/after table and motion differences](../PERFORMANCE.md#flowhmr-query-batches-and-four-frame-hands-2026-11-03).++Independent 60/120/240-frame tests of four-frame hand sampling reduced warm SAM+feature time by **41–49%**, with allocated VRAM **5.43 → 4.21 GiB** at body batch+16. A separate 327-frame upper-body dance gave **20.55 → 11.33 s** for features;+feature-plus-generator stage sums were **21.38 → 12.11 s**. These sums exclude+initial loading, decoding, tracking, camera estimation, correction and export.+That clip's body/wrist joint disagreement averaged **22 mm**, with a maximum+**84 mm**. There is no ground-truth accuracy claim; reduced hand conditioning+can affect more than fingers. Disable the option when preserving per-frame hand+evidence matters more than speed/memory. HaMeR is an optional separate pass below.++### Optional HaMeR fingers++**HaMeR Finger Refinement** aims to improve finger tracking accuracy with a+separate hand model. Results vary by video; jitter or inaccurate fingers can+remain. It defaults off, including projects without a saved+`hamer` option. Enabling it automatically turns on Fast SAM and four-frame SAM+hand sampling; those two switches stay checked while HaMeR is on. HaMeR itself+still infers hands **every frame**. It uses hand boxes from each frame's SAM body+decoder, not interpolated boxes or another detector.++Prepare **Hand Features / HaMeR**, **HaMeR mean parameters** and **MANO Right** in+FlowHMR's Model Manager after enabling the option. These files are shared with+ExMR/HandFlow; existing verified files are reused. The normal `install.cmd`+already installs the independent ExMR runtime used for this pass. No separate+HaMeR setup or new runtime is added. MANO still requires its provider's access+and license steps; do not substitute or redistribute registered body data.++The pass uses ExMR's 2× hand crops, left-hand mirroring, FP16 network execution+and the same Gaussian rotation filter (sigma 1 frame, up to four future frames).+It does **not** run ExMR's learned temporal HandMR/body network, so it does not+promise ExMR-level quality. Only the 30 local finger rotations are replaced;+FlowHMR's body, wrist rotations, trajectory, shape and native foot contacts are+retained. Invalid or out-of-view hand crops retain FlowHMR's fingers. Filtering+does not bridge invalid-crop gaps. The untouched FlowHMR prediction is preserved+separately from the optional hand result.++This adds model loading and another full video read, and can be substantially+slower and require more VRAM than FlowHMR without HaMeR. Automatic runs at most eight hand crops per batch; Low Memory uses one+and CPU-first loading. FlowHMR's GPU weights are released before the separate+HaMeR worker starts. Console/CMD report the pass, hand batch, valid hand counts,+time and measured worker peaks. Existing OOM recovery and Resource Safety apply.+Use **Reconstruct 3D** after changing the option. Toggling alone does not replace+an already committed preview; disabling and reconstructing restores SAM hands.++Console and CMD report query size, hand interval, sampled frame count and the+selected spatial batch. Changing hand sampling requires **Reconstruct 3D** and+invalidates the affected feature/motion caches; it does not replace the currently+displayed cached result merely by toggling the checkbox.+Adaptive Batching preserves the previous batching checkbox's saved on/off value.Memory is checked again between prepared batches. CUDA allocation failures retryonly unpublished frames with a smaller batch after releasing the failed call;diff --git a/mocap/flow_backend.py b/mocap/flow_backend.pyindex bc0cd5b..9597132 100644--- a/mocap/flow_backend.py+++ b/mocap/flow_backend.py@@ -112,6 +112,9 @@ def identity(project,stage):root_state=json.loads((root/'project.json').read_text(encoding='utf-8'))selected=root_state.get('flow_options',{}).get('camera_interval',0)files={name:file_stat(project/name) for name in names if (project/name).exists()}+ from .flow_hamer import enabled as hamer_enabled,source_identity as hamer_identity+ hamer=hamer_enabled(project)+ if stage=='flowhmr' and hamer:files['flow_hand_boxes.npy']=file_stat(project/'flow_hand_boxes.npy')# Full-scene camera is shared even when each person has shorter visible takes.if stage=='flow_camera':files={'root_input':file_stat(root/'input.mp4')}@@ -129,11 +132,16 @@ def identity(project,stage):for name in ('memory_mode.py','gpu_offload.py','model_session.py'):code[name]=sha256(ROOT/'mocap'/name)if stage in ('flow_camera','flowhmr'):code['flow_camera.py']=sha256(ROOT/'mocap/flow_camera.py')if stage=='flow_features':- for name in ('flow_sam.py','flow_fast_sam.py','flow_sam_batch.py','batch_prefetch.py'):code[name]=code_hash(ROOT/'mocap'/name)+ for name in ('flow_sam.py','flow_fast_sam.py','flow_sam_batch.py','flow_hand_sampling.py','batch_prefetch.py'):code[name]=code_hash(ROOT/'mocap'/name)+ if stage=='flowhmr':+ for name in ('network/hymotion_mmdit_for_v2m.py','network/token_refiner.py','network/mmdit/query_batched_attention.py'):+ code[name]=code_hash(UPSTREAM/'FlowHMR/flowhmr'/name)if stage=='flow_features':from .flow_sam import saved_fast_sam, source_identity, acceleration_optionscode['sam_source']=source_identity(saved_fast_sam(project,state))code['sam_acceleration']=acceleration_options(project,state)+ code['hamer_boxes']=hamer+ if stage=='flowhmr' and hamer:code['hamer']=hamer_identity()import torchreturn dict(version=VERSION,stage=stage,inputs=files,camera_interval=selected if stage=='flow_camera' else None,models={key:file_stat(BY_KEY[key].path) for key in STAGE_REQUIREMENTS[stage] if not (stage=='flow_camera' and selected==-1)},@@ -222,6 +230,10 @@ def _features(project,emit,low_memory):cap=cv2.VideoCapture(str(project/'input.mp4'));cap.set(cv2.CAP_PROP_N_THREADS,2) if hasattr(cv2,'CAP_PROP_N_THREADS') else Nonefrom .flow_sam import extract_tokenstokens=torch.empty((n,3072),dtype=torch.float32);anchors=[]+ from .flow_hamer import enabled as hamer_enabled+ hand_boxes=np.empty((n,2,4),np.float32) if hamer_enabled(project) else None+ from .flow_hand_sampling import sample_indices,interpolate_hands+ hand_samples=sample_indices(n,options['sam_hand_stride4'])try:from .flow_sam_batch import current_batch_size, extract_boundedbatch_size = current_batch_size(n,state['width'],state['height'],enabled=options['sam_batch4'],@@ -229,6 +241,7 @@ def _features(project,emit,low_memory):batch_limit = batch_sizeif fast:emit('info', message=f"Fast SAM acceleration: {batch_size} frame(s) per batch; GPU hand crops {'on' if options['sam_gpu_crop'] else 'off'}.")+ emit('info', message=f"SAM hand sampling: {'every 4 frames + linear feature interpolation' if options['sam_hand_stride4'] else 'every frame'}; {len(hand_samples)}/{n} hand frames. Body features use every frame.")if options['sam_batch4'] and low_memory:emit('info', message='Low Memory: using one frame per SAM batch to reduce VRAM. GPU hand crop selection is retained.')def cpu_batches():@@ -245,9 +258,13 @@ def _features(project,emit,low_memory):if any(options.values()):batch_limit = min(batch_limit,current_batch_size(n,state['width'],state['height'],enabled=options['sam_batch4'],low_memory=low_memory,gpu_crops=options['sam_gpu_crop']))+ captured=[] if hand_boxes is not None else Nonevalues, outputs, batch_limit = extract_bounded(extractor, images, boxes[begin:begin+count],torch.from_numpy(k[None]), gpu_crops=options['sam_gpu_crop'], placement=begin<30,- limit=batch_limit,emit=emit)+ limit=batch_limit,emit=emit,+ hand_indices=(hand_samples[(hand_samples>=begin)&(hand_samples<begin+count)]-begin).tolist() if options['sam_hand_stride4'] else None,+ **({'hand_boxes':captured} if captured is not None else {}))+ if hand_boxes is not None:hand_boxes[begin:begin+count]=np.concatenate(captured)else:token, outputs = extract_tokens(extractor, images[0], boxes[begin:begin+1],torch.from_numpy(k[None]), placement=begin<30)@@ -268,6 +285,15 @@ def _features(project,emit,low_memory):cap.release()from .model_session import releaserelease(extractor)+ if options['sam_hand_stride4']:+ interpolate_hands(tokens,hand_samples)+ if not torch.isfinite(tokens).all():raise ValueError('Invalid interpolated FlowHMR features')+ if hand_boxes is not None:+ target=project/'flow_hand_boxes.npy';temporary=target.with_name(target.name+'.'+uuid.uuid4().hex+'.partial')+ try:+ with temporary.open('wb') as stream:np.save(stream,hand_boxes,allow_pickle=False)+ os.replace(temporary,target)+ finally:temporary.unlink(missing_ok=True)save_tensor(project/'flow_tokens.pt',tokens)atomic_json(project/'flow_placement.json',dict(camera_pelvis=anchors,intrinsics=k.tolist(),method='Constant X/Z placement from SAM MHR70 pelvis; native FlowHMR height and motion retained'))return project/'flow_tokens.pt'@@ -285,13 +311,16 @@ def infer(project,emit):if tuple(rt.shape)!=(n,4,4):raise ValueError('Camera and body frame counts differ')from .model_session import acquire,model_keydef build():- pipeline=build_pipeline(load_yaml(str(BY_KEY['flow_config'].path)),device='cuda',ckpt=str(checkpoint),validation_steps=20)+ config=load_yaml(str(BY_KEY['flow_config'].path))+ config['network_module_args'].update(attention_backend='query_batched',attention_query_chunk_size=256)+ pipeline=build_pipeline(config,device='cuda',ckpt=str(checkpoint),validation_steps=20)weights=load_tensor(checkpoint)weights=weights.get('model_state_dict',weights.get('state_dict',weights))if any(name not in weights or tuple(weights[name].shape)!=tuple(value.shape) for name,value in pipeline.named_parameters()):raise ValueError('FlowHMR checkpoint is missing required learned parameters. Repair its checkpoint and configuration.')return pipelinepipeline=acquire(model_key('flowhmr',checkpoint,BY_KEY['flow_config'].path),build)+ emit('info',message='FlowHMR attention: query batches of 256; FP32, full temporal context, 20 ODE steps.')emit('progress',current=0,total=20,message='FlowHMR: integrate 20 ODE steps')from .flow_camera import relative_camerawith torch.inference_mode():@@ -300,6 +329,10 @@ def infer(project,emit):validate_motion(output,n)save_tensor(project/'flow_prediction.pt',output) # untouched official predictiondel pipeline;gc.collect();torch.cuda.empty_cache()+ from .flow_hamer import enabled as hamer_enabled,refine as refine_hands+ if hamer_enabled(project):+ output=refine_hands(project,output,emit)+ validate_motion(output,n);save_tensor(project/'flow_hamer_prediction.pt',output)placement=json.loads((project/'flow_placement.json').read_text(encoding='utf-8'))anchors=np.asarray(placement['camera_pelvis'],float)offset=np.zeros(3,np.float32)@@ -318,7 +351,9 @@ def infer(project,emit):placed['scene_offset']=torch.from_numpy(offset)placed['source_representation']='smplh';placed['flow_version']=VERSIONsave_tensor(project/'hmr4d_results.pt',placed)- atomic_json(project/'initial_sources.json',{name:file_stat(project/name) for name in ('flow_prediction.pt','flow_tokens.pt','flow_camera.npz','flow_placement.json','tracking.npz')})+ sources=['flow_prediction.pt','flow_tokens.pt','flow_camera.npz','flow_placement.json','tracking.npz']+ if hamer_enabled(project):sources.append('flow_hamer_prediction.pt')+ atomic_json(project/'initial_sources.json',{name:file_stat(project/name) for name in sources})return project/'hmr4d_results.pt'@@ -335,6 +370,10 @@ def run_stage(project,stage,result,emit,force=False):if result not in ('auto','initial','corrected_initial'):raise ValueError('FlowHMR supports original or corrected original motion only')static=(stage=='flow_camera' and json.loads((scene_root(project)/'project.json').read_text(encoding='utf-8')).get('flow_options',{}).get('camera_interval',0)==-1)absent=[] if static else missing(stage)+ from .flow_hamer import enabled as hamer_enabled,MODEL_KEYS+ if stage in ('flow_features','flowhmr') and hamer_enabled(project):+ from .models import BY_KEY,ready+ absent += [BY_KEY[k] for k in MODEL_KEYS if not ready(BY_KEY[k])]if absent:raise ValueError('Open FlowHMR Model Manager and prepare: '+', '.join(m.name for m in absent))state=json.loads((project/'project.json').read_text(encoding='utf-8'))signature=identity(project,stage)@@ -380,6 +419,9 @@ def run_stage(project,stage,result,emit,force=False):if stage=='flow_camera' and root!=project:outputs.append('flow_camera_sources.json')if stage=='flow_features':outputs.append('flow_placement.json')if stage=='flowhmr':outputs+=['flow_prediction.pt','initial_sources.json','flow_world.json']+ if hamer_enabled(project):+ if stage=='flow_features':outputs.append('flow_hand_boxes.npy')+ if stage=='flowhmr':outputs+=['flow_hamer_prediction.pt','flow_hamer_hands.npz','flow_hamer_receipt.json']committed_identity=identity(project,stage)if stage=='flow_features' and committed_identity!=signature:raise RuntimeError('SAM inputs or settings changed during extraction. Reconstruct 3D again; this extraction was not committed.')diff --git a/mocap/flow_fast_sam.py b/mocap/flow_fast_sam.pyindex ce7ecb6..afd4d29 100644--- a/mocap/flow_fast_sam.py+++ b/mocap/flow_fast_sam.py@@ -23,7 +23,7 @@ def merge_batches(batches):return merged-def extract_batch(extractor, images, boxes, intrinsics, gpu_crops=False, placement=False):+def extract_batch(extractor, images, boxes, intrinsics, gpu_crops=False, placement=False, hand_indices=None, hand_boxes=None):import numpy as npimport torchfrom sam_3d_body.sam_3d_body_estimator import prepare_batch, recursive_to@@ -34,6 +34,12 @@ def extract_batch(extractor, images, boxes, intrinsics, gpu_crops=False, placemeraise ValueError('Fast SAM requires one tracked body per frame, in batches of at most sixteen')if any(image.shape != images[0].shape for image in images):raise ValueError('Fast SAM frame sizes must match')+ sampled = np.arange(count) if hand_indices is None else np.asarray(hand_indices)+ if (sampled.ndim != 1 or (len(sampled) and (sampled.dtype.kind not in 'iu'+ or sampled[0] < 0 or sampled[-1] >= count or np.any(np.diff(sampled) <= 0)))):+ raise ValueError('Hand sample indices must be sorted unique frame indices within this batch')+ sampled = sampled.astype(np.int64)+ sparse = len(sampled) != countestimator = extractor.estimatormodel = estimator.modelbody, hands = extractor._flow_fast_collectors@@ -41,8 +47,11 @@ def extract_batch(extractor, images, boxes, intrinsics, gpu_crops=False, placemehands.clear()def prepare_hands(image, left, right, camera):+ if hand_boxes is not None:hand_boxes.append(np.stack((left,right),axis=1).copy())+ selected = images if hand_indices is None else [images[i] for i in sampled]+ if hand_indices is not None:left, right = left[sampled].copy(), right[sampled].copy()if gpu_crops:- return _prepare_hand_batches_gpu(np.stack(images), left, right, camera,+ return _prepare_hand_batches_gpu(np.stack(selected), left, right, camera,output_size=(model.cfg.MODEL.IMAGE_SIZE[1], model.cfg.MODEL.IMAGE_SIZE[0]), padding=.9,device=camera.device)flipped = left.copy()@@ -50,9 +59,9 @@ def extract_batch(extractor, images, boxes, intrinsics, gpu_crops=False, placemeflipped[:, 0] = width - left[:, 2] - 1flipped[:, 2] = width - left[:, 0] - 1left_batch = merge_batches([prepare_batch(frame[:, ::-1], estimator.transform_hand,- flipped[i:i+1], cam_int=camera.clone()) for i, frame in enumerate(images)])+ flipped[i:i+1], cam_int=camera.clone()) for i, frame in enumerate(selected)])right_batch = merge_batches([prepare_batch(frame, estimator.transform_hand,- right[i:i+1], cam_int=camera.clone()) for i, frame in enumerate(images)])+ right[i:i+1], cam_int=camera.clone()) for i, frame in enumerate(selected)])return recursive_to(left_batch, camera.device), recursive_to(right_batch, camera.device), flippedtry:@@ -62,16 +71,28 @@ def extract_batch(extractor, images, boxes, intrinsics, gpu_crops=False, placemebatch = recursive_to(batch, 'cuda')model._initialize_batch(batch)batch['cam_int'] = intrinsics.to(batch['img']).clone()- output = model.run_inference(images[0], batch, inference_type='full',+ output = model.run_inference(images[0], batch, inference_type='full' if len(sampled) else 'body',transform_hand=estimator.transform_hand, thresh_wrist_angle=estimator.thresh_wrist_angle,- hand_batch_preparer=prepare_hands, features_only=not placement)- if len(body) != 1 or len(hands) != 1 or len(body[0]) != count or len(hands[0]) != count * 2:+ hand_batch_preparer=prepare_hands, features_only=sparse or not placement)+ if hand_boxes is not None and not len(sampled):+ left,right=model._get_hand_box(output,batch)+ hand_boxes.append(np.stack((left,right),axis=1).copy())+ if (len(body) != 1 or len(body[0]) != count or len(hands) != bool(len(sampled))+ or (len(sampled) and len(hands[0]) != len(sampled) * 2)):raise ValueError('Fast SAM returned incomplete body/hand features')- tokens = torch.stack([torch.cat((body[0][i, 0], hands[0][i, 0], hands[0][count+i, 0]))- for i in range(count)]).float().cpu()+ if not sparse:+ tokens = torch.stack([torch.cat((body[0][i,0],hands[0][i,0],hands[0][count+i,0]))+ for i in range(count)]).float().cpu()+ else:+ tokens = torch.zeros((count,3072),dtype=torch.float32)+ tokens[:,:1024] = body[0][:,0].float().cpu()+ if len(sampled):+ tokens[sampled,1024:] = torch.cat((hands[0][:len(sampled),0],hands[0][len(sampled):,0]),dim=-1).float().cpu()people = []if placement:- pose = output[0]['mhr']+ # Sparse features stop before hand fusion. Pelvis placement uses the+ # body decoder's MHR hips, which do not depend on finger fusion.+ pose = (output if not len(sampled) else output[0])['mhr']joints = pose['pred_keypoints_3d'].detach().cpu().numpy()camera = pose['pred_cam_t'].detach().cpu().numpy()people = [dict(pred_keypoints_3d=joints[i], pred_cam_t=camera[i]) for i in range(count)]diff --git a/mocap/flow_hamer.py b/mocap/flow_hamer.pynew file mode 100644index 0000000..9170d98--- /dev/null+++ b/mocap/flow_hamer.py@@ -0,0 +1,180 @@+"""Optional finger-only HaMeR pass, isolated from FlowHMR's Python runtime."""+from pathlib import Path+import json,os,subprocess,uuid,zipfile+from .paths import ROOT,UPSTREAM++MODEL_KEYS=('hand_hamer','hand_mean','mano_right')+++def enabled(project):+ from .flow_sam import saved_options+ return saved_options(project,json.loads((Path(project)/'project.json').read_text(encoding='utf-8')))['hamer']+++def prediction_name(project,generated=False):+ if generated:use_hamer=enabled(project)+ else:+ try:use_hamer=bool(json.loads((Path(project)/'flowhmr_receipt.json').read_text(encoding='utf-8'))['identity']['code'].get('hamer'))+ except (OSError,ValueError,KeyError,TypeError):use_hamer=False+ return 'flow_hamer_prediction.pt' if use_hamer else 'flow_prediction.pt'+++def source_identity():+ from .resource_cache import code_hash+ from .models import BY_KEY+ from .result_artifacts import file_stat+ from .runtime_registry import PROFILES+ files=[ROOT/'mocap/flow_hamer.py',ROOT/'mocap/flow_hamer_entry.py',+ ROOT/'mocap/exmr_backend.py',UPSTREAM/'ExMR/configs/hamer_model_config.yaml',+ UPSTREAM/'ExMR/exmr/preprocessing/hand_features.py',UPSTREAM/'ExMR/exmr/geometry/smoothing.py']+ files+=sorted((UPSTREAM/'ExMR/third_party/hamer/hamer').rglob('*.py'))+ return dict(version=1,code={str(p.relative_to(ROOT)):code_hash(p) for p in files},+ models={k:file_stat(BY_KEY[k].path) for k in MODEL_KEYS},runtime=PROFILES['exmr'],+ hands='every frame, ExMR crops, FP16 network, Gaussian rotation sigma=1 frame')+++def hand_identity(project):+ from .result_artifacts import file_stat+ return dict(source=source_identity(),inputs={n:file_stat(Path(project)/n) for n in ('input.mp4','flow_hand_boxes.npy')})+++def load_hands(project,n):+ import numpy as np+ with np.load(Path(project)/'flow_hamer_hands.npz',allow_pickle=False) as z:+ r=z['rotations'].copy();valid=z['valid'].copy()+ if r.shape!=(n,2,15,3,3) or valid.shape!=(n,2) or valid.dtype!=bool or not np.isfinite(r).all():+ raise ValueError('Invalid HaMeR finger cache')+ if np.max(np.abs(r.swapaxes(-1,-2)@r-np.eye(3)))>2e-4 or np.min(np.linalg.det(r))<.999:+ raise ValueError('Invalid HaMeR finger rotations')+ return r,valid+++def refine(project,output,emit):+ import torch,numpy as np+ from .model_session import current+ from .result_artifacts import file_stat+ project=Path(project);n=output['rot6d'].shape[1];identity=hand_identity(project)+ receipt=project/'flow_hamer_receipt.json';payload=project/'flow_hamer_hands.npz';cached=False+ try:+ value=json.loads(receipt.read_text(encoding='utf-8'))+ cached=value['identity']==identity and value['output']==file_stat(payload)+ if cached:load_hands(project,n)+ except (OSError,ValueError,KeyError,TypeError,EOFError,zipfile.BadZipFile):cached=False+ if not cached:+ # Do not hold FlowHMR weights while the independent ExMR worker runs.+ session=current()+ if session is not None:session.discard()+ import gc+ gc.collect();torch.cuda.empty_cache()+ python=ROOT/'runtime_exmr/python.exe'+ if not python.is_file():python=ROOT/'.venv-exmr/Scripts/python.exe'+ if not python.is_file():raise RuntimeError('HaMeR needs the base ExMR runtime. Run install.cmd to repair it.')+ emit('info',message='FlowHMR HaMeR: every-frame fingers; ExMR crops and Gaussian smoothing. Body, wrists and trajectory are retained.')+ command=[str(python),'-I','-X','utf8',str(ROOT/'mocap/flow_hamer_entry.py'),str(project)]+ from collections import deque+ tail=deque(maxlen=20)+ with subprocess.Popen(command,cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,+ text=True,encoding='utf-8',errors='replace',creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0)) as child:+ try:+ for line in child.stdout:+ tail.append(line[-1000:])+ if line.startswith('@@FLOW_HAND@@'):+ event=json.loads(line[len('@@FLOW_HAND@@'):]);kind=event.pop('type');emit(kind,**event)+ if child.wait():raise RuntimeError('FlowHMR HaMeR failed:\n'+''.join(tail)[-4000:])+ except BaseException:+ child.kill();child.wait();raise+ if hand_identity(project)!=identity:raise RuntimeError('HaMeR inputs changed during inference. Reconstruct 3D again.')+ r,valid=load_hands(project,n)+ result=dict(output);result['rot6d']=output['rot6d'].clone()+ for side,offset in enumerate((22,37)):+ pose=torch.from_numpy(r[:,side,:,:,:2].reshape(n,15,6).astype(np.float32))+ result['rot6d'][0,valid[:,side],offset:offset+15]=pose[valid[:,side]]+ result['body_rot6d']=result['rot6d'][:,:,1:]+ result.pop('local_joints_positions',None)+ emit('info',message=f'FlowHMR HaMeR: {int(valid[:,0].sum())}/{n} left and {int(valid[:,1].sum())}/{n} right hand frames; unavailable crops retain FlowHMR fingers.'+(' Verified hand cache reused.' if cached else ''))+ return result+++def run(project,emit):+ """Called only by the separate pinned ExMR runtime."""+ import cv2,numpy as np,torch,gc,time,psutil+ started=time.monotonic()+ from scipy.spatial.transform import Rotation+ from .storage import atomic_json+ from .result_artifacts import file_stat+ from .memory_mode import run as memory_run+ from .model_session import set_memory_budget+ from .compute_policy import configure_worker_cpu+ project=Path(project).resolve();state=json.loads((project/'project.json').read_text(encoding='utf-8'));n=state['frames']+ if state.get('pipeline',{}).get('model')!='flowhmr' or not enabled(project) or not 1<=n<=5000:+ raise ValueError('Invalid FlowHMR HaMeR project')+ identity=hand_identity(project)+ boxes=np.load(project/'flow_hand_boxes.npy',allow_pickle=False)+ if boxes.shape!=(n,2,4):raise ValueError('SAM hand boxes do not match the motion')+ torch.set_num_threads(configure_worker_cpu('exmr_features'))+ if not torch.cuda.is_available():raise RuntimeError('HaMeR requires a compatible NVIDIA GPU')+ free,total=torch.cuda.mem_get_info();set_memory_budget(free,total)+ from .exmr_backend import activate,prepare_mano+ root,weights=activate();prepare_mano(root,weights)+ from exmr.preprocessing.hand_features import HamerHandFeatures,_expand_to_aspect_ratio,_crop_hand+ from exmr.geometry.smoothing import gaussian_smooth_rotations+ from .batch_prefetch import batch_source+ W,H=state['width'],state['height'];size=boxes[:,:,2:]-boxes[:,:,:2]+ clipped=np.maximum(0,np.minimum(boxes[:,:,2:],[W,H])-np.maximum(boxes[:,:,:2],0))+ valid=np.isfinite(boxes).all(-1)&(size.min(-1)>2)&(clipped.min(-1)>=4)&(clipped.prod(-1)/np.maximum(size.prod(-1),1)>=.1)+ def infer(low):+ emit('progress',current=0,total=n,phase='hamer',message='Load HaMeR finger model')+ model=HamerHandFeatures(weights/'hamer',fp16=True,batch_size=4,num_workers=0,low_memory=low)+ rotations=np.tile(np.eye(3,dtype=np.float32),(n,2,15,1,1));batch_size=1 if low else 8+ emit('info',message=f'HaMeR fingers: batch {batch_size} hand crop(s); FP16 network; ExMR crops; rotation Gaussian sigma=1 frame.')+ try:+ cfg=model.cfg;mean=255*np.asarray(cfg.MODEL.IMAGE_MEAN);std=255*np.asarray(cfg.MODEL.IMAGE_STD)+ def batches():+ cap=cv2.VideoCapture(str(project/'input.mp4'));pending=[]+ try:+ for i in range(n):+ ok,img=cap.read()+ if not ok:raise ValueError(f'Cannot decode HaMeR frame {i+1}')+ for side in np.flatnonzero(valid[i]):+ b=boxes[i,side];center=(b[2:]+b[:2])/2+ scale=_expand_to_aspect_ratio(2*(b[2:]-b[:2]),cfg.MODEL.BBOX_SHAPE).max()+ crop=_crop_hand(img.copy(),*center,scale,cfg.MODEL.IMAGE_SIZE,flip=side==0)+ crop=crop[:,:,::-1].transpose(2,0,1).astype(np.float32)+ pending.append((i,int(side),((crop-mean[:,None,None])/std[:,None,None]).astype(np.float32)))+ if len(pending)==batch_size:yield pending;pending=[]+ if cap.read()[0]:raise ValueError('HaMeR video frame count differs from the project')+ if pending:yield pending+ finally:cap.release()+ with batch_source(batches(),batch_bytes=batch_size*3*256*256*4) as items,torch.inference_mode():+ for batch in items:+ image=torch.from_numpy(np.stack([x[2] for x in batch])).cuda()+ with torch.autocast('cuda',dtype=torch.float16):+ features=model.model.backbone(image[:,:,:,32:-32]);params,_,_=model.model.mano_head(features)+ hand=params['hand_pose'].float().cpu().numpy()+ for k,(i,side,_) in enumerate(batch):+ r=hand[k]+ if side==0:+ mirror=np.diag([-1.,1.,1.]);r=mirror@r@mirror+ rotations[i,side]=Rotation.from_matrix(r).as_matrix()+ model._tokens=None+ emit('progress',current=batch[-1][0]+1,total=n,phase='hamer',message='HaMeR: infer every-frame fingers')+ finally:+ model.close();del model;gc.collect();torch.cuda.empty_cache()+ return rotations+ rotations=memory_run('FlowHMR HaMeR fingers',infer,5.5,emit) if valid.any() else np.tile(np.eye(3,dtype=np.float32),(n,2,15,1,1))+ for side in range(2):+ edges=np.diff(np.r_[False,valid[:,side],False].astype(np.int8));starts=np.flatnonzero(edges==1);stops=np.flatnonzero(edges==-1)+ for a,b in zip(starts,stops):+ aa=Rotation.from_matrix(rotations[a:b,side].reshape(-1,3,3)).as_rotvec().reshape(1,b-a,45)+ with torch.inference_mode():smoothed=gaussian_smooth_rotations(torch.from_numpy(aa.astype(np.float32)),sigma=1.,dim=-2)+ rotations[a:b,side]=Rotation.from_rotvec(smoothed.numpy().reshape(-1,3)).as_matrix().reshape(b-a,15,3,3)+ if hand_identity(project)!=identity:raise RuntimeError('HaMeR inputs changed before commit')+ target=project/'flow_hamer_hands.npz';temp=target.with_name(target.name+'.'+uuid.uuid4().hex+'.partial')+ try:+ with temp.open('wb') as f:np.savez(f,rotations=rotations,valid=valid)+ os.replace(temp,target)+ finally:temp.unlink(missing_ok=True)+ load_hands(project,n)+ atomic_json(project/'flow_hamer_receipt.json',dict(identity=identity,output=file_stat(target)))+ emit('progress',current=n,total=n,phase='hamer',message='HaMeR finger smoothing complete')+ emit('info',message=f'HaMeR finger pass: {time.monotonic()-started:.2f} s; peak allocated VRAM {torch.cuda.max_memory_allocated()/2**30:.2f} GiB; peak worker RAM {psutil.Process().memory_info().peak_wset/2**30:.2f} GiB.')diff --git a/mocap/flow_hamer_entry.py b/mocap/flow_hamer_entry.pynew file mode 100644index 0000000..3735cc2--- /dev/null+++ b/mocap/flow_hamer_entry.py@@ -0,0 +1,11 @@+"""Private optional FlowHMR HaMeR entry point in the existing ExMR runtime."""+from pathlib import Path+import sys,json+sys.dont_write_bytecode=True+root=Path(__file__).resolve().parents[1];sys.path.insert(0,str(root))+from mocap.runtime_registry import activate+activate(root,'exmr')+from mocap.flow_hamer import run+def emit(kind,**value):print('@@FLOW_HAND@@'+json.dumps(dict(type=kind,**value)),flush=True)+if len(sys.argv)!=2:raise ValueError('An explicit FlowHMR project path is required')+run(Path(sys.argv[1]),emit)diff --git a/mocap/flow_hand_sampling.py b/mocap/flow_hand_sampling.pynew file mode 100644index 0000000..44c3ba8--- /dev/null+++ b/mocap/flow_hand_sampling.py@@ -0,0 +1,31 @@+"""Four-frame hand conditioning; body frames and generator context stay intact."""+++def sample_indices(frames, enabled):+ import numpy as np+ if isinstance(frames,bool) or not isinstance(frames,int) or frames<1:+ raise ValueError('Hand sampling requires a positive frame count')+ if not isinstance(enabled,bool):raise ValueError('Hand sampling must be on or off')+ return np.unique(np.r_[np.arange(0,frames,4),frames-1]) if enabled else np.arange(frames)+++def interpolate_hands(tokens, indices):+ """Fill hand slots only, in bounded CPU blocks with original anchor tokens."""+ import torch+ if tokens.device.type!='cpu' or tokens.dtype!=torch.float32 or tokens.ndim!=2 or tokens.shape[1]!=3072:+ raise ValueError('Hand interpolation requires CPU float32 body/hand conditioning')+ indices=torch.as_tensor(indices,dtype=torch.long)+ n=len(tokens)+ if (not n or indices.ndim!=1 or not len(indices) or indices[0]!=0 or indices[-1]!=n-1+ or (len(indices)>1 and not bool((indices[1:]>indices[:-1]).all()))):+ raise ValueError('Hand interpolation anchors must cover both endpoints in order')+ anchors=tokens[indices,1024:].clone()+ if not torch.isfinite(anchors).all():raise ValueError('Invalid sampled hand features')+ for start in range(0,n,256):+ at=torch.arange(start,min(n,start+256))+ left=(torch.searchsorted(indices,at,right=True)-1).clamp_min(0)+ right=(left+1).clamp_max(len(indices)-1)+ span=indices[right]-indices[left]+ weight=(at-indices[left]).float()/span.clamp_min(1)+ tokens[start:start+len(at),1024:]=anchors[left]*(1-weight[:,None])+anchors[right]*weight[:,None]+ return tokensdiff --git a/mocap/flow_placement.py b/mocap/flow_placement.pyindex c89792c..b49bbbb 100644--- a/mocap/flow_placement.py+++ b/mocap/flow_placement.py@@ -48,12 +48,15 @@ def placement_fit(pelvis,anchors,cameras,scene_first):anchor_residual_m=dict(mean=float(np.linalg.norm(residual,axis=1).mean()),maximum=float(np.linalg.norm(residual,axis=1).max())))-def context(project):+def context(project,generated=False):from .flow_backend import scene_rootfrom .models import BY_KEYproject=Path(project);root=scene_root(project)state=json.loads((project/'project.json').read_text(encoding='utf-8'))inputs={name:file_stat(project/name) for name in ('flow_prediction.pt','flow_placement.json','flow_camera.npz','tracking.npz')}+ from .flow_hamer import prediction_name+ selected=prediction_name(project,generated=generated)+ if selected!='flow_prediction.pt':inputs[selected]=file_stat(project/selected)inputs['scene_camera']=file_stat(root/'flow_camera.npz')return dict(version=VERSION,inputs=inputs,frames=state['frames'],take=state.get('person_frames'),model=(file_stat(BY_KEY['smplh'].path) if BY_KEY['smplh'].path.exists() else json.loads((project/'flow_world.json').read_text(encoding='utf-8'))['context']['model']))@@ -79,7 +82,11 @@ def prediction_current(project):project=Path(project)try:record=json.loads((project/'flowhmr_receipt.json').read_text(encoding='utf-8'))- return not (project/'flowhmr_pending.json').exists() and record['identity']==identity(project,'flowhmr') and record['outputs']['flow_prediction.pt']==file_stat(project/'flow_prediction.pt')+ from .flow_hamer import prediction_name+ selected=prediction_name(project)+ return (not (project/'flowhmr_pending.json').exists() and record['identity']==identity(project,'flowhmr')+ and record['outputs']['flow_prediction.pt']==file_stat(project/'flow_prediction.pt')+ and (selected=='flow_prediction.pt' or record['outputs'][selected]==file_stat(project/selected)))except (OSError,ValueError,KeyError,TypeError):return False@@ -93,7 +100,7 @@ def ensure(project,generated=False,body=None):if current(project):return Falseif not generated and not prediction_current(project):raise ValueError('FlowHMR prediction no longer matches its camera/features/models. Reconstruct 3D before rebuilding placement.')- before=context(project);root=scene_root(project)+ before=context(project,generated=generated);root=scene_root(project)state=json.loads((project/'project.json').read_text(encoding='utf-8'));n=state['frames']with np.load(root/'flow_camera.npz',allow_pickle=False) as data:scene_first=data['camera_RT_yup'][0,:3,:3].copy()with np.load(project/'flow_camera.npz',allow_pickle=False) as data:cameras=data['camera_RT_yup'].copy()@@ -102,7 +109,8 @@ def ensure(project,generated=False,body=None):with np.load(root/'flow_camera.npz',allow_pickle=False) as data:if end-begin!=n or not np.array_equal(cameras,data['camera_RT_yup'][begin:end]):raise ValueError('Person take does not use the matching shared scene camera slice')- raw=load_tensor(project/'flow_prediction.pt');validate_motion(raw,n)+ from .flow_hamer import prediction_name+ raw=load_tensor(project/prediction_name(project,generated=generated));validate_motion(raw,n)body=body if body is not None else SMPLSkeleton(model_path=str(BY_KEY['smplh'].path))with torch.inference_mode():rest=body.compute_j_shaped(raw['shapes'].reshape(1,16))[0,0].numpy()pelvis=raw['trans'][0].numpy()+rest@@ -121,15 +129,17 @@ def ensure(project,generated=False,body=None):placed.update(scene_offset=offset,source_representation='smplh',flow_version=1,placement_version=VERSION)validate_motion(placed,n)atomic_json(project/'flow_world_pending.json',dict(version=VERSION))- if before!=context(project):raise ValueError('FlowHMR placement inputs changed; retry Prepare Preview.')+ if before!=context(project,generated=generated):raise ValueError('FlowHMR placement inputs changed; retry Prepare Preview.')save_tensor(project/'hmr4d_results.pt',placed)record=dict(context=before,output=file_stat(project/'hmr4d_results.pt'),camera_height=fit['camera_height'],scene_basis=fit['scene_basis'].tolist(),rotation=fit['rotation'].tolist(),offset=fit['offset'].tolist(),anchor_residual_m=fit['anchor_residual_m'],intrinsics=anchors['intrinsics'],method='Official WV yaw; shared scene basis; rigid XZ offset; native height retained')- if before!=context(project):raise ValueError('FlowHMR inputs changed during placement commit; retry Prepare Preview.')+ if before!=context(project,generated=generated):raise ValueError('FlowHMR inputs changed during placement commit; retry Prepare Preview.')atomic_json(project/'flow_world.json',record)sources={name:file_stat(project/name) for name in ('flow_prediction.pt','flow_tokens.pt','flow_camera.npz','flow_placement.json','tracking.npz','flow_world.json')}+ selected=prediction_name(project,generated=generated)+ if selected!='flow_prediction.pt':sources[selected]=file_stat(project/selected)atomic_json(project/'initial_sources.json',sources)# The original generator identity and immutable prediction remain reusable.receipt=project/'flowhmr_receipt.json'diff --git a/mocap/flow_sam.py b/mocap/flow_sam.pyindex 7c7f106..dab8b12 100644--- a/mocap/flow_sam.py+++ b/mocap/flow_sam.py@@ -23,11 +23,12 @@ def saved_options(project, state):if project.resolve().is_relative_to(root) and (root / 'people.json').is_file():options = json.loads((root / 'project.json').read_text(encoding='utf-8')).get('flow_options', options)result = {}- for key in ('fast_sam', 'sam_batch4', 'sam_gpu_crop'):- value = options.get(key, True)+ for key in ('fast_sam', 'sam_batch4', 'sam_gpu_crop', 'sam_hand_stride4', 'hamer'):+ value = options.get(key, key!='hamer')if not isinstance(value, bool):raise ValueError('Invalid FlowHMR setting: '+key+'; expected on or off')result[key] = value+ if result['hamer']:result.update(fast_sam=True,sam_hand_stride4=True)return result@@ -37,7 +38,7 @@ def saved_fast_sam(project, state):def acceleration_options(project, state):options = saved_options(project, state)- return {key: options['fast_sam'] and options[key] for key in ('sam_batch4', 'sam_gpu_crop')}+ return {key: options['fast_sam'] and options[key] for key in ('sam_batch4', 'sam_gpu_crop', 'sam_hand_stride4')}def source_root(fast):diff --git a/mocap/flow_sam_batch.py b/mocap/flow_sam_batch.pyindex 08d8b3d..1add606 100644--- a/mocap/flow_sam_batch.py+++ b/mocap/flow_sam_batch.py@@ -39,7 +39,7 @@ def current_batch_size(frames, width, height, *, enabled=True, low_memory=False,enabled=enabled,low_memory=low_memory,gpu_crops=gpu_crops)-def extract_bounded(extractor,images,boxes,intrinsics,*,gpu_crops,placement,limit,emit):+def extract_bounded(extractor,images,boxes,intrinsics,*,gpu_crops,placement,limit,emit,hand_indices=None,hand_boxes=None):"""Retry only an unpublished sub-batch after releasing the OOM traceback."""import torch,gcfrom .flow_fast_sam import extract_batch@@ -47,9 +47,12 @@ def extract_bounded(extractor,images,boxes,intrinsics,*,gpu_crops,placement,limiwhile offset<len(images):count=min(limit,len(images)-offset)failed=False+ captured=[] if hand_boxes is not None else Nonetry:+ selected = None if hand_indices is None else [i-offset for i in hand_indices if offset<=i<offset+count]value,output=extract_batch(extractor,images[offset:offset+count],boxes[offset:offset+count],- intrinsics,gpu_crops=gpu_crops,placement=placement)+ intrinsics,gpu_crops=gpu_crops,placement=placement,hand_indices=selected,+ **({'hand_boxes':captured} if captured is not None else {}))except torch.cuda.OutOfMemoryError:if count==1:raisefailed=True@@ -59,5 +62,8 @@ def extract_bounded(extractor,images,boxes,intrinsics,*,gpu_crops,placement,limilimit=max(1,min(limit//2,count//2))emit('info',message=f'SAM GPU memory pressure: retrying unpublished frames with batch {limit}.')continue+ if hand_boxes is not None:+ if len(captured)!=1 or captured[0].shape!=(count,2,4):raise ValueError('Incomplete SAM hand boxes')+ hand_boxes.append(captured[0])values.append(value);people.extend(output);offset+=countreturn torch.cat(values),people,limitdiff --git a/mocap/gui.py b/mocap/gui.pyindex 7148006..2b608d9 100644--- a/mocap/gui.py+++ b/mocap/gui.py@@ -135,7 +135,11 @@ class ModelsDialog(QDialog):{key for stage in (*self.tool.stages(refine=True, footmr=True, handflow=True),'people') for key in STAGE_REQUIREMENTS.get(stage, ())})if self.tool.key=='pear':keys.update(STAGE_REQUIREMENTS['pear_align'])if self.tool.key=='prompthmr':keys.update(STAGE_REQUIREMENTS['prompthmr_camera_assets'])- if self.tool.key=='flowhmr':keys.add('flow_metadata')+ if self.tool.key=='flowhmr':+ keys.add('flow_metadata')+ if window.flow_hamer.isChecked():+ from .flow_hamer import MODEL_KEYS+ keys.update(MODEL_KEYS)# Keep public automatic downloads together, followed by manual-only files.# Stable sorting preserves the existing component order within each group.self.models = sorted((model for model in MODELS_LIST if model.key in keys),@@ -453,6 +457,12 @@ class MainWindow(PreviewExportWorkspace,PearWorkspace,PromptHMRWorkspace,MammaWostages = tool.stages(self.htd_refine.isChecked(), self.footmr_refine.isChecked(), handflow=self.handflow_refine.isChecked())from .models import STAGE_REQUIREMENTS, BY_KEYrequired = {key for stage in stages for key in STAGE_REQUIREMENTS.get(stage, ())}+ if self.flow_hamer.isChecked():+ for checkbox in (self.fast_sam,self.flow_hand_stride4):+ blocked=checkbox.blockSignals(True);checkbox.setChecked(True);checkbox.blockSignals(blocked)+ if tool.key=='flowhmr':+ from .flow_hamer import MODEL_KEYS+ required.update(MODEL_KEYS)if tool.key=='flowhmr' and self.flow_sampling.currentData()==-1:required.discard('flow_vggt')if tool.key=='mamma' and self.mamma_camera_mode.currentData()=='manual':required.difference_update(('flow_vggt','pear_geocalib'))if tool.key=='prompthmr' and self.prompthmr_camera.currentData()=='moving':required.update(STAGE_REQUIREMENTS['prompthmr_camera_assets'])@@ -497,7 +507,9 @@ class MainWindow(PreviewExportWorkspace,PearWorkspace,PromptHMRWorkspace,MammaWoself.mesh_button.setEnabled(self.preview_preparation_available())self.import_character_action.setEnabled(not self.busy and not self.contact_saving)self.flow_sampling.setEnabled(not self.busy)- self.fast_sam.setEnabled(not self.busy)+ self.fast_sam.setEnabled(not self.busy and not self.flow_hamer.isChecked())+ self.flow_hand_stride4.setEnabled(not self.busy and not self.flow_hamer.isChecked())+ self.flow_hamer.setEnabled(not self.busy)self.flow_acceleration.setVisible(self.fast_sam.isChecked())self.flow_acceleration.setEnabled(not self.busy)self.exmr_camera.setEnabled(not self.busy)@@ -685,6 +697,8 @@ class MainWindow(PreviewExportWorkspace,PearWorkspace,PromptHMRWorkspace,MammaWoself.fast_sam.setChecked(True)self.flow_batch4.setChecked(True)self.flow_gpu_crop.setChecked(True)+ self.flow_hand_stride4.setChecked(True)+ self.flow_hamer.setChecked(False)self.exmr_camera.setCurrentIndex(0)self.exmr_smoothing.setChecked(True)self.camera_tools.restore_background({})@@ -788,9 +802,12 @@ class MainWindow(PreviewExportWorkspace,PearWorkspace,PromptHMRWorkspace,MammaWofrom .flow_camera import saved_intervalfrom .flow_sam import saved_optionsflow=saved_options(project,manifest)+ self.flow_hamer.setChecked(False)self.fast_sam.setChecked(flow['fast_sam'])self.flow_batch4.setChecked(flow['sam_batch4'])self.flow_gpu_crop.setChecked(flow['sam_gpu_crop'])+ self.flow_hand_stride4.setChecked(flow['sam_hand_stride4'])+ self.flow_hamer.setChecked(flow['hamer'])from .exmr_options import saved as saved_exmrexmr=saved_exmr(project,manifest)self.exmr_camera.setCurrentIndex(self.exmr_camera.findData(exmr['static_camera']))@@ -996,6 +1013,10 @@ class MainWindow(PreviewExportWorkspace,PearWorkspace,PromptHMRWorkspace,MammaWoif 'people' not in stages and self.input_person_jobs(stages,result):returnunavailable = [model for stage in stages for model in ([] if self.model_choice.currentData()=='flowhmr' and stage=='flow_camera' and self.flow_sampling.currentData()==-1 else missing('flow_export' if self.model_choice.currentData()=='flowhmr' and stage in ('correct','export') else stage))]+ if self.model_choice.currentData()=='flowhmr' and self.flow_hamer.isChecked():+ from .flow_hamer import MODEL_KEYS+ from .models import BY_KEY+ unavailable += [BY_KEY[k] for k in MODEL_KEYS if not ready(BY_KEY[k])]if unavailable:names = ", ".join(dict.fromkeys(model.name for model in unavailable))self.status.setText(f"Prepare these models first: {names}")@@ -1234,7 +1255,7 @@ class MainWindow(PreviewExportWorkspace,PearWorkspace,PromptHMRWorkspace,MammaWoframes=int(arguments[arguments.index('--end-frame')+1])-int(arguments[arguments.index('--first-frame')+1])model=arguments[arguments.index('--model')+1] if '--model' in arguments else ''result=arguments[arguments.index('--result')+1] if '--result' in arguments else self.active_result- key=(stage,tool,frames,model,result,self.compute_mode.currentData(),self.fast_sam.isChecked(),self.flow_batch4.isChecked(),self.flow_gpu_crop.isChecked(),self.flow_sampling.currentData(),self.exmr_camera.currentData())+ key=(stage,tool,frames,model,result,self.compute_mode.currentData(),self.fast_sam.isChecked(),self.flow_batch4.isChecked(),self.flow_gpu_crop.isChecked(),self.flow_hand_stride4.isChecked(),self.flow_hamer.isChecked(),self.flow_sampling.currentData(),self.exmr_camera.currentData())if not isinstance(estimate,(int,float)) or not math.isfinite(estimate) or not 1<=estimate<=7*86400:estimate=Noneif stage in ('flow_batch','exmr_batch','gvhmr_batch'):from .queue_groups import argument@@ -1378,6 +1399,8 @@ class MainWindow(PreviewExportWorkspace,PearWorkspace,PromptHMRWorkspace,MammaWoenvironment.insert('RGB_MOCAP_FLOW_FAST_SAM','1' if self.fast_sam.isChecked() else '0')environment.insert('RGB_MOCAP_FLOW_BATCH4','1' if self.flow_batch4.isChecked() else '0')environment.insert('RGB_MOCAP_FLOW_GPU_CROP','1' if self.flow_gpu_crop.isChecked() else '0')+ environment.insert('RGB_MOCAP_FLOW_HAND_STRIDE4','1' if self.flow_hand_stride4.isChecked() else '0')+ environment.insert('RGB_MOCAP_FLOW_HAMER','1' if self.flow_hamer.isChecked() else '0')environment.insert('RGB_MOCAP_EXMR_OPTIONS',json.dumps({'static_camera':self.exmr_camera.currentData(),'smoothing':'global' if self.exmr_smoothing.isChecked() else 'none'}))self.process.setProcessEnvironment(environment)self.process.readyReadStandardOutput.connect(self.read_stdout)diff --git a/mocap/model_guide.py b/mocap/model_guide.pyindex d1c3d00..731da3b 100644--- a/mocap/model_guide.py+++ b/mocap/model_guide.py@@ -30,11 +30,14 @@ DESCRIPTIONS = {'mamma': 'Multi-view reconstruction of one or several people from two or more synchronized fixed-camera videos of the same performance. No fixed camera-count maximum; practical capacity depends on available RAM and VRAM. Detects people automatically; Find person is not needed. Uses SAM 2.1 masks and FP32 landmarks. Automatic cameras combine VGGT-Omega placement with GeoCalib background gravity before 3D fitting; manual calibration bypasses both. GeoCalib uses the base Flow support overlay and a shared checkpoint in Model Manager. Unreliable gravity needs manual calibration or clearer views; it does not fall back to the person as a vertical reference. Body and finger motion, original results and contact-corrected results are preserved. Best suited to views that complement each other; occlusion and bad masks can cause errors. Slower than single-video methods. Requires the separate Setup_MAMMA.cmd runtime and registered restricted-use models. See Model Manager > Runtime Setup and docs/MAMMA.md.','gvhmr': 'Lowest overall motion quality in our tests, but sometimes better for unusual poses such as backflips. ''No native finger tracking. Optional HandFlow adds finger motion; FootMR refines ankles, and HTD refines body motion. These add processing time.',- 'flowhmr': 'Slow, but the best overall motion quality in our tests. Tracks body and fingers together without a separate finger add-on. With Fast SAM and Adaptive Batching on, Automatic selects 1-16 frames from available memory and image size; Low Memory uses one. Tests of 4 to 16 frames reduced warm feature time by 16-23%, with allocated VRAM 3.84 to 5.43 GiB and small numerical motion differences. Short whole jobs benefit much less because model loading dominates. Batch selection, GPU Hand Crops and OOM batch retries appear in Console and CMD. Optional Refine Camera Rotation validates small background-based corrections for camera display only; source motion is unchanged. See docs/models/FLOWHMR.md.',+ 'flowhmr': 'Slow, but the best overall motion quality in our tests. Tracks body and fingers without a separate hand add-on. Motion generation uses 256-query attention batches with FP32 and full temporal context, reducing VRAM especially for long clips. Fast SAM offers independent Adaptive Batching, GPU Hand Crops and default-on 4-Frame Hand Sampling. Four-frame hands interpolate intermediate features: tests reduced warm feature time by 41-49% and allocated VRAM from 5.43 to 4.21 GiB at batch 16, but finger accuracy, body/wrist motion and automatic contacts can change. Turn it off for every-frame hand inference. Automatic selects 1-16 spatial frames; Low Memory uses one and retains hand sampling. Whole-job gains vary because loading dominates short clips. Query size, hand interval, batches and OOM retries appear in Console and CMD. Optional Refine Camera Rotation changes camera display only. See docs/models/FLOWHMR.md.','exmr': 'Generally fast, with good motion quality in our tests. A practical choice for a first attempt. Tracks body and fingers together without a separate finger add-on. Optional Refine Camera Rotation validates small background-based corrections for camera display only; source motion is unchanged.',}+DESCRIPTIONS['flowhmr'] += (' Optional HaMeR Finger Refinement aims to improve finger tracking accuracy and defaults off. It uses ExMR hand crops and Gaussian rotation smoothing, not ExMR learned HandMR inference. Only fingers are replaced; invalid crops retain FlowHMR hands. Slower and may still jitter. Enabling it also enables Fast SAM and 4-Frame Hand Sampling; HaMeR itself uses every frame. Shared HaMeR/MANO files are prepared in Model Manager, and the existing ExMR runtime runs this pass. Reconstruct 3D after changing it.')++def guide_html(selected):descriptions = ''.join(f'<p><b>{tool.label}</b> <a href="{PROJECT_URLS[key]}">Original project</a><br>'diff --git a/mocap/project_workspace_ui.py b/mocap/project_workspace_ui.pyindex 087c34a..fc5899a 100644--- a/mocap/project_workspace_ui.py+++ b/mocap/project_workspace_ui.py@@ -11,7 +11,8 @@ from .video import select_previewclass ModelWorkspace:def selected_flow_options(self):return dict(camera_interval=self.flow_sampling.currentData(), fast_sam=self.fast_sam.isChecked(),- sam_batch4=self.flow_batch4.isChecked(), sam_gpu_crop=self.flow_gpu_crop.isChecked())+ sam_batch4=self.flow_batch4.isChecked(), sam_gpu_crop=self.flow_gpu_crop.isChecked(),+ sam_hand_stride4=self.flow_hand_stride4.isChecked(),hamer=self.flow_hamer.isChecked())def workspace_settings(self):return dict(result=self.active_result,correction=self.selected_correction_options(),@@ -29,10 +30,13 @@ class ModelWorkspace:widget.blockSignals(True);widget.setChecked(value);widget.blockSignals(False)self.restore_correction_options(settings.get('correction',{}))flow=settings.get('flow_options',{})+ self.flow_hamer.setChecked(False)self.flow_sampling.setCurrentIndex(max(0,self.flow_sampling.findData(flow.get('camera_interval',0))))self.fast_sam.setChecked(flow.get('fast_sam',True))self.flow_batch4.setChecked(flow.get('sam_batch4',True))self.flow_gpu_crop.setChecked(flow.get('sam_gpu_crop',True))+ self.flow_hand_stride4.setChecked(flow.get('sam_hand_stride4',True))+ self.flow_hamer.setChecked(flow.get('hamer',False))exmr=settings.get('exmr_options',{})self.exmr_camera.setCurrentIndex(self.exmr_camera.findData(exmr.get('static_camera',True)))self.exmr_smoothing.setChecked(exmr.get('smoothing','global')=='global')diff --git a/mocap/sidebar_scroll.py b/mocap/sidebar_scroll.pynew file mode 100644index 0000000..6d739e5--- /dev/null+++ b/mocap/sidebar_scroll.py@@ -0,0 +1,32 @@+"""Keep sidebar wheel input scrolling instead of editing inference settings."""+from PySide6.QtCore import QEvent,QPointF,Qt+from PySide6.QtGui import QWheelEvent+from PySide6.QtWidgets import QApplication,QScrollArea,QComboBox,QAbstractSpinBox+++class SettingsScrollArea(QScrollArea):+ def setWidget(self,widget):+ super().setWidget(widget)+ self._wheel_controls={}+ for control in [*widget.findChildren(QComboBox),*widget.findChildren(QAbstractSpinBox)]:+ self._wheel_controls[control]=control+ control.installEventFilter(self)+ if isinstance(control,QAbstractSpinBox):+ edit=control.lineEdit()+ self._wheel_controls[edit]=control;edit.installEventFilter(self)++ def eventFilter(self,watched,event):+ if event.type()!=QEvent.Wheel:return super().eventFilter(watched,event)+ control=getattr(self,'_wheel_controls',{}).get(watched)+ if control is None:return super().eventFilter(watched,event)+ # A deliberately opened list retains its normal popup scrolling.+ if isinstance(control,QComboBox) and control.view().isVisible():return False+ # Deliberate focused editing remains available without capturing ordinary scrolls.+ focused=control.hasFocus() or (isinstance(control,QAbstractSpinBox) and control.lineEdit().hasFocus())+ if focused and event.modifiers()&Qt.ControlModifier:return False+ point=QPointF(self.viewport().mapFromGlobal(event.globalPosition().toPoint()))+ forwarded=QWheelEvent(point,event.globalPosition(),event.pixelDelta(),event.angleDelta(),+ event.buttons(),event.modifiers(),event.phase(),event.inverted(),event.source(),event.pointingDevice())+ QApplication.sendEvent(self.viewport(),forwarded)+ event.accept()+ return Truediff --git a/mocap/worker.py b/mocap/worker.pyindex cbd8d63..f6a32e9 100644--- a/mocap/worker.py+++ b/mocap/worker.py@@ -174,7 +174,9 @@ def main() -> int:project = prepare(args.video.resolve(), args.start, args.end,motion_tool=args.motion_tool or 'gvhmr',project=args.project)manifest = json.loads((project / "project.json").read_text(encoding="utf-8"))if args.motion_tool=='flowhmr':- manifest['flow_options']={**manifest.get('flow_options',{}),'camera_interval':int(os.environ.get('RGB_MOCAP_FLOW_INTERVAL','0')),'fast_sam':os.environ.get('RGB_MOCAP_FLOW_FAST_SAM','1')=='1','sam_batch4':os.environ.get('RGB_MOCAP_FLOW_BATCH4','1')=='1','sam_gpu_crop':os.environ.get('RGB_MOCAP_FLOW_GPU_CROP','1')=='1'}+ manifest['flow_options']={**manifest.get('flow_options',{}),'camera_interval':int(os.environ.get('RGB_MOCAP_FLOW_INTERVAL','0')),'fast_sam':os.environ.get('RGB_MOCAP_FLOW_FAST_SAM','1')=='1','sam_batch4':os.environ.get('RGB_MOCAP_FLOW_BATCH4','1')=='1','sam_gpu_crop':os.environ.get('RGB_MOCAP_FLOW_GPU_CROP','1')=='1','sam_hand_stride4':os.environ.get('RGB_MOCAP_FLOW_HAND_STRIDE4','1')=='1'}+ manifest['flow_options']['hamer']=os.environ.get('RGB_MOCAP_FLOW_HAMER','0')=='1'+ if manifest['flow_options']['hamer']:manifest['flow_options'].update(fast_sam=True,sam_hand_stride4=True)if args.motion_tool=='exmr':from .exmr_options import optionsmanifest['exmr_options']=options(json.loads(os.environ.get('RGB_MOCAP_EXMR_OPTIONS','{}')))diff --git a/mocap/workspace_ui.py b/mocap/workspace_ui.pyindex 6a2487a..e10b4fe 100644--- a/mocap/workspace_ui.py+++ b/mocap/workspace_ui.py@@ -4,13 +4,14 @@ from .console_log import ConsoleLogfrom PySide6.QtCore import Qt, QSizefrom PySide6.QtGui import QIconfrom PySide6.QtWidgets import (QWidget, QFrame, QLabel, QPushButton, QComboBox, QCheckBox,- QVBoxLayout, QHBoxLayout, QGroupBox, QSplitter, QScrollArea,+ QVBoxLayout, QHBoxLayout, QGroupBox, QSplitter,QSpinBox, QDoubleSpinBox, QProgressBar, QTextEdit, QMessageBox, QSizePolicy, QStackedWidget)from .viewer import VideoView, MotionViewfrom .timeline import TimelineSliderfrom .motion_tools import MOTION_TOOLSfrom .paths import ROOTfrom .correction_settings import PRESETS+from .sidebar_scroll import SettingsScrollAreaclass WrappedLabel(QLabel):@@ -312,7 +313,7 @@ def build_workspace(w):side_layout = QVBoxLayout(sidebar)side_layout.setContentsMargins(4, 0, 4, 0)side_layout.setSpacing(7)- scroll = QScrollArea()+ scroll = SettingsScrollArea()scroll.setObjectName("modelSettings")scroll.viewport().setObjectName("modelSettingsViewport")scroll.setWidgetResizable(True)@@ -384,13 +385,19 @@ def build_workspace(w):w.flow_acceleration=acceleration.parentWidget()w.flow_batch4=QCheckBox('Adaptive Batching')w.flow_gpu_crop=QCheckBox('GPU Hand Crops')+ w.flow_hand_stride4=QCheckBox('4-Frame Hand Sampling')+ w.flow_hand_stride4.setToolTip(tooltip_text('Infer hands every 4 frames and interpolate the hand features between them. Faster and uses less VRAM, but finger accuracy may decrease. Body/wrist motion and automatic contact timing can also change. Tests: 41-49% less SAM feature time and allocated VRAM 5.43 to 4.21 GiB at batch 16. Off infers hands every frame. Applies on Reconstruct 3D.'))w.flow_batch4.setToolTip(tooltip_text('Automatic selects 1-16 frames from available VRAM/RAM and image size. Tests of 4 to 16 frames reduced warm SAM feature time by 16-23%, with allocated VRAM about 3.84 to 5.43 GiB. Low Memory and this option off use one frame. Small numerical motion differences are possible. Applies on Reconstruct 3D; whole-job gains vary.'))w.flow_gpu_crop.setToolTip(tooltip_text('Prepare hand crops on the GPU. Short tests: about 10-15% faster SAM features, with little extra VRAM beyond the selected batch size. Different image interpolation can change motion (about 1 mm at the 95th percentile; up to 5 mm in these tests). Model precision stays unchanged. Applies on Reconstruct 3D; results vary.'))- for check in (w.flow_batch4,w.flow_gpu_crop):+ for check in (w.flow_batch4,w.flow_gpu_crop,w.flow_hand_stride4):check.setChecked(True)acceleration.addWidget(check)check.toggled.connect(lambda _: w.update_readiness())w.fast_sam.toggled.connect(lambda _: w.update_readiness())+ w.flow_hamer=QCheckBox('HaMeR Finger Refinement')+ w.flow_hamer.setToolTip(tooltip_text('Use HaMeR for more accurate finger tracking with every-frame hand inference and ExMR crop/rotation smoothing. Accuracy varies; jitter can remain. Slower and uses additional VRAM. Keeps FlowHMR body, wrists and movement. Requires HaMeR and MANO files. Automatically enables Fast SAM and 4-Frame Hand Sampling. Applies on Reconstruct 3D.'))+ flow_camera.addWidget(w.flow_hamer)+ w.flow_hamer.toggled.connect(lambda _: w.update_readiness())flow_camera.addWidget(QLabel('Camera / Sampling'))w.flow_sampling = QComboBox()for label, interval in [('Moving / Unknown - Auto', 0), ('Static Camera', -1), ('Every Frame', 1), ('Every 2 Frames', 2), ('Every 5 Frames', 5), ('Every 10 Frames', 10), ('Every 30 Frames', 30)]:diff --git a/third_party/FlowHMR/RGB_MOCAP_PROVENANCE.json b/third_party/FlowHMR/RGB_MOCAP_PROVENANCE.jsonindex 242a00a..583d02c 100644--- a/third_party/FlowHMR/RGB_MOCAP_PROVENANCE.json+++ b/third_party/FlowHMR/RGB_MOCAP_PROVENANCE.json@@ -2,5 +2,14 @@"repository": "https://github.com/flowhmr/flowhmr","commit": "b23040f10732b59acaad37afbd9fe0fa823c54b3","runtime": "Native Windows Python 3.10 / PyTorch 2.7.1+cu128",- "registered_models_bundled": false-}\ No newline at end of file+ "registered_models_bundled": false,+ "query_attention": {+ "commit": "87ebb483ce9da32be72c67971bc8fd76f27251f3",+ "files": [+ "network/hymotion_mmdit_for_v2m.py",+ "network/token_refiner.py",+ "network/mmdit/query_batched_attention.py"+ ],+ "default_in_app": "query_batched, 256 queries, all clip lengths; FP32 and original temporal visibility retained"+ }+}diff --git a/third_party/FlowHMR/flowhmr/network/hymotion_mmdit_for_v2m.py b/third_party/FlowHMR/flowhmr/network/hymotion_mmdit_for_v2m.pyindex 60d97f5..8f5f5ad 100644--- a/third_party/FlowHMR/flowhmr/network/hymotion_mmdit_for_v2m.py+++ b/third_party/FlowHMR/flowhmr/network/hymotion_mmdit_for_v2m.py@@ -17,6 +17,13 @@ from .mmdit.bricks import get_activation_layer, get_norm_layerfrom .mmdit.encoders import MLP, MLPEncoder, TimestepEmbeddingEncoderfrom .mmdit.modulate_layers import ModulateDiT, apply_gate, modulatefrom .mmdit.positional_encoding import RotaryEmbedding+from .mmdit.query_batched_attention import (+ AttentionPlan,+ build_local_attention_plan,+ query_batched_attention,+ resolve_query_attention_config,+)+from .token_refiner import SingleTokenRefinerclass MMDoubleStreamBlock(nn.Module):@@ -94,7 +101,10 @@ class MMDoubleStreamBlock(nn.Module):attn_mask: Optional[Tensor] = None,return_attn: bool = False,attn_collector: Optional[List[Tensor]] = None,+ attention_plan: Optional[AttentionPlan] = None,) -> Tuple[Tensor, Tensor]:+ if attention_plan is not None and (self.training or return_attn):+ raise ValueError("An attention plan requires evaluation without attention-map output")(motion_shift_msa,motion_scale_msa,@@ -150,7 +160,7 @@ class MMDoubleStreamBlock(nn.Module):text_len = text_feat.shape[1]dropout_p = 0.0 if not self.training else self.dropout- ret = attention(+ ret = query_batched_attention(q, k, v, attention_plan) if attention_plan is not None else attention(q,k,v,@@ -257,7 +267,10 @@ class MMSingleStreamBlock(nn.Module):attn_mask: Optional[Tensor] = None,return_attn: bool = False,attn_collector: Optional[List[Tensor]] = None,+ attention_plan: Optional[AttentionPlan] = None,) -> Tensor:+ if attention_plan is not None and (self.training or return_attn):+ raise ValueError("An attention plan requires evaluation without attention-map output")(shift_msa,scale_msa,@@ -287,7 +300,7 @@ class MMSingleStreamBlock(nn.Module):bsz, total_len = x_modulated.shape[:2]dropout_p = 0.0 if not self.training else self.dropout- ret = attention(+ ret = query_batched_attention(q, k, v, attention_plan) if attention_plan is not None else attention(q,k,v,@@ -342,9 +355,14 @@ class HunyuanMotionMMDiT(nn.Module):apply_rope_to_single_branch: bool = True,insert_start_token: bool = False,with_long_skip_connection: bool = False,+ attention_backend: Optional[str] = None,+ attention_query_chunk_size: Optional[int] = None,**kwargs,):super().__init__()+ self.attention_backend, self.attention_query_chunk_size = resolve_query_attention_config(+ attention_backend, attention_query_chunk_size+ )self.motion_input_dim = input_dimself.ctxt_input_dim = ctxt_input_dimself.vtxt_input_dim = vtxt_input_dim@@ -483,10 +501,31 @@ class HunyuanMotionMMDiT(nn.Module):ctxt_key_padding_mask = self._canonical_mask(ctxt_mask_temporal).to(device)seq_key_padding_mask = torch.cat((motion_key_padding_mask, ctxt_key_padding_mask), dim=1)+ use_query_batched = (+ not self.training and self.attention_backend == "query_batched" and self.mask_mode == "narrowband_v2m"+ )if hasattr(self, "text_refiner"):- ctxt_feat = self.text_refiner(x=ctxt_feat, t=timesteps, mask=(ctxt_key_padding_mask == 0).to(device))+ refiner_kwargs = {}+ if use_query_batched and isinstance(self.text_refiner, SingleTokenRefiner):+ refiner_kwargs["attention_query_chunk_size"] = self.attention_query_chunk_size+ ctxt_feat = self.text_refiner(+ x=ctxt_feat, t=timesteps, mask=(ctxt_key_padding_mask == 0).to(device), **refiner_kwargs+ )- if self.mask_mode is None:+ attention_plan = None+ if use_query_batched:+ tt_length = self.narrowband_tt_length if self.narrowband_tt_length is not None else self.narrowband_v2m_length+ attention_plan = build_local_attention_plan(+ motion_feat.shape[1], ctxt_feat.shape[1], chunk_size=self.attention_query_chunk_size,+ mm_window=int(round(self.narrowband_length)),+ mc_window=int(round(self.narrowband_v2m_length)) if self.narrowband_v2m_length > 0 else None,+ cm_window=(-1 if self.narrowband_tm_length == 0 else+ int(round(self.narrowband_tm_length)) if self.narrowband_tm_length > 0 else None),+ cc_window=int(round(tt_length)) if tt_length > 0 else None,+ key_padding_mask=torch.isneginf(seq_key_padding_mask), device=device,+ )+ seq_mask = None+ elif self.mask_mode is None:seq_mask = Noneelif self.mask_mode == "causal":motion_len = motion_feat.shape[1]@@ -557,7 +596,7 @@ class HunyuanMotionMMDiT(nn.Module):mask_dtype = motion_feat.dtype# narrowband_v2m mode handles T→M in seq_mask; other modes need _build to disable ittm_in_seq_mask = (self.mask_mode == "narrowband_v2m")- attn_mask_double = self._build_dmm_attn_mask_shared(+ attn_mask_double = None if attention_plan is not None else self._build_dmm_attn_mask_shared(bsz=bsz,motion_len=motion_len,text_len=text_len,@@ -582,12 +621,13 @@ class HunyuanMotionMMDiT(nn.Module):text_feat=ctxt_feat,adapter=adapter,attn_mask=attn_mask_double,+ attention_plan=attention_plan,)# precompute shared attention masks for single stream blocks toosplit_len = motion_feat.shape[1]x = torch.cat((motion_feat, ctxt_feat), 1)- attn_mask_single = self._build_smm_attn_mask_shared(+ attn_mask_single = None if attention_plan is not None else self._build_smm_attn_mask_shared(bsz=bsz,split_len=split_len,total_len=total_len,@@ -612,6 +652,7 @@ class HunyuanMotionMMDiT(nn.Module):split_len=split_len,adapter=adapter,attn_mask=attn_mask_single,+ attention_plan=attention_plan,)x = x[:, :split_len, ...]diff --git a/third_party/FlowHMR/flowhmr/network/mmdit/query_batched_attention.py b/third_party/FlowHMR/flowhmr/network/mmdit/query_batched_attention.pynew file mode 100644index 0000000..3d85962--- /dev/null+++ b/third_party/FlowHMR/flowhmr/network/mmdit/query_batched_attention.py@@ -0,0 +1,248 @@+"""Inference SDPA with bounded query batches and unchanged visibility rules."""++import os+from dataclasses import dataclass+from typing import Optional, Tuple++import torch+import torch.nn.functional as F+from torch import Tensor+from torch.nn.attention import SDPBackend, sdpa_kernel+++def resolve_query_attention_config(backend=None, chunk_size=None) -> Tuple[str, int]:+ """Resolve optional constructor settings without changing existing defaults."""+ if backend is None:+ backend = os.environ.get("FLOWHMR_ATTENTION_BACKEND", "original")+ if backend not in ("original", "query_batched"):+ raise ValueError("attention_backend must be 'original' or 'query_batched'")+ if chunk_size is None:+ chunk_size = os.environ.get("FLOWHMR_ATTENTION_QUERY_CHUNK_SIZE", "256")+ if isinstance(chunk_size, str):+ if not chunk_size.isdecimal():+ raise ValueError("attention_query_chunk_size must be a positive integer")+ chunk_size = int(chunk_size)+ if isinstance(chunk_size, bool) or not isinstance(chunk_size, int) or chunk_size <= 0:+ raise ValueError("attention_query_chunk_size must be a positive integer")+ return backend, chunk_size+++@dataclass(frozen=True)+class LocalVisibility:+ query_start: int+ motion_length: int+ motion_window: Optional[int]+ condition_window: Optional[int]+ key_padding_mask: Optional[Tensor]+ fully_masked: Optional[Tensor]+ key_ranges: Optional[Tuple[Tuple[int, int], Tuple[int, int]]]+++@dataclass(frozen=True)+class AttentionChunk:+ query_start: int+ query_stop: int+ key_indices: Optional[Tensor]+ attn_mask: Optional[Tensor]+ local_visibility: Optional[LocalVisibility] = None+++@dataclass(frozen=True)+class AttentionPlan:+ length: int+ chunks: Tuple[AttentionChunk, ...]+ # Refiner masks stay factored; caching every global chunk would retain L² masks.+ valid_tokens: Optional[Tensor] = None+++def _validate_length(length: int, name: str) -> None:+ if isinstance(length, bool) or not isinstance(length, int) or length < 0:+ raise ValueError(f"{name} must be a nonnegative integer")+++def _validate_window(window: Optional[int], name: str) -> None:+ if window is not None and (isinstance(window, bool) or not isinstance(window, int)):+ raise ValueError(f"{name} must be an integer or None")+++def _prepare_mask(mask: Optional[Tensor], length: int, device) -> Optional[Tensor]:+ if mask is None:+ return None+ if mask.dtype != torch.bool or mask.ndim != 2 or mask.shape[1] != length:+ raise ValueError(f"token mask must be bool [B, {length}], got {mask.shape}/{mask.dtype}")+ return mask.to(device=device) if device is not None else mask+++def _key_range(query_start: int, query_stop: int, key_length: int,+ window: Optional[int]) -> Tuple[int, int]:+ if window is None:+ return 0, key_length+ if window < 0:+ return 0, 0+ start = min(key_length, max(0, query_start - window))+ stop = min(key_length, query_stop + window)+ return start, max(start, stop)+++def _quadrant_visible(queries: Tensor, keys: Tensor, window: Optional[int]) -> Tensor:+ if window is None:+ return torch.ones((queries.numel(), keys.numel()), dtype=torch.bool, device=queries.device)+ return (queries[:, None] - keys[None, :]).abs() <= window+++def _local_mask(queries, indices, motion_length, motion_window, condition_window, padding):+ motion_keys = indices < motion_length+ local_keys = torch.where(motion_keys, indices, indices - motion_length)+ visible = torch.where(+ motion_keys[None, :],+ _quadrant_visible(queries, local_keys, motion_window),+ _quadrant_visible(queries, local_keys, condition_window),+ )[None, None, :, :]+ if padding is not None:+ visible = visible & ~padding[:, None, None, indices]+ return visible+++def build_local_attention_plan(+ motion_length: int,+ condition_length: int,+ *,+ chunk_size: int = 256,+ mm_window: Optional[int],+ mc_window: Optional[int] = None,+ cm_window: Optional[int] = -1,+ cc_window: Optional[int] = None,+ key_padding_mask: Optional[Tensor] = None,+ device=None,+) -> AttentionPlan:+ """Plan the four narrowband_v2m quadrants without a full sequence mask.++ Window ``None`` means full visibility, a nonnegative integer is an inclusive+ radius in each stream's original coordinates, and a negative integer disables+ that quadrant. ``key_padding_mask`` is bool [B, M+C], True for invalid keys.+ Plans are shared by every attention layer in one model forward.+ """+ _validate_length(motion_length, "motion_length")+ _validate_length(condition_length, "condition_length")+ _, chunk_size = resolve_query_attention_config("query_batched", chunk_size)+ for name, window in (("mm_window", mm_window), ("mc_window", mc_window),+ ("cm_window", cm_window), ("cc_window", cc_window)):+ _validate_window(window, name)+ length = motion_length + condition_length+ padding = _prepare_mask(key_padding_mask, length, device)+ if device is None:+ device = padding.device if padding is not None else torch.device("cpu")++ pending = []+ for offset, query_length, motion_window, condition_window in (+ (0, motion_length, mm_window, mc_window),+ (motion_length, condition_length, cm_window, cc_window),+ ):+ for start in range(0, query_length, chunk_size):+ stop = min(start + chunk_size, query_length)+ mr = _key_range(start, stop, motion_length, motion_window)+ cr = _key_range(start, stop, condition_length, condition_window)+ key_ranges = (mr, (cr[0] + motion_length, cr[1] + motion_length))+ indices = torch.cat([torch.arange(*bounds, device=device) for bounds in key_ranges])+ queries = torch.arange(start, stop, device=device)+ visible = _local_mask(queries, indices, motion_length, motion_window, condition_window, padding)+ fully_masked = ~visible.any(dim=-1, keepdim=True)+ # Retain only compact local masks. Full/very wide quadrants otherwise+ # accumulate quadratic mask storage even when each Q batch is small.+ cache_mask = indices.numel() < length and indices.numel() <= 4 * chunk_size+ pending.append((offset + start, offset + stop, start,+ indices if cache_mask else None, visible if cache_mask else None,+ fully_masked, motion_window, condition_window,+ None if indices.numel() == length else key_ranges))++ # One device synchronization during planning, never one per attention layer.+ fallback_chunks = torch.stack([item[5].any() for item in pending]).tolist() if pending else []+ chunks = []+ for item, needs_fallback in zip(pending, fallback_chunks):+ start, stop, local_start, indices, visible, fully_masked, mw, cw, key_ranges = item+ lazy_visibility = None+ if needs_fallback:+ # The original MATH path unmasks every sequence key for an empty row,+ # including padded keys and keys outside the nominal local window.+ lazy_visibility = LocalVisibility(local_start, motion_length, mw, cw,+ padding, fully_masked, None)+ indices = None+ visible = None+ elif visible is None:+ lazy_visibility = LocalVisibility(local_start, motion_length, mw, cw,+ padding, None, key_ranges)+ chunks.append(AttentionChunk(start, stop, indices, visible, lazy_visibility))+ return AttentionPlan(length, tuple(chunks))+++def build_global_attention_plan(+ length: int,+ *,+ chunk_size: int = 256,+ valid_tokens: Optional[Tensor] = None,+ device=None,+) -> AttentionPlan:+ """Plan refiner attention, retaining every valid key for every valid query.++ Invalid queries attend only their own diagonal, as in IndividualTokenRefiner.+ Keeping the validity vector factored avoids retaining quadratic masks.+ """+ _validate_length(length, "length")+ _, chunk_size = resolve_query_attention_config("query_batched", chunk_size)+ valid_tokens = _prepare_mask(valid_tokens, length, device)+ chunks = tuple(AttentionChunk(start, min(start + chunk_size, length), None, None)+ for start in range(0, length, chunk_size))+ return AttentionPlan(length, chunks, valid_tokens)+++def query_batched_attention(q: Tensor, k: Tensor, v: Tensor, plan: AttentionPlan) -> Tensor:+ """Apply inference-only MATH SDPA to [B, L, H, D], returning [B, L, H*D].++ Q/K already include positional encoding. Motion and condition keys stay in+ one softmax; only masked-out keys are omitted. Input precision is unchanged.+ """+ if q.ndim != 4 or q.shape != k.shape or q.shape != v.shape or q.shape[1] != plan.length:+ raise ValueError("q, k and v must have matching [B, plan.length, H, D] shapes")+ if plan.valid_tokens is not None and plan.valid_tokens.shape[0] != q.shape[0]:+ raise ValueError("valid_tokens batch size does not match q")+ if not plan.chunks:+ return q.flatten(2)+ output = []+ keys = torch.arange(plan.length, device=q.device) if plan.valid_tokens is not None else None+ with sdpa_kernel(SDPBackend.MATH):+ for chunk in plan.chunks:+ q_chunk = q[:, chunk.query_start:chunk.query_stop].transpose(1, 2)+ indices = chunk.key_indices+ mask = chunk.attn_mask+ if chunk.local_visibility is not None:+ rule = chunk.local_visibility+ if rule.key_ranges is None:+ if keys is None:+ keys = torch.arange(plan.length, device=q.device)+ mask_keys = keys+ else:+ indices = torch.cat([torch.arange(*bounds, device=q.device) for bounds in rule.key_ranges])+ mask_keys = indices+ queries = torch.arange(rule.query_start,+ rule.query_start + chunk.query_stop - chunk.query_start, device=q.device)+ mask = _local_mask(queries, mask_keys, rule.motion_length,+ rule.motion_window, rule.condition_window, rule.key_padding_mask)+ if rule.fully_masked is not None:+ mask = mask | rule.fully_masked+ if indices is None:+ k_chunk, v_chunk = k, v+ else:+ k_chunk = k.index_select(1, indices)+ v_chunk = v.index_select(1, indices)+ if plan.valid_tokens is not None:+ valid_q = plan.valid_tokens[:, None, chunk.query_start:chunk.query_stop, None]+ queries = keys[chunk.query_start:chunk.query_stop]+ diagonal = queries[:, None] == keys[None, :]+ mask = ((valid_q & plan.valid_tokens[:, None, None, :]) |+ (~valid_q & diagonal[None, None, :, :]))+ attended = F.scaled_dot_product_attention(+ q_chunk, k_chunk.transpose(1, 2), v_chunk.transpose(1, 2),+ attn_mask=mask, dropout_p=0.0, is_causal=False,+ )+ output.append(attended.transpose(1, 2).flatten(2))+ return torch.cat(output, dim=1)diff --git a/third_party/FlowHMR/flowhmr/network/token_refiner.py b/third_party/FlowHMR/flowhmr/network/token_refiner.pyindex dac632d..b27b4f6 100644--- a/third_party/FlowHMR/flowhmr/network/token_refiner.py+++ b/third_party/FlowHMR/flowhmr/network/token_refiner.py@@ -10,6 +10,7 @@ from .mmdit.attention import attentionfrom .mmdit.bricks import get_norm_layerfrom .mmdit.encoders import MLP, MLPEncoder, TimestepEmbeddingEncoderfrom .mmdit.modulate_layers import ModulateDiT, apply_gate+from .mmdit.query_batched_attention import AttentionPlan, build_global_attention_plan, query_batched_attentionclass IndividualTokenRefinerBlock(nn.Module):@@ -45,7 +46,10 @@ class IndividualTokenRefinerBlock(nn.Module):self.adaLN_modulation = ModulateDiT(feat_dim=feat_dim, factor=2, act_type="silu")- def forward(self, x: Tensor, c: Tensor, attn_mask: Optional[Tensor] = None) -> Tensor:+ def forward(self, x: Tensor, c: Tensor, attn_mask: Optional[Tensor] = None,+ attention_plan: Optional[AttentionPlan] = None) -> Tensor:+ if attention_plan is not None and self.training:+ raise ValueError("An attention plan requires evaluation mode")dtype = self.self_attn_qkv.weight.dtypegate_msa, gate_mlp = self.adaLN_modulation(c).chunk(2, dim=-1)qkv = self.self_attn_qkv(self.norm1(x).to(dtype))@@ -54,7 +58,8 @@ class IndividualTokenRefinerBlock(nn.Module):q = self.self_attn_q_norm(q).to(v)k = self.self_attn_k_norm(k).to(v)# Self-Attention- attn = attention(q, k, v, mode="torch", attn_mask=attn_mask)+ attn = (attention(q, k, v, mode="torch", attn_mask=attn_mask) if attention_plan is None+ else query_batched_attention(q, k, v, attention_plan))x = x.float() + apply_gate(self.self_attn_proj(attn), gate_msa.float())# FFN Layerx = x + apply_gate(self.mlp(self.norm2(x).to(dtype)).float(), gate_mlp.float())@@ -89,7 +94,15 @@ class IndividualTokenRefiner(nn.Module):])- def forward(self, x: Tensor, c: Tensor, mask: Optional[Tensor] = None) -> Tensor:+ def forward(self, x: Tensor, c: Tensor, mask: Optional[Tensor] = None,+ attention_query_chunk_size: Optional[int] = None) -> Tensor:+ if attention_query_chunk_size is not None and not self.training:+ plan = build_global_attention_plan(+ x.shape[1], chunk_size=attention_query_chunk_size, valid_tokens=mask, device=x.device+ )+ for block in self.blocks:+ x = block(x, c, attention_plan=plan)+ return xself_attn_mask = Noneif mask is not None:batch_size = mask.shape[0]@@ -165,7 +178,8 @@ class SingleTokenRefiner(nn.Module):qkv_bias=qkv_bias,)- def forward(self, x: Tensor, t: Tensor, mask: Optional[Tensor] = None) -> Tensor:+ def forward(self, x: Tensor, t: Tensor, mask: Optional[Tensor] = None,+ attention_query_chunk_size: Optional[int] = None) -> Tensor:t = cast_to_module_dtype(t, self.timestep_encoder)timestep_aware_representations = self.timestep_encoder(t)@@ -182,6 +196,6 @@ class SingleTokenRefiner(nn.Module):x = cast_to_module_dtype(x, self.input_embedder)x = self.input_embedder(x)- x = self.individual_token_refiner(x, c, mask)+ x = self.individual_token_refiner(x, c, mask, attention_query_chunk_size=attention_query_chunk_size)return x