MinPair / modeling_minpair.py
lschiweck's picture
MinPair model, inference code and model card
e58a265 verified
Raw History Blame Contribute Delete
20.3 kB
"""MinPair: part-track diffusion denoiser and sampler for text-to-motion generation.
Load with
from transformers import AutoModel
model = AutoModel.from_pretrained("<repo or local folder>", trust_remote_code=True).to("cuda")
motions = model.generate_motion([prompt, ...])
The denoiser is a Transformer over motion frames. Two extra tokens carry the diffusion step and the global caption
(frozen CLIP). In each of its four blocks, every frame reads the sentence that is active at this frame on each of the
eight caption tracks (frozen T5-Large tokens) through cross-attention. The sampler is a 100-step DDPM with a cosine
schedule and clean-motion prediction, without classifier-free guidance.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Sequence, Union
import numpy as np
import torch
from torch import Tensor, nn
from transformers import PreTrainedModel
from .configuration_minpair import MinPairConfig
from .motion_minpair import Motion, SMPLHBody
from .text_minpair import (TRACKS, CaptionEncoder, WordEncoder, caption_present, frame_text_ids, normalize_prompt,
one_sentence, track_runs)
# ---------------------------------------------------------------------------------------------------------- denoiser
def sinusoidal_embedding(positions: Tensor, width: int) -> Tensor:
"""Transformer sin/cos features of integer positions (float32)."""
frequencies = torch.exp(torch.arange(0, width, 2, device=positions.device).float() * (-math.log(10000.0) / width))
angles = positions.float()[..., None] * frequencies
out = torch.empty(*positions.shape, width, device=positions.device)
out[..., 0::2] = angles.sin()
out[..., 1::2] = angles.cos()
return out
@dataclass(frozen=True)
class RoutingChunk:
"""Frames that read the same text on the same track, grouped so that each text's keys are stored once."""
samples: Tensor # [G]
tracks: Tensor # [G]
text_ids: Tensor # [G]
frames: Tensor # [G, Qmax]
valid: Tensor # [G, Qmax]
destinations: Tensor # [G, Qmax], flat index into [B, T, 8]
def build_routing_chunks(frame_ids: Tensor, frame_mask: Tensor, chunk_size: int) -> List[RoutingChunk]:
ids = torch.where(frame_mask[..., None], frame_ids, -1).detach().cpu()
groups = []
for b in range(ids.shape[0]):
for k in range(len(TRACKS)):
for text_id in torch.unique(ids[b, :, k]).tolist():
if text_id >= 0:
groups.append((b, k, text_id, torch.where(ids[b, :, k] == text_id)[0]))
groups.sort(key=lambda g: len(g[3])) # similar group sizes need less padding
chunks = []
device, t = frame_ids.device, frame_ids.shape[1]
for offset in range(0, len(groups), chunk_size):
subset = groups[offset:offset + chunk_size]
n, qmax = len(subset), max(len(g[3]) for g in subset)
frames = torch.zeros(n, qmax, dtype=torch.long)
valid = torch.zeros(n, qmax, dtype=torch.bool)
samples, tracks, text_ids = [], [], []
for i, (b, k, text_id, ts) in enumerate(subset):
frames[i, :len(ts)] = ts
valid[i, :len(ts)] = True
samples.append(b)
tracks.append(k)
text_ids.append(text_id)
samples, tracks, text_ids = [torch.tensor(x, dtype=torch.long) for x in (samples, tracks, text_ids)]
destinations = (samples[:, None] * t + frames) * 8 + tracks[:, None]
chunks.append(RoutingChunk(*(a.to(device) for a in (samples, tracks, text_ids, frames, valid, destinations))))
return chunks
class TrackReader(nn.Module):
"""Each frame reads its active sentence on each of the eight tracks; an MLP fuses the eight reads."""
def __init__(self, width: int, attention_dim: int, readout_dim: int, num_heads: int, dropout: float):
super().__init__()
self.motion_norm = nn.LayerNorm(width)
self.query = nn.Linear(width, attention_dim)
self.track_embedding = nn.Parameter(torch.randn(8, attention_dim) * 0.02)
self.attention = nn.MultiheadAttention(attention_dim, num_heads, dropout=dropout, batch_first=True)
self.readout = nn.Linear(attention_dim, readout_dim)
self.missing = nn.Parameter(torch.randn(8, readout_dim) * 0.02)
self.fuse = nn.Sequential(nn.Linear(8 * readout_dim + 8, width), nn.GELU(), nn.Linear(width, width))
self.dropout = nn.Dropout(dropout)
def forward(self, motion: Tensor, words: Tensor, word_mask: Tensor, frame_ids: Tensor,
chunks: List[RoutingChunk]) -> Tensor:
b, t, _ = motion.shape
queries = self.query(self.motion_norm(motion))
contexts = self.missing.to(queries.dtype)[None, None].expand(b, t, -1, -1).reshape(b * t * 8, -1)
destinations, values = [], []
for chunk in chunks:
q = queries[chunk.samples[:, None], chunk.frames]
q = q + self.track_embedding[chunk.tracks, None].to(q.dtype)
kv = words[chunk.text_ids]
result, _ = self.attention(q, kv, kv, key_padding_mask=~word_mask[chunk.text_ids], need_weights=False)
values.append(self.readout(result)[chunk.valid])
destinations.append(chunk.destinations[chunk.valid])
if destinations:
contexts = contexts.index_copy(0, torch.cat(destinations), torch.cat(values).to(contexts.dtype))
contexts = contexts.reshape(b, t, -1)
present = (frame_ids >= 0).to(contexts.dtype)
return self.dropout(self.fuse(torch.cat((contexts, present), dim=-1)))
class PartTrackDenoiser(nn.Module):
"""Predicts the clean (normalized) motion from a noisy one, the diffusion step and the part caption."""
def __init__(self, config: MinPairConfig):
super().__init__()
d, a = config.latent_dim, config.text_attention_dim
self.motion_dim, self.latent_dim = config.motion_dim, d
self.max_frames, self.route_chunk_size = config.max_frames, config.route_chunk_size
self.motion_embedding = nn.Linear(config.motion_dim, d)
self.caption_embedding = nn.Sequential(nn.Linear(config.caption_dim, 2 * d), nn.GELU(), nn.Linear(2 * d, d),
nn.LayerNorm(d))
self.missing_caption = nn.Parameter(torch.randn(d) * 0.02)
self.timestep_embedding = nn.Sequential(nn.Linear(d, d), nn.SiLU(), nn.Linear(d, d))
self.position_dropout = nn.Dropout(config.dropout)
self.word_adapter = nn.Sequential(nn.LayerNorm(config.word_dim), nn.Linear(config.word_dim, a), nn.GELU(),
nn.Linear(a, a))
self.temporal_layers = nn.ModuleList([
nn.TransformerEncoderLayer(d, config.num_heads, config.ff_size, config.dropout, activation="gelu",
batch_first=True, norm_first=True)
for _ in range(config.num_layers)])
self.text_readers = nn.ModuleList([
TrackReader(d, a, config.readout_dim, config.num_heads, config.dropout) for _ in range(config.num_layers)])
self.output = nn.Linear(d, config.motion_dim)
def forward(self, x: Tensor, valid: Tensor, t: Tensor, caption: Tensor, caption_present: Tensor, tokens: Tensor,
token_mask: Tensor, frame_ids: Tensor) -> Tensor:
"""
x [B, T, 205] normalized noisy motion
valid bool [B, T], True for frames of the motion
t long [B], diffusion step
caption [B, 512] normalized CLIP embedding of the global caption
caption_present bool [B]
tokens [N, L, 1024] T5 token features of the N distinct sentences of the batch
token_mask bool [N, L]
frame_ids long [B, T, 8], index into the N sentences per frame and track, -1 = no sentence
"""
b, frames, _ = x.shape
if frames > self.max_frames:
raise ValueError(f"at most {self.max_frames} frames")
motion = torch.where(valid[..., None], x, 0.0)
h = self.motion_embedding(motion)
step = self.timestep_embedding(sinusoidal_embedding(t, self.latent_dim).to(
self.timestep_embedding[0].weight.dtype)).to(h.dtype)
cap = torch.where(caption_present[:, None], caption, 0.0)
cap = self.caption_embedding(cap)
cap = torch.where(caption_present[:, None], cap, self.missing_caption.to(cap.dtype)).to(h.dtype)
s = torch.cat((step[:, None], cap[:, None], h), dim=1)
position = sinusoidal_embedding(torch.arange(frames + 2, device=x.device), self.latent_dim)
s = self.position_dropout(s + position.to(s.dtype))
combined_mask = torch.cat((torch.ones(b, 2, dtype=torch.bool, device=x.device), valid), 1)
ids = torch.where(valid[..., None], frame_ids, -1)
words = self.word_adapter(torch.where(token_mask[..., None], tokens, 0.0))
chunks = build_routing_chunks(ids, valid, self.route_chunk_size)
for temporal, reader in zip(self.temporal_layers, self.text_readers):
s = temporal(s, src_key_padding_mask=~combined_mask)
h = s[:, 2:] + reader(s[:, 2:], words, token_mask, ids, chunks)
h = torch.where(valid[..., None], h, 0.0)
s = torch.cat((s[:, :2], h), dim=1)
return torch.where(valid[..., None], self.output(s[:, 2:]), 0.0)
# ---------------------------------------------------------------------------------------------------------- sampling
def cosine_posterior(steps: int, s: float) -> Dict[str, Tensor]:
"""DDPM posterior coefficients of the cosine schedule (float64, cast to the motion dtype at use)."""
x = torch.linspace(0, steps, steps + 1, dtype=torch.float64)
alphas_cumprod = torch.cos(((x / steps) + s) / (1 + s) * torch.pi * 0.5) ** 2
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
betas = torch.clip(1 - (alphas_cumprod[1:] / alphas_cumprod[:-1]), 0, 0.999)
alphas = 1.0 - betas
alphas_cumprod = torch.cumprod(alphas, axis=0)
one_minus = 1.0 - alphas_cumprod
prev = torch.cat([torch.ones(1), alphas_cumprod[:-1]])
return {
"variance": betas * (1.0 - prev) / one_minus,
"coef_x0": betas * torch.sqrt(prev) / one_minus,
"coef_xt": (1.0 - prev) * torch.sqrt(alphas) / one_minus,
}
class PerSampleNoise:
"""Noise of each motion from its own generator, seeded with the prompt's seed.
A caption and its edit with the same seed therefore receive the same noise, whatever else is in the batch. Each
call returns the next [B, T, width] draw (once at the start, then once per diffusion step); padding frames are 0."""
def __init__(self, seeds: Sequence[int], lengths: Sequence[int], width: int, device):
self.lengths = [int(n) for n in lengths]
self.width = int(width)
self.device = torch.device(device)
self.generators = [torch.Generator(device=self.device).manual_seed(int(s)) for s in seeds]
def __call__(self) -> Tensor:
z = torch.zeros((len(self.lengths), max(self.lengths), self.width), device=self.device)
for i, (n, g) in enumerate(zip(self.lengths, self.generators)):
z[i, :n] = torch.randn((n, self.width), generator=g, device=self.device)
return z
NoiseFactory = Callable[[Sequence[int], Sequence[int], int, torch.device], Callable[[], Tensor]]
# ---------------------------------------------------------------------------------------------------------- model
class MinPairPreTrainedModel(PreTrainedModel):
config_class = MinPairConfig
base_model_prefix = "minpair"
main_input_name = "x"
def _init_weights(self, module):
# All weights come from the checkpoint; nothing to initialise.
pass
class MinPairModel(MinPairPreTrainedModel):
"""MinPair text-to-motion model: denoiser weights, motion normalization and the sampler."""
def __init__(self, config: MinPairConfig):
super().__init__(config)
self.denoiser = PartTrackDenoiser(config)
self.register_buffer("motion_mean", torch.zeros(config.motion_dim))
self.register_buffer("motion_std", torch.ones(config.motion_dim))
self.register_buffer("caption_mean", torch.zeros(config.caption_dim))
self.register_buffer("caption_std", torch.ones(config.caption_dim))
self._encoders: Dict[str, object] = {} # frozen text encoders, created on first use, never saved
self.post_init()
# -------------------------------------------------------------------- normalization
def normalize_motion(self, x: Tensor) -> Tensor:
return (x - self.motion_mean) / (self.motion_std + self.config.normalizer_eps)
def denormalize_motion(self, x: Tensor) -> Tensor:
return x * (self.motion_std + self.config.normalizer_eps) + self.motion_mean
def normalize_caption(self, c: Tensor) -> Tensor:
return (c - self.caption_mean) / (self.caption_std + self.config.normalizer_eps)
# -------------------------------------------------------------------- text encoders
def caption_encoder(self) -> CaptionEncoder:
if "caption" not in self._encoders:
self._encoders["caption"] = CaptionEncoder(self.config.caption_encoder, self.device)
return self._encoders["caption"]
def word_encoder(self) -> WordEncoder:
if "word" not in self._encoders:
self._encoders["word"] = WordEncoder(self.config.word_encoder, self.config.word_encoder_revision,
self.device, self.config.word_encoder_batch_size)
return self._encoders["word"]
@torch.no_grad()
def encode_caption(self, text: str) -> Tensor:
"""CLIP embedding [512] of a global caption (before normalization)."""
return self.caption_encoder()(text)[0]
# -------------------------------------------------------------------- helpers
@staticmethod
def one_sentence(sentence: str, duration: float, seed: int = 0, num_frames: Optional[int] = None) -> dict:
"""Prompt with one sentence as the global caption and on all eight tracks (the paper's one-sentence input)."""
return one_sentence(sentence, duration, seed=seed, num_frames=num_frames)
@staticmethod
def smplh_body(model_path, gender: str = "male", device="cpu") -> SMPLHBody:
"""SMPL-H forward kinematics and mesh for generated motions (needs your own SMPL-H model files)."""
return SMPLHBody(model_path, gender=gender, device=device)
# -------------------------------------------------------------------- generation
def forward(self, *args, **kwargs):
return self.denoiser(*args, **kwargs)
@torch.no_grad()
def generate_motion(
self,
prompts: Union[dict, Sequence[dict]],
batch_frames: int = 32000,
caption_vectors: Optional[Dict[str, np.ndarray]] = None,
noise_factory: Optional[NoiseFactory] = None,
reuse_text_features: bool = False,
progress: bool = False,
) -> Union[Motion, List[Motion]]:
"""Generates one motion per prompt (format in text_minpair.py).
batch_frames motions are sorted by length and batched so that batch size x longest motion <= batch_frames
caption_vectors optional {caption text: CLIP vector [512]} used instead of encoding these captions
noise_factory optional replacement of PerSampleNoise, called as noise_factory(seeds, lengths, width, device)
reuse_text_features keep the T5 features of sentences across calls and encode only new sentences
Returns a Motion (one prompt) or a list of Motions in prompt order."""
previous = torch.get_float32_matmul_precision()
torch.set_float32_matmul_precision(self.config.matmul_precision)
try:
return self._generate(prompts, batch_frames, caption_vectors, noise_factory, reuse_text_features, progress)
finally:
torch.set_float32_matmul_precision(previous)
def _generate(self, prompts, batch_frames, caption_vectors, noise_factory, reuse_text_features, progress):
single = isinstance(prompts, dict)
plist = [prompts] if single else list(prompts)
cfg = self.config
items = [normalize_prompt(p, cfg.fps, cfg.max_frames) for p in plist]
order = sorted(range(len(items)), key=lambda i: items[i]["num_frames"])
batches, cur = [], []
for i in order:
if cur and (len(cur) + 1) * items[i]["num_frames"] > batch_frames:
batches.append(cur)
cur = []
cur.append(i)
if cur:
batches.append(cur)
out: List[Optional[Motion]] = [None] * len(items)
for bi, idx in enumerate(batches):
feats = self._sample_batch([items[i] for i in idx], caption_vectors or {}, noise_factory, reuse_text_features)
for i, f in zip(idx, feats):
out[i] = Motion.from_features(f, fps=cfg.fps, first_angle=cfg.first_angle, id=items[i].get("id"))
if progress:
print(f"[minpair] batch {bi + 1}/{len(batches)} ({len(idx)} motions)", flush=True)
return out[0] if single else out
def _condition(self, items: List[dict], caption_vectors: Dict[str, np.ndarray], reuse: bool = False):
cfg, dev = self.config, self.device
lengths = [it["num_frames"] for it in items]
b, t = len(items), max(lengths)
valid = torch.arange(t)[None] < torch.tensor(lengths)[:, None]
frame_ids = torch.full((b, t, len(TRACKS)), -1, dtype=torch.long)
texts: Dict[str, int] = {}
for i, it in enumerate(items):
frame_text_ids(track_runs(it, cfg.fps), it["num_frames"], texts, frame_ids[i])
tokens, token_mask = self.word_encoder().batch(list(texts), dev, reuse=reuse)
present = torch.tensor([caption_present(it) for it in items], dtype=torch.bool, device=dev)
caps = torch.zeros(b, cfg.caption_dim, device=dev)
for i, it in enumerate(items):
text = it.get("caption")
if text:
vec = caption_vectors.get(text)
vec = torch.as_tensor(np.asarray(vec, dtype=np.float32)).reshape(-1) if vec is not None \
else self.caption_encoder()(text)[0]
caps[i] = vec.to(dev)
caps = self.normalize_caption(caps)
return {"valid": valid.to(dev), "caption": caps, "caption_present": present, "tokens": tokens,
"token_mask": token_mask, "frame_ids": frame_ids.to(dev)}
def _sample_batch(self, items: List[dict], caption_vectors, noise_factory, reuse=False) -> List[np.ndarray]:
cfg, dev = self.config, self.device
self.eval()
cond = self._condition(items, caption_vectors, reuse)
lengths = [it["num_frames"] for it in items]
seeds = [int(it["seed"]) for it in items]
noise = (noise_factory or PerSampleNoise)(seeds, lengths, cfg.noise_width, dev)
valid = cond["valid"]
md = cfg.motion_dim
coef = cosine_posterior(cfg.diffusion_steps, cfg.cosine_s)
def masked(x):
x[~valid] = 0.0
return x
def at(name, step, like):
return coef[name][torch.full((len(items),), step, dtype=torch.long)].reshape(-1, 1, 1).to(like)
xt = masked(noise())[..., :md]
x0 = None
for step in range(cfg.diffusion_steps - 1, -1, -1):
t = torch.full((len(items),), step, device=dev, dtype=torch.long)
x0 = self.denoiser(xt, valid, t, cond["caption"], cond["caption_present"], cond["tokens"],
cond["token_mask"], cond["frame_ids"])
mean = at("coef_x0", step, xt) * x0 + at("coef_xt", step, xt) * xt
var = at("variance", step, xt)
z = noise()[..., :md]
if step > 0:
xt = masked(mean + var.clamp(min=0).sqrt() * 1.0 * z)
else:
xt = masked(mean)
motion = self.denormalize_motion(x0).float().cpu().numpy()
return [motion[i, :n].astype(np.float32) for i, n in enumerate(lengths)]