FrameXlabs commited on
Commit
f3b08bd
·
verified ·
1 Parent(s): 573a02d

Add trout/sampler.py

Browse files
Files changed (1) hide show
  1. trout/sampler.py +198 -0
trout/sampler.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trout sampler: parallel confidence-ordered unmasking of the full 256-token canvas.
2
+
3
+ Per step:
4
+ 1. one batched forward pass (conditional + unconditional when CFG is on)
5
+ 2. guided logits l = l_u + w * (l_c - l_u)
6
+ 3. sample a colour for every masked pixel
7
+ 4. keep the most confident ones so that the number still masked follows a cosine
8
+ schedule; Gumbel noise anneals the choice (MaskGIT-style) and spatial
9
+ non-maximum suppression stops two *uncertain* neighbouring pixels from being
10
+ committed in the same step
11
+ 5. feed the full predicted distribution back as self-conditioning
12
+ Optional "polish" steps re-mask the least confident committed pixels and re-predict.
13
+ Inpainting: pass `init_tokens` and `keep_mask`; kept pixels are never changed.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Iterator, Optional
21
+
22
+ import torch
23
+ import torch.nn.functional as F
24
+
25
+
26
+ def filter_logits(logits: torch.Tensor, top_k: int = 0, top_p: float = 1.0, min_p: float = 0.0) -> torch.Tensor:
27
+ if top_k and 0 < top_k < logits.shape[-1]:
28
+ kth = torch.topk(logits, top_k, dim=-1).values[..., -1:]
29
+ logits = logits.masked_fill(logits < kth, -math.inf)
30
+ if min_p and min_p > 0:
31
+ p = logits.softmax(-1)
32
+ logits = logits.masked_fill(p < min_p * p.amax(-1, keepdim=True), -math.inf)
33
+ if top_p is not None and top_p < 1.0:
34
+ sorted_l, idx = torch.sort(logits, dim=-1, descending=True)
35
+ sp = sorted_l.softmax(-1)
36
+ remove = (sp.cumsum(-1) - sp) > top_p
37
+ sorted_l = sorted_l.masked_fill(remove, -math.inf)
38
+ logits = torch.full_like(logits, -math.inf).scatter(-1, idx, sorted_l)
39
+ return logits
40
+
41
+
42
+ def cfg_weight(scale: float, schedule: str, frac: float) -> float:
43
+ if schedule == "constant":
44
+ return scale
45
+ if schedule == "linear":
46
+ return 1.0 + (scale - 1.0) * frac
47
+ if schedule == "cosine":
48
+ return 1.0 + (scale - 1.0) * (1 - math.cos(math.pi * frac)) / 2
49
+ raise ValueError(f"unknown cfg schedule {schedule!r}")
50
+
51
+
52
+ def _gumbel(shape, device, generator):
53
+ u = torch.rand(shape, device=device, generator=generator).clamp_(1e-10, 1 - 1e-10)
54
+ return -torch.log(-torch.log(u))
55
+
56
+
57
+ def _nms_eligible(score: torch.Tensor, masked: torch.Tensor, certain: torch.Tensor, grid: int) -> torch.Tensor:
58
+ B, N = score.shape
59
+ cand = masked & ~certain
60
+ s = torch.where(cand, score, torch.full_like(score, -math.inf)).view(B, 1, grid, grid)
61
+ local_max = F.max_pool2d(s, 3, stride=1, padding=1).view(B, N)
62
+ return certain | (cand & (score >= local_max))
63
+
64
+
65
+ @dataclass
66
+ class SampleStep:
67
+ """State after one decoding step (tensors (B, N) on the sampling device)."""
68
+ index: int
69
+ total: int
70
+ phase: str # "decode" or "polish"
71
+ tokens: torch.Tensor # current canvas; still-masked pixels hold the mask id
72
+ preview: torch.Tensor # the model's current best guess for every pixel
73
+ confidence: torch.Tensor
74
+ committed: torch.Tensor
75
+
76
+
77
+ @torch.no_grad()
78
+ def sample(model, text_states: torch.Tensor, text_pooled: torch.Tensor, steps: int = 16,
79
+ return_history: bool = False, **kwargs):
80
+ """Generate palette-token canvases. Returns tokens (B, N) [and the per-step history]."""
81
+ x, history = None, []
82
+ for st in sample_iter(model, text_states, text_pooled, steps=steps, **kwargs):
83
+ x = st.tokens
84
+ if return_history:
85
+ history.append(x.clone())
86
+ if x is None:
87
+ x = _initial_canvas(model.cfg, text_pooled, kwargs.get("init_tokens"), kwargs.get("keep_mask"))
88
+ return (x, history) if return_history else x
89
+
90
+
91
+ def _initial_canvas(cfg, text_pooled, init_tokens, keep_mask):
92
+ B, N, M = text_pooled.shape[0], cfg.num_tokens, cfg.mask_id
93
+ if init_tokens is not None and keep_mask is not None:
94
+ init_tokens = init_tokens.to(text_pooled.device).long()
95
+ return torch.where(keep_mask.to(text_pooled.device).bool(), init_tokens, torch.full_like(init_tokens, M))
96
+ return torch.full((B, N), M, dtype=torch.long, device=text_pooled.device)
97
+
98
+
99
+ @torch.no_grad()
100
+ def sample_iter(model, text_states: torch.Tensor, text_pooled: torch.Tensor, steps: int = 16,
101
+ cfg_scale: float = 3.0, cfg_schedule: str = "constant",
102
+ temperature: float = 1.0, temperature_end: Optional[float] = None,
103
+ top_k: int = 0, top_p: float = 1.0, min_p: float = 0.0,
104
+ choice_temperature: float = 2.0, spatial_nms: bool = True, nms_threshold: float = 0.9,
105
+ commit_threshold: float = 0.0, polish_steps: int = 0, polish_frac: float = 0.08,
106
+ init_tokens: Optional[torch.Tensor] = None, keep_mask: Optional[torch.Tensor] = None,
107
+ self_cond: bool = True, generator: Optional[torch.Generator] = None):
108
+ """Same decoding as `sample`, but yields a `SampleStep` after every step (for live previews)."""
109
+ cfg = model.cfg
110
+ device = text_pooled.device
111
+ B, N, K, M, G = text_pooled.shape[0], cfg.num_tokens, cfg.vocab_size, cfg.mask_id, cfg.grid_size
112
+
113
+ x = _initial_canvas(cfg, text_pooled, init_tokens, keep_mask)
114
+ masked = x == M
115
+ total = steps + polish_steps
116
+ n_start = masked.sum(1)
117
+ conf_map = torch.where(masked, torch.zeros(B, N, device=device), torch.full((B, N), math.inf, device=device))
118
+
119
+ use_cfg = cfg_scale is not None and abs(cfg_scale - 1.0) > 1e-6
120
+ if use_cfg:
121
+ ts2 = torch.cat([text_states, text_states])
122
+ tp2 = torch.cat([text_pooled, text_pooled])
123
+ drop2 = torch.cat([torch.zeros(B, dtype=torch.bool, device=device),
124
+ torch.ones(B, dtype=torch.bool, device=device)])
125
+ sc = torch.zeros(B, N, K, device=device) if (cfg.self_cond and self_cond) else None
126
+
127
+ def step_state(index, phase, probs_full, committed):
128
+ best_p, best = probs_full.max(-1)
129
+ conf = torch.where(masked, best_p, conf_map)
130
+ return SampleStep(index, total, phase, x, best, conf, committed)
131
+
132
+ def predict(x_in, sc_in, frac):
133
+ ratio = (x_in == M).float().mean(1)
134
+ if use_cfg:
135
+ sc2 = torch.cat([sc_in, sc_in]) if sc_in is not None else None
136
+ out = model(torch.cat([x_in, x_in]), ts2, tp2, torch.cat([ratio, ratio]), sc2, drop2).float()
137
+ lc, lu = out.chunk(2)
138
+ w = cfg_weight(cfg_scale, cfg_schedule, frac)
139
+ return lu + w * (lc - lu)
140
+ return model(x_in, text_states, text_pooled, ratio, sc_in, None).float()
141
+
142
+ for k in range(steps):
143
+ if not masked.any():
144
+ break
145
+ frac = (k + 1) / steps
146
+ logits = predict(x, sc, frac)
147
+ probs_full = logits.softmax(-1)
148
+
149
+ T = temperature if temperature_end is None else temperature + (temperature_end - temperature) * (k / max(1, steps - 1))
150
+ if T <= 0:
151
+ sampled = logits.argmax(-1)
152
+ p_sel = probs_full.gather(-1, sampled.unsqueeze(-1)).squeeze(-1)
153
+ else:
154
+ probs = filter_logits(logits / T, top_k, top_p, min_p).softmax(-1)
155
+ sampled = torch.multinomial(probs.view(-1, K), 1, generator=generator).view(B, N)
156
+ p_sel = probs.gather(-1, sampled.unsqueeze(-1)).squeeze(-1)
157
+
158
+ n_masked = masked.sum(1)
159
+ remaining = torch.floor(n_start.float() * math.cos(math.pi / 2 * frac)).long()
160
+ if k == steps - 1:
161
+ remaining = torch.zeros_like(remaining)
162
+ n_commit = torch.minimum((n_masked - remaining).clamp(min=1), n_masked)
163
+ if commit_threshold > 0:
164
+ n_commit = torch.maximum(n_commit, ((p_sel >= commit_threshold) & masked).sum(1))
165
+
166
+ score = torch.log(p_sel.clamp(min=1e-12))
167
+ if choice_temperature > 0:
168
+ score = score + choice_temperature * (1.0 - frac) * _gumbel(score.shape, device, generator)
169
+ priority = score
170
+ if spatial_nms:
171
+ elig = _nms_eligible(score, masked, p_sel >= nms_threshold, G)
172
+ priority = score + elig.float() * 1e4
173
+ priority = torch.where(masked, priority, torch.full_like(priority, -math.inf))
174
+ ranks = priority.argsort(1, descending=True).argsort(1)
175
+ commit = (ranks < n_commit.unsqueeze(1)) & masked
176
+
177
+ x = torch.where(commit, sampled, x)
178
+ conf_map = torch.where(commit, p_sel, conf_map)
179
+ masked = masked & ~commit
180
+ if sc is not None:
181
+ sc = probs_full
182
+ yield step_state(k, "decode", probs_full, commit)
183
+
184
+ # ---- optional polish: re-mask the least confident generated pixels and re-predict ----
185
+ n_re = max(1, int(round(polish_frac * N)))
186
+ for j in range(polish_steps):
187
+ low = torch.topk(-conf_map, n_re, dim=1).indices
188
+ remask = torch.zeros(B, N, dtype=torch.bool, device=device).scatter_(1, low, True)
189
+ remask &= torch.isfinite(conf_map)
190
+ x_in = torch.where(remask, torch.full_like(x, M), x)
191
+ logits = predict(x_in, sc, 1.0)
192
+ probs_full = logits.softmax(-1)
193
+ new = logits.argmax(-1)
194
+ x = torch.where(remask, new, x)
195
+ conf_map = torch.where(remask, probs_full.gather(-1, new.unsqueeze(-1)).squeeze(-1), conf_map)
196
+ if sc is not None:
197
+ sc = probs_full
198
+ yield step_state(steps + j, "polish", probs_full, remask)