MinPair / text_minpair.py
lschiweck's picture
MinPair model, inference code and model card
e58a265 verified
Raw History Blame Contribute Delete
9.53 kB
"""Text side of MinPair: part captions, one-sentence prompts and the two frozen text encoders.
A prompt is a plain dict:
{
"caption": "a person kicks with the left leg.", # global caption, optional (None = no caption)
"segments": [ # timed sentences on the eight tracks
{"track": "left_leg", "text": "The left leg lifts from the ground to hip height.", "start": 0.5, "end": 1.4},
...
],
"duration": 4.0, # seconds covered by the caption
"num_frames": None, # motion length in frames at 20 fps (default: int(duration * 20), at most 400)
"offset": 0.0, # time origin of the segment times (default 0)
"seed": 0, # noise seed; a caption and its edit with the same seed share the noise
}
Tracks: action, trajectory (the pelvis path, "path" is accepted as well), spine, head, left_arm, right_arm, left_leg,
right_leg. A track without a segment at some frame has no instruction there. The text "unknown" also means no
instruction.
"""
from __future__ import annotations
import copy
from typing import Dict, List, Optional, Sequence
import numpy as np
import torch
TRACKS = ("action", "trajectory", "spine", "head", "left_arm", "right_arm", "left_leg", "right_leg")
TRACK_ALIASES = {"path": "trajectory"}
MISSING = "unknown"
# ---------------------------------------------------------------------------------------------------------- prompts
def one_sentence(sentence: str, duration: float, seed: int = 0, num_frames: Optional[int] = None) -> dict:
"""A single sentence as the global caption and on all eight tracks for the whole clip (the paper's one-sentence
input for part-track models)."""
return {
"caption": sentence,
"segments": [{"track": t, "text": sentence, "start": 0.0, "end": float(duration)} for t in TRACKS],
"duration": float(duration),
"num_frames": num_frames,
"seed": seed,
}
def normalize_prompt(prompt: dict, fps: float, max_frames: int) -> dict:
"""Checks a prompt and fills in the defaults. Returns a new dict."""
p = copy.deepcopy(prompt)
if "duration" not in p:
raise ValueError("a prompt needs 'duration' (seconds covered by the caption)")
p.setdefault("caption", None)
p.setdefault("segments", [])
p.setdefault("offset", 0.0)
p.setdefault("seed", 0)
p["text_frames"] = int(p["duration"] * fps)
if p.get("num_frames") is None:
p["num_frames"] = p["text_frames"]
p["num_frames"] = int(p["num_frames"])
if not 1 <= p["num_frames"] <= max_frames:
raise ValueError(f"num_frames must be between 1 and {max_frames} (20 s at 20 fps), got {p['num_frames']}")
for s in p["segments"]:
s["track"] = TRACK_ALIASES.get(s["track"], s["track"])
if s["track"] not in TRACKS:
raise ValueError(f"unknown track '{s['track']}', expected one of {TRACKS}")
return p
def caption_present(prompt: dict) -> bool:
c = prompt.get("caption")
return bool(c) and c != MISSING
def track_runs(prompt: dict, fps: float) -> Dict[str, List[tuple]]:
"""Per track, the (text, number of frames) runs over the caption window.
Frame i has the time offset + i / fps and takes the first segment of its track (sorted by start time) with
start <= time < end; frames without a segment are "unknown"."""
n = prompt["text_frames"]
offset = prompt["offset"]
times = [offset + (i / fps) for i in range(n)]
by_track: Dict[str, list] = {}
for s in prompt["segments"]:
by_track.setdefault(s["track"], []).append(s)
runs = {}
for track, segs in by_track.items():
segs = sorted(segs, key=lambda s: s.get("start", 0))
labels = []
for t in times:
text = MISSING
for s in segs:
if s.get("start", 0) <= t < s.get("end", 0):
text = s.get("text", MISSING)
break
labels.append(text)
if not labels:
continue
out, cur, count = [], labels[0], 1
for label in labels[1:]:
if label == cur:
count += 1
else:
out.append((cur, count))
cur, count = label, 1
out.append((cur, count))
runs[track] = out
return runs
def frame_text_ids(runs: Dict[str, List[tuple]], length: int, texts: Dict[str, int], out: torch.Tensor) -> None:
"""Writes one sample's per-frame text indices into out [length, 8] (filled with -1 beforehand).
Runs are cut at `length`. If the motion is longer than the caption window, the last text of a track continues.
`texts` maps every distinct text of the batch to its index and is extended in place."""
for k, track in enumerate(TRACKS):
rs = runs.get(track, [])
f = 0
for label, n in rs:
e = min(f + int(n), length)
if e > f and label != MISSING:
out[f:e, k] = texts.setdefault(label, len(texts))
f = e
if f >= length:
break
if f < length and rs and rs[-1][0] != MISSING:
out[f:length, k] = texts.setdefault(rs[-1][0], len(texts))
# ---------------------------------------------------------------------------------------------------------- encoders
class CaptionEncoder:
"""Global caption -> 512-d OpenAI CLIP ViT-B/32 text embedding.
On a GPU the CLIP package runs the text tower in float16, as for the released results. On the CPU it runs in
float32, which changes the embedding slightly (about 1e-3)."""
def __init__(self, name: str, device):
try:
import clip
except ImportError as e: # pragma: no cover - message only
raise ImportError("the global caption needs OpenAI CLIP: pip install -r requirements.txt") from e
self.clip = clip
self.device = torch.device(device)
self.model, _ = clip.load(name, device=self.device)
self.model.eval()
@torch.no_grad()
def __call__(self, text: str) -> torch.Tensor:
tokens = self.clip.tokenize(text, truncate=True).to(self.device)
return self.model.encode_text(tokens).float() # [1, 512]
class WordEncoder:
"""Track sentences -> frozen T5-Large token features (float32 compute, stored as float16).
Texts are sorted by token count and encoded in padded chunks, the convention the model was trained with."""
def __init__(self, name: str, revision: str, device, batch_size: int = 256):
from transformers import AutoTokenizer, T5EncoderModel
self.device = torch.device(device)
self.batch_size = int(batch_size)
self.cache: Dict[str, np.ndarray] = {} # used only when a caller asks to reuse features across calls
self.tokenizer = AutoTokenizer.from_pretrained(name, revision=revision)
self.model = T5EncoderModel.from_pretrained(name, revision=revision, torch_dtype=torch.float32)
self.model = self.model.to(self.device).eval().requires_grad_(False)
@torch.no_grad()
def encode(self, texts: Sequence[str]) -> List[np.ndarray]:
"""One float16 array [tokens, 1024] per text, including the closing </s> token."""
texts = list(texts)
lengths = [len(ids) for ids in self.tokenizer(texts, add_special_tokens=True)["input_ids"]]
order = np.argsort(lengths, kind="stable")
out: List[np.ndarray] = [None] * len(texts) # type: ignore[list-item]
for s in range(0, len(order), self.batch_size):
idx = order[s:s + self.batch_size]
enc = self.tokenizer([texts[i] for i in idx], padding=True, truncation=False, add_special_tokens=True,
return_tensors="pt").to(self.device)
h = self.model(**enc).last_hidden_state.float().cpu().numpy()
for j, i in enumerate(idx):
out[i] = h[j, :lengths[i]].astype(np.float16)
return out
def batch(self, texts: Sequence[str], device, reuse: bool = False) -> tuple:
"""Distinct texts of a batch -> tokens float32 [N, L, 1024] (zero padded) and token mask bool [N, L].
No text gives the empty bank [0, 1, 1024] / [0, 1] that the denoiser accepts.
By default every call encodes its texts together. With reuse=True, texts encoded in an earlier call keep their
features and only new texts are encoded (faster for repeated sentences; the padding of the first encoding then
decides the last bits)."""
texts = list(texts)
n = len(texts)
if n == 0:
return (torch.zeros(0, 1, self.model.config.d_model, device=device),
torch.zeros(0, 1, dtype=torch.bool, device=device))
if reuse:
new = [t for t in texts if t not in self.cache]
if new:
self.cache.update(zip(new, self.encode(new)))
arrays = [self.cache[t] for t in texts]
else:
arrays = self.encode(texts)
feats = [torch.from_numpy(f).to(device) for f in arrays]
lens = torch.tensor([len(f) for f in feats], dtype=torch.long, device=device)
lmax = int(lens.max())
mask = torch.arange(lmax, device=device)[None] < lens[:, None]
tokens = torch.zeros(n, lmax, feats[0].shape[1], device=device, dtype=torch.float16)
for i, f in enumerate(feats):
tokens[i, :len(f)] = f
return tokens.float(), mask