Download code/anim_model.py from ihor-umanets/pixelsprite-animgpt: direct link, hf CLI and curl.
- Browser
- Download file 7.09 kB
-
https://huggingface.co/ihor-umanets/pixelsprite-animgpt/resolve/main/code/anim_model.py
- Command line
-
hf download hf://ihor-umanets/pixelsprite-animgpt/code/anim_model.py
-
curl -L -o anim_model.py https://huggingface.co/ihor-umanets/pixelsprite-animgpt/resolve/main/code/anim_model.py
7.09 kB
| """AnimGPT: the pixelsprite v2 canvas transformer taught to draw a character's next frame / another view. | |
| Sequence (one size S per example, S in 16 / 24 / 32): | |
| [text (null), size, S unknown-mask rows] v2 prefix, unchanged | |
| [condition] kind + action + azimuth + elevation + frame + n_frames | |
| + reference type (0: the original v2 sprite, 1: front render) | |
| [reference canvas: S*S tokens] the character: its original sprite (what v2 draws) or the | |
| pixelated front view (azimuth 0, eye level) | |
| [previous canvas: S*S tokens] frame k-1 of this action and direction (k = 0: the static view | |
| in that direction; view targets: the front view again) | |
| [target pixels: S*S tokens, shifted by one like v2] the frame to draw | |
| Reference / previous tokens carry the colour of their own pixel (not shifted) and a segment embedding; target | |
| tokens are v2 pixel tokens (previous pixel's colour + row / column) plus their segment embedding. Weights of v2 are | |
| loaded into the shared parts (transformer, colour / position embeddings, head); the new embeddings start small. | |
| """ | |
| from __future__ import annotations | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from pixelsprite_model import EDGE_UNKNOWN, CanvasConfig, CanvasGPT2 | |
| ACTIONS = ["view", "idle", "walk", "run", "jump", "crouch", "crouch_walk", "roll", "punch", "kick", "spin_kick", "slash", | |
| "cast", "block", "hurt", "death", "cheer", "wave", "fly", "glide"] | |
| KINDS = ["human", "quadruped", "bird"] | |
| AZIMUTHS = [0, 45, 90, 135, 180, 225, 270, 315] | |
| ELEVATIONS = [0, 20] | |
| MAX_FRAMES = 16 | |
| class AnimGPT(CanvasGPT2): | |
| def __init__(self, cfg: CanvasConfig): | |
| super().__init__(cfg) | |
| d = cfg.d_model | |
| self.act_emb = nn.Embedding(32, d) | |
| self.kind_emb = nn.Embedding(4, d) | |
| self.az_emb = nn.Embedding(len(AZIMUTHS), d) | |
| self.el_emb = nn.Embedding(len(ELEVATIONS), d) | |
| self.frame_emb = nn.Embedding(MAX_FRAMES, d) | |
| self.nfr_emb = nn.Embedding(MAX_FRAMES + 1, d) | |
| self.refk_emb = nn.Embedding(2, d) | |
| self.seg = nn.Embedding(4, d) # 0 condition, 1 reference, 2 previous, 3 target | |
| for e in (self.act_emb, self.kind_emb, self.az_emb, self.el_emb, self.frame_emb, self.nfr_emb, self.refk_emb, self.seg): | |
| nn.init.normal_(e.weight, std=0.02) | |
| # ---- pieces of the sequence | |
| def cond_token(self, c: dict) -> torch.Tensor: | |
| """c: dict of (B,) long tensors kind, action, az, el, frame, nfr, refk -> (B, 1, d)""" | |
| x = (self.kind_emb(c["kind"]) + self.refk_emb(c["refk"]) + self.act_emb(c["action"]) + self.az_emb(c["az"]) + self.el_emb(c["el"]) | |
| + self.frame_emb(c["frame"].clamp(max=MAX_FRAMES - 1)) + self.nfr_emb(c["nfr"].clamp(max=MAX_FRAMES)) | |
| + self.seg.weight[0]) | |
| return x[:, None] | |
| def _pos(self, size: int, device): | |
| p = torch.arange(size * size, device=device) | |
| return p // size, p % size | |
| def canvas_tokens(self, idx: torch.Tensor, size: int, seg: int) -> torch.Tensor: | |
| """idx (B, S*S) token ids of a whole canvas (EMPTY = K) -> (B, S*S, d)""" | |
| r, c = self._pos(size, idx.device) | |
| e = torch.full_like(idx, EDGE_UNKNOWN) | |
| return self.tokens(idx, r[None].expand_as(idx), c[None].expand_as(idx), e) + self.seg.weight[seg] | |
| def target_tokens(self, prev: torch.Tensor, rows, cols, size: int) -> torch.Tensor: | |
| e = torch.full_like(prev, EDGE_UNKNOWN) | |
| return self.tokens(prev, rows, cols, e) + self.seg.weight[3] | |
| def context(self, size: int, c: dict, ref: torch.Tensor, prv: torch.Tensor) -> torch.Tensor: | |
| """everything before the target pixels: (B, 2 + S + 1 + 2*S*S, d)""" | |
| b = ref.shape[0] | |
| cond = self.cond(None, batch=b) | |
| mask = torch.zeros((b, size, size), dtype=torch.bool, device=ref.device) | |
| known = torch.zeros(b, dtype=torch.bool, device=ref.device) | |
| return torch.cat([self.prefix(cond, size, mask, known), self.cond_token(c), self.canvas_tokens(ref, size, 1), | |
| self.canvas_tokens(prv, size, 2)], 1) | |
| def forward_train(self, size: int, c: dict, ref: torch.Tensor, prv: torch.Tensor, tgt: torch.Tensor) -> torch.Tensor: | |
| """teacher forcing; tgt (B, S*S) token ids -> per-example NLL summed over the target pixels (nats)""" | |
| b = tgt.shape[0] | |
| r, col = self._pos(size, tgt.device) | |
| shifted = torch.cat([torch.full((b, 1), self.BOS, dtype=tgt.dtype, device=tgt.device), tgt[:, :-1]], 1) | |
| x = torch.cat([self.context(size, c, ref, prv), | |
| self.target_tokens(shifted, r[None].expand_as(tgt), col[None].expand_as(tgt), size)], 1) | |
| for blk in self.blocks: | |
| x = blk(x) | |
| logits = self.head(self.ln(x[:, -size * size:])).float() | |
| nll = F.cross_entropy(logits.reshape(-1, logits.shape[-1]), tgt.reshape(-1), reduction="none") | |
| return nll.view(b, -1).sum(1) | |
| def sample(self, size: int, c: dict, ref: torch.Tensor, prv: torch.Tensor, temperature: float = 1.0, | |
| allowed: torch.Tensor | None = None, gen: torch.Generator | None = None) -> torch.Tensor: | |
| """draw target canvases (B, S*S) pixel by pixel with a KV cache; allowed (B, K+1) bool restricts the colours | |
| (e.g. to the reference's palette + EMPTY)""" | |
| b, n = ref.shape[0], size * size | |
| ctx = self.context(size, c, ref, prv) | |
| cache = self.new_cache(b, ctx.shape[1] + n, ref.device, torch.bfloat16 if ref.is_cuda else torch.float32) | |
| r, col = self._pos(size, ref.device) | |
| tok = torch.full((b, 1), self.BOS, dtype=torch.long, device=ref.device) | |
| x = torch.cat([ctx, self.target_tokens(tok, r[None, :1].expand(b, 1), col[None, :1].expand(b, 1), size)], 1) | |
| logits = self.step(x, cache, 0) | |
| pos = x.shape[1] | |
| out = torch.empty((b, n), dtype=torch.long, device=ref.device) | |
| for t in range(n): | |
| lg = logits.float() / temperature | |
| if allowed is not None: | |
| lg = lg.masked_fill(~allowed, float("-inf")) | |
| nxt = torch.multinomial(torch.softmax(lg, -1), 1, generator=gen)[:, 0] | |
| out[:, t] = nxt | |
| if t + 1 == n: | |
| break | |
| x = self.target_tokens(nxt[:, None], r[None, t + 1:t + 2].expand(b, 1), col[None, t + 1:t + 2].expand(b, 1), size) | |
| logits = self.step(x, cache, pos) | |
| pos += 1 | |
| return out | |
| def load_v2(model: AnimGPT, state: dict) -> tuple[list, list]: | |
| """copy the v2 weights into the shared parts; returns (missing, unexpected) keys""" | |
| res = model.load_state_dict(state, strict=False) | |
| return list(res.missing_keys), list(res.unexpected_keys) | |