Download anima_pose/control.py from AlexSinHF/Anima: direct link, hf CLI and curl.
- Browser
- Download file 9.39 kB
-
https://huggingface.co/spaces/AlexSinHF/Anima/resolve/main/anima_pose/control.py
- Command line
-
hf download hf://spaces/AlexSinHF/Anima/anima_pose/control.py
-
curl -L -o control.py https://huggingface.co/spaces/AlexSinHF/Anima/resolve/main/anima_pose/control.py
9.39 kB
| """Runtime for Claquasse/Anima-Control-Pose on DiffSynth's ``AnimaDiT``. | |
| Port of the two ComfyUI pieces the adapter ships with: | |
| * ``LoraLoaderModelOnly`` -- the ``lora.*`` keys (PEFT ``lora_A``/``lora_B``, rank 16, no | |
| alpha -> scale 1.0) on the DiT blocks and the LLM adapter. Applied here as reversible | |
| forward wrappers (``y = W x + B(A x)``) instead of merging into the bf16 weights, so a | |
| pose-free generation right after is bit-identical to the base model. | |
| * ``AnimaControlApply`` -- a zero-init ``ControlEmbedder`` (a patch-embed ``Linear`` on the | |
| 16-ch VAE latent of the skeleton) whose output is *added* to ``dit.x_embedder``'s output | |
| on every DiT call (cond and uncond). | |
| DiffSynth's ``AnimaDiT`` uses the same module names as ComfyUI's Cosmos DiT once the | |
| ``diffusion_model.`` prefix is stripped (``blocks.N.self_attn.q_proj``, ``x_embedder``, | |
| ``llm_adapter.blocks.N.self_attn.o_proj`` ...), so every key resolves via | |
| ``get_submodule``. Any key that does not resolve raises -- no silent no-op. | |
| Latent space: ComfyUI's ``VAEEncode`` (the path the author's node and workflows use) | |
| returns the *raw* Wan/Qwen-Image VAE mean, while DiffSynth's ``WanVideoVAE.encode`` returns | |
| ``(mu - mean) / std``. We undo that normalisation by default; set | |
| ``ANIMA_POSE_LATENT_NORMALIZED=1`` to feed DiffSynth's normalised latent instead. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| from typing import Optional | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from einops import rearrange | |
| from PIL import Image | |
| _PREFIX = "diffusion_model." | |
| _EMBEDDER_KEY = "control_embedder." | |
| LATENT_NORMALIZED = os.getenv("ANIMA_POSE_LATENT_NORMALIZED", "0") == "1" | |
| class ControlEmbedder(nn.Module): | |
| """Mirror of the adapter's ControlEmbedder (patch 2x2, temporal 1, no padding-mask ch).""" | |
| def __init__(self, in_channels=16, spatial_patch_size=2, temporal_patch_size=1, model_channels=2048): | |
| super().__init__() | |
| self.spatial_patch_size = spatial_patch_size | |
| self.temporal_patch_size = temporal_patch_size | |
| self.proj = nn.Linear(in_channels * spatial_patch_size * spatial_patch_size * temporal_patch_size, model_channels) | |
| def forward(self, control_B_C_T_H_W): | |
| x = rearrange( | |
| control_B_C_T_H_W, | |
| "b c (t r) (h m) (w n) -> b t h w (c r m n)", | |
| r=self.temporal_patch_size, m=self.spatial_patch_size, n=self.spatial_patch_size, | |
| ) | |
| return self.proj(x) | |
| class PoseAdapter: | |
| """Loaded adapter weights (kept on the DiT's device between calls).""" | |
| def __init__(self, path: str, device, dtype): | |
| from safetensors.torch import load_file | |
| sd = load_file(path) | |
| embed_sd = {k.split(_EMBEDDER_KEY, 1)[1]: v for k, v in sd.items() if _EMBEDDER_KEY in k} | |
| if not embed_sd: | |
| raise RuntimeError(f"No '{_EMBEDDER_KEY}*' keys in {path} -- not an Anima control-LoRA file.") | |
| in_features = embed_sd["proj.weight"].shape[1] | |
| model_channels = embed_sd["proj.weight"].shape[0] | |
| self.embedder = ControlEmbedder(in_channels=in_features // 4, model_channels=model_channels) | |
| self.embedder.load_state_dict(embed_sd, strict=True) | |
| self.embedder.to(device=device, dtype=torch.float32).eval().requires_grad_(False) | |
| pairs: dict[str, dict[str, torch.Tensor]] = {} | |
| for k, v in sd.items(): | |
| if _EMBEDDER_KEY in k: | |
| continue | |
| for part in ("lora_A", "lora_B"): | |
| tag = f".{part}.weight" | |
| if k.endswith(tag): | |
| module_path = k[: -len(tag)] | |
| if module_path.startswith(_PREFIX): | |
| module_path = module_path[len(_PREFIX):] | |
| pairs.setdefault(module_path, {})[part] = v.to(device=device, dtype=dtype) | |
| break | |
| else: | |
| if not k.endswith(".alpha"): | |
| raise RuntimeError(f"Unexpected key in pose adapter: {k}") | |
| alphas = {k[: -len(".alpha")].removeprefix(_PREFIX): float(v) for k, v in sd.items() if k.endswith(".alpha")} | |
| self.lora: list[tuple[str, torch.Tensor, torch.Tensor, float]] = [] | |
| for module_path, ab in sorted(pairs.items()): | |
| if "lora_A" not in ab or "lora_B" not in ab: | |
| raise RuntimeError(f"Incomplete LoRA pair for {module_path}") | |
| rank = ab["lora_A"].shape[0] | |
| scale = alphas.get(module_path, rank) / rank | |
| self.lora.append((module_path, ab["lora_A"], ab["lora_B"], scale)) | |
| class _LoRAWrap: | |
| def __init__(self, module: nn.Module, down: torch.Tensor, up: torch.Tensor, scale: float): | |
| self.module = module | |
| self.down = down | |
| self.up = up | |
| self.scale = scale | |
| self.active = True | |
| self.org_forward = None | |
| def apply(self): | |
| self.org_forward = self.module.forward | |
| self.module.forward = self.forward | |
| def restore(self): | |
| if self.org_forward is not None: | |
| self.module.forward = self.org_forward | |
| self.org_forward = None | |
| def forward(self, x, *args, **kwargs): | |
| y = self.org_forward(x, *args, **kwargs) | |
| if not self.active: | |
| return y | |
| delta = F.linear(F.linear(x.to(self.down.dtype), self.down), self.up) | |
| return y + (delta * self.scale).to(y.dtype) | |
| def encode_control_latent(pipe, skeleton: Image.Image, height: int, width: int) -> torch.Tensor: | |
| """Skeleton PIL -> (1, 16, 1, H/8, W/8) latent in the space the adapter expects.""" | |
| img = skeleton.convert("RGB") | |
| if img.size != (width, height): | |
| img = img.resize((width, height), Image.NEAREST) | |
| pipe.load_models_to_device(["vae"]) | |
| pixels = pipe.preprocess_image(img).to(device=pipe.device, dtype=pipe.torch_dtype) # (1,3,H,W) in [-1,1] | |
| z = pipe.vae.encode(pixels.unsqueeze(2), device=pipe.device) # normalised (1,16,1,h,w) | |
| if not LATENT_NORMALIZED: | |
| mean = pipe.vae.mean.to(device=z.device, dtype=z.dtype).view(1, -1, 1, 1, 1) | |
| std = pipe.vae.std.to(device=z.device, dtype=z.dtype).view(1, -1, 1, 1, 1) | |
| z = z * std + mean | |
| return z | |
| class PoseControlSession: | |
| """Context manager: attach the pose adapter to ``pipe.dit`` for one generation. | |
| ``set_active(bool)`` gates the control tokens *and* the adapter LoRA per denoising | |
| step (start/end window). Outside the window the DiT is exactly the base model, so the | |
| late (detail/style) steps are not pulled toward the adapter's training-set look. | |
| (ComfyUI keeps the LoRA on for the whole call; with end=1.0 this is identical.) | |
| """ | |
| def __init__(self, pipe, adapter: PoseAdapter, control_latent: torch.Tensor, strength: float): | |
| self.pipe = pipe | |
| self.adapter = adapter | |
| self.control_latent = control_latent | |
| self.strength = float(strength) | |
| self.active = True | |
| self._wraps: list[_LoRAWrap] = [] | |
| self._hook = None | |
| self._tokens: Optional[torch.Tensor] = None | |
| def set_active(self, active: bool): | |
| self.active = bool(active) | |
| for wrap in self._wraps: | |
| wrap.active = self.active | |
| def __enter__(self): | |
| dit = self.pipe.dit | |
| try: | |
| for module_path, down, up, scale in self.adapter.lora: | |
| try: | |
| module = dit.get_submodule(module_path) | |
| except AttributeError as exc: | |
| raise RuntimeError(f"Pose LoRA target '{module_path}' not found in AnimaDiT") from exc | |
| # Strength < 1 also fades the adapter LoRA (it is what pulls style/character toward | |
| # the adapter's training set), so strength 0 is exactly the base model and lowering | |
| # strength trades pose accuracy for keeping the prompt's character. Above 1 only the | |
| # control tokens grow, as in ComfyUI. | |
| wrap = _LoRAWrap(module, down, up, scale * min(1.0, self.strength)) | |
| wrap.apply() | |
| self._wraps.append(wrap) | |
| p = next(dit.parameters()) | |
| with torch.no_grad(): | |
| tokens = self.adapter.embedder(self.control_latent.to(device=p.device, dtype=torch.float32)) | |
| self._tokens = (tokens * self.strength).to(dtype=p.dtype) | |
| def add_control(_module, _inputs, output): | |
| if not self.active or self.strength == 0.0: | |
| return output | |
| tokens = self._tokens | |
| if tokens.shape[1:] != output.shape[1:]: | |
| raise RuntimeError( | |
| f"Pose control tokens {tuple(tokens.shape)} do not match patch embeddings " | |
| f"{tuple(output.shape)} -- control latent was encoded at a different size." | |
| ) | |
| return output + tokens.to(device=output.device, dtype=output.dtype) | |
| self._hook = dit.x_embedder.register_forward_hook(add_control) | |
| except Exception: | |
| self._restore() | |
| raise | |
| return self | |
| def _restore(self): | |
| if self._hook is not None: | |
| self._hook.remove() | |
| self._hook = None | |
| for wrap in reversed(self._wraps): | |
| wrap.restore() | |
| self._wraps.clear() | |
| self._tokens = None | |
| def __exit__(self, exc_type, exc, tb): | |
| self._restore() | |
| return False | |