Skip to content

Native Windows video motion capture with ExMR, FlowHMR and GVHMR, contact correction, humanoid retargeting, and FBX/VMD export.

Python

Use runtime memory-pressure safeguards and shared VRAM headroom

toyxyzfb3767bf1ed4
diff --git a/SOURCE_MANIFEST.json b/SOURCE_MANIFEST.json
index ac29c43..217b70c 100644
--- a/SOURCE_MANIFEST.json
+++ b/SOURCE_MANIFEST.json
@@ -1,6 +1,6 @@
{
"schema": 1,
- "date": "2026-10-27",
+ "date": "2026-10-28",
"purpose": "Public source distribution; excludes model weights and runtime binaries",
"version": "git-source",
"files": [
@@ -86,8 +86,8 @@
},
{
"path": "docs/AGENT_GUIDE.md",
- "bytes": 11497,
- "sha256": "e83a93812b8ab368595202d33313d92c2ba1b5a43ace1361fba6734d222f1437"
+ "bytes": 12249,
+ "sha256": "4875d1f281c21d2a57e7f1c092ebce8511b64d772b9259290659ca93a2b217d1"
},
{
"path": "docs/BUILD.md",
@@ -96,13 +96,13 @@
},
{
"path": "docs/USER_GUIDE.md",
- "bytes": 27504,
- "sha256": "adca6d25a2c46ad71b7319cfb6e7b25ac12820df4d9d9ec8c5ee1b8f11138e73"
+ "bytes": 28468,
+ "sha256": "82d87a3532d5fe88927e878f73086843673d98f879026a3c764186ac152d6341"
},
{
"path": "docs/VALIDATION.md",
- "bytes": 6413,
- "sha256": "1d7d6ba9c064699c3d864dd9f8cabbf55d0ee5e4ab4256513eb1e98ec41d9c70"
+ "bytes": 12060,
+ "sha256": "a14e63734693e32d8af7eb7d5e9263c2976b133d18de787a184c3a1941983f26"
},
{
"path": "docs/images/rgbmocap-workspace.png",
@@ -971,8 +971,8 @@
},
{
"path": "mocap/compute_policy.py",
- "bytes": 6513,
- "sha256": "3125b5a360d71c229a958a553548af0f03c82b58698f1b758a14f2048a2f7e92"
+ "bytes": 5723,
+ "sha256": "f47c0da4b7f7671931174e2aaf8ed09a7d1fde1047fd3c07d96065b8cc14425b"
},
{
"path": "mocap/console_log.py",
@@ -1026,8 +1026,8 @@
},
{
"path": "mocap/exmr_backend.py",
- "bytes": 17548,
- "sha256": "8e5e7e5e2c6f677299d4a6081f20c5e7c2fb0fe17f18c0e0a4e5599bb01f8b1a"
+ "bytes": 17106,
+ "sha256": "6d2702884592ca28a6fba2875b24dc2afd7ef149f8bfb24ac11acb95d9c60f0f"
},
{
"path": "mocap/exmr_options.py",
@@ -1066,8 +1066,8 @@
},
{
"path": "mocap/flow_backend.py",
- "bytes": 24380,
- "sha256": "cecfd3fd5edc0cd273f41fd29849acf380f8f4607c5e0361518cd59d8746d9df"
+ "bytes": 22729,
+ "sha256": "7204c9d6f0fab769e6440a740d7fb0309e53f1c80644f70fa80e0e62712b3567"
},
{
"path": "mocap/flow_camera.py",
@@ -1121,13 +1121,13 @@
},
{
"path": "mocap/gui.py",
- "bytes": 93839,
- "sha256": "69cba589e41ff1e3964fa9644c710fdf58570174b9aa0f556748341d05b01513"
+ "bytes": 94171,
+ "sha256": "900c3f0c913e20d56cab477663a03767cd6a88d0b83be979b8164a1696365e99"
},
{
"path": "mocap/gvhmr_attention.py",
- "bytes": 4877,
- "sha256": "d0d32032fad3470cc4801134d4bf4fafdf8bfc5bc805228ece5cc8dabe4f370e"
+ "bytes": 4747,
+ "sha256": "a0fa66d293dde00400c3367fc68cb6b9faeae591c87cabeeb8e06a0bf9f5feaa"
},
{
"path": "mocap/gvhmr_preprocess.py",
@@ -1261,8 +1261,8 @@
},
{
"path": "mocap/processing_guard.py",
- "bytes": 2793,
- "sha256": "b9c66f55ffaa2ed2b6e993f1c084a7991dd98fe4f75ecfce6e82664875839a39"
+ "bytes": 2783,
+ "sha256": "d440382289bda7479b5d3189661a9a784f7da4b48fe07a5971e6f5eabcad4be7"
},
{
"path": "mocap/progress_events.py",
@@ -1294,6 +1294,11 @@
"bytes": 8736,
"sha256": "a49d009da0adcfb911936526db1769270b76692ee6cf6f0dc737782841f1263f"
},
+ {
+ "path": "mocap/resource_cache.py",
+ "bytes": 1776,
+ "sha256": "128666deaa628e32f8d0089338c8d85f16eb7c344a0820e87e19bcc8cf08189c"
+ },
{
"path": "mocap/result_artifacts.py",
"bytes": 5030,
@@ -1541,8 +1546,8 @@
},
{
"path": "mocap/worker.py",
- "bytes": 26638,
- "sha256": "6c1de70d9628ae41528a4494de39034764e0b938982d61c7470e631a371f4435"
+ "bytes": 26292,
+ "sha256": "0b479a3a33a4f4df3804ee57e233f314dd5554044c1af6a274317878241fc972"
},
{
"path": "mocap/worker_progress.py",
diff --git a/docs/AGENT_GUIDE.md b/docs/AGENT_GUIDE.md
index bcf5f27..c72c636 100644
--- a/docs/AGENT_GUIDE.md
+++ b/docs/AGENT_GUIDE.md
@@ -53,7 +53,9 @@ See [the full workflow and controls](USER_GUIDE.md#start-here). Do not confuse v
## Resources and performance
-Use **Resource Mode > Automatic** by default. **Low Memory** uses smaller image batches; it is a separate choice, not a promise every clip will fit. GPU/CPU memory availability, resolution, clip duration and camera settings affect workloads. Close competing GPU applications or shorten the clip when preflight reports insufficient resources; do not silently change model quality or truncate the motion. Avoid expensive AI reruns for operations that can use existing results.
+Use **Resource Mode > Automatic** by default. **Low Memory** uses smaller image batches; it is a separate choice, not a promise every clip will fit. GPU/CPU memory availability, resolution, clip duration and camera settings affect workloads. Model processing is not rejected using predicted RAM/VRAM requirements. The desktop checks actual available RAM and Windows allocation headroom every 0.5 seconds and stops the worker tree when these become low; actual allocation failures also produce an error. Close competing applications or shorten the clip after a memory-related stop. Keep genuine model frame limits, bounded buffers and adaptive batch/attention choices; do not silently change model quality or truncate motion. Avoid expensive AI reruns for operations that can use existing results.
+
+GPU allocator limits share ComfyUI's external-use margin: 600 MiB on Windows, 700 MiB above 15 GiB GPU capacity (400 MiB on other systems). Subtract it from actual free VRAM without an additional percentage cap or fixed FlowHMR/ExMR 3/2 GiB reserve. This margin is separate from inference working space, which stays inside the allocator budget. Do not copy ComfyUI's model offload or quality-changing policies into these models.
The app uses separate runtime profiles to maintain compatibility, with bounded batches, previews and background workers. Keep video decoding, large I/O and numerical work off the GUI thread. Playback responsiveness, synchronization and resource cleanup are correctness requirements. If changes affect these, measure frame-time outliers and repeated open/close behavior; do not infer universal performance from a short test.
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index 9af6224..383fa0a 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -329,6 +329,21 @@ Use **Console** for details and errors. Loading or unmeasured work shows activit
instead of an invented percentage. FlowHMR is limited to 5,000 frames per take
(about 166.7 seconds); available memory may require a shorter clip.
+Processing is allowed to start without a predicted RAM/VRAM minimum. While it
+runs, the app monitors actual available RAM and Windows allocation headroom.
+If either becomes low, it stops the processing job and shows the available memory
+in the error message. The app also reports actual CPU/GPU allocation failures.
+Completed stages are retained for retry. Low Memory can reduce supported batch
+sizes, but cannot guarantee that every model or video fits. A sudden large
+allocation can still fail before the next monitor check.
+
+GPU allocator budgets use ComfyUI's external-use margin: 600 MiB on Windows,
+or 700 MiB on GPUs larger than 15 GiB, subtracted from currently free VRAM.
+All three model paths use this rule; FlowHMR/ExMR no longer subtract fixed
+3/2 GiB or impose an additional 95/90% ceiling. Inference working memory is
+part of the allowed budget. This is not a guarantee of free VRAM: other apps
+and allocations outside PyTorch can still consume it.
+
## Motion Correction
Contact correction reduces sliding when feet or palms rest on a support. It uses
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index 429dc7a..bcb02a9 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -92,6 +92,85 @@ interactive playback, standalone MMD playback or testing on other GPUs.
Full PBR materials and general translucent-material sorting are not implemented.
Tests and generated character assets remained outside the public checkout.
+## Runtime memory-pressure policy (2026-10-28)
+
+- Removed predicted RAM/VRAM admission failures from shared workers, FlowHMR and
+ ExMR. FlowHMR's 5,000-frame limit, adaptive batches, FP32 temporal context,
+ allocator reserves and the existing GVHMR full-key query-split path remain.
+ Estimates can still select a computation path; they no longer reject it.
+- A real 12-frame 1920 x 1080 input completed moving-camera VGGT, Fast SAM and
+ FlowHMR generation while worker policies were given 24 GiB available RAM.
+ This simulated the reported availability; the physical test PC had more RAM.
+ VGGT peak process RAM was 8.89 GiB and peak Torch CUDA allocation 6.32 GiB.
+ This does not establish a minimum RAM requirement or behavior on other GPUs.
+- Qt timer/worker-tree integration tests simulated low available RAM, low Windows
+ allocation headroom and critical pressure. Workers and their children stopped
+ in 0.65–1.14 seconds; stage errors were saved and prior committed test data
+ survived. One low sample followed by recovery did not stop a job. The largest
+ observed 16 ms UI-timer gap was 31.8 ms in these short tests.
+- Injected CPU MemoryError and CUDA allocation failures returned explicit failed
+ events and retained existing motion files. A real FlowHMR retry completed and
+ cleared its pending marker. Actual system RAM was never exhausted deliberately.
+- Exact policy-only file-hash aliases preserve preceding generic/GVHMR signatures
+ and all three ExMR stage identities. Later byte changes invalidate them normally.
+ ExMR identity checks used synthetic input stamps and installed model statistics;
+ full ExMR and GVHMR inference were not repeated. GVHMR allocation/retry control
+ flow was exercised with a test model and simulated allocator observations.
+- Tests and generated inputs/results remain outside the source checkout. Runtime
+ monitoring cannot guarantee intervention before every sudden large allocation.
+
+## ComfyUI-style external VRAM margin (2026-10-28)
+
+- Shared, FlowHMR and ExMR CUDA allocator budgets now subtract 600 MiB from
+ current free VRAM on Windows, or 700 MiB above 15 GiB GPU capacity, matching
+ [ComfyUI's external-use margin](https://github.com/Comfy-Org/ComfyUI/blob/master/comfy/model_management.py).
+ The old FlowHMR/ExMR fixed 3/2 GiB deductions and extra 95/90% caps are removed.
+ ComfyUI's separate 0.8 GiB inference planning allowance is not another allocator
+ deduction: weights, activations and temporary buffers share the allowed budget.
+ This does not implement ComfyUI's offloading or guarantee free memory against
+ other applications or non-PyTorch allocations.
+- Boundary checks covered simulated 4/8/12/15/16/24/32 GiB capacities, the exact
+ 15 GiB transition, exhausted free memory and all four allocator call sites.
+ Existing batch backoff and GVHMR dense-OOM/full-key retry checks passed.
+- On the RTX 5090 test PC, all three isolated runtime profiles applied a 700 MiB
+ margin, performed CUDA allocations, raised a real allocator OOM under a tiny
+ test cap and successfully allocated again after restoring the normal budget.
+ The test deliberately limited the allocator rather than exhausting the GPU.
+- A private 12-frame 1080 x 1920 clip completed FlowHMR camera/Fast SAM/generation,
+ GVHMR observations/generation and ExMR keypoints/features/generation using the
+ installed model weights. Other GPUs and long clips were not tested here.
+ FlowHMR generation from identical cached features produced identical motion
+ tensors with the old and new allocator caps.
+- Existing generic/GVHMR cache fingerprints and all three ExMR stage identities
+ were retained. Test code, inputs, generated motion and logs remain outside the
+ public checkout under the private validation artifacts directory.
+
+## Memory-policy follow-up review (2026-10-28)
+
+- Fixed GVHMR's dense-OOM retry report to compute `fits` from observed capacity
+ rather than always reporting a shortfall. The retry still preserves FP32 and
+ the full key/temporal context and does not reject work using that estimate.
+- Made worker cancellation idempotent while its Windows termination helper is
+ active. Late helper callbacks check that the worker still exists and only clear
+ their own helper reference. Four callback/worker-lifetime combinations, each
+ with five duplicate requests, passed without Qt callback exceptions.
+- ExMR now replaces a previous failed stage status after successful computation
+ or validated cache reuse. Its explicit force flag also bypasses the cache.
+ All three cached ExMR stages repaired failed status without altering tensors;
+ a forced 12-frame generation was separately checked for a non-cached completion.
+- Each model's actual worker entry reported injected CPU allocation failures and
+ real CUDA allocator OOMs with an error, exit code 1 and unchanged prior motion.
+ Tiny allocator limits triggered CUDA failures without exhausting system VRAM.
+ Subsequent retries completed using existing preprocessing data.
+- Four Qt timer/worker-tree tests simulated low RAM, low Windows allocation
+ headroom and critical pressure. Stops completed in 0.66-1.17 seconds, preserved
+ committed results and left no test child worker running. The largest observed
+ 16 ms UI heartbeat gap was 29.12 ms; a transient low sample did not stop work.
+- Exact RAM/VRAM boundaries, Windows commit observations, traceback cleanup,
+ exhausted-batch errors, existing inference cache identities and source checks
+ passed. This is a single-PC regression check, not a low-memory hardware test or
+ a guarantee against sudden allocations or competing GPU applications.
+
These checks describe the recorded examples, not a guarantee for every video,
character or computer. Model weights and registered body data remain separate and
subject to their providers' terms. Review the applicable third-party notices and
diff --git a/mocap/compute_policy.py b/mocap/compute_policy.py
index cf82b7b..7e9874d 100644
--- a/mocap/compute_policy.py
+++ b/mocap/compute_policy.py
@@ -10,7 +10,18 @@ def ram_reserve(total):
def gpu_reserve(total):
- return max(.75*GIB,min(1.5*GIB,total*.10))
+ """ComfyUI's external-use margin, separate from inference working memory."""
+ mib=1024**2
+ return (600+(100 if total>15*GIB else 0))*mib if os.name=='nt' else 400*mib
+
+
+def gpu_memory_fraction(free,total):
+ """Budget the CUDA allocator from current free VRAM, without a second cap.
+
+ Model weights, activations and temporary inference buffers share this budget.
+ It does not cap non-PyTorch allocations or reserve memory against other apps.
+ """
+ return max(0.,min(1.,(free-gpu_reserve(total))/total))
def worker_threads(stage, logical=None):
@@ -80,31 +91,14 @@ def image_plan(stage,free_vram,available_ram,mode=None):
'halo_frames':720,'precision':'float32','flip_test':True,'mode':mode}
-def resource_error(stage,frames,available_ram,total_ram,free_vram=None,total_vram=None):
- """Conservative admission estimates, not a claim of universal memory bounds."""
- frames=max(0,frames)
- fixed={'track':2.,'people':2.2,'person':1.,'pva':5.,'gvhmr':4.,'features':4.,'refine':2.2,
- 'footmr':3.5,'handflow':10.,'correct':.8,'export':1.,'mesh':1.}.get(stage,.5)*GIB
- per_frame={'track':512,'pva':2048,'features':8192,'gvhmr':16384,'refine':8192,
- 'footmr':16384,'handflow':32768,'correct':8192,'export':16384,'mesh':16384}.get(stage,4096)
- required=fixed+frames*per_frame+ram_reserve(total_ram)
- if available_ram<required:
- return (f'Not enough available RAM for {stage}. Need about {required/GIB:.1f} GiB including '
- f'the system reserve; {available_ram/GIB:.1f} GiB available. Close other apps or trim the clip.')
- if free_vram is not None:
- # Include whole-sequence intermediates and the selected attention path.
- gpu={'track':.6,'pva':5.2,'gvhmr':3.,'features':3.,'refine':.3,'footmr':3.,'handflow':3.8}.get(stage,.3)*GIB
- if stage=='pva':gpu=(3.5+.014*min(max(4,frames),120))*GIB
- # Upstream explicitly materializes an 8-head FP32 attention matrix,
- # plus another score/softmax buffer. This is quadratic, not image batching.
- if stage=='gvhmr':gpu=gvhmr_plan(frames,free_vram,total_vram or free_vram)['estimated_bytes']
- if stage=='refine':gpu+=frames*262144
- reserve=gpu_reserve(total_vram or free_vram)
- if free_vram<gpu+reserve:
- return (f'Not enough free GPU memory for {stage} and this clip length. Estimated need '
- f'{(gpu+reserve)/GIB:.1f} GiB including the desktop reserve; '
- f'{free_vram/GIB:.1f} GiB free. Close GPU apps or trim the clip.')
- return None
+def memory_pressure_message(available,total,commit=None):
+ """Report measured system pressure, never a predicted stage allocation."""
+ reserve=ram_reserve(total)
+ if available>=reserve and (commit is None or commit>=GIB):return None
+ detail=f'Available RAM {available/GIB:.2f} GiB (system reserve {reserve/GIB:.2f} GiB)'
+ if commit is not None:detail+=f'; Windows allocation headroom {commit/GIB:.2f} GiB'
+ return ('Processing stopped because available system memory is low. '+detail+
+ '. Close other apps or use a shorter clip. Completed stages can be reused.')
def retry_cuda(operation,batch,on_retry,oom_type=None,cleanup=None):
diff --git a/mocap/exmr_backend.py b/mocap/exmr_backend.py
index c83b6bb..8c4792d 100644
--- a/mocap/exmr_backend.py
+++ b/mocap/exmr_backend.py
@@ -8,6 +8,8 @@ import gc, hashlib, json, math, os, sys, time
import numpy as np
from .paths import ROOT, HOME, UPSTREAM
from .storage import atomic_json, sha256
+from .resource_cache import code_hash
+from .compute_policy import gpu_memory_fraction
from .result_artifacts import file_stat
from .exmr_options import saved
@@ -35,19 +37,6 @@ def scene_root(project):
return root
-def admission(stage,n,ram,vram=None):
- gib=1024**3
- if n<1:raise ValueError('ExMR clip is empty')
- # Entire temporal context is retained. Attention has quadratic buffers;
- # admission and an allocator cap fail safely instead of shortening a take.
- temporal=max(5.,2.+8*4*4*n*n/gib)
- gpu={'exmr_preprocess':max(12.,temporal),'exmr_features':6.,'exmr':temporal}[stage]
- required_ram={'exmr_preprocess':max(23.,temporal+5.),'exmr_features':16.,'exmr':max(10.,gpu+5.)}[stage]
- if ram<(required_ram+4)*gib:
- raise MemoryError(f'ExMR needs about {required_ram+4:.1f} GiB available RAM for this stage and the desktop. Close other apps or trim the clip.')
- if vram is not None and vram<(gpu+2)*gib:
- raise MemoryError(f'ExMR needs about {gpu+2:.1f} GiB free VRAM including desktop headroom for this stage. Close GPU apps or trim the clip.')
-
def activate():
import torch,cv2
@@ -151,7 +140,7 @@ def identity(project,stage):
'exmr_features':('image_io.py','body_features.py','hand_features.py'),
'exmr':(),
}[stage]},
- code=sha256(Path(__file__)),upstream=sha256(UPSTREAM/'ExMR/RGB_MOCAP_PROVENANCE.json'))
+ code=code_hash(Path(__file__)),upstream=sha256(UPSTREAM/'ExMR/RGB_MOCAP_PROVENANCE.json'))
def frame_dir(project,n):
@@ -191,12 +180,20 @@ def validate_native(native,n):
if tuple(native['static_conf_logits'].shape)!=(n,6) or not torch.isfinite(native['static_conf_logits']).all():raise ValueError('Invalid ExMR contact predictions')
+def complete_stage(project,stage,output,elapsed,cached,emit):
+ state=json.loads((project/'project.json').read_text(encoding='utf-8'))
+ state.setdefault('stages',{})[stage]=dict(status='complete',output=str(output),elapsed=elapsed)
+ atomic_json(project/'project.json',state)
+ emit('complete',stage=stage,cached=cached,elapsed=0 if cached else elapsed,output=str(output))
+
+
def run_stage(project,stage,result,emit,force=False):
import torch,cv2,psutil
from .models import missing,BY_KEY
from .engines import save_tensor
project=Path(project);state=json.loads((project/'project.json').read_text(encoding='utf-8'));n=state['frames']
if stage not in STAGES or result not in ('auto','initial','corrected_initial'):raise ValueError('Unsupported ExMR stage/result')
+ if n<1:raise ValueError('ExMR clip is empty')
absent=missing(stage)
if absent:raise ValueError('Open ExMR Model Manager and prepare: '+', '.join(m.name for m in absent))
signature=identity(project,stage);receipt=project/(stage+'_receipt.json');pending=project/(stage+'_pending.json')
@@ -205,7 +202,7 @@ def run_stage(project,stage,result,emit,force=False):
cached=False
try:
old=json.loads(receipt.read_text(encoding='utf-8'))
- cached=not pending.exists() and old['identity']==signature and all(file_stat(project/k)==v for k,v in old['outputs'].items())
+ cached=not force and not pending.exists() and old['identity']==signature and all(file_stat(project/k)==v for k,v in old['outputs'].items())
if cached:
for name in outputs:
if name.endswith('.pt'):
@@ -214,10 +211,10 @@ def run_stage(project,stage,result,emit,force=False):
elif stage!='exmr' and (len(value)!=n or not torch.isfinite(value).all()):cached=False
except (OSError,ValueError,KeyError,RuntimeError,EOFError):cached=False
if cached:
- emit('complete',stage=stage,cached=True,elapsed=0,output=str(project/outputs[0]));return
+ complete_stage(project,stage,project/outputs[0],old.get('elapsed',0),True,emit);return
if not torch.cuda.is_available():raise RuntimeError('ExMR requires a supported NVIDIA CUDA GPU. Check System in Help for details.')
- started=time.monotonic();admission(stage,n,psutil.virtual_memory().available,torch.cuda.mem_get_info()[0])
- free,total=torch.cuda.mem_get_info();torch.cuda.set_per_process_memory_fraction(min(.9,(free-2*1024**3)/total))
+ started=time.monotonic()
+ free,total=torch.cuda.mem_get_info();torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
torch.set_num_threads(4);cv2.setNumThreads(2);torch.manual_seed(0);np.random.seed(0)
torch.cuda.reset_peak_memory_stats();atomic_json(pending,dict(identity=signature))
# Invalidate the old source generation as soon as new observations begin.
@@ -274,4 +271,4 @@ def run_stage(project,stage,result,emit,force=False):
elapsed=time.monotonic()-started,ground_snap=False,native_precision=True))
pending.unlink(missing_ok=True)
if stage=='exmr':(project/'exmr_pending.json').unlink(missing_ok=True)
- emit('complete',stage=stage,cached=False,elapsed=time.monotonic()-started,output=str(project/outputs[0]))
+ complete_stage(project,stage,project/outputs[0],time.monotonic()-started,False,emit)
diff --git a/mocap/flow_backend.py b/mocap/flow_backend.py
index 93ff0b0..8599f8a 100644
--- a/mocap/flow_backend.py
+++ b/mocap/flow_backend.py
@@ -8,6 +8,7 @@ import gc, hashlib, json, math, os, sys, uuid
import numpy as np
from .paths import ROOT, UPSTREAM
from .storage import atomic_json, sha256
+from .compute_policy import gpu_memory_fraction
from .result_artifacts import file_stat
VERSION=1
@@ -38,27 +39,11 @@ def camera_interval(frames,requested=0):
return requested or max(1,math.ceil((frames-1)/127))
-def admission(stage,frames,available_ram,free_vram=None,interval=1):
- gib=1024**3
+def validate_length(frames):
+ """Retain the pinned model's real context limit, without memory estimates."""
if frames<1:raise ValueError('The motion clip is empty')
- # Preserve whole-sequence context and the pinned 5000-frame RoPE limit.
if frames>MAX_FRAMES:
raise ValueError(f'FlowHMR supports up to {MAX_FRAMES:,} frames ({MAX_FRAMES/30:.1f} seconds at 30 fps). Trim the timeline clip; full temporal context is retained.')
- if stage=='flow_camera' and interval==-1:
- if available_ram<5*gib:raise MemoryError('Static camera needs available RAM including a desktop reserve')
- return
- samples=min(frames,math.ceil((frames-1)/interval)+1) if interval>0 else frames
- # FP32 MATH attention holds three score-size buffers over both N-frame
- # branches, with 16 heads. Measured at 4191 and 5000 frames on the pinned
- # runtime; includes model/intermediate headroom, without changing attention.
- motion_gpu=max(4*gib,2*gib+3*16*4*(2*frames)**2)
- required=(7+.0003*samples*samples)*gib if stage=='flow_camera' else 5*gib if stage=='flow_features' else motion_gpu
- ram={'flow_camera':26,'flow_features':15,'flowhmr':12,'flow_export':3}.get(stage,3)*gib
- if stage=='flowhmr':ram=max(ram,motion_gpu+7*gib)
- if available_ram<ram+4*gib:
- raise MemoryError(f'FlowHMR {stage} needs about {(ram/gib+4):.1f} GiB of available RAM including a desktop reserve. Close other apps or use a shorter clip.')
- if free_vram is not None and free_vram<required+3*gib:
- raise MemoryError(f'FlowHMR needs about {(required+3*gib)/gib:.1f} GiB free GPU memory for this stage and the desktop. Use Automatic camera sampling, close GPU apps, or trim the clip.')
def activate():
@@ -310,12 +295,8 @@ def run_stage(project,stage,result,emit,force=False):
if stage!='flow_export' and not static:
if not torch.cuda.is_available():raise RuntimeError('FlowHMR requires a supported NVIDIA CUDA GPU.')
free,total=torch.cuda.mem_get_info()
- admission(stage,n,psutil.virtual_memory().available,free,interval)
- if stage=='flow_features':
- # Fail before lengthy SAM extraction when the following full-context
- # generation cannot fit; camera/SAM sampling never reduces motion frames.
- admission('flowhmr',n,psutil.virtual_memory().available,free,interval)
- if free is not None:torch.cuda.set_per_process_memory_fraction(max(.01,min(.95,(free-3*1024**3)/total)))
+ validate_length(n)
+ if free is not None:torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
if not static:activate()
atomic_json(pending,dict(stage=stage,started=time.time()))
if stage=='flow_camera':output=camera(project,emit,force=force)
@@ -356,7 +337,7 @@ def run_post(project,stage,result,emit,force=False):
if kind not in ('initial','corrected_initial'):raise ValueError('FlowHMR supports original or corrected original motion only')
absent=missing('flow_export')
if absent:raise ValueError('Import the SMPL-H neutral body model in FlowHMR Model Manager.')
- admission('flow_export',json.loads((project/'project.json').read_text(encoding='utf-8'))['frames'],psutil.virtual_memory().available)
+ validate_length(json.loads((project/'project.json').read_text(encoding='utf-8'))['frames'])
activate()
from .flow_placement import ensure_group
ensure_group(project)
diff --git a/mocap/gui.py b/mocap/gui.py
index 9ea4141..4919615 100644
--- a/mocap/gui.py
+++ b/mocap/gui.py
@@ -1360,27 +1360,31 @@ class MainWindow(CharacterWorkspace,ModelWorkspace,ProjectSaving,PeopleWorkspace
self.status.setText('Cancelling project save...')
self.cancel_button.setEnabled(False)
return
+ from shiboken6 import isValid
+ pending=getattr(self,'cancel_process',None)
+ if pending is not None and isValid(pending) and pending.state()!=QProcess.NotRunning:
+ return
self.task_timer.stop();self.task_state.active=False;self.task_info.setText('Stopping...')
self.guard_timer.stop()
self.cancelled = True
self.jobs.clear()
worker = self.process
- if worker and worker.processId():
+ if worker and isValid(worker) and worker.processId():
if os.name == "nt":
# Stop FFmpeg/other descendants before losing their parent PID.
helper = QProcess(self)
self.cancel_process = helper
def fallback(error):
- if error == QProcess.FailedToStart and self.process is worker:
+ if error == QProcess.FailedToStart and self.process is worker and isValid(worker):
worker.kill()
- from shiboken6 import isValid
+ if error == QProcess.FailedToStart:
+ if self.cancel_process is helper:self.cancel_process=None
if isValid(helper):helper.deleteLater()
helper.errorOccurred.connect(fallback)
def cancelled(code, _):
- if code and self.process is worker:
+ if code and self.process is worker and isValid(worker):
worker.kill()
- self.cancel_process = None
- from shiboken6 import isValid
+ if self.cancel_process is helper:self.cancel_process=None
if isValid(helper):helper.deleteLater()
helper.finished.connect(cancelled)
helper.start("taskkill.exe", ["/PID", str(worker.processId()), "/T", "/F"])
diff --git a/mocap/gvhmr_attention.py b/mocap/gvhmr_attention.py
index f3bce33..c3cc7c8 100644
--- a/mocap/gvhmr_attention.py
+++ b/mocap/gvhmr_attention.py
@@ -9,7 +9,7 @@ from types import MethodType
def predict(model,data,project,emit):
- """Budget before allocation, and retry dense OOM once with released traceback."""
+ """Select full-context attention and recover once from an actual dense OOM."""
import gc
import torch
from .compute_policy import gvhmr_plan,gpu_reserve
@@ -24,8 +24,6 @@ def predict(model,data,project,emit):
return min(free+allocated,room+gpu_reserve(total)),total
free,total=capacity()
selected=gvhmr_plan(frames,free,total)
- if not selected['fits']:
- raise RuntimeError('Not enough free GPU memory for full-context GVHMR. Close GPU apps or trim the clip.')
atomic_json(project/'gvhmr_attention_plan.json',selected)
emit('compute_plan',**selected)
failed=False
@@ -40,9 +38,10 @@ def predict(model,data,project,emit):
gc.collect();torch.cuda.empty_cache()
free,total=capacity()
low=gvhmr_plan(frames,0,total)
- if frames<=2048 or low['estimated_bytes']>free-gpu_reserve(total):
+ if frames<=2048:
raise RuntimeError('Not enough free GPU memory for full-context GVHMR. Close GPU apps or trim the clip.')
- low.update(fits=True,reduced_after_oom=True)
+ low.update(reduced_after_oom=True,
+ fits=low['estimated_bytes']<=max(0,free-gpu_reserve(total)))
atomic_json(project/'gvhmr_attention_plan.json',low)
emit('compute_plan',**low)
with torch.inference_mode(),query_split(model,True):
diff --git a/mocap/processing_guard.py b/mocap/processing_guard.py
index 1cbc0c6..af6488d 100644
--- a/mocap/processing_guard.py
+++ b/mocap/processing_guard.py
@@ -2,7 +2,7 @@
import ctypes
import os
import time
-from .compute_policy import GIB,ram_reserve,idle_timeout
+from .compute_policy import memory_pressure_message,idle_timeout
class PerformanceInfo(ctypes.Structure):
@@ -51,10 +51,11 @@ class ProcessingGuard:
except psutil.NoSuchProcess:return None
except psutil.AccessDenied:pass
memory=psutil.virtual_memory();commit=commit_headroom()
- low=memory.available<ram_reserve(memory.total) or (commit is not None and commit<GIB)
+ message=memory_pressure_message(memory.available,memory.total,commit)
+ low=message is not None
self.low_samples=self.low_samples+1 if low else 0
- if self.low_samples>=2:
- return 'Processing stopped to protect system memory. Close other apps, select Low Memory, or trim the clip. Completed stages can be reused.'
+ critical=memory.available<256*1024**2 or (commit is not None and commit<256*1024**2)
+ if self.low_samples>=2 or critical:return message
if idle_timeout(self.last_output,self.last_cpu_change,now):
return 'Processing stopped after 180 seconds without output or CPU activity. The app is still available; retry or use a shorter clip.'
return None
diff --git a/mocap/resource_cache.py b/mocap/resource_cache.py
new file mode 100644
index 0000000..636403c
--- /dev/null
+++ b/mocap/resource_cache.py
@@ -0,0 +1,24 @@
+"""Cache aliases for the reviewed memory-policy-only transition.
+
+Match complete file bytes: later numerical edits automatically invalidate caches.
+Do not add aliases for changed inference algorithms or settings.
+"""
+from .storage import sha256
+
+POLICY_ONLY = {
+ "6d2702884592ca28a6fba2875b24dc2afd7ef149f8bfb24ac11acb95d9c60f0f": "8e5e7e5e2c6f677299d4a6081f20c5e7c2fb0fe17f18c0e0a4e5599bb01f8b1a",
+ "61da72ab4b9ea248ee5c79eefee6282b91c7dc1773fcf72e9186d382893c4f04": "8e5e7e5e2c6f677299d4a6081f20c5e7c2fb0fe17f18c0e0a4e5599bb01f8b1a",
+ "a0fa66d293dde00400c3367fc68cb6b9faeae591c87cabeeb8e06a0bf9f5feaa": "d0d32032fad3470cc4801134d4bf4fafdf8bfc5bc805228ece5cc8dabe4f370e",
+ "0b479a3a33a4f4df3804ee57e233f314dd5554044c1af6a274317878241fc972": "6c1de70d9628ae41528a4494de39034764e0b938982d61c7470e631a371f4435",
+ "f47c0da4b7f7671931174e2aaf8ed09a7d1fde1047fd3c07d96065b8cc14425b": "3125b5a360d71c229a958a553548af0f03c82b58698f1b758a14f2048a2f7e92",
+ "7cf59b6f095e76bbaf372664659a0fe4810a499473e06db64056cf4865bdd4d6": "8e5e7e5e2c6f677299d4a6081f20c5e7c2fb0fe17f18c0e0a4e5599bb01f8b1a",
+ "951f52af4e4820ab63cda224dbda7b6e3d464a3d893a81759d89b99226546e1e": "6c1de70d9628ae41528a4494de39034764e0b938982d61c7470e631a371f4435",
+ "a2fb18686236d6852df13f03b95890860e961b63072d809eeaf5cd3331edd6bc": "3125b5a360d71c229a958a553548af0f03c82b58698f1b758a14f2048a2f7e92",
+ "3d166c1b0807397328f82f973b7617118b3c35d6435f4f85036bd8be2925268a": "d0d32032fad3470cc4801134d4bf4fafdf8bfc5bc805228ece5cc8dabe4f370e",
+ "86e0f23ca7a6d06bf177436bf8d2a8462577a8f151d3bdc7380c63dcdef016a3": "8e5e7e5e2c6f677299d4a6081f20c5e7c2fb0fe17f18c0e0a4e5599bb01f8b1a"
+}
+
+
+def code_hash(path):
+ actual=sha256(path)
+ return POLICY_ONLY.get(actual,actual)
diff --git a/mocap/worker.py b/mocap/worker.py
index fa49358..14e56c7 100644
--- a/mocap/worker.py
+++ b/mocap/worker.py
@@ -10,6 +10,7 @@ from pathlib import Path
from .paths import ROOT
from .storage import atomic_json, sha256
+from .resource_cache import code_hash
from .motion_tools import MOTION_TOOLS, resolve_motion_result, RESULTS, result_sources, result_options, result_is_current, base_result, body_result, has_handflow, require_supported_project, UnsupportedMotionTool
PREFIX = "@@MOCAP@@"
@@ -95,7 +96,7 @@ def fingerprint(stage, project, result="auto", _worker_hash=None, _legacy_routin
'compute_policy.py':'a5953e6dfe424c30c2992e5e84c3c78e2dc4217c3658f8a7ae622bafdefe484b'}
if stage=='export':
sources.extend(Path(__file__).with_name(name) for name in ('mixamo_rig.py','mixamo_data.py','mixamo_native.py','bvh_bind.py','source_pose_fit.py'))
- identity = {"stage": stage, "code": [(_worker_hash if _worker_hash and p == Path(__file__) else predecessor[p.name] if _legacy_routing and p.name in predecessor else non_generator[p.name] if stage!='export' and p.name in non_generator else sha256(p)) for p in sources], "inputs": [], "models": []}
+ identity = {"stage": stage, "code": [(_worker_hash if _worker_hash and p == Path(__file__) else predecessor[p.name] if _legacy_routing and p.name in predecessor else non_generator[p.name] if stage!='export' and p.name in non_generator else code_hash(p)) for p in sources], "inputs": [], "models": []}
if stage in ('gvhmr','features'):
import torch
identity['runtime']=[str(torch.__version__),torch.version.cuda,torch.backends.cudnn.version(),
@@ -150,7 +151,7 @@ def main() -> int:
parser.add_argument('--correction-mode',choices=['flat','multi_level'],default='flat')
parser.add_argument('--pelvis-offset',type=float,default=0.)
args = parser.parse_args()
- from .compute_policy import configure_worker_cpu,resource_error,gpu_reserve,GIB
+ from .compute_policy import configure_worker_cpu,gpu_memory_fraction,GIB
threads=configure_worker_cpu(args.stage)
os.environ['RGB_MOCAP_STAGE']=args.stage
if args.project:
@@ -256,10 +257,8 @@ def main() -> int:
if args.stage=='people':
if not torch.cuda.is_available():raise RuntimeError('A supported NVIDIA CUDA GPU is required for person detection.')
free,total=torch.cuda.mem_get_info()
- problem=resource_error('track',manifest['frames'],memory.available,memory.total,free,total)
- if problem:raise RuntimeError(problem)
if free is not None:
- torch.cuda.set_per_process_memory_fraction(max(.01,min(.95,(free-gpu_reserve(total))/total)))
+ torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
from .person_tracking import discover,prepare_person
if args.stage=='people':
output=discover(project,emit)
@@ -328,10 +327,8 @@ def main() -> int:
raise RuntimeError('A supported NVIDIA CUDA GPU is required for this model. Check System in Help for details.')
free,total=torch.cuda.mem_get_info()
memory=psutil.virtual_memory()
- problem=resource_error(args.stage,manifest.get('frames',0),memory.available,memory.total,free,total if free is not None else None)
- if problem:raise RuntimeError(problem)
if free is not None:
- torch.cuda.set_per_process_memory_fraction(max(.01,min(.95,(free-gpu_reserve(total))/total)))
+ torch.cuda.set_per_process_memory_fraction(gpu_memory_fraction(free,total))
plan=dict(stage=args.stage,threads=threads,mode=os.environ.get('RGB_MOCAP_COMPUTE_MODE','auto'),
frames=manifest.get('frames',0),available_ram_gib=round(memory.available/GIB,2),
free_vram_gib=round(free/GIB,2) if free is not None else None)