"""FlashMotion -- music-to-3D-dance demo. ZeroGPU / Gradio Space for *FlashMotion: Ultra-Fast Long-Term 3D Motion Generation* (https://huggingface.co/papers/2611.13626). The Space covers the paper's **music-to-dance** (M2D) task: the two released ``m2d/genre`` checkpoints are the only ones whose inference path is fully self-contained in the public release. The text-to-motion checkpoints need the UMT5 sentence-feature cache plus the BABEL-long corpus and the FloodDiffusion evaluator; the speech-to-gesture checkpoints need BEAT2's 1024-D HuBERT and 300-D fastText caches and the licence-gated SMPL-X body model. Neither can be shipped in a Space. Everything numeric lives in the vendored packages next to this file: ``fmlib/m2d.py`` (35-D audio feature stack + x0-flow sampler + checkpoint loading), ``fmlib/skeleton.py`` (SMPL forward kinematics), ``fmlib/render.py`` (Pillow skeleton rasteriser -> MP4 with the music muxed in), plus in-tree pure-PyTorch replacements for the ``mamba_ssm`` / ``causal_conv1d`` / ``pytorch3d`` CUDA extensions, which have no sm_120 build. """ import math import os import sys import tempfile import time import spaces # noqa: F401 -- MUST precede every torch/CUDA-touching import APP_DIR = os.path.dirname(os.path.abspath(__file__)) if APP_DIR not in sys.path: sys.path.insert(0, APP_DIR) import numpy as np # noqa: E402 import torch # noqa: E402 import gradio as gr # noqa: E402 from huggingface_hub import snapshot_download # noqa: E402 from fmlib.m2d import ( # noqa: E402 FPS, GENRES, GENRE_TO_ID, MOTION_DIM, SAMPLE_RATE, build_decoder, decode_motion, euler_sample, extract_baseline_features, estimate_tempo, load_audio_clip, normalize_features, ) from fmlib.render import render_mp4, write_audio_clip # noqa: E402 from fmlib.skeleton import SMPLSkeleton # noqa: E402 DEVICE = "cuda" MODEL_REPO = "yangkaixing/FlashMotion-models" # Defaults for every non-primary input. ``gr.Examples`` only supplies the # audio; Gradio fills the remaining slots with ``None`` when it pre-runs an # example through this function (``Examples.cache`` inserts ``None`` for every # input column without an example value), so anything arriving as ``None`` has # to fall back to the value the matching UI component starts with. DEFAULTS = dict( horizon=12.0, genre="Hiphop", quality="1-step (fastest)", start=0.0, seed=42 ) def _or(value, key): return DEFAULTS[key] if value is None else value # The two released M2D checkpoints. Their NFE (number of function evaluations) # comes from each checkpoint's own ``config['sampling_steps']``; the 1-step one # is the paper's headline "ultra-fast" setting, the 4-step one trades 4x the # sampling for a better FID. CHECKPOINTS = { "1-step (fastest)": ("m2d/genre/train-2250.pt", 1), "4-step (highest quality)": ("m2d/genre/train-2100.pt", 4), } CKPT_FILES = [path for path, _ in CHECKPOINTS.values()] # --------------------------------------------------------------------------- # # Model loading (module scope, eager .to("cuda") -- the ZeroGPU contract) # --------------------------------------------------------------------------- # def _download_checkpoints(): local = {} root = snapshot_download( MODEL_REPO, allow_patterns=["m2d/genre/train-2250.pt", "m2d/genre/train-2100.pt"], ) for label, (rel, _nfe) in CHECKPOINTS.items(): local[label] = os.path.join(root, rel) return local print("Downloading FlashMotion m2d checkpoints ...", flush=True) _CKPT_PATHS = _download_checkpoints() DECODERS = {} NORMALIZERS = {} for _label, (_rel, _nfe) in CHECKPOINTS.items(): _t0 = time.perf_counter() _decoder, _normalizer, _ckpt = build_decoder( _CKPT_PATHS[_label], device=DEVICE, dtype=torch.float32 ) DECODERS[_label] = _decoder NORMALIZERS[_label] = _normalizer print( f" loaded {_label}: epoch={_ckpt.get('epoch')} " f"nfe={_nfe} vram_load={time.perf_counter() - _t0:.1f}s", flush=True, ) SKELETON = SMPLSkeleton(device=DEVICE) def _warmup_feature_stack(): """Compile librosa's numba kernels at boot, on synthetic audio. ``librosa``'s onset / MFCC / chroma / beat functions are numba-JIT'd and compile on first call -- that is ~10 s of CPU, measured live as ``features 10.5s`` on the very first request after a boot versus ``0.2s`` on every one after it. Paying it inside the first ``@spaces.GPU`` request would blow that request's ZeroGPU duration budget, so it is paid here, before the Space reports ready, on a synthetic 120 BPM click track that exercises every branch of the real stack. """ seconds = 12.0 count = int(round(seconds * SAMPLE_RATE)) mono = np.zeros(count, dtype=np.float32) mono[:: SAMPLE_RATE // 2] = 0.8 # impulses every 0.5 s -> 120 BPM frames = int(round(seconds * FPS)) extract_baseline_features(mono, frames, estimate_tempo(mono, SAMPLE_RATE)) try: _t0 = time.perf_counter() _warmup_feature_stack() print(f" warmed feature stack in {time.perf_counter() - _t0:.1f}s", flush=True) except Exception as _exc: # never let warm-up take the whole Space down print(f" feature-stack warm-up skipped: {_exc!r}", flush=True) print("FlashMotion ready.", flush=True) # --------------------------------------------------------------------------- # # ZeroGPU duration sizing # --------------------------------------------------------------------------- # def estimate_duration( audio, horizon=12.0, genre="Hiphop", quality="1-step (fastest)", start=0.0, seed=42, *args, **kwargs, ): """ZeroGPU quota for one request, from the clip length and the step count. Fitted to live ``gradio_client`` timings on zero-a10g, in seconds of in-handler wall clock (``features + motion + render``, as reported in the run summary). Each cell is the max over 3 repeats on the bundled clips (``/tmp/long30.wav`` stands in for the 24 s rows, since the bundled clips are only ~13 s): ====== ======= ============= clip steps measured (s) ====== ======= ============= 12 s 1-step 1.4 - 1.5 12 s 4-step 3.2 - 3.4 24 s 1-step 2.7 - 2.7 24 s 4-step 6.3 - 6.9 ====== ======= ============= The all-Python mamba scan dominates and scales with ``steps x frames``; the Pillow rasteriser scales with ``frames`` alone. Those are the two slope terms. The intercept drops out (~0.15 s), because the librosa feature stack is now warmed at boot (``_warmup_feature_stack``) instead of being paid inside the first request. The fit tracks every measured max within ~10%, and the ``1.18x`` margin takes the worst UI setting (24 s horizon, 4-step) to 9 s against 6.9 s measured. ``*args, **kwargs`` swallows the ``progress`` object Gradio appends. """ frames = max(1, int(round(float(_or(horizon, "horizon")) * FPS))) steps = CHECKPOINTS.get(_or(quality, "quality"), CHECKPOINTS["1-step (fastest)"])[1] est = 0.00195 * steps * frames + 0.00220 * frames # 4 s floor covers the GPU worker's per-session spin-up, which is not part of # the in-handler time the fit is built from but does sit inside the session. return int(min(20, max(4, math.ceil(est * 1.18)))) # --------------------------------------------------------------------------- # # Inference # --------------------------------------------------------------------------- # @spaces.GPU(duration=estimate_duration) def generate( audio, horizon, genre, quality, start=0.0, seed=42, progress=gr.Progress(), ): """Generate a 3D dance that matches the music and render it to MP4. Args: audio: music track (any common audio format). horizon: length of the generated dance in seconds (4-32). genre: dance-style condition -- one of the 16 FineDance genres. quality: "1-step (fastest)" or "4-step (highest quality)"; picks the released checkpoint and its number of sampling steps. start: offset into the track to start from, in seconds. seed: RNG seed for the initial noise. Returns: (path to the rendered MP4 with the music muxed in, run summary text). """ if audio is None: raise gr.Error("Please upload a music track (or pick one of the examples).") # ``gr.Examples`` supplies only the audio and Gradio passes ``None`` for the # rest, so resolve those to the UI defaults before touching them. horizon = float(_or(horizon, "horizon")) genre = _or(genre, "genre") quality = _or(quality, "quality") start = max(0.0, float(_or(start, "start"))) seed = _or(seed, "seed") label = quality if quality in CHECKPOINTS else "1-step (fastest)" decoder = DECODERS[label] normalizer = NORMALIZERS[label] nfeats = CHECKPOINTS[label][1] total_start = time.perf_counter() try: mono, tempo_audio, tempo_sr, frames = load_audio_clip(audio, start, horizon) except ValueError as exc: raise gr.Error(str(exc)) from exc torch.manual_seed(int(seed)) progress(0.05, desc="Extracting music features") bpm = estimate_tempo(tempo_audio, tempo_sr) features = extract_baseline_features(mono, frames, bpm) cond = torch.from_numpy(normalize_features(features))[None].to(DEVICE) genre_ids = torch.tensor( [GENRE_TO_ID.get(genre, GENRE_TO_ID["Hiphop"])], dtype=torch.long, device=DEVICE ) t_features = time.perf_counter() progress(0.15, desc=f"Sampling motion ({nfeats} step{'s' if nfeats > 1 else ''})") samples = euler_sample( decoder, (1, frames, MOTION_DIM), cond, genre_ids, nfeats=nfeats ) q, pos, contact = decode_motion(decoder, normalizer, samples, DEVICE) joints = SKELETON.forward(q, pos)[0].detach().float().cpu().numpy() contact_np = contact[0].detach().float().cpu().numpy() t_motion = time.perf_counter() workdir = tempfile.mkdtemp(prefix="flashmotion-") try: wav = os.path.join(workdir, "clip.wav") write_audio_clip(audio, start, horizon, wav) progress(0.55, desc="Rendering animation") out = os.path.join(workdir, "dance.mp4") render_mp4( joints, contact_np, wav, out, progress=progress, progress_offset=0.55, progress_span=0.44, ) except Exception as exc: # keep the renderer's failure legible in the UI raise gr.Error(f"Rendering failed: {exc}") from exc elapsed = time.perf_counter() - total_start progress(1.0, desc="Done") summary = ( f"{label} checkpoint | {frames} frames @ {FPS} fps ({frames / FPS:.1f} s) | " f"music {start:.1f}s-{start + horizon:.1f}s @ {bpm:.1f} BPM | " f"features {t_features - total_start:.1f}s + motion {t_motion - t_features:.1f}s " f"+ render {elapsed - (t_motion - total_start):.1f}s = {elapsed:.1f}s total" ) print(f"[flashmotion] {summary}", flush=True) return out, summary # --------------------------------------------------------------------------- # # UI # --------------------------------------------------------------------------- # CSS = """ #col-container { max-width: 1100px; margin: 0 auto; } .dark .gradio-container { color: var(--body-text-color); } """ EXAMPLES = [ [os.path.join(APP_DIR, "assets", "dance-fairies-14s.ogg")], [os.path.join(APP_DIR, "assets", "phonk-13s.ogg")], ] with gr.Blocks(title="FlashMotion - Music to 3D Dance") as demo: gr.Markdown( "# FlashMotion - Music to 3D Dance\n" "Long-horizon 3D human motion from music, from the paper " "[*FlashMotion: Ultra-Fast Long-Term 3D Motion Generation*]" "(https://huggingface.co/papers/2611.13626). The track's 35-D hand-crafted " "music features drive an all-Mamba flow-matching decoder that emits a " "151-channel SMPL motion sequence, rendered here as a skeleton with the " "music muxed in.\n\n" "The **1-step** checkpoint is the paper's ultra-fast setting; the " "**4-step** one spends 4x the sampling for a better FID_k (15.15 vs 18.32 " "on FineDance)." ) with gr.Column(elem_id="col-container"): with gr.Row(): with gr.Column(scale=5): audio_in = gr.Audio( label="Music track", type="filepath", sources=["upload", "microphone"], ) horizon_in = gr.Slider( minimum=4, maximum=24, value=12, step=1, label="Dance length (seconds)", info="The model was trained on 40 s horizons; 12 s keeps the " "ZeroGPU request short.", ) quality_in = gr.Radio( choices=list(CHECKPOINTS), value="1-step (fastest)", label="Checkpoint / sampling steps", ) genre_in = gr.Dropdown( choices=GENRES, value="Hiphop", label="Dance style (genre condition)", ) with gr.Accordion("Advanced options", open=False): start_in = gr.Slider( minimum=0, maximum=300, value=0, step=1, label="Start offset in the track (seconds)", ) seed_in = gr.Number( value=42, precision=0, label="Seed", info="The paper's base seed is 42.", ) run_btn = gr.Button("Generate dance", variant="primary") with gr.Column(scale=6): video_out = gr.Video( label="Generated 3D dance", autoplay=True, height=480, ) info_out = gr.Textbox( label="Run summary", lines=3, interactive=False, buttons=["copy"], ) gr.Examples( examples=EXAMPLES, inputs=[audio_in], fn=generate, outputs=[video_out, info_out], cache_examples=True, cache_mode="lazy", label="Example tracks (CC0)", ) run_btn.click( fn=generate, inputs=[ audio_in, horizon_in, genre_in, quality_in, start_in, seed_in, ], outputs=[video_out, info_out], api_name="generate", ) demo.queue(default_concurrency_limit=2).launch( theme=gr.themes.Citrus(), css=CSS, mcp_server=True, )