Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(model-text2motion): stop the motion lane being starved of a GPU by idle us-east4 standbys
nirholasb40f568decc2
diff --git a/prompts/swarm-100/worker-model-text2motion.md b/prompts/swarm-100/worker-model-text2motion.mddeleted file mode 100644index eb92a3756..000000000--- a/prompts/swarm-100/worker-model-text2motion.md+++ /dev/null@@ -1,98 +0,0 @@-# Worker audit: workers/model-text2motion--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Read workers/model-text2motion/README.md and its build config (cloudbuild.yaml,- Dockerfile, package.json; whichever exist).-2. Is it deployed?-- export PATH="$HOME/google-cloud-sdk/bin:$PATH"- gcloud run services list --project aerial-vehicle-466722-p5 --region us-central1 | grep -i "model-text2motion" || echo "not deployed as its own service"--3. If deployed: which commit is the running revision built from, and does main- contain fixes it has not picked up? A fix in main can sit undeployed for- days; never call a bug unfixed without checking the running revision.-4. Logs, last 24h, if deployed:-- gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="<service name from step 2>"' --freshness=24h --limit 100 --project aerial-vehicle-466722-p5--## Task: bring this worker to verified-healthy--1. README accuracy: what it does, how to run it, its inputs and outputs. Fix- every stale claim; a README that lies fails the audit.-2. Build it the way its own config says. The build must succeed from a clean- checkout of this worktree. Model workers that need weights stage them from- gs://three-ws-model-weights (staging weights is part of the job, not a- blocker).-3. Run its tests; add a smoke test if it has none that proves its core path.-4. If deployed: last 24h of logs free of unhandled errors; fix root causes in- code and commit. Redeploying is owner-gated: prepare everything so the- deploy is one command and say so in the report.-5. If not deployed by design: its README must state how and where it runs, and- that path must be verified locally.--## Definition of done--- [ ] Build succeeds from this worktree with the worker's own config.-- [ ] Tests pass, including at least one core-path smoke test.-- [ ] README verified accurate against the code.-- [ ] If deployed: running revision identified, 24h logs clean or root causes- fixed and committed (deploy itself flagged for the owner).-- [ ] npm run check:rules -- --paths <touched files> exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/worker-model-text2motion.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/workers/model-text2motion/README.md b/workers/model-text2motion/README.mdindex 82b6be216..2c86e1411 100644--- a/workers/model-text2motion/README.md+++ b/workers/model-text2motion/README.md@@ -2,7 +2,7 @@Text → animation. A GPU Cloud Run worker that samples a motion-diffusion modelfrom a natural-language prompt and returns a **retargetable three.js-AnimationClip JSON** on the canonical Wolf3D skeleton — the same format the+AnimationClip JSON** on the canonical Wolf3D skeleton, the same format thecurated animation library serves, so a generated motion retargets onto anyrigged avatar with the existing engine (`src/animation-retarget.js`), identicalto a preset.@@ -12,59 +12,162 @@ motion that does not pre-exist, rather than only applying preset clips.## Model-[MDM — Motion Diffusion Model](https://github.com/GuyTevet/motion-diffusion-model)+[MDM, Motion Diffusion Model](https://github.com/GuyTevet/motion-diffusion-model)(GuyTevet), **MIT-licensed** → commercial-safe. Chosen over MoMask / T2M-GPTspecifically for the unambiguous commercial license. Swapping models touches only`mdm_sampler.py`; the contract and the SMPL→clip conversion are model-agnostic.+The deployed checkpoint is the HumanML3D text-to-motion model: `arch=trans_enc`,+`diffusion_steps=50`, `guidance_param=2.5` (read from the checkpoint's own+`args.json` at load, not hardcoded).+## Contract-Identical shape to the other `model-*` workers:+Identical shape to the other `model-*` workers. Every route except `/health`+requires `Authorization: Bearer $API_KEY`.```POST /infer { prompt, duration_seconds?=4, fps?=30, job_id? } → 202 { task_id, status }-GET /tasks/:id → { task_id, status, result_url?, frames?, fps?, error? }-GET /health → { ok, model_loaded }+GET /tasks/:id → { task_id, status, model, result_url?, frames?, fps?, elapsed_ms?, error? }+GET /health → { ok, model_loaded, status: loading|ready|failed, load_error }```-`result_url` is a three.js `AnimationClip.toJSON()` document in GCS. The platform-reaches this worker through the GCP provider's `text2motion` mode-(`GCP_TEXT2MOTION_URL`), exposed as:+`prompt` is 3 to 1000 characters, `fps` is 8 to 60, and `duration_seconds` is+clamped to `MAX_DURATION_SEC` (default 10). `result_url` is a three.js+`AnimationClip.toJSON()` document in GCS. Task state is in-process memory, so a+`task_id` does not survive an instance restart; the platform polls within a+single job's lifetime and treats a missing task as a failed job.++The platform reaches this worker through the GCP provider's `text2motion` mode+(`GCP_TEXT2MOTION_URL`, key `GCP_RECONSTRUCTION_KEY`), exposed as:- REST: `POST /api/forge-motion` (+ `GET /api/forge-motion?job=<id>`)- MCP: `text_to_animation` (generates + retargets onto a model_url in one call)## Pipeline-1. `mdm_sampler.MdmSampler.sample(prompt, n_frames)` → SMPL motion: local joint- rotations `(T,24,3)` axis-angle + root translation `(T,3)`.-2. `smpl_to_clip.smpl_motion_to_clip(poses, trans, fps)` → AnimationClip JSON with- canonical Wolf3D bone names (`Hips.quaternion`, …) + `Hips.position`.-3. Upload JSON to `gs://$GCS_BUCKET/motion-clips/mdm/<task_id>.json`; return the URL.--## What is tested vs deploy-validated--- **Tested here** (`test_smpl_to_clip.py`, 16 cases, pure NumPy): axis-angle →- quaternion correctness + unit-norm, the SMPL→Wolf3D bone mapping, clip JSON- shape (track names, value lengths, monotonic times, duration), rest-offset- calibration, flattened-pose input, single-frame/static, and input validation.- The JS provider mode + REST endpoint are covered by `tests/api/forge-motion.test.js`.-- **Deploy-validated** (needs the GPU image + checkpoint): the MDM inference in- `mdm_sampler.py`. In particular, `_decode_to_smpl()` — recovering SMPL- axis-angle from the HumanML3D feature representation — is the integration point- to confirm against the deployed checkpoint's representation (positions vs- rotation output). The SMPL→Wolf3D **rest-pose offset** (`rest_offsets` in- `smpl_to_clip`) defaults to identity and should be calibrated against the- Wolf3D rig on first deploy for best fidelity; the retarget engine already- aligns bone names and hip scale.+1. `mdm_sampler.MdmSampler.sample(prompt, n_frames)` samples the diffusion model,+ denormalizes with the HumanML3D dataset stats, and calls upstream's+ `recover_from_ric` to get global joint **positions** `(T,22,3)`.+2. `mdm_sampler._positions_to_local_quats` recovers each joint's **local+ rotation** from where its own children landed (Kabsch fit against the rest+ directions), then `_quat_to_axis_angle` + `_resample` produce SMPL-indexed+ axis-angle `(T,22,3)` plus root translation `(T,3)` at the requested frame+ count.+3. `smpl_to_clip.smpl_motion_to_clip(poses, trans, fps)` emits the AnimationClip+ JSON: 22 quaternion tracks with canonical Wolf3D bone names+ (`Hips.quaternion`, …) plus `Hips.position`.+4. Upload to `gs://$GCS_BUCKET/motion-clips/mdm/<task_id>.json`; return the URL.++## Environment++| Var | Required | Purpose |+|---|---|---|+| `API_KEY` | yes | Bearer secret; mounted from Secret Manager (`avatar-reconstruction-key`) |+| `GCS_BUCKET` | yes | Output bucket (`three-ws-avatar-reconstructions`) |+| `MOTION_MODEL_DIR` | no | Checkpoint dir, default `/weights/mdm` |+| `MAX_CONCURRENT` | no | In-instance job semaphore, default 2 |+| `MAX_DURATION_SEC` | no | Hard cap on requested clip length, default 10 |++## Weights++`gs://three-ws-model-weights/mdm/` holds exactly two objects, mounted at+`/weights/mdm` by the Cloud Run GCS volume: `model.pt` (78 MiB checkpoint) and+`args.json` (the checkpoint's own hyperparameters).++The real SMPL body model (`SMPL_NEUTRAL.pkl`) is deliberately **not** staged: it+is gated behind SMPL's own registration license, and this worker never needs it.+`model.mdm.MDM` eagerly constructs a `Rotation2xyz`/`SMPL` submodule that would+load it, so `mdm_sampler` patches in a real (license-file-free) `nn.Module`+stand-in purely so `.to(device)` / `.eval()` have something to walk into. That+submodule's output is never consumed: motion is decoded from the HumanML3D+feature vectors instead. See the Dockerfile comment for the full reasoning.++## Where it runs++| Region | Role | minScale / maxScale |+|---|---|---|+| **us-east4** | **production lane**: `GCP_TEXT2MOTION_URL` and the `model-text2motion-warm` scheduler probe both point here | 0 / 2 |+| us-central1 | dormant failback copy, same image | 0 / 2 |++L4 GPU quota is **per region** and us-east4's grant is 3, shared with the idle+`model-trellis` and `model-triposr` standbys pinned there. This lane runs at+minScale 0, so a warm pin held by an idle service in the same region is what+starves it: that happened twice (us-central1 2026-07-26, us-east4 2026-08-11),+both times showing up as `exceeded its quota limit for+run.googleapis.com/nvidia_l4_gpu_allocation_no_zonal_redundancy` on the+10-minute keep-warm probe. Fix is to unpin the idle holder, not to wait on a+quota raise. Full history and the measurement procedure:+[docs/ops/gcp-credits-plan.md](../../docs/ops/gcp-credits-plan.md).++`api/cron/gpu-keepwarm.js` pings the lane root every 10 minutes during peak+hours to absorb the cold start; a 404 at `/` is the expected success signal+there (the worker defines no root route), so those 404 lines in the logs are the+probe working, not a fault.++## Tests++Pure NumPy, no torch, no GPU, no checkpoint. From this directory:++```bash+python3 -m unittest discover -p 'test_*.py'+```++Both modules import sibling files directly, so they must be run with this+directory as the working directory (running them by path from the repo root+fails on `ModuleNotFoundError: smpl_to_clip`).++- `test_smpl_to_clip.py` (16 cases): axis-angle → quaternion correctness and+ unit-norm, the SMPL→Wolf3D bone mapping, clip JSON shape (track names, value+ lengths, monotonic times, duration), rest-offset calibration, flattened-pose+ input, single-frame/static, and input validation.+- `test_mdm_decode.py` (21 cases): the decode path this worker owns. The+ kinematic-chain flattening, the Kabsch solve, `_quat_to_axis_angle` as the+ exact inverse of `axis_angle_to_quaternion`, `_resample`, and a+ forward-kinematics → `_positions_to_local_quats` → forward-kinematics round+ trip that must reproduce the input positions (asserted on positions rather+ than rotations, because single-child joints carry no twist signal in position+ data). Two smoke cases run the whole owned chain end to end: joint positions+ in, a valid AnimationClip out.++The JS provider mode + REST endpoint are covered by+`tests/api/forge-motion.test.js` (`npm test`).++What only a deploy can validate is the pair of upstream calls in+`_decode_to_smpl` (`recover_from_ric` and the sampler itself), which need the+GPU image and the checkpoint. Those are exercised in production: verified+2026-08-11 against the us-east4 lane, a 3-second 30 fps prompt returning 90+frames in 2.7 s warm, with all 22 quaternion tracks unit-norm, 17 of 22 bones+actually animating, and `Hips.position` carrying real travel.++`smpl_to_clip`'s `rest_offsets` parameter defaults to identity, which emits the+raw SMPL local rotations. That is the correct baseline for SMPL-rest targets;+the retarget engine already aligns bone names and hip scale, and any residual+SMPL-rest vs Wolf3D-rest orientation offset is what that parameter exists to+calibrate.## Build / deploy```bash-gcloud builds submit --config workers/model-text2motion/cloudbuild.yaml .+gcloud builds submit --config workers/model-text2motion/cloudbuild.yaml . \+ --substitutions=SHORT_SHA=manual$(date +%s)```-Mounts MDM checkpoints + SMPL body models from the weights bucket at-`MOTION_MODEL_DIR=/weights/mdm`. L4 GPU, 4 CPU / 16Gi, max 2 instances — same-shape as `model-triposr`. Set `GCP_TEXT2MOTION_URL` (+ the shared-`GCP_RECONSTRUCTION_KEY`) on the web deployment to light up the REST + MCP paths.+One build, two deploys: the image is built and stored in the us-central1+Artifact Registry, then rolled out to **us-east4 first (production)** and+us-central1 second (failback), so the standby can never be newer than the lane+users hit. L4 GPU, 4 CPU / 16 Gi, max 2 instances. Deploys are owner-gated per+CLAUDE.md; the build itself is safe to run.++Verify a deploy landed:++```bash+KEY=$(gcloud secrets versions access latest --secret=avatar-reconstruction-key \+ --project aerial-vehicle-466722-p5)+URL=https://model-text2motion-93741856042.us-east4.run.app+curl -s "$URL/health" -H "authorization: Bearer $KEY"+curl -s -X POST "$URL/infer" -H "authorization: Bearer $KEY" \+ -H 'content-type: application/json' \+ -d '{"prompt":"a person waves hello with the right hand","duration_seconds":3,"fps":30}'+curl -s "$URL/tasks/<task_id>" -H "authorization: Bearer $KEY"+```diff --git a/workers/model-text2motion/cloudbuild.yaml b/workers/model-text2motion/cloudbuild.yamlindex b2138083f..354ec8fba 100644--- a/workers/model-text2motion/cloudbuild.yaml+++ b/workers/model-text2motion/cloudbuild.yaml@@ -1,5 +1,13 @@substitutions:+ # _REGION is where the image is built and stored (Artifact Registry). The+ # SERVING regions are below: us-east4 is the lane production talks to+ # (GCP_TEXT2MOTION_URL on three-ws-api), us-central1 is a dormant failback+ # copy. Both are deployed from the same image so the standby can never be+ # older than the primary. A rebuild that only touched us-central1 would+ # silently leave production on the previous revision._REGION: us-central1+ _PRIMARY_REGION: us-east4+ _STANDBY_REGION: us-central1_RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com_SERVICE: model-text2motion_REPO: model-text2motion@@ -29,7 +37,9 @@ steps:- --all-tags- ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server- - id: deploy+ # The production lane. us-east4 pulls the image cross-region from the+ # us-central1 registry and gcsfuse-mounts the same weights bucket.+ - id: deploy-primaryname: gcr.io/google.com/cloudsdktool/cloud-sdk:slimentrypoint: gcloudargs:@@ -37,7 +47,36 @@ steps:- deploy- ${_SERVICE}- --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA- - --region=${_REGION}+ - --region=${_PRIMARY_REGION}+ - --service-account=${_RUN_SA}+ - --platform=managed+ - --port=8080+ - --gpu=1+ - --gpu-type=nvidia-l4+ - --no-gpu-zonal-redundancy+ - --no-cpu-throttling+ - --cpu=4+ - --memory=16Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ - --timeout=900+ - --allow-unauthenticated+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}+ - --add-volume-mount=volume=weights,mount-path=/weights+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},MOTION_MODEL_DIR=/weights/mdm,MAX_CONCURRENT=2+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++ # The dormant failback copy. Same image, same flags, min 0 so it holds no GPU+ # until traffic is pointed at it.+ - id: deploy-standby+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_STANDBY_REGION}- --service-account=${_RUN_SA}- --platform=managed- --port=8080diff --git a/workers/model-text2motion/test_mdm_decode.py b/workers/model-text2motion/test_mdm_decode.pynew file mode 100644index 000000000..0dcb2a123--- /dev/null+++ b/workers/model-text2motion/test_mdm_decode.py@@ -0,0 +1,325 @@+"""Deterministic tests for the MDM decode path: joint positions to local rotations.++`mdm_sampler._decode_to_smpl` is the riskiest code in this worker: it takes what+the diffusion model actually emits (global joint POSITIONS, via upstream's+`recover_from_ric`) and recovers the local joint ROTATIONS a three.js clip needs.+Everything in that recovery except the two upstream calls is pure NumPy, so it is+testable here without torch, a GPU, or the checkpoint.++The load-bearing property is a forward/inverse round trip: run known local+rotations through forward kinematics to get positions, feed those positions to+`_positions_to_local_quats`, and the recovered rotations must reproduce the same+positions. Comparing rotations directly would fail spuriously on single-child+joints, whose twist about their own bone axis leaves no trace in position data+(the ambiguity is inherent to the representation, not to this implementation),+so the round trip is asserted on positions, which is exactly what a viewer sees.++Run (from this directory):+ python3 -m unittest discover -p 'test_*.py'+"""++from __future__ import annotations++import math+import unittest++import numpy as np++from mdm_sampler import (+ _kabsch_quat,+ _parents_from_kinematic_chain,+ _positions_to_local_quats,+ _quat_multiply,+ _quat_rotate,+ _quat_to_axis_angle,+ _resample,+)+from smpl_to_clip import axis_angle_to_quaternion, smpl_motion_to_clip++# The HumanML3D 22-joint topology MDM samples on, as limb chains rooted at joint+# 0, the same shape as upstream's `data_loaders.humanml.utils.paramUtil+# .t2m_kinematic_chain`, which the worker reads at runtime. Held here as a+# fixture so the decode math is testable without the MDM repo checked out; the+# assertions below are round-trip properties, so they hold for any topology of+# this shape rather than depending on these exact indices.+T2M_CHAINS = [+ [0, 2, 5, 8, 11], # right leg+ [0, 1, 4, 7, 10], # left leg+ [0, 3, 6, 9, 12, 15], # spine → head+ [9, 14, 17, 19, 21], # right arm+ [9, 13, 16, 18, 20], # left arm+]+N_JOINTS = 22+++def _rest_directions(parents: np.ndarray) -> np.ndarray:+ """Unit rest direction of each bone (joint → its parent's frame), T-pose-ish.++ Joint 0 has no bone, so its row is unused by the solver and stays zero-free+ (an arbitrary unit vector) to keep normalization well defined.+ """+ dirs = np.zeros((len(parents), 3), dtype=np.float64)+ dirs[0] = [0.0, 1.0, 0.0]+ for j in range(1, len(parents)):+ if j in (1, 2): # hips → upper legs, splayed outward and down+ dirs[j] = [-1.0 if j == 1 else 1.0, -0.6, 0.0]+ elif j in (13, 14): # chest → shoulders, straight out sideways+ dirs[j] = [-1.0 if j == 13 else 1.0, 0.2, 0.0]+ elif j in (16, 17, 18, 19, 20, 21): # arms continue sideways+ dirs[j] = [-1.0 if j % 2 == 0 else 1.0, 0.0, 0.0]+ elif j in (10, 11): # toes point forward+ dirs[j] = [0.0, -0.2, 1.0]+ elif j in (4, 5, 7, 8): # legs continue downward+ dirs[j] = [0.0, -1.0, 0.0]+ else: # spine, neck, head: up+ dirs[j] = [0.0, 1.0, 0.0]+ return dirs / np.linalg.norm(dirs, axis=-1, keepdims=True)+++def _forward_kinematics(+ local_quat: np.ndarray, parents: np.ndarray, rest_dirs: np.ndarray, bone_len: np.ndarray+) -> np.ndarray:+ """(T,J,4) local rotations → (T,J,3) global joint positions.++ The exact convention `_positions_to_local_quats` inverts: a joint's global+ orientation is its parent's composed with its own local rotation, and a+ bone's world offset is its rest direction rotated by the PARENT joint's+ global orientation.+ """+ n_frames, n_joints, _ = local_quat.shape+ global_quat = np.tile(np.array([0.0, 0.0, 0.0, 1.0]), (n_frames, n_joints, 1))+ positions = np.zeros((n_frames, n_joints, 3), dtype=np.float64)+ for j in range(n_joints):+ if j == 0:+ global_quat[:, j] = local_quat[:, j]+ continue+ p = parents[j]+ global_quat[:, j] = _quat_multiply(global_quat[:, p], local_quat[:, j])+ offset = np.broadcast_to(rest_dirs[j] * bone_len[j], (n_frames, 3))+ positions[:, j] = positions[:, p] + _quat_rotate(global_quat[:, p], offset)+ return positions+++def _random_local_quats(n_frames: int, n_joints: int, seed: int, scale: float = 0.4) -> np.ndarray:+ rng = np.random.default_rng(seed)+ aa = rng.standard_normal((n_frames, n_joints, 3)) * scale+ return axis_angle_to_quaternion(aa)+++class KinematicChainTest(unittest.TestCase):+ def test_flattens_chains_to_parents(self):+ parents = _parents_from_kinematic_chain([[0, 1, 2], [0, 3, 4, 5]], 6)+ np.testing.assert_array_equal(parents, [-1, 0, 1, 0, 3, 4])++ def test_root_has_no_parent(self):+ parents = _parents_from_kinematic_chain(T2M_CHAINS, N_JOINTS)+ self.assertEqual(parents[0], -1)+ self.assertEqual(int((parents == -1).sum()), 1)++ def test_every_joint_is_reachable_from_the_root(self):+ parents = _parents_from_kinematic_chain(T2M_CHAINS, N_JOINTS)+ for j in range(1, N_JOINTS):+ seen, cur = 0, j+ while cur != 0 and seen <= N_JOINTS:+ cur = parents[cur]+ seen += 1+ self.assertEqual(cur, 0, f"joint {j} does not chain back to the root")++ def test_parents_precede_children(self):+ # The single top-down pass in `_positions_to_local_quats` depends on this+ # ordering: a joint's parent must already be resolved when it is reached.+ parents = _parents_from_kinematic_chain(T2M_CHAINS, N_JOINTS)+ for j in range(1, N_JOINTS):+ self.assertLess(parents[j], j)+++class KabschTest(unittest.TestCase):+ def test_recovers_a_known_rotation(self):+ q = axis_angle_to_quaternion(np.array([0.3, -0.7, 0.2]))+ sources = np.eye(3)[None, :, :] # (1,3,3): three orthonormal directions+ targets = _quat_rotate(np.broadcast_to(q, (1, 3, 4)), sources)+ recovered = _kabsch_quat(sources, targets)[0]+ # Quaternions double-cover rotations, so compare up to sign.+ if np.dot(recovered, q) < 0:+ recovered = -recovered+ np.testing.assert_allclose(recovered, q, atol=1e-8)++ def test_result_is_a_proper_rotation(self):+ rng = np.random.default_rng(7)+ sources = rng.standard_normal((4, 2, 3))+ sources /= np.linalg.norm(sources, axis=-1, keepdims=True)+ targets = rng.standard_normal((4, 2, 3))+ targets /= np.linalg.norm(targets, axis=-1, keepdims=True)+ quats = _kabsch_quat(sources, targets)+ np.testing.assert_allclose(np.linalg.norm(quats, axis=-1), np.ones(4), atol=1e-8)++ def test_single_direction_aligns_that_direction(self):+ # One child is the common case: the solve degenerates to shortest-arc,+ # which must still land the source exactly on the target.+ source = np.array([[[0.0, 1.0, 0.0]]])+ target = np.array([[[1.0, 0.0, 0.0]]])+ q = _kabsch_quat(source, target)+ np.testing.assert_allclose(_quat_rotate(q, source)[0, 0], target[0, 0], atol=1e-8)+++class QuatToAxisAngleTest(unittest.TestCase):+ def test_inverts_axis_angle_to_quaternion(self):+ rng = np.random.default_rng(3)+ aa = rng.standard_normal((25, 3))+ aa = aa / np.linalg.norm(aa, axis=-1, keepdims=True) * rng.uniform(0.05, 2.8, (25, 1))+ np.testing.assert_allclose(_quat_to_axis_angle(axis_angle_to_quaternion(aa)), aa, atol=1e-8)++ def test_identity_maps_to_zero(self):+ q = np.array([[0.0, 0.0, 0.0, 1.0]])+ np.testing.assert_allclose(_quat_to_axis_angle(q), np.zeros((1, 3)), atol=1e-12)++ def test_angle_matches_quaternion_half_angle(self):+ q = axis_angle_to_quaternion(np.array([0.0, math.pi / 2, 0.0]))+ aa = _quat_to_axis_angle(q)+ self.assertAlmostEqual(float(np.linalg.norm(aa)), math.pi / 2, places=9)+++class PositionsToLocalQuatsTest(unittest.TestCase):+ def setUp(self):+ self.parents = _parents_from_kinematic_chain(T2M_CHAINS, N_JOINTS)+ self.rest_dirs = _rest_directions(self.parents)+ self.bone_len = np.full(N_JOINTS, 0.4)++ def _round_trip(self, local_quat: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ positions = _forward_kinematics(local_quat, self.parents, self.rest_dirs, self.bone_len)+ recovered = _positions_to_local_quats(positions, self.parents, self.rest_dirs)+ replayed = _forward_kinematics(recovered, self.parents, self.rest_dirs, self.bone_len)+ return positions, replayed++ def test_rest_pose_recovers_identity(self):+ local = np.tile(np.array([0.0, 0.0, 0.0, 1.0]), (5, N_JOINTS, 1))+ positions = _forward_kinematics(local, self.parents, self.rest_dirs, self.bone_len)+ recovered = _positions_to_local_quats(positions, self.parents, self.rest_dirs)+ np.testing.assert_allclose(np.abs(recovered[..., 3]), np.ones((5, N_JOINTS)), atol=1e-8)++ def test_position_round_trip(self):+ local = _random_local_quats(6, N_JOINTS, seed=11)+ positions, replayed = self._round_trip(local)+ np.testing.assert_allclose(replayed, positions, atol=1e-8)++ def test_position_round_trip_survives_large_rotations(self):+ local = _random_local_quats(4, N_JOINTS, seed=12, scale=1.2)+ positions, replayed = self._round_trip(local)+ np.testing.assert_allclose(replayed, positions, atol=1e-8)++ def test_output_quaternions_are_unit(self):+ local = _random_local_quats(3, N_JOINTS, seed=13)+ positions = _forward_kinematics(local, self.parents, self.rest_dirs, self.bone_len)+ recovered = _positions_to_local_quats(positions, self.parents, self.rest_dirs)+ np.testing.assert_allclose(np.linalg.norm(recovered, axis=-1), np.ones((3, N_JOINTS)), atol=1e-8)++ def test_leaf_joints_are_identity(self):+ # Hands, feet tips and head have no children, so position data carries no+ # evidence for their rotation and they must stay at rest, not drift.+ local = _random_local_quats(3, N_JOINTS, seed=14)+ positions = _forward_kinematics(local, self.parents, self.rest_dirs, self.bone_len)+ recovered = _positions_to_local_quats(positions, self.parents, self.rest_dirs)+ leaves = [j for j in range(N_JOINTS) if j not in set(self.parents.tolist())]+ self.assertTrue(leaves)+ for leaf in leaves:+ np.testing.assert_allclose(+ recovered[:, leaf], np.tile([0.0, 0.0, 0.0, 1.0], (3, 1)), atol=1e-12+ )++ def test_root_rotation_is_recovered_exactly(self):+ # The root branches into three chains, so Kabsch is fully determined+ # there and its rotation must come back exactly, twist included.+ local = np.tile(np.array([0.0, 0.0, 0.0, 1.0]), (2, N_JOINTS, 1))+ q = axis_angle_to_quaternion(np.array([0.1, 0.9, -0.2]))+ local[:, 0] = q+ positions = _forward_kinematics(local, self.parents, self.rest_dirs, self.bone_len)+ recovered = _positions_to_local_quats(positions, self.parents, self.rest_dirs)[0, 0]+ if np.dot(recovered, q) < 0:+ recovered = -recovered+ np.testing.assert_allclose(recovered, q, atol=1e-8)+++class ResampleTest(unittest.TestCase):+ def test_exact_length_is_a_passthrough(self):+ poses = np.arange(24, dtype=np.float64).reshape(4, 2, 3)+ trans = np.zeros((4, 3))+ out_poses, out_trans = _resample(poses, trans, 4)+ self.assertIs(out_poses, poses)+ self.assertIs(out_trans, trans)++ def test_upsample_preserves_endpoints_and_shape(self):+ poses = np.linspace(0.0, 1.0, 5)[:, None, None] * np.ones((1, 22, 3))+ trans = np.linspace(0.0, 2.0, 5)[:, None] * np.ones((1, 3))+ out_poses, out_trans = _resample(poses, trans, 13)+ self.assertEqual(out_poses.shape, (13, 22, 3))+ self.assertEqual(out_trans.shape, (13, 3))+ np.testing.assert_allclose(out_poses[0], poses[0], atol=1e-12)+ np.testing.assert_allclose(out_poses[-1], poses[-1], atol=1e-12)+ np.testing.assert_allclose(out_trans[-1], trans[-1], atol=1e-12)++ def test_downsample_interpolates_linearly(self):+ poses = np.linspace(0.0, 1.0, 9)[:, None, None] * np.ones((1, 1, 3))+ trans = np.linspace(0.0, 1.0, 9)[:, None] * np.ones((1, 3))+ out_poses, out_trans = _resample(poses, trans, 5)+ np.testing.assert_allclose(out_poses[:, 0, 0], [0.0, 0.25, 0.5, 0.75, 1.0], atol=1e-12)+ np.testing.assert_allclose(out_trans[:, 0], [0.0, 0.25, 0.5, 0.75, 1.0], atol=1e-12)+++class DecodePipelineSmokeTest(unittest.TestCase):+ """The worker's core path, end to end, minus the two GPU-only upstream calls.++ `_decode_to_smpl` is: recover positions (upstream, torch) → this module's IK →+ axis-angle; `main._run_inference` then hands that to `smpl_motion_to_clip`.+ Feeding the IK positions that upstream would have produced exercises every+ line of that chain the worker owns, and asserts the artifact a browser+ actually loads.+ """++ def test_positions_become_a_valid_animation_clip(self):+ parents = _parents_from_kinematic_chain(T2M_CHAINS, N_JOINTS)+ rest_dirs = _rest_directions(parents)+ local = _random_local_quats(40, N_JOINTS, seed=21)+ positions = _forward_kinematics(local, parents, rest_dirs, np.full(N_JOINTS, 0.4))+ # A moving root, the way sampled motion travels through the world.+ positions += np.linspace(0.0, 1.5, 40)[:, None, None] * np.array([0.0, 0.0, 1.0])++ recovered = _positions_to_local_quats(positions, parents, rest_dirs)+ poses = _quat_to_axis_angle(recovered)+ trans = positions[:, 0, :]+ poses, trans = _resample(poses, trans, 30)++ clip = smpl_motion_to_clip(poses, trans, fps=30, name="smoke")++ self.assertEqual(clip["name"], "smoke")+ self.assertAlmostEqual(clip["duration"], 29 / 30)+ quat_tracks = [t for t in clip["tracks"] if t["type"] == "quaternion"]+ # Every one of the 22 HumanML3D joints maps to a Wolf3D bone.+ self.assertEqual(len(quat_tracks), 22)+ self.assertIn("Hips.quaternion", {t["name"] for t in quat_tracks})+ for track in quat_tracks:+ values = np.array(track["values"]).reshape(-1, 4)+ self.assertEqual(len(values), 30)+ np.testing.assert_allclose(np.linalg.norm(values, axis=1), 1.0, atol=1e-8)++ hips = next(t for t in clip["tracks"] if t["name"] == "Hips.position")+ self.assertEqual(len(hips["values"]), 30 * 3)+ # The root track must carry the travel, not sit at the origin.+ travelled = np.array(hips["values"]).reshape(-1, 3)+ self.assertGreater(float(travelled[-1, 2] - travelled[0, 2]), 1.0)++ def test_static_input_yields_a_still_clip(self):+ parents = _parents_from_kinematic_chain(T2M_CHAINS, N_JOINTS)+ rest_dirs = _rest_directions(parents)+ local = np.tile(np.array([0.0, 0.0, 0.0, 1.0]), (12, N_JOINTS, 1))+ positions = _forward_kinematics(local, parents, rest_dirs, np.full(N_JOINTS, 0.4))+ poses = _quat_to_axis_angle(_positions_to_local_quats(positions, parents, rest_dirs))+ clip = smpl_motion_to_clip(poses, positions[:, 0, :], fps=24, name="still")+ for track in clip["tracks"]:+ if track["type"] != "quaternion":+ continue+ values = np.array(track["values"]).reshape(-1, 4)+ np.testing.assert_allclose(values, np.tile(values[0], (len(values), 1)), atol=1e-9)+++if __name__ == "__main__":+ unittest.main()