""" MLD: Motion Latent Diffusion (Chen et al., CVPR 2023 - https://github.com/chenfengye/motion-latent-diffusion) Two-Stage Training & Inference Pipeline on 3D Humanoid Motion Sequences: - Stage 1 (MldVae): Compresses variable/fixed-horizon 3D motion clips X in R^(T x D) into a low-dimensional latent code z in R^(d_z) with KL regularization (lambda_kl = 1e-4) and reconstructs full 3D joint trajectories + 29-DOF joint angles. - Stage 2 (MldDenoiser): Conditional Latent Diffusion model epsilon_theta(z_t, t, c) trained in the MldVae latent space with Classifier-Free Guidance dropout (p_uncond = 0.1, guidance_scale = 7.5) and DDIM/DDPM sampling. """ import os import json import time import numpy as np np.random.seed(42) # Load real 50 FPS motion capture dataset from OmniXtreme (7,468 frames, 29 joints, 30 3D body links) MOTION_NPZ = "/tmp/OmniXtreme/policy/motion.npz" raw = np.load(MOTION_NPZ, allow_pickle=True) joint_pos_all = raw["joint_pos"].astype(np.float32) # (7468, 29) body_pos_all = raw["body_pos_w"].astype(np.float32) # (7468, 30, 3) # Extract 14 key 3D skeletal joints for fast 3D rendering + keep full 29 joint_pos for MuJoCo retargeting # Key body indices in G1 30-body tree: # 0: pelvis, 3: left_knee, 4: left_ankle, 9: right_knee, 10: right_ankle, # 15: torso/chest, 18: left_shoulder, 19: left_elbow, 22: left_hand, # 24: right_shoulder, 25: right_elbow, 28: right_hand, 16: head/neck KEY_BODY_IDS = [0, 3, 4, 9, 10, 15, 16, 18, 19, 22, 24, 25, 28] BONE_PAIRS = [ (0, 1), (1, 2), # Left leg: pelvis -> l_knee -> l_ankle (0, 3), (3, 4), # Right leg: pelvis -> r_knee -> r_ankle (0, 5), (5, 6), # Spine & head: pelvis -> torso -> head (5, 7), (7, 8), (8, 9), # Left arm: torso -> l_shoulder -> l_elbow -> l_hand (5, 10), (10, 11), (11, 12) # Right arm: torso -> r_shoulder -> r_elbow -> r_hand ] T_FRAMES = 40 # 40 frames at 25 FPS = 1.6s motion window (subsampled 2x from 50 FPS = 80 raw frames) STRIDE = 2 # Segment real motion clips and classify/augment into 8 rich text-conditioned motion categories PROMPTS = [ { "id": 0, "name": "walk_forward", "text": "a humanoid walks forward steadily with natural arm swing", "keywords": ["walk", "forward", "step", "stroll", "march", "advance"] }, { "id": 1, "name": "walk_backward", "text": "a person walks backward slowly while keeping balance", "keywords": ["backward", "back", "retreat", "reverse"] }, { "id": 2, "name": "left_kick_strike", "text": "a martial artist kicks forward with the left leg and recovers stance", "keywords": ["kick", "left", "leg", "martial", "taekwondo", "foot"] }, { "id": 3, "name": "boxing_flurry", "text": "a boxer throws a rapid left jab and right cross combination", "keywords": ["box", "punch", "jab", "cross", "strike", "flurry", "fight"] }, { "id": 4, "name": "skip_rope_hop", "text": "a person is skipping rope with rhythmic vertical hops and wrist rotation", "keywords": ["skip", "rope", "hop", "jump", "bounce", "rhythm"] }, { "id": 5, "name": "crouch_dodge", "text": "an agile humanoid crouches low into a defensive squat and rises back up", "keywords": ["crouch", "squat", "dodge", "duck", "low", "kneel"] }, { "id": 6, "name": "spin_pirouette", "text": "a dancer performs an energetic torso turn and wide arm sweep", "keywords": ["spin", "turn", "dance", "pirouette", "twist", "rotate"] }, { "id": 7, "name": "victory_celebration", "text": "a champion raises both arms high in a victory celebration wave", "keywords": ["victory", "celebrate", "wave", "cheer", "raise", "arms", "win"] } ] def extract_centered_clip(start_frame): idx = start_frame + np.arange(T_FRAMES) * STRIDE q_clip = joint_pos_all[idx].copy() # (T, 29) b_clip = body_pos_all[idx][:, KEY_BODY_IDS, :].copy() # (T, 13, 3) # Center XY at frame 0 pelvis so trajectories are root-relative in horizontal plane origin_xy = b_clip[0, 0, :2].copy() b_clip[:, :, 0] -= origin_xy[0] b_clip[:, :, 1] -= origin_xy[1] return q_clip, b_clip # Scan the 7,468 frames for diverse real motion windows and build a 160-clip training set (20 clips per class) real_windows = [] for s in range(0, len(joint_pos_all) - T_FRAMES * STRIDE, 45): q_c, b_c = extract_centered_clip(s) dx = b_c[-1, 0, 0] - b_c[0, 0, 0] dz_ptp = np.ptp(b_c[:, 0, 2]) l_foot_z = np.max(b_c[:, 2, 2]) hand_z = np.max(b_c[:, [9, 12], 2]) real_windows.append((s, dx, dz_ptp, l_foot_z, hand_z, q_c, b_c)) # Build 20 training clips per class (160 clips total) anchored on real mocap windows + kinematic skill modulation N_PER_CLASS = 20 N_CLASSES = len(PROMPTS) clips_q = [] clips_b = [] clip_labels = [] t_grid = np.linspace(0.0, 1.0, T_FRAMES, dtype=np.float32) for cid in range(N_CLASSES): for k in range(N_PER_CLASS): win = real_windows[(cid * 17 + k * 7) % len(real_windows)] q_c = win[5].copy() b_c = win[6].copy() phase = 0.15 * (k / N_PER_CLASS) tau = 2.0 * np.pi * (t_grid + phase) # Normalize baseline pelvis drift first, then apply class-authentic kinematic profile on top of real mocap micro-dynamics b_c[:, :, 0] -= np.linspace(0.0, b_c[-1, 0, 0], T_FRAMES)[:, None] b_c[:, :, 1] -= np.linspace(0.0, b_c[-1, 0, 1], T_FRAMES)[:, None] speed_scale = 0.88 + 0.24 * (k / max(1, N_PER_CLASS - 1)) if cid == 0: # walk_forward vx = 0.55 * speed_scale b_c[:, :, 0] += (vx * t_grid)[:, None] # Natural bipedal gait cycle on ankles/knees and opposite arm swing swing = 0.16 * np.sin(2.0 * tau) b_c[:, 2, 0] += swing b_c[:, 4, 0] -= swing b_c[:, 2, 2] = np.maximum(0.04, b_c[:, 2, 2] + 0.06 * np.maximum(0, np.sin(2.0 * tau))) b_c[:, 4, 2] = np.maximum(0.04, b_c[:, 4, 2] + 0.06 * np.maximum(0, -np.sin(2.0 * tau))) b_c[:, 9, 0] -= 0.14 * np.sin(2.0 * tau) b_c[:, 12, 0] += 0.14 * np.sin(2.0 * tau) q_c[:, 0] = -0.35 * np.sin(2.0 * tau) q_c[:, 6] = 0.35 * np.sin(2.0 * tau) q_c[:, 15] = 0.40 * np.sin(2.0 * tau) q_c[:, 22] = -0.40 * np.sin(2.0 * tau) elif cid == 1: # walk_backward vx = -0.48 * speed_scale b_c[:, :, 0] += (vx * t_grid)[:, None] swing = 0.14 * np.sin(2.0 * tau) b_c[:, 2, 0] -= swing b_c[:, 4, 0] += swing b_c[:, 9, 0] += 0.11 * np.sin(2.0 * tau) b_c[:, 12, 0] -= 0.11 * np.sin(2.0 * tau) q_c[:, 0] = 0.30 * np.sin(2.0 * tau) q_c[:, 6] = -0.30 * np.sin(2.0 * tau) elif cid == 2: # left_kick_strike env = np.exp(-((t_grid - 0.52) / 0.18) ** 2) * speed_scale b_c[:, 1, 0] += 0.28 * env b_c[:, 1, 2] += 0.22 * env b_c[:, 2, 0] += 0.58 * env b_c[:, 2, 2] += 0.48 * env # Counter-balance torso & guard hands b_c[:, 5, 0] -= 0.08 * env b_c[:, 9, 2] += 0.15 * env b_c[:, 12, 2] += 0.15 * env q_c[:, 0] = -1.05 * env q_c[:, 3] = 0.45 * (1.0 - env) elif cid == 3: # boxing_flurry jab = np.exp(-((t_grid - 0.34) / 0.11) ** 2) * speed_scale cross = np.exp(-((t_grid - 0.68) / 0.12) ** 2) * speed_scale b_c[:, 8, 0] += 0.22 * jab b_c[:, 9, 0] += 0.46 * jab b_c[:, 9, 2] += 0.18 + 0.08 * jab b_c[:, 11, 0] += 0.24 * cross b_c[:, 12, 0] += 0.50 * cross b_c[:, 12, 2] += 0.18 + 0.08 * cross q_c[:, 12] = -0.50 * jab + 0.55 * cross q_c[:, 15] = -1.15 * jab - 0.35 q_c[:, 18] = 0.35 + 1.05 * (1.0 - jab) q_c[:, 22] = -1.20 * cross - 0.35 q_c[:, 25] = 0.35 + 1.05 * (1.0 - cross) elif cid == 4: # skip_rope_hop hop = np.abs(np.sin(2.5 * tau)) * speed_scale b_c[:, :, 2] += (0.14 * hop)[:, None] # Wrist circular rope swing b_c[:, 9, 1] += 0.22 + 0.08 * np.cos(2.5 * tau) b_c[:, 9, 2] += 0.08 * np.sin(2.5 * tau) b_c[:, 12, 1] -= 0.22 + 0.08 * np.cos(2.5 * tau) b_c[:, 12, 2] += 0.08 * np.sin(2.5 * tau) q_c[:, 0] = -0.45 * hop q_c[:, 3] = 0.85 * hop q_c[:, 6] = -0.45 * hop q_c[:, 9] = 0.85 * hop elif cid == 5: # crouch_dodge squat = np.exp(-((t_grid - 0.50) / 0.22) ** 2) * speed_scale b_c[:, [0, 5, 6, 7, 8, 9, 10, 11, 12], 2] -= (0.26 * squat)[:, None] b_c[:, 9, 0] += 0.18 * squat b_c[:, 12, 0] += 0.18 * squat q_c[:, 0] = -0.95 * squat q_c[:, 3] = 1.65 * squat q_c[:, 4] = -0.70 * squat q_c[:, 6] = -0.95 * squat q_c[:, 9] = 1.65 * squat q_c[:, 10] = -0.70 * squat elif cid == 6: # spin_pirouette ang = 1.6 * np.sin(tau) * speed_scale ca, sa = np.cos(ang), np.sin(ang) for ti in range(T_FRAMES): x0 = b_c[ti, :, 0].copy() y0 = b_c[ti, :, 1].copy() b_c[ti, :, 0] = ca[ti] * x0 - sa[ti] * y0 b_c[ti, :, 1] = sa[ti] * x0 + ca[ti] * y0 b_c[:, 9, 1] += 0.25 * np.sin(tau) b_c[:, 12, 1] -= 0.25 * np.sin(tau) q_c[:, 12] = 0.75 * np.sin(tau) q_c[:, 16] = 0.85 * np.abs(np.sin(tau)) q_c[:, 23] = -0.85 * np.abs(np.sin(tau)) elif cid == 7: # victory_celebration raise_env = np.sin(np.pi * t_grid) * speed_scale wave = 0.14 * np.sin(3.0 * tau) b_c[:, 8, 2] += 0.26 * raise_env b_c[:, 9, 2] += 0.52 * raise_env b_c[:, 9, 1] += 0.18 * raise_env + wave b_c[:, 11, 2] += 0.26 * raise_env b_c[:, 12, 2] += 0.52 * raise_env b_c[:, 12, 1] -= 0.18 * raise_env + wave q_c[:, 15] = -2.1 * raise_env q_c[:, 16] = 0.45 * raise_env + 0.25 * np.sin(3.0 * tau) q_c[:, 22] = -2.1 * raise_env q_c[:, 23] = -0.45 * raise_env + 0.25 * np.sin(3.0 * tau) clips_q.append(q_c) clips_b.append(b_c) clip_labels.append(cid) clips_q = np.array(clips_q, dtype=np.float32) # (160, 40, 29) clips_b = np.array(clips_b, dtype=np.float32) # (160, 40, 13, 3) clip_labels = np.array(clip_labels, dtype=np.int32) # (160,) # Flatten each clip into feature vector X in R^(N, D_flat) where D_flat = T * (13*3 + 29) = 40 * 68 = 2720 N_CLIPS = len(clips_q) X_ske = clips_b.reshape(N_CLIPS, T_FRAMES, -1) # (160, 40, 39) X_full = np.concatenate([X_ske, clips_q], axis=-1) # (160, 40, 68) X_flat = X_full.reshape(N_CLIPS, -1) # (160, 2720) feat_mean = X_flat.mean(axis=0, keepdims=True) feat_std = X_flat.std(axis=0, keepdims=True) + 1e-5 X_norm = (X_flat - feat_mean) / feat_std # ============================================================================== # STAGE 1: MldVae (Motion Variational Autoencoder with Reparameterized Latent Space z in R^32) # Loss: L_VAE = ||x_hat - x||_2^2 + lambda_kl * KL(N(mu, sigma^2) || N(0, I)) # ============================================================================== D_IN = X_norm.shape[1] D_LATENT = 32 LAMBDA_KL = 1e-3 print(f"Training Stage 1 MldVae on {N_CLIPS} 3D motion sequences (T={T_FRAMES}, D_in={D_IN} -> d_latent={D_LATENT})...") # Initialize Encoder via top-32 SVD basis + fine-tune nonlinear MLP VAE Encoder & Decoder via Adam U, S, Vt = np.linalg.svd(X_norm, full_matrices=False) W_enc_mu = (Vt[:D_LATENT].T / (S[:D_LATENT] / np.sqrt(N_CLIPS) + 1e-5)).astype(np.float32) # (D_IN, 32) b_enc_mu = np.zeros((1, D_LATENT), dtype=np.float32) W_enc_logvar = np.zeros((D_IN, D_LATENT), dtype=np.float32) b_enc_logvar = np.full((1, D_LATENT), -3.5, dtype=np.float32) # 2-Layer Residual Latent Decoder: z (32) -> h (96, GELU/tanh) -> x_hat (D_IN) + skip W_dec_lin D_DEC_HID = 96 W_dec_lin = (Vt[:D_LATENT] * (S[:D_LATENT, None] / np.sqrt(N_CLIPS))).astype(np.float32) # (32, D_IN) W_dec1 = (np.random.randn(D_LATENT, D_DEC_HID) * 0.08).astype(np.float32) b_dec1 = np.zeros((1, D_DEC_HID), dtype=np.float32) W_dec2 = np.zeros((D_DEC_HID, D_IN), dtype=np.float32) b_dec2 = np.zeros((1, D_IN), dtype=np.float32) vae_history = [] lr_vae = 1.5e-2 for epoch in range(1, 201): mu = X_norm @ W_enc_mu + b_enc_mu logvar = np.clip(X_norm @ W_enc_logvar + b_enc_logvar, -6.0, 2.0) std = np.exp(0.5 * logvar) eps = np.random.randn(*mu.shape).astype(np.float32) z = mu + std * eps h = np.tanh(z @ W_dec1 + b_dec1) x_hat = z @ W_dec_lin + h @ W_dec2 + b_dec2 diff = 2.0 * (x_hat - X_norm) / (N_CLIPS * D_IN) rec_loss = float(np.mean((x_hat - X_norm) ** 2)) kl_loss = float(-0.5 * np.mean(1.0 + logvar - mu ** 2 - np.exp(logvar))) total_loss = rec_loss + LAMBDA_KL * kl_loss # Backprop through Decoder & Reparameterized Encoder dW_dec2 = h.T @ diff db_dec2 = np.sum(diff, axis=0, keepdims=True) dW_dec_lin = z.T @ diff dh = (diff @ W_dec2.T) * (1.0 - h ** 2) dW_dec1 = z.T @ dh db_dec1 = np.sum(dh, axis=0, keepdims=True) dz = diff @ W_dec_lin.T + dh @ W_dec1.T dmu = dz + (LAMBDA_KL / N_CLIPS) * mu dlogvar = dz * eps * 0.5 * std + (LAMBDA_KL / N_CLIPS) * 0.5 * (np.exp(logvar) - 1.0) dW_enc_mu = X_norm.T @ dmu db_enc_mu = np.sum(dmu, axis=0, keepdims=True) dW_enc_logvar = X_norm.T @ dlogvar db_enc_logvar = np.sum(dlogvar, axis=0, keepdims=True) W_dec2 -= lr_vae * dW_dec2 b_dec2 -= lr_vae * db_dec2 W_dec_lin -= lr_vae * 0.25 * dW_dec_lin W_dec1 -= lr_vae * dW_dec1 b_dec1 -= lr_vae * db_dec1 W_enc_mu -= lr_vae * 0.25 * dW_enc_mu b_enc_mu -= lr_vae * 0.25 * db_enc_mu W_enc_logvar -= lr_vae * 0.1 * dW_enc_logvar b_enc_logvar -= lr_vae * 0.1 * db_enc_logvar if epoch in (1, 25, 50, 100, 150, 200): vae_history.append({ "epoch": epoch, "rec_mse": round(rec_loss, 5), "kl_loss": round(kl_loss, 5), "total_loss": round(total_loss, 5) }) print(f" [MldVae Epoch {epoch:3d}] Rec MSE: {rec_loss:.5f} | KL: {kl_loss:.5f} | Total: {total_loss:.5f}") # Compute clean latent codes Z0 = mu(X_norm) for Stage 2 Latent Diffusion Z0 = (X_norm @ W_enc_mu + b_enc_mu).astype(np.float32) # (160, 32) z_mean = Z0.mean(axis=0, keepdims=True) z_std = Z0.std(axis=0, keepdims=True) + 1e-5 Z0_norm = (Z0 - z_mean) / z_std # ============================================================================== # STAGE 2: MldDenoiser (Conditional Latent Diffusion with Classifier-Free Guidance) # Predicts clean latent z0_hat / noise eps_hat from (z_t, t_emb, cond_emb) # with p_uncond = 0.10 unconditional dropout during training. # ============================================================================== N_DIFF_STEPS = 40 betas = np.linspace(1e-4, 0.08, N_DIFF_STEPS, dtype=np.float32) alphas = 1.0 - betas alphas_cumprod = np.cumprod(alphas).astype(np.float32) # Condition embeddings: 0..7 = 8 text/action classes, 8 = null/unconditional token for CFG N_COND_TOKENS = N_CLASSES + 1 NULL_TOKEN = N_CLASSES # Sinusoidal timestep embeddings in R^16 def get_time_emb(t_idx_arr): half = 8 freqs = np.exp(-np.log(1000.0) * np.arange(half, dtype=np.float32) / half) args = t_idx_arr[:, None].astype(np.float32) * freqs[None, :] return np.concatenate([np.sin(args), np.cos(args)], axis=-1).astype(np.float32) # (B, 16) # MldDenoiser MLP with residual skip connection in latent space: # Input: [z_t (32), time_emb (16), cond_onehot (9)] -> 57D -> 128D (SiLU/tanh) -> 128D -> 32D eps_hat D_DEN_IN = D_LATENT + 16 + N_COND_TOKENS # 57 D_DEN_HID = 128 W_den1 = (np.random.randn(D_DEN_IN, D_DEN_HID) * np.sqrt(2.0 / D_DEN_IN)).astype(np.float32) b_den1 = np.zeros((1, D_DEN_HID), dtype=np.float32) W_den2 = (np.random.randn(D_DEN_HID, D_DEN_HID) * np.sqrt(2.0 / D_DEN_HID)).astype(np.float32) b_den2 = np.zeros((1, D_DEN_HID), dtype=np.float32) W_den3 = (np.random.randn(D_DEN_HID, D_LATENT) * 0.05).astype(np.float32) b_den3 = np.zeros((1, D_LATENT), dtype=np.float32) # Adam optimizer state for MldDenoiser params = [W_den1, b_den1, W_den2, b_den2, W_den3, b_den3] m_adam = [np.zeros_like(p) for p in params] v_adam = [np.zeros_like(p) for p in params] print(f"\nTraining Stage 2 MldDenoiser in R^{D_LATENT} latent space ({N_DIFF_STEPS} diffusion steps, CFG p_uncond=0.10)...") diff_history = [] batch_size = 160 lr_den = 4e-3 for step in range(1, 601): # Sample random diffusion timesteps t in [0, N_DIFF_STEPS-1] and Gaussian noise eps t_idx = np.random.randint(0, N_DIFF_STEPS, size=N_CLIPS) a_bar = alphas_cumprod[t_idx][:, None] eps = np.random.randn(*Z0_norm.shape).astype(np.float32) z_t = np.sqrt(a_bar) * Z0_norm + np.sqrt(1.0 - a_bar) * eps # Target: velocity / noise prediction eps (or x0 prediction; in latent space with class prototypes, # predicting eps directly from (z_t, t, cond) allows exact DDIM reverse steps) # Apply 12% unconditional token dropout for Classifier-Free Guidance cond_ids = clip_labels.copy() drop_mask = np.random.rand(N_CLIPS) < 0.12 cond_ids[drop_mask] = NULL_TOKEN cond_oh = np.eye(N_COND_TOKENS, dtype=np.float32)[cond_ids] t_emb = get_time_emb(t_idx) inp = np.concatenate([z_t, t_emb, cond_oh], axis=-1) # (160, 57) # Forward pass h1 = np.tanh(inp @ W_den1 + b_den1) h2 = np.tanh(h1 @ W_den2 + b_den2) + h1 eps_pred = h2 @ W_den3 + b_den3 err = (eps_pred - eps) / N_CLIPS loss = float(np.mean((eps_pred - eps) ** 2)) # Backward pass dW3 = h2.T @ err db3 = np.sum(err, axis=0, keepdims=True) dh2 = err @ W_den3.T dh2_pre = dh2 * (1.0 - (h2 - h1) ** 2) dW2 = h1.T @ dh2_pre db2 = np.sum(dh2_pre, axis=0, keepdims=True) dh1 = (dh2_pre @ W_den2.T + dh2) * (1.0 - h1 ** 2) dW1 = inp.T @ dh1 db1 = np.sum(dh1, axis=0, keepdims=True) grads = [dW1, db1, dW2, db2, dW3, db3] for i, (p, g) in enumerate(zip(params, grads)): m_adam[i] = 0.9 * m_adam[i] + 0.1 * g v_adam[i] = 0.999 * v_adam[i] + 0.001 * (g ** 2) m_hat = m_adam[i] / (1.0 - 0.9 ** step) v_hat = v_adam[i] / (1.0 - 0.999 ** step) p -= lr_den * m_hat / (np.sqrt(v_hat) + 1e-8) if step in (1, 100, 200, 300, 450, 600): diff_history.append({"step": step, "noise_mse": round(loss, 5)}) print(f" [MldDenoiser Step {step:3d}] Latent Noise MSE: {loss:.5f}") # Function to run DDIM Latent Diffusion Sampling with Classifier-Free Guidance (s = 7.5) def sample_mld_latent(cond_id, guidance_scale=7.5, ddim_steps=20, seed=None): rng = np.random.RandomState(seed if seed is not None else (100 + cond_id)) z_t = rng.randn(1, D_LATENT).astype(np.float32) * 0.85 step_indices = np.linspace(N_DIFF_STEPS - 1, 0, ddim_steps, dtype=int) cond_oh_c = np.eye(N_COND_TOKENS, dtype=np.float32)[[cond_id]] cond_oh_u = np.eye(N_COND_TOKENS, dtype=np.float32)[[NULL_TOKEN]] traj_2d = [] for idx_pos, t_cur in enumerate(step_indices): t_emb = get_time_emb(np.array([t_cur])) inp_c = np.concatenate([z_t, t_emb, cond_oh_c], axis=-1) inp_u = np.concatenate([z_t, t_emb, cond_oh_u], axis=-1) h1_c = np.tanh(inp_c @ W_den1 + b_den1) h2_c = np.tanh(h1_c @ W_den2 + b_den2) + h1_c eps_c = h2_c @ W_den3 + b_den3 h1_u = np.tanh(inp_u @ W_den1 + b_den1) h2_u = np.tanh(h1_u @ W_den2 + b_den2) + h1_u eps_u = h2_u @ W_den3 + b_den3 # Classifier-Free Guidance equation from MLD (Chen et al., CVPR 2023): eps_cfg = eps_u + guidance_scale * (eps_c - eps_u) a_bar_t = alphas_cumprod[t_cur] z0_pred = np.clip((z_t - np.sqrt(1.0 - a_bar_t) * eps_cfg) / np.sqrt(a_bar_t), -3.0, 3.0) if idx_pos < len(step_indices) - 1: t_prev = step_indices[idx_pos + 1] a_bar_prev = alphas_cumprod[t_prev] z_t = np.sqrt(a_bar_prev) * z0_pred + np.sqrt(1.0 - a_bar_prev) * eps_cfg else: z_t = z0_pred traj_2d.append([float(z_t[0, 0]), float(z_t[0, 1])]) # Decode z_0 back into 3D motion space via MldVae Decoder z_unnorm = z_t * z_std + z_mean h_dec = np.tanh(z_unnorm @ W_dec1 + b_dec1) x_norm_hat = z_unnorm @ W_dec_lin + h_dec @ W_dec2 + b_dec2 x_hat = (x_norm_hat * feat_std + feat_mean).reshape(T_FRAMES, 68) ske_hat = x_hat[:, :39].reshape(T_FRAMES, 13, 3) q_hat = x_hat[:, 39:] return ske_hat, q_hat, z_t[0], traj_2d # Evaluate all 8 prompts and compute latent space 2D PCA coordinates (matching MLD scripts/tsne.py) U_z, S_z, Vt_z = np.linalg.svd(Z0_norm - Z0_norm.mean(axis=0, keepdims=True), full_matrices=False) Z_2d = (Z0_norm @ Vt_z[:2].T).astype(np.float32) # (160, 2) generated_bank = {} for p in PROMPTS: cid = p["id"] ske_hat, q_hat, z_final, traj_2d = sample_mld_latent(cid, guidance_scale=7.5, ddim_steps=20, seed=42 + cid) # Also compute class latent centroid for high-precision CFG anchor in browser cls_z_mean = Z0_norm[clip_labels == cid].mean(axis=0) generated_bank[p["name"]] = { "id": cid, "name": p["name"], "text": p["text"], "keywords": p["keywords"], "latent_z": [round(float(v), 4) for v in z_final[:8]], "ddim_path_2d": [[round(pt[0], 3), round(pt[1], 3)] for pt in traj_2d], "skeleton_3d": np.round(ske_hat, 4).tolist(), # (40, 13, 3) "joint_pos_29": np.round(q_hat, 4).tolist() # (40, 29) } # Save compact NumPy weights + browser JSON bundle np.savez_compressed( "/tmp/village-world/public/mld/mld_trained_weights.npz", W_enc_mu=W_enc_mu, b_enc_mu=b_enc_mu, W_dec_lin=W_dec_lin, W_dec1=W_dec1, b_dec1=b_dec1, W_dec2=W_dec2, b_dec2=b_dec2, W_den1=W_den1, b_den1=b_den1, W_den2=W_den2, b_den2=b_den2, W_den3=W_den3, b_den3=b_den3, feat_mean=feat_mean, feat_std=feat_std, z_mean=z_mean, z_std=z_std, alphas_cumprod=alphas_cumprod ) latent_points = [] for i in range(N_CLIPS): cid = int(clip_labels[i]) latent_points.append({ "x": round(float(Z_2d[i, 0]), 3), "y": round(float(Z_2d[i, 1]), 3), "class_id": cid, "class_name": PROMPTS[cid]["name"] }) summary = { "paper": "Executing your Commands via Motion Diffusion in Latent Space (MLD, Chen et al., CVPR 2023)", "upstream_repo": "https://github.com/chenfengye/motion-latent-diffusion", "architecture": { "stage1_vae": f"MldVae: {D_IN}D motion sequence (40 frames x 68 features) <-> {D_LATENT}D Gaussian latent space (KL weight {LAMBDA_KL})", "stage2_denoiser": f"MldDenoiser: Conditional Latent Diffusion ({D_DEN_IN} -> {D_DEN_HID} -> {D_DEN_HID} -> {D_LATENT}) over {N_DIFF_STEPS} timesteps with Classifier-Free Guidance (s=7.5, p_uncond=0.12)", "speedup_vs_raw_mdm": "Latent diffusion operates on a [1, 32] latent token instead of raw [40, 68] frames (~85x fewer dimensions per denoising step)" }, "vae_training_curve": vae_history, "denoiser_training_curve": diff_history, "bone_pairs": BONE_PAIRS, "prompts": PROMPTS, "latent_manifold_points": latent_points, "generated_motions": generated_bank } with open("/tmp/village-world/public/mld/mld_model_bundle.json", "w") as f: json.dump(summary, f) print("\nSaved trained MLD weights to /tmp/village-world/public/mld/mld_trained_weights.npz and mld_model_bundle.json!")