makepad/libs/ai/hub/python/motion_hymotion.py
Admin e37c263b9c ai backbone: the hub era — makepad_ai deleted, every backend is a hub pipe; machine residency elections, job leases, ETA placement; the store only stores; creator pipelines run in the app (aicore)
Squashed from work:
- asset-ai: FastH3 4-step fast video backend; clip keyframes on the wire
- asset-ui: loop video chains — text→image→video that ends where it began
- h3: safetensors -> pruned-Q4_K GGUF quantizer for the 24GB DiT tiers
- h3_quant_gguf verify: row-error gates calibrated to the measured Q4_K floor
- asset-ai realtime: the feedback loop — the source anchors, the drifted frame inits
- asset-ai realtime: a feedback loop survives a resize and travels by default
- asset-ai realtime: the feedback loop frees itself from the feed handshake and pauses for its listener
- asset-ai realtime: the outbound encode leaves the loop's critical path
- asset-ai ocr: the ocr domain — Chandra 2 at page resolution, and the tower goes planner-owned
- llm slots: a lane can hold an image span — embedding prefill and a rope cursor of its own
- vision tower on CUDA: the encode leg gets its two missing kernels
- llm/ocr: one M-RoPE grid encoder for both image paths, and a livelock made an error
- vision tower on CUDA: the f16 GEMM keeps the precision it was throwing away
- live: a feed that moves box takes its trip with it — one seed image
- vision tower on CUDA: the tiled attention becomes bit-exact, and tensor cores go
- llm prefill on CUDA: the MMA attention kernel gets the tile a 4-to-1 model needs
- asset-ai ocr: the CUDA encode lane joins the integration — vision-parity sits beside run's three arms, and the kernels
- Merge branch 'ocr-perf-integration' into work
- asset-ai: the live anchor can follow the trip, and text leaves the 5090
- asset-ai: the camera moves the world, and the world starts still
- asset-import: the EA strategy classics, in the one 2D contract
- rtsmap: one seeded generator for tiled strategy maps
- asset-ui: one card for the strategy classics, with a pack dropdown
- asset-ai: music3 reference-audio path, ocr/h3 backends, registry
- asset: mp4 sample index for range-streaming, chat tools, import profiles
- cnc: tiberium is twelve growth frames, not twelve empty variants
- platform: native file and save dialogs, in-house on all three desktops
- chat: the scan holds out for a lane home
- chat: a full home queues you — take the free lane
- chat: the preload has a percentage, and the boundless cap stops showing
- llm cuda: the 32x2 attention tile — even GQA ratios stay on MMA
- sa3 gets a bake path: the sfx model's tables precomputed by a diffusion-side bin
- sqlite_query: anti-join regression test
- td import: HARV's second frame block is its harvesting cycle, not a turret
- asset-ui: sprite enhancement runs on the 32B dev DiT — distillation, not the prompt, was the ceiling
- ai-hub: makepad-asset-ai becomes makepad-ai-hub at libs/ai/hub, the chat pane becomes makepad-chat-ui, the service bin
- asset-ui: test health fixtures grow the realtime field they were born without
- ai-hub: one home at ~/.makepad — weights/ run/ cache/ logs/, the service cache migrates from ai_content by a single re
- ai-hub: subprocess workers die with the node — process groups everywhere, PDEATHSIG on linux, one KILL_ON_JOB_CLOSE Jo
- ai-hub: the hub object — AiHub::in_process, pipes vocabulary, and the local LLM engine generalized out of mpfiles (aic
- strict-json: the dependency-free JSON module gets its own crate; asset-client re-exports it so nothing downstream move
- ai-hub: the machine layer — node entries, the 0600 machine token, and the residency election that IS the lock (aicore
- ai-hub: MPHUB1 — the fabric beacon only dedicated nodes can send (aicore §4)
- ai-hub: job leases — work lives only while it is renewed (aicore §8)
- asset-creator: the pipeline library is born — specs, the deps gate, and the derived-state law (aicore §9)
- ai-hub: RAM residency facts — the CPU-side twin of residency.rs (aicore §3)
- ai-hub: ETA placement primitives — relative GPU throughput, the four-term estimate, and an observable breakdown (aicor
- ai-hub: leases go live on the wire — origin fields on submit, /job/<id>/keepalive, /bye, and the reaper that cancels w
- ai-hub: the chat providers move in — fleet qwen, openai, grok, claude/codex/grok CLIs, the responses driver, and the w
- asset-creator: the engine — one pipeline run against the hub, deps-gated, spliced, cancellable, resumable-by-construct
- ai-hub: the machine node mode — --machine binds loopback, registers in ~/.makepad/run, and exits on its own once idle
- asset-creator: makepad-creator-run — the detached client for runs that must outlive a window (aicore §9)
- ai-hub: a native Claude Messages-API provider — API-key or Claude Code OAuth, bounded SSE streaming, injected tools (a
- route + converse: off makepad_ai — the Agent seam moves to converse, route's cloud dispatcher rides the hub's Claude p
- asset-creator: the preset tables move in — fifteen chain-policy constants shared by every creator app (aicore §9 / P6)
- makepad_ai is deleted — every backend is a hub pipe, the agent seam lives with its consumers (aicore §14, decided 2026
- ai-hub: loads hold the machine residency election — set_model_state claims on Loaded and publishes the service port (a
- ai-hub: chats run the machine election — route to a serving holder, wait on a loading one, claim and publish when open
- ai-hub: pick_for_domain_eta — ETA-ranked placement over the shared hard-filter core (aicore §6 / P4)
- asset-creator: the engine picks a provider per stage at dispatch time — a chain's later stages see fresh fleet state (
- ai-hub: the fabric secret gates the service HTTP surface — bearer on everything but /health and the ticketed peer path
- vj: DREAM runs execute in the app — pipelines.rs becomes the run it used to watch (aicore §9 / F1)
- asset-creator: the runner — generate one thing and put it in the catalog, one implementation for every surface (aicore
- chat-ui: the session runs in the app — no broker anywhere on the chat path (aicore P8 / F5)
- asset-store: assets.query is a first-class query endpoint — the bounded SQL surface outlives the broker (aicore P8 / F
- asset-creator: CreatorTools — the chat tool pack for a store that only stores (aicore §9 / P8)
- asset-store: the shrink — the store stores (aicore P7)
- importer + asset-server host: the coordination era ends (aicore P7)
- store config purge + asset-ui goes fleet-direct; the derive protocol gets its route proof (aicore P7)
- client + chat dispatcher: the dead wire comes out (aicore P7/P8)
- ai-hub: 0.3.0 — the health version says which era a node runs
- ai-hub: the default fleet is 'gen' — apps hear the LAN without env plumbing
- ai-hub: the preload note percents the prefill, not the job bar
- ai-hub: conversations keep their KV — the wire mirror, the lane identity, the in-turn dynamic context (aicore §7)
- ai-hub: an open-think model is thinking from its first token
- libs: the zero-warning sweep — stitch casts say what they mean, xatlas keeps upstream's surface quietly
- zero-warning sweep, round two — the first full-workspace pass
- zero-warning sweep, round three — the model lanes and the deep examples
- zero-warning sweep, round four — the last stragglers
- zero-warning sweep, round five — vj and chat-ui
- zero-warning sweep, round six — three cascades

Co-authored-by: Claude <info@makepad.nl>
2026-09-01 16:46:31 +02:00

195 lines
8.6 KiB
Python

#!/usr/bin/env python
"""motion_hymotion.py <in.glb> <out.glb> — the motion domain's box script.
Rigged GLB + params sidecar in, animated GLB with NAMED in-place clips out.
Two proven stages from the motion campaign (local/agent_state/motion-123.md):
1. HY-Motion text-to-motion (C:\\ai\\HY-Motion-1.0, THIS interpreter =
venv_hymotion): one prompt line per requested clip ("text#frames#id" in
a txt file under --input_text_dir), local_infer.py --disable_rewrite
--disable_duration_est --num_seeds 1 -> per-task SMPL-H NPZ
(0000000N_000.npz, N = 1-based prompt-line order; Rh/trans/poses156).
Stock local_infer.py exposes no seed argument. This wrapper seeds its
imported `random` module before runpy executes the stock entry point, so
the sidecar seed deterministically controls its generated seed list.
2. Direction-based retarget (venv_unirig python + bpy, retarget_multi.py —
the campaign's retarget.py extended with the --in-place strip): NEVER
the global-delta transfer (double-applies the rest pose). Writes the
final GLB with one named NLA-track animation per clip.
Params sidecar <in.glb>.json (motion_backend.rs MotionParamsJson):
{"prompt": style hint, "clips": ["idle","walk","jump"], "seed": N,
"fps": 30, "in_place": true}
Env knobs:
HYMOTION_DIR repo dir (default C:\\ai\\HY-Motion-1.0)
HYMOTION_MODEL ckpt dir under the repo (default ckpts/tencent/
HY-Motion-1.0 — the FULL 1B model, per user directive:
never downsize for co-residency; motion is hosted on the
96GB box)
UNIRIG_PYTHON bpy-capable python (default C:\\ai\\venv_unirig\\
Scripts\\python.exe)
RETARGET_SCRIPT retarget entry (default C:\\ai\\retarget_multi.py)
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
def progress(frac, stage):
# bpy-as-module can leave the console stdout handle invalid on Windows
# after its subprocess runs (observed: errno 22 on the FINAL print, after
# a fully successful export). Progress is advisory — never let it turn a
# produced artifact into a failed job.
try:
print("@P %.3f %s" % (frac, stage), flush=True)
except OSError:
pass
# Per-clip motion prompts and frame budgets at 30fps. HY-Motion's official
# prompting contract says to describe limb/torso ACTION and explicitly does
# not support visual/subject attributes. Feeding the image prompt (clothes,
# colors, species) into every clip made locomotion needlessly prompt-fragile;
# appearance belongs to TRELLIS/SkinTokens and motion retargets afterwards.
CLIP_RECIPES = {
"idle": ("A person stands in a relaxed neutral idle pose, with subtle breathing, feet apart and arms resting at their sides", 120),
"walk": ("A person walks forward naturally at a steady pace, upright, with alternating arm swing and feet kept apart", 120),
"jump": ("A person bends both knees, jumps straight up once, and lands balanced on both feet", 100),
"run": ("A person runs forward naturally with alternating arm swing", 120),
}
def run_streamed(cmd, cwd, tag, frac_lo, frac_hi):
"""Run a child, stream output, walk the fraction lo->hi on output."""
print("%s: run %r (cwd %s)" % (tag, cmd, cwd), flush=True)
child = subprocess.Popen(
cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1,
)
n = 0
for line in child.stdout:
n += 1
if n % 20 == 0:
frac = min(frac_hi, frac_lo + (frac_hi - frac_lo) * n / 400.0)
progress(frac, "%s: working" % tag)
print("%s| %s" % (tag, line.rstrip("\r\n")), flush=True)
return child.wait()
def main():
if len(sys.argv) != 3:
print("usage: motion_hymotion.py <in.glb> <out.glb>", flush=True)
return 2
in_glb = os.path.abspath(sys.argv[1])
out_glb = os.path.abspath(sys.argv[2])
repo = os.environ.get("HYMOTION_DIR", r"C:\ai\HY-Motion-1.0")
model = os.environ.get("HYMOTION_MODEL", "ckpts/tencent/HY-Motion-1.0")
unirig_py = os.environ.get(
"UNIRIG_PYTHON", r"C:\ai\venv_unirig\Scripts\python.exe"
)
retarget = os.environ.get("RETARGET_SCRIPT", r"C:\ai\retarget_multi.py")
params = {}
try:
with open(in_glb + ".json", "r", encoding="utf-8") as f:
params = json.load(f)
except OSError:
pass
hint = (params.get("prompt") or "a person").strip() or "a person"
clips = params.get("clips") or ["idle", "walk", "jump"]
seed = int(params.get("seed") or 42)
in_place = bool(params.get("in_place", True))
print("motion: hint %r clips %r seed %d in_place %r"
% (hint, clips, seed, in_place), flush=True)
work = tempfile.mkdtemp(prefix="motion_", dir=os.path.dirname(in_glb))
try:
# ---- stage 1: HY-Motion clips -----------------------------------
# One txt file (line = "prompt#frames#id") in its own directory:
# local_infer.py scans --input_text_dir for txt/json files.
prompt_dir = os.path.join(work, "prompts")
os.makedirs(prompt_dir, exist_ok=True)
with open(os.path.join(prompt_dir, "job.txt"), "w", encoding="utf-8") as f:
for i, clip in enumerate(clips):
recipe, frames = CLIP_RECIPES.get(
clip, ("A person performs this action: " + clip, 120)
)
f.write("%s#%d#%d\n" % (recipe, frames, i))
out_dir = os.path.join(work, "npz")
os.makedirs(out_dir, exist_ok=True)
progress(0.05, "hy-motion: loading (text encoder + dit)")
code = run_streamed(
[
# local_infer.generate_random_seeds uses Python's module-level
# random generator. Seed it in-process, then execute the
# unmodified official CLI with its normal argv contract.
sys.executable, "-c",
"import random,runpy; random.seed(%d); "
"runpy.run_path('local_infer.py', run_name='__main__')" % seed,
"--model_path", model,
"--input_text_dir", prompt_dir,
"--output_dir", out_dir,
"--disable_rewrite", "--disable_duration_est",
"--num_seeds", "1",
],
repo, "hym", 0.05, 0.55,
)
if code != 0:
print("motion: local_infer.py exit %d" % code, flush=True)
return 1
# Collect one NPZ per clip, in prompt order (outputs are
# 0000000N_000.npz under the output dir, possibly nested).
npzs = []
for root, _dirs, files in os.walk(out_dir):
for name in sorted(files):
if name.endswith(".npz"):
npzs.append(os.path.join(root, name))
npzs.sort()
if len(npzs) < len(clips):
print("motion: expected %d npz, found %d (%r)"
% (len(clips), len(npzs), npzs), flush=True)
return 1
progress(0.60, "retarget: %d clips onto rig" % len(clips))
# ---- stage 2: retarget onto the input rig -----------------------
# retarget_multi.py CLI = the campaign retarget.py's ("clip=npz"
# positional pairs) + the --in-place flag.
cmd = [unirig_py, retarget, in_glb, out_glb]
for clip, npz in zip(clips, npzs):
cmd.append("%s=%s" % (clip, npz))
if in_place:
cmd.append("--in-place")
code = run_streamed(cmd, os.path.dirname(retarget) or ".",
"retarget", 0.60, 0.92)
if code != 0:
# bpy-as-module is known to crash with 0xC0000005 during
# interpreter TEARDOWN, after a fully successful export
# (observed on the box the first standalone run). The output
# contract below is the real gate — log and fall through.
print("motion: retarget exit %d (checking output anyway — "
"bpy teardown crashes are benign)" % code, flush=True)
# Output contract: a GLB with skins AND animations.
try:
with open(out_glb, "rb") as f:
head = f.read(96 * 1024 * 1024)
except OSError as e:
print("motion: output missing (retarget exit %d): %s"
% (code, e), flush=True)
return 1
if head[:4] != b"glTF" or b'"skins"' not in head \
or b'"animations"' not in head:
print("motion: output is not an animated rigged GLB", flush=True)
return 1
progress(0.98, "motion: done")
return 0
finally:
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
sys.exit(main())