cozyclay 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +674 -0
- package/README.md +109 -0
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/bin/cozyclay.mjs +194 -0
- package/dist/ardy/cskel27-rest.json +557 -0
- package/dist/assets/basis_transcoder-VXdx5NbI.wasm +0 -0
- package/dist/assets/basis_transcoder-o4Hde_L7.js +19 -0
- package/dist/assets/draco_decoder-C32yEggz.wasm +0 -0
- package/dist/assets/draco_decoder-Z1_iN-Ht.wasm +0 -0
- package/dist/assets/draco_decoder-fzg4nYZr.js +34 -0
- package/dist/assets/draco_wasm_wrapper-DxJM36Ib.js +117 -0
- package/dist/assets/draco_wasm_wrapper-fZCQGLGb.js +116 -0
- package/dist/assets/index-BW_S1YRy.js +4395 -0
- package/dist/assets/index-nRmmJgap.css +1 -0
- package/dist/demo/walk-then-stop.npz +0 -0
- package/dist/fonts/instrument-serif-italic-latin.woff2 +0 -0
- package/dist/fonts/instrument-serif-latin.woff2 +0 -0
- package/dist/fonts/inter-latin.woff2 +0 -0
- package/dist/index.html +13 -0
- package/dist/models/x-bot-tpose.fbx +0 -0
- package/dist/models/y-bot-tpose.fbx +0 -0
- package/package.json +80 -0
- package/src/App.jsx +3840 -0
- package/src/ardy/client.js +140 -0
- package/src/ardy/convert.js +313 -0
- package/src/ardy/cskel27-neutral.js +39 -0
- package/src/ardy/cskel27.js +68 -0
- package/src/ardy/export.js +157 -0
- package/src/ardy/ik.js +610 -0
- package/src/ardy/npz.js +520 -0
- package/src/ardy/playback.js +414 -0
- package/src/ardy/prompt-clips.js +16 -0
- package/src/ardy/timeline-coordinates.js +17 -0
- package/src/ardy/timeline-resize.js +11 -0
- package/src/ardy/timeline.jsx +723 -0
- package/src/ardy/to-cskel27.js +205 -0
- package/src/ardy/waypoints.js +364 -0
- package/src/camera-follow.js +366 -0
- package/src/camera-move.js +286 -0
- package/src/controls.jsx +245 -0
- package/src/dualview.jsx +305 -0
- package/src/hierarchy-model.js +77 -0
- package/src/hierarchy-panel.jsx +365 -0
- package/src/history.js +90 -0
- package/src/main.jsx +10 -0
- package/src/object-catalog.jsx +90 -0
- package/src/object-gizmo.jsx +755 -0
- package/src/planview.jsx +653 -0
- package/src/poses.js +424 -0
- package/src/posestudio.jsx +811 -0
- package/src/props.jsx +302 -0
- package/src/room.jsx +64 -0
- package/src/scene-history.js +125 -0
- package/src/scene-objects.js +420 -0
- package/src/shot-authoring.js +113 -0
- package/src/shot.js +239 -0
- package/src/styles.css +5639 -0
- package/src/ui.jsx +391 -0
- package/src/use-render-activity.js +96 -0
- package/tools/ardy/BRIDGE.md +255 -0
- package/tools/ardy/README.md +136 -0
- package/tools/ardy/__pycache__/cclay_sequence_generate.cpython-313.pyc +0 -0
- package/tools/ardy/bridge.mjs +1427 -0
- package/tools/ardy/cclay_motion_edit.py +445 -0
- package/tools/ardy/cclay_sequence_generate.py +595 -0
- package/tools/ardy/dump-npz.py +205 -0
- package/tools/ardy/extract-rest.mjs +299 -0
- package/tools/ardy/npz.mjs +335 -0
- package/tools/ardy/out/gen-1786443326924-c6019e-generated.npz +0 -0
- package/tools/ardy/out/gen-1786443609325-0053db-generated.npz +0 -0
- package/tools/ardy/out/gen-1786443835628-749ed1-generated.npz +0 -0
- package/tools/ardy/out/gen-1786462605247-03cb19-generated.npz +0 -0
- package/tools/ardy/pose-to-npz.mjs +106 -0
- package/tools/ardy/run-edit-on-box.sh +73 -0
- package/tools/ardy/run-on-box.sh +568 -0
- package/tools/ardy/run-sequence-on-box.sh +162 -0
- package/tools/ardy/visual-qa.mjs +188 -0
- package/tools/ardy/vq-car.mjs +52 -0
- package/tools/dev-full.mjs +29 -0
- package/tools/process-supervisor.mjs +63 -0
- package/tools/qa-browser.mjs +84 -0
- package/tools/qa-crop3.mjs +22 -0
- package/tools/qa-playview.mjs +49 -0
- package/tools/qa-screenshot.mjs +24 -0
- package/tools/qa-visual.mjs +51 -0
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# SPDX-FileCopyrightText: CozyClay contributors
|
|
3
|
+
#
|
|
4
|
+
# cclay-owned script. Source of truth lives in the CozyClay repo at
|
|
5
|
+
# scripts/ardy/cclay_sequence_generate.py and is deployed to the ARDY box at
|
|
6
|
+
# ~/ardy/scripts/cclay_sequence_generate.py. Do not edit the deployed copy.
|
|
7
|
+
"""Segment-chained text-to-motion generation for the cclay ARDY pipeline.
|
|
8
|
+
|
|
9
|
+
Generates ONE continuous rollout across multiple text segments ("run forward,
|
|
10
|
+
then bow"): each segment is generated by the model's autoregressive sampling
|
|
11
|
+
loop with its own prompt, conditioned on the tail of the previously generated
|
|
12
|
+
motion via ``init_history_sequence`` — the same history-conditioning mechanism
|
|
13
|
+
the interactive demo's replan path uses. No npz splicing, no crossfading, no
|
|
14
|
+
array blending: segment continuity comes purely from history conditioning.
|
|
15
|
+
|
|
16
|
+
Two empirically load-bearing choices (tuned on ARDY-Core-RP-20FPS-Horizon40):
|
|
17
|
+
|
|
18
|
+
* Each segment is generated with a full ``model(...)`` call whose pad mask
|
|
19
|
+
marks the segment's exact clip length. The model was trained on clips that
|
|
20
|
+
start/end near rest, so it settles the action before the segment boundary —
|
|
21
|
+
which is what makes the next segment's transition smooth.
|
|
22
|
+
* Only a SHORT history tail (default 0.6 s) is passed into the next segment.
|
|
23
|
+
Long histories dominate the window and suppress the new segment's prompt
|
|
24
|
+
(e.g. a 3 s running history makes the model ignore "bows deeply").
|
|
25
|
+
|
|
26
|
+
Segment tails are additionally gated on continuity: if the last frames of a
|
|
27
|
+
non-final segment still move faster than --max_boundary_jump, the segment is
|
|
28
|
+
regenerated with a derived seed (bounded attempts, deterministic given
|
|
29
|
+
--seed); the calmest attempt wins. This is regeneration, never blending.
|
|
30
|
+
|
|
31
|
+
Root 2D waypoints (--root-2d FRAME X Z HEADING, frames in the ROLLOUT-GLOBAL
|
|
32
|
+
0..total-1 range) ride the same chained calls: the constraint set is built
|
|
33
|
+
once over the whole rollout, and each segment call receives the slice covering
|
|
34
|
+
its history tail + new frames with the history frames zeroed — exactly the
|
|
35
|
+
interactive demo's streaming-constraint pattern. The model re-anchors observed
|
|
36
|
+
roots by its running global translation, so rollout-global coordinates stay
|
|
37
|
+
valid across every seam. Waypoint conditioning and history conditioning are
|
|
38
|
+
first-class together in ``Ardy.__call__``; nothing here is off-label.
|
|
39
|
+
|
|
40
|
+
Usage (from ~/ardy):
|
|
41
|
+
.venv/bin/python scripts/cclay_sequence_generate.py \
|
|
42
|
+
--segment "A person runs forward." 3 \
|
|
43
|
+
--segment "A person bows deeply." 4 \
|
|
44
|
+
--output outputs/cclay/seq --seed 7
|
|
45
|
+
|
|
46
|
+
The last stdout line is a single JSON object:
|
|
47
|
+
{"frames": int, "fps": int,
|
|
48
|
+
"segments": [{"prompt", "requested_s", "start_frame", "end_frame"}],
|
|
49
|
+
"continuity": {"mean_jump_m", "max_jump_m", "max_jump_frame",
|
|
50
|
+
"boundary_max_jump_m"}}
|
|
51
|
+
start_frame/end_frame are 0-based inclusive npz frame indices. A "jump" is the
|
|
52
|
+
max per-frame L2 displacement across all posed joints between consecutive
|
|
53
|
+
frames (meters); jump index j measures the transition from frame j to j+1 and
|
|
54
|
+
is reported as the landing frame j+1 in max_jump_frame.
|
|
55
|
+
|
|
56
|
+
The output npz has exactly the same keys/shapes/conventions as
|
|
57
|
+
scripts/generate.py single-prompt output (Y-up meters, cskel27), with
|
|
58
|
+
text = " then ".join(segment prompts).
|
|
59
|
+
"""
|
|
60
|
+
import argparse
|
|
61
|
+
import json
|
|
62
|
+
import math
|
|
63
|
+
import os
|
|
64
|
+
|
|
65
|
+
import numpy as np
|
|
66
|
+
import torch
|
|
67
|
+
|
|
68
|
+
from ardy.model import DEFAULT_MODEL, load_model
|
|
69
|
+
from ardy.model.loading import get_env_var
|
|
70
|
+
from ardy.model.registry import resolve_model_name
|
|
71
|
+
from ardy.motion_rep.tools import length_to_mask
|
|
72
|
+
from ardy.postprocess import post_process_motion
|
|
73
|
+
from ardy.skeleton import SOMASkeleton30
|
|
74
|
+
from ardy.tools import seed_everything, to_numpy
|
|
75
|
+
|
|
76
|
+
# Prime stride between per-segment base seeds so retry seeds never collide.
|
|
77
|
+
_SEED_STRIDE = 9973
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def parse_args():
|
|
81
|
+
parser = argparse.ArgumentParser(
|
|
82
|
+
description="Segment-chained autoregressive text-to-motion generation (cclay)"
|
|
83
|
+
)
|
|
84
|
+
parser.add_argument(
|
|
85
|
+
"--segment",
|
|
86
|
+
action="append",
|
|
87
|
+
nargs=2,
|
|
88
|
+
metavar=("PROMPT", "SECONDS"),
|
|
89
|
+
required=True,
|
|
90
|
+
help="Repeatable: a text prompt and its duration in seconds.",
|
|
91
|
+
)
|
|
92
|
+
parser.add_argument(
|
|
93
|
+
"--output",
|
|
94
|
+
type=str,
|
|
95
|
+
default="output",
|
|
96
|
+
help="Output stem name; bare names are placed under outputs/.",
|
|
97
|
+
)
|
|
98
|
+
parser.add_argument(
|
|
99
|
+
"--model",
|
|
100
|
+
type=str,
|
|
101
|
+
default=DEFAULT_MODEL,
|
|
102
|
+
help="Model nickname or full folder name (default: %(default)s).",
|
|
103
|
+
)
|
|
104
|
+
parser.add_argument(
|
|
105
|
+
"--seed",
|
|
106
|
+
type=int,
|
|
107
|
+
default=None,
|
|
108
|
+
help="Seed for reproducible results.",
|
|
109
|
+
)
|
|
110
|
+
parser.add_argument(
|
|
111
|
+
"--diffusion_steps",
|
|
112
|
+
type=int,
|
|
113
|
+
default=None,
|
|
114
|
+
help="Denoising steps, at most the model's num_base_steps (the default).",
|
|
115
|
+
)
|
|
116
|
+
parser.add_argument(
|
|
117
|
+
"--history_frames",
|
|
118
|
+
type=int,
|
|
119
|
+
default=None,
|
|
120
|
+
help=(
|
|
121
|
+
"History crop budget within the FIRST segment (multiple of the model's "
|
|
122
|
+
"token size), as in scripts/generate.py. Default: the longest history "
|
|
123
|
+
"fitting the trained 10 s window together with the generation horizon."
|
|
124
|
+
),
|
|
125
|
+
)
|
|
126
|
+
parser.add_argument(
|
|
127
|
+
"--transition_frames",
|
|
128
|
+
type=int,
|
|
129
|
+
default=None,
|
|
130
|
+
help=(
|
|
131
|
+
"Frames of previous-motion tail passed as init history into each "
|
|
132
|
+
"subsequent segment (multiple of the model's token size). Short tails "
|
|
133
|
+
"keep boundaries continuous while letting the new prompt take over. "
|
|
134
|
+
"Default: ~0.6 s at the model fps."
|
|
135
|
+
),
|
|
136
|
+
)
|
|
137
|
+
parser.add_argument(
|
|
138
|
+
"--root-2d",
|
|
139
|
+
dest="root_2d",
|
|
140
|
+
action="append",
|
|
141
|
+
nargs=4,
|
|
142
|
+
metavar=("FRAME", "X", "Z", "HEADING"),
|
|
143
|
+
help=(
|
|
144
|
+
"Repeatable: pin the root's ground position (meters) at a rollout-global "
|
|
145
|
+
"frame, optionally with a heading in radians ('none' to omit). Headings "
|
|
146
|
+
"are all-or-none across the set. Frame 0 is the rollout origin facing +Z."
|
|
147
|
+
),
|
|
148
|
+
)
|
|
149
|
+
parser.add_argument(
|
|
150
|
+
"--max_boundary_jump",
|
|
151
|
+
type=float,
|
|
152
|
+
default=0.08,
|
|
153
|
+
help=(
|
|
154
|
+
"Continuity gate (meters/frame): a non-final segment whose tail still "
|
|
155
|
+
"moves faster than this is regenerated with a derived seed (default: "
|
|
156
|
+
"%(default)s)."
|
|
157
|
+
),
|
|
158
|
+
)
|
|
159
|
+
parser.add_argument(
|
|
160
|
+
"--max_segment_attempts",
|
|
161
|
+
type=int,
|
|
162
|
+
default=6,
|
|
163
|
+
help="Max generation attempts per non-final segment for the continuity gate (default: %(default)s).",
|
|
164
|
+
)
|
|
165
|
+
parser.add_argument(
|
|
166
|
+
"--cfg_weight",
|
|
167
|
+
type=float,
|
|
168
|
+
nargs="+",
|
|
169
|
+
default=[2.0, 2.0],
|
|
170
|
+
help="CFG scale(s): one float (text) or two floats (text, constraint).",
|
|
171
|
+
)
|
|
172
|
+
parser.add_argument(
|
|
173
|
+
"--no-postprocess",
|
|
174
|
+
action="store_true",
|
|
175
|
+
help="Don't apply motion post-processing (foot-skate reduction).",
|
|
176
|
+
)
|
|
177
|
+
parser.add_argument(
|
|
178
|
+
"--checkpoints_dir",
|
|
179
|
+
type=str,
|
|
180
|
+
default=None,
|
|
181
|
+
help="Local dir holding released model folders (falls back to CHECKPOINTS_DIR env).",
|
|
182
|
+
)
|
|
183
|
+
return parser.parse_args()
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _default_history_frames(fps: float, gen_horizon_len: int, num_frames_per_token: int) -> int:
|
|
187
|
+
"""Longest history that, together with the generation horizon, fits the trained 10 s window.
|
|
188
|
+
|
|
189
|
+
Same budget as scripts/generate.py and the interactive demo: unbounded
|
|
190
|
+
history degrades long generations into jitter.
|
|
191
|
+
"""
|
|
192
|
+
max_window_len = (int(10 * fps) // num_frames_per_token) * num_frames_per_token
|
|
193
|
+
return ((max_window_len - gen_horizon_len) // num_frames_per_token) * num_frames_per_token
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _resolve_output_base(path: str, default_dir: str = "outputs") -> str:
|
|
197
|
+
"""Place bare output names under ``default_dir``; honor explicit paths (as generate.py)."""
|
|
198
|
+
if os.path.dirname(path):
|
|
199
|
+
return path
|
|
200
|
+
return os.path.join(default_dir, path)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _single_file_path(path: str, ext: str) -> str:
|
|
204
|
+
"""Return path for a single output file; add ext if missing, create parent dirs."""
|
|
205
|
+
if not path.endswith(ext):
|
|
206
|
+
path = path.rstrip(os.sep) + ext
|
|
207
|
+
parent = os.path.dirname(path)
|
|
208
|
+
if parent:
|
|
209
|
+
os.makedirs(parent, exist_ok=True)
|
|
210
|
+
return path
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def save_motion_npz(path: str, motion_dict: dict, fps: float, text: str) -> None:
|
|
214
|
+
"""Save a motion output dict to ``.npz`` along with fps and the prompt (as generate.py)."""
|
|
215
|
+
arrays = {k: np.asarray(v) for k, v in motion_dict.items()}
|
|
216
|
+
arrays["fps"] = np.asarray(fps)
|
|
217
|
+
arrays["text"] = np.asarray(text)
|
|
218
|
+
np.savez(path, **arrays)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _parse_frame(raw, num_frames: int, flag: str) -> int:
|
|
222
|
+
try:
|
|
223
|
+
frame = int(raw)
|
|
224
|
+
except ValueError:
|
|
225
|
+
raise ValueError(f"{flag} frame must be an integer, got {raw!r}.")
|
|
226
|
+
if not 0 <= frame < num_frames:
|
|
227
|
+
raise ValueError(
|
|
228
|
+
f"{flag} frame {frame} is outside the rollout (0..{num_frames - 1} for "
|
|
229
|
+
f"these segments); lengthen a segment or move the constraint."
|
|
230
|
+
)
|
|
231
|
+
return frame
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _parse_floats(raw_values, flag: str, names: str) -> list:
|
|
235
|
+
try:
|
|
236
|
+
return [float(value) for value in raw_values]
|
|
237
|
+
except ValueError:
|
|
238
|
+
raise ValueError(f"{flag} {names} must be numbers, got {tuple(raw_values)!r}.")
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def parse_root_waypoints(raw_waypoints, num_frames: int) -> list:
|
|
242
|
+
"""Validate --root-2d. HEADING is radians or the literal 'none'.
|
|
243
|
+
|
|
244
|
+
Same contract as cclay_constrained_generate.py, with frames measured in
|
|
245
|
+
the rollout-global 0..total-1 range.
|
|
246
|
+
"""
|
|
247
|
+
if not raw_waypoints:
|
|
248
|
+
return []
|
|
249
|
+
waypoints = []
|
|
250
|
+
seen = set()
|
|
251
|
+
for raw_frame, raw_x, raw_z, raw_heading in raw_waypoints:
|
|
252
|
+
frame = _parse_frame(raw_frame, num_frames, "--root-2d")
|
|
253
|
+
if frame in seen:
|
|
254
|
+
raise ValueError(
|
|
255
|
+
f"duplicate --root-2d for frame {frame}; one waypoint per frame."
|
|
256
|
+
)
|
|
257
|
+
seen.add(frame)
|
|
258
|
+
x, z = _parse_floats((raw_x, raw_z), "--root-2d", "X Z")
|
|
259
|
+
if str(raw_heading).lower() == "none":
|
|
260
|
+
heading = None
|
|
261
|
+
else:
|
|
262
|
+
heading = _parse_floats((raw_heading,), "--root-2d", "HEADING")[0]
|
|
263
|
+
waypoints.append({"frame": frame, "xz": [x, z], "heading": heading})
|
|
264
|
+
waypoints.sort(key=lambda entry: entry["frame"])
|
|
265
|
+
if len({entry["heading"] is None for entry in waypoints}) > 1:
|
|
266
|
+
# ARDY conditions the whole waypoint set on one heading tensor, so a
|
|
267
|
+
# partly-headed request would silently invent headings for the rest.
|
|
268
|
+
raise ValueError(
|
|
269
|
+
"--root-2d heading must be given for every waypoint or for none of them; "
|
|
270
|
+
"ARDY conditions the whole waypoint set on one heading tensor."
|
|
271
|
+
)
|
|
272
|
+
return waypoints
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def measure_waypoints(waypoints: list, generated_joints, skeleton) -> list:
|
|
276
|
+
"""Horizontal distance from each requested root waypoint to the rollout's root."""
|
|
277
|
+
report = []
|
|
278
|
+
root_index = skeleton.root_idx
|
|
279
|
+
for entry in waypoints:
|
|
280
|
+
root = np.asarray(generated_joints[entry["frame"], root_index], dtype=np.float64)
|
|
281
|
+
achieved = [float(root[0]), float(root[2])]
|
|
282
|
+
error = float(np.linalg.norm(np.asarray(achieved) - np.asarray(entry["xz"])))
|
|
283
|
+
report.append(
|
|
284
|
+
{
|
|
285
|
+
"frame": entry["frame"],
|
|
286
|
+
"requested_xz": [round(value, 4) for value in entry["xz"]],
|
|
287
|
+
"achieved_xz": [round(value, 4) for value in achieved],
|
|
288
|
+
"achieved_error_m": round(error, 4),
|
|
289
|
+
"heading_rad": entry["heading"],
|
|
290
|
+
}
|
|
291
|
+
)
|
|
292
|
+
return report
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _posed_joint_jumps(posed_joints: np.ndarray) -> np.ndarray:
|
|
296
|
+
"""jump[j] = max over joints of the L2 displacement between frames j and j+1 (meters)."""
|
|
297
|
+
disp = np.linalg.norm(posed_joints[1:] - posed_joints[:-1], axis=-1) # (F-1, J)
|
|
298
|
+
return disp.max(axis=-1) # (F-1,)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _continuity_metrics(posed_joints: np.ndarray, boundaries: list) -> dict:
|
|
302
|
+
"""Continuity metrics from posed joints (F, J, 3), meters.
|
|
303
|
+
|
|
304
|
+
boundary_max_jump_m = max jump within +/-2 frames of every segment boundary
|
|
305
|
+
(jumps whose either endpoint frame is within 2 frames of a boundary start).
|
|
306
|
+
"""
|
|
307
|
+
jumps = _posed_joint_jumps(posed_joints)
|
|
308
|
+
boundary_max = 0.0
|
|
309
|
+
for b in boundaries:
|
|
310
|
+
lo = max(0, b - 3)
|
|
311
|
+
hi = min(len(jumps), b + 2)
|
|
312
|
+
if lo < hi:
|
|
313
|
+
boundary_max = max(boundary_max, float(jumps[lo:hi].max()))
|
|
314
|
+
return {
|
|
315
|
+
"mean_jump_m": float(jumps.mean()),
|
|
316
|
+
"max_jump_m": float(jumps.max()),
|
|
317
|
+
"max_jump_frame": int(jumps.argmax()) + 1,
|
|
318
|
+
"boundary_max_jump_m": boundary_max,
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def main():
|
|
323
|
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
|
324
|
+
print(f"Using device: {device}")
|
|
325
|
+
args = parse_args()
|
|
326
|
+
|
|
327
|
+
segments = []
|
|
328
|
+
for prompt, seconds_str in args.segment:
|
|
329
|
+
prompt = prompt.strip()
|
|
330
|
+
try:
|
|
331
|
+
seconds = float(seconds_str)
|
|
332
|
+
except ValueError:
|
|
333
|
+
raise ValueError(f"--segment duration must be a number, got {seconds_str!r}.")
|
|
334
|
+
if not prompt:
|
|
335
|
+
raise ValueError("--segment prompt must be non-empty.")
|
|
336
|
+
if seconds <= 0:
|
|
337
|
+
raise ValueError(f"--segment duration must be > 0 seconds, got {seconds}.")
|
|
338
|
+
segments.append((prompt, seconds))
|
|
339
|
+
|
|
340
|
+
if len(args.cfg_weight) == 1:
|
|
341
|
+
cfg_weight = float(args.cfg_weight[0])
|
|
342
|
+
elif len(args.cfg_weight) == 2:
|
|
343
|
+
cfg_weight = (float(args.cfg_weight[0]), float(args.cfg_weight[1]))
|
|
344
|
+
else:
|
|
345
|
+
raise ValueError("--cfg_weight expects one float (text) or two floats (text, constraint).")
|
|
346
|
+
if args.max_segment_attempts < 1:
|
|
347
|
+
raise ValueError(f"--max_segment_attempts must be >= 1, got {args.max_segment_attempts}.")
|
|
348
|
+
|
|
349
|
+
# Load model (same path as scripts/generate.py)
|
|
350
|
+
checkpoints_dir = args.checkpoints_dir or get_env_var("CHECKPOINTS_DIR")
|
|
351
|
+
resolved_model = resolve_model_name(args.model, checkpoints_dir=checkpoints_dir)
|
|
352
|
+
model = load_model(resolved_model, device=device, checkpoints_dir=checkpoints_dir)
|
|
353
|
+
print(f"Loaded model: {resolved_model}")
|
|
354
|
+
|
|
355
|
+
fps = model.motion_rep.fps
|
|
356
|
+
patch = model.num_frames_per_token
|
|
357
|
+
gen_horizon = model.gen_horizon_len
|
|
358
|
+
max_window_len = (int(10 * fps) // patch) * patch # trained-window budget
|
|
359
|
+
|
|
360
|
+
num_base_steps = int(model.diffusion.num_base_steps)
|
|
361
|
+
diffusion_steps = args.diffusion_steps if args.diffusion_steps is not None else num_base_steps
|
|
362
|
+
if not 1 <= diffusion_steps <= num_base_steps:
|
|
363
|
+
raise ValueError(
|
|
364
|
+
f"--diffusion_steps must be between 1 and {num_base_steps} "
|
|
365
|
+
f"(this model's num_base_steps); got {diffusion_steps}."
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
history_budget = args.history_frames
|
|
369
|
+
if history_budget is None:
|
|
370
|
+
history_budget = _default_history_frames(fps, gen_horizon, patch)
|
|
371
|
+
elif history_budget < patch or history_budget % patch != 0:
|
|
372
|
+
raise ValueError(f"--history_frames must be a positive multiple of {patch} (this model's token size).")
|
|
373
|
+
|
|
374
|
+
transition_frames = args.transition_frames
|
|
375
|
+
if transition_frames is None:
|
|
376
|
+
transition_frames = max(patch, (int(0.6 * fps) // patch) * patch)
|
|
377
|
+
elif transition_frames < patch or transition_frames % patch != 0:
|
|
378
|
+
raise ValueError(f"--transition_frames must be a positive multiple of {patch} (this model's token size).")
|
|
379
|
+
print(
|
|
380
|
+
f"Using {history_budget} history frames (first-segment crop), "
|
|
381
|
+
f"{transition_frames} transition frames, {diffusion_steps} denoising steps"
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
# Per-segment frame counts. Later segments must fit the trained window
|
|
385
|
+
# together with the transition history (init history cannot be cropped
|
|
386
|
+
# mid-generation by the model).
|
|
387
|
+
seg_bounds = []
|
|
388
|
+
cum = 0
|
|
389
|
+
for i, (prompt, seconds) in enumerate(segments):
|
|
390
|
+
n = max(1, int(round(seconds * fps)))
|
|
391
|
+
if n < patch:
|
|
392
|
+
raise ValueError(
|
|
393
|
+
f"segment {prompt!r}: {seconds}s = {n} frames is shorter than one model "
|
|
394
|
+
f"token ({patch} frames at {fps} fps)."
|
|
395
|
+
)
|
|
396
|
+
if i > 0:
|
|
397
|
+
window = transition_frames + math.ceil(n / gen_horizon) * gen_horizon
|
|
398
|
+
if window > max_window_len:
|
|
399
|
+
max_s = (max_window_len - transition_frames) / fps
|
|
400
|
+
raise ValueError(
|
|
401
|
+
f"segment {prompt!r}: {seconds}s exceeds the trained window for a "
|
|
402
|
+
f"chained segment (max ~{max_s:.1f}s); split it into shorter segments."
|
|
403
|
+
)
|
|
404
|
+
seg_bounds.append({"prompt": prompt, "requested_s": seconds, "start_frame": cum, "end_frame": cum + n - 1})
|
|
405
|
+
cum += n
|
|
406
|
+
total_frames = cum
|
|
407
|
+
print(f"Will generate {total_frames} frames ({total_frames / fps:.2f}s at {fps} fps) over {len(segments)} segments")
|
|
408
|
+
|
|
409
|
+
# Root waypoints: ONE constraint set over the whole rollout, built in the
|
|
410
|
+
# rollout-global frame (frame 0 at the origin facing +Z — the first
|
|
411
|
+
# segment's canonical frame). Each chained call slices its own span below.
|
|
412
|
+
waypoints = parse_root_waypoints(args.root_2d or [], total_frames)
|
|
413
|
+
observed_full = None
|
|
414
|
+
mask_full = None
|
|
415
|
+
constraint_lst = []
|
|
416
|
+
if waypoints:
|
|
417
|
+
from ardy.constraints import Root2DConstraintSet
|
|
418
|
+
|
|
419
|
+
headings = [entry["heading"] for entry in waypoints]
|
|
420
|
+
constraint_lst = [
|
|
421
|
+
Root2DConstraintSet(
|
|
422
|
+
model.skeleton,
|
|
423
|
+
frame_indices=torch.tensor([entry["frame"] for entry in waypoints]),
|
|
424
|
+
root_2d=torch.tensor(
|
|
425
|
+
[entry["xz"] for entry in waypoints], device=device, dtype=torch.float32
|
|
426
|
+
),
|
|
427
|
+
global_root_heading=(
|
|
428
|
+
None
|
|
429
|
+
if headings[0] is None
|
|
430
|
+
else torch.tensor(headings, device=device, dtype=torch.float32)
|
|
431
|
+
),
|
|
432
|
+
)
|
|
433
|
+
]
|
|
434
|
+
observed_full, mask_full = model.motion_rep.create_conditions_from_constraints_batched(
|
|
435
|
+
constraint_lst,
|
|
436
|
+
torch.tensor([total_frames], device=device),
|
|
437
|
+
to_normalize=True,
|
|
438
|
+
device=device,
|
|
439
|
+
)
|
|
440
|
+
print(
|
|
441
|
+
f"Root2DConstraintSet on rollout frames "
|
|
442
|
+
f"{[entry['frame'] for entry in waypoints]}"
|
|
443
|
+
)
|
|
444
|
+
|
|
445
|
+
def generate_segment(prompt: str, n: int, history: torch.Tensor | None, seg_start: int) -> torch.Tensor:
|
|
446
|
+
"""One segment: full sampling loop conditioned on the (optional) history tail.
|
|
447
|
+
|
|
448
|
+
``seg_start`` is the segment's first frame in rollout-global numbering;
|
|
449
|
+
with waypoints present the call receives the observed-motion slice for
|
|
450
|
+
its history tail + new frames, history frames zeroed (the demo's
|
|
451
|
+
streaming pattern — constraints never fight the conditioning history).
|
|
452
|
+
Returns only the n newly generated NORMALIZED frames.
|
|
453
|
+
"""
|
|
454
|
+
history_len = 0 if history is None else history.shape[1]
|
|
455
|
+
num_frames = history_len + n
|
|
456
|
+
pad_mask = length_to_mask(torch.tensor([num_frames], device=device))
|
|
457
|
+
first_heading_angle = torch.zeros(1, device=device) if history is None else None
|
|
458
|
+
seg_mask = None
|
|
459
|
+
seg_observed = None
|
|
460
|
+
if mask_full is not None:
|
|
461
|
+
call_start = seg_start - history_len
|
|
462
|
+
seg_mask = mask_full[:, call_start : call_start + num_frames].clone()
|
|
463
|
+
seg_observed = observed_full[:, call_start : call_start + num_frames].clone()
|
|
464
|
+
seg_mask[:, :history_len] = 0.0
|
|
465
|
+
seg_observed[:, :history_len] = 0.0
|
|
466
|
+
if not bool(seg_mask.any()):
|
|
467
|
+
# no waypoint lands in this call's generated span; a pure
|
|
468
|
+
# zero mask would only cost compute
|
|
469
|
+
seg_mask = None
|
|
470
|
+
seg_observed = None
|
|
471
|
+
with torch.no_grad():
|
|
472
|
+
motion = model(
|
|
473
|
+
[prompt],
|
|
474
|
+
num_frames,
|
|
475
|
+
num_denoising_steps=diffusion_steps,
|
|
476
|
+
pad_mask=pad_mask,
|
|
477
|
+
first_heading_angle=first_heading_angle,
|
|
478
|
+
motion_mask=seg_mask,
|
|
479
|
+
observed_motion=seg_observed,
|
|
480
|
+
cfg_weight=cfg_weight,
|
|
481
|
+
progress_bar=lambda iterable: iterable,
|
|
482
|
+
init_history_sequence=history,
|
|
483
|
+
crop_history_length=history_budget if history is None else None,
|
|
484
|
+
)
|
|
485
|
+
return motion[:, history_len:]
|
|
486
|
+
|
|
487
|
+
def tail_jump(segment_motion: torch.Tensor) -> float:
|
|
488
|
+
"""Max posed-joint jump over the last `patch` transitions of a segment (meters/frame)."""
|
|
489
|
+
with torch.no_grad():
|
|
490
|
+
out = model.motion_rep.inverse(segment_motion[:, -(patch + 1) :], is_normalized=True)
|
|
491
|
+
pj = out["posed_joints"][0].cpu().numpy()
|
|
492
|
+
return float(_posed_joint_jumps(pj).max())
|
|
493
|
+
|
|
494
|
+
# Single continuous rollout: `acc` holds the accumulated NORMALIZED motion
|
|
495
|
+
# tensor (1, F, D); each segment conditions on its tail.
|
|
496
|
+
acc = None
|
|
497
|
+
gate_worst_jump = None
|
|
498
|
+
gate_exhausted = False
|
|
499
|
+
for seg_idx, seg in enumerate(seg_bounds):
|
|
500
|
+
n = seg["end_frame"] - seg["start_frame"] + 1
|
|
501
|
+
is_final = seg_idx == len(seg_bounds) - 1
|
|
502
|
+
best, best_jump = None, None
|
|
503
|
+
attempts = 1 if is_final else args.max_segment_attempts
|
|
504
|
+
for attempt in range(attempts):
|
|
505
|
+
if args.seed is not None:
|
|
506
|
+
seed_everything(args.seed + _SEED_STRIDE * seg_idx + attempt)
|
|
507
|
+
if acc is None:
|
|
508
|
+
history = None
|
|
509
|
+
else:
|
|
510
|
+
# Clamp to the largest token multiple available so a short
|
|
511
|
+
# first segment never feeds a non-token-multiple history.
|
|
512
|
+
hist_len = min(transition_frames, (acc.shape[1] // patch) * patch)
|
|
513
|
+
history = acc[:, -hist_len:]
|
|
514
|
+
segment_motion = generate_segment(seg["prompt"], n, history, seg["start_frame"])
|
|
515
|
+
if is_final:
|
|
516
|
+
best = segment_motion
|
|
517
|
+
break
|
|
518
|
+
jump = tail_jump(segment_motion)
|
|
519
|
+
if best_jump is None or jump < best_jump:
|
|
520
|
+
best, best_jump = segment_motion, jump
|
|
521
|
+
if jump <= args.max_boundary_jump:
|
|
522
|
+
break
|
|
523
|
+
if not is_final:
|
|
524
|
+
print(
|
|
525
|
+
f"[segment {seg['start_frame']}-{seg['end_frame']}] tail jump "
|
|
526
|
+
f"{best_jump:.4f} m/frame after {attempt + 1} attempt(s)"
|
|
527
|
+
)
|
|
528
|
+
gate_worst_jump = best_jump if gate_worst_jump is None else max(gate_worst_jump, best_jump)
|
|
529
|
+
if best_jump > args.max_boundary_jump:
|
|
530
|
+
gate_exhausted = True
|
|
531
|
+
acc = best if acc is None else torch.cat([acc, best], dim=1)
|
|
532
|
+
|
|
533
|
+
# Unnormalize + inverse ONCE over the full rollout, then the same tail as
|
|
534
|
+
# scripts/generate.py: postprocess once, numpy, save.
|
|
535
|
+
with torch.no_grad():
|
|
536
|
+
output = model.motion_rep.inverse(acc, is_normalized=True)
|
|
537
|
+
|
|
538
|
+
use_postprocess = "g1" not in resolved_model.lower() and not args.no_postprocess
|
|
539
|
+
if use_postprocess:
|
|
540
|
+
corrected = post_process_motion(
|
|
541
|
+
output["local_rot_mats"],
|
|
542
|
+
output["root_positions"],
|
|
543
|
+
output["foot_contacts"],
|
|
544
|
+
model.skeleton,
|
|
545
|
+
# With waypoints, ARDY's own postprocess enforces the pinned root
|
|
546
|
+
# contacts instead of skating them away (as the one-shot path).
|
|
547
|
+
constraint_lst=constraint_lst if constraint_lst else None,
|
|
548
|
+
)
|
|
549
|
+
output.update(corrected)
|
|
550
|
+
|
|
551
|
+
if isinstance(model.skeleton, SOMASkeleton30):
|
|
552
|
+
output = model.skeleton.output_to_SOMASkeleton77(output)
|
|
553
|
+
|
|
554
|
+
output = to_numpy(output)
|
|
555
|
+
# Single sample: drop the batch dim (generate.py _select_sample with index 0).
|
|
556
|
+
motion_dict = {
|
|
557
|
+
k: (v[0] if hasattr(v, "shape") and len(v.shape) > 0 and v.shape[0] == 1 else v)
|
|
558
|
+
for k, v in output.items()
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
text = " then ".join(seg["prompt"] for seg in seg_bounds)
|
|
562
|
+
output_base = _resolve_output_base(args.output)
|
|
563
|
+
npz_path = _single_file_path(output_base, ".npz")
|
|
564
|
+
print(f"Saving the npz output to {npz_path}")
|
|
565
|
+
save_motion_npz(npz_path, motion_dict, fps, text)
|
|
566
|
+
|
|
567
|
+
boundaries = [seg["start_frame"] for seg in seg_bounds[1:]]
|
|
568
|
+
frames = int(motion_dict["posed_joints"].shape[0])
|
|
569
|
+
if frames != total_frames:
|
|
570
|
+
raise RuntimeError(
|
|
571
|
+
f"generated frame count {frames} does not match the planned segment table "
|
|
572
|
+
f"({total_frames}); segment boundaries would be mislabeled."
|
|
573
|
+
)
|
|
574
|
+
result = {
|
|
575
|
+
"frames": frames,
|
|
576
|
+
"fps": int(fps),
|
|
577
|
+
"model": resolved_model,
|
|
578
|
+
"segments": seg_bounds,
|
|
579
|
+
"continuity": _continuity_metrics(np.asarray(motion_dict["posed_joints"]), boundaries),
|
|
580
|
+
"boundary_gate": {
|
|
581
|
+
"threshold_m": args.max_boundary_jump,
|
|
582
|
+
"max_attempts": args.max_segment_attempts,
|
|
583
|
+
"worst_tail_jump_m": gate_worst_jump,
|
|
584
|
+
"exhausted": gate_exhausted,
|
|
585
|
+
},
|
|
586
|
+
# Measured, never asserted: horizontal error at every pinned frame.
|
|
587
|
+
"waypoints": measure_waypoints(
|
|
588
|
+
waypoints, np.asarray(motion_dict["posed_joints"]), model.skeleton
|
|
589
|
+
),
|
|
590
|
+
}
|
|
591
|
+
print(json.dumps(result))
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
if __name__ == "__main__":
|
|
595
|
+
main()
|