Spaces:
No application file
No application file
File size: 21,042 Bytes
4f2b2f4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 |
# TOOD: This is a very inflexible sampling algorithm -- Only works for semiautoregressive with one token addition at one time
# TODO: This code is quite bad, we'd like to refactor, can we use ein / einops?
import torch
from dataclasses import dataclass
from typing import Any, Literal, Optional
from lightning_modules.mdm import MaskedDiffusionModule
@dataclass
class SamplingTraceDatapoint:
t: float
event_type: Literal["insertion", "change"]
position: int
token: Any
@dataclass
class SamplingResult:
samples: torch.Tensor
# Trace is supposed to be processed sequentially as updates are not commutative
trace: Optional[list[SamplingTraceDatapoint]]
def __iter__(self):
yield from [self.samples, self.trace]
# Sample from categorical distribution for each position using the transition probabilities
def _sample_tokens(probs: torch.Tensor) -> torch.Tensor:
"""Sample one token per position from probability distribution.
Args:
probs: [batch_size, seq_len, vocab_size] transition probabilities
Returns:
[batch_size, seq_len] sampled token indices
"""
batch_size, seq_len, vocab_size = probs.shape
flat_probs = probs.view(-1, vocab_size)
samples = torch.multinomial(flat_probs, num_samples=1)
return samples.view(batch_size, seq_len)
@torch.no_grad()
def mdm_euler_sampling(
model: MaskedDiffusionModule,
steps: int,
mask: int,
pad: int,
batch_size: int,
max_length: int,
return_trace: bool = False,
):
assert not return_trace, "Trace is not yet implemented in MDM Euler sampling"
device = model.device
xt = torch.full((batch_size, max_length), mask, dtype=torch.int64, device=device)
dt = 1.0 / steps
t = torch.zeros(batch_size, device=device)
for i in range(steps):
print("i-th sampling step")
# βββ predict and convert rates βββ
pred_rate = model(xt, t)
pred_rate = model.interpolant.to_actual_rate(xt, pred_rate, t)
unmask_rate = pred_rate.unmask_rate
# βββ unmask step (Euler) βββ
mask_pos = (xt == mask).nonzero(as_tuple=True)
unmask_rate[xt != mask] = 0
unmask_rate[*mask_pos, mask] = 0
unmask_rate[*mask_pos, mask] = -unmask_rate[*mask_pos, :].sum(dim=1)
trans_prob = (unmask_rate * dt).clamp(0.0, 1.0)
_xt = xt.clone()
trans_prob.scatter_add_(
2,
_xt.unsqueeze(-1),
torch.ones_like(_xt.unsqueeze(-1), dtype=trans_prob.dtype),
)
if i == steps - 1:
print("Final step, removing mask token from sampling")
trans_prob[*mask_pos, mask] = 0.0
print(trans_prob[*mask_pos, mask])
new_xt = _sample_tokens(trans_prob)
new_xt = torch.where(xt != mask, xt, new_xt)
xt = new_xt
t = t + dt
return xt, []
@torch.no_grad()
def any_order_mask_insertion_euler_sampling(
model: torch.nn.Module,
steps: int,
mask: int,
pad: int,
batch_size: int,
max_length: int,
return_trace: bool = False,
) -> SamplingResult:
device = model.device
# 1) Initialize allβpad sequence and trace
xt = torch.full((batch_size, max_length), pad, dtype=torch.int64, device=device)
sampling_trace = []
dt = 1.0 / steps
t = torch.zeros(batch_size, device=device)
# Precompute row indices for scatter
batch_idx_L = (
torch.arange(batch_size, device=device)
.view(batch_size, 1)
.expand(batch_size, max_length)
)
pos_idx_L = (
torch.arange(max_length, device=device)
.view(1, max_length)
.expand(batch_size, max_length)
)
sampling_trace = [[] for _ in range(batch_size)] if return_trace else None
for i in range(steps):
# βββ predict and convert rates βββ
pred_rate = model(xt, t)
pred_rate = model.interpolant.to_actual_rate(xt, pred_rate, t)
unmask_rate = pred_rate.unmask_rate # (B, L, V)
len_rate = pred_rate.length_rate # (B, L+1)
# βββ unmask step (Euler) βββ
mask_pos = (xt == mask).nonzero(as_tuple=True)
unmask_rate[xt != mask] = 0
unmask_rate[*mask_pos, mask] = 0
unmask_rate[*mask_pos, mask] = -unmask_rate[*mask_pos, :].sum(dim=1)
trans_prob = (unmask_rate * dt).clamp(0.0, 1.0)
# add βstayβ probability
_xt = xt.clone()
_xt[xt == pad] = mask
trans_prob.scatter_add_(
2,
_xt.unsqueeze(-1),
torch.ones_like(_xt.unsqueeze(-1), dtype=trans_prob.dtype),
)
if i == steps - 1:
print("Final step, removing mask token from sampling")
trans_prob[*mask_pos, mask] = (
0.0 # remove mask token from sampling at the last step
)
print(trans_prob[*mask_pos, mask])
new_xt = _sample_tokens(trans_prob)
new_xt[xt == pad] = pad
new_xt = torch.where((xt != mask) & (xt != pad), xt, new_xt)
if i != steps - 1:
# βββ gap-wise insertion refactored β compute new length, fill masks, scatter tokens βββ
ext = torch.bernoulli((len_rate * dt).clamp(0.0, 1.0)).long() # (B, L+1)
xt_len = xt.ne(pad).sum(dim=1) # (B,)
gaps = torch.arange(max_length + 1, device=device).view(1, -1)
ext = ext * (gaps <= xt_len.view(batch_size, 1)).long()
total_ext = ext.sum(dim=1)
valid = xt_len + total_ext <= max_length
ext = ext * valid.view(batch_size, 1).long()
ext_ex = ext.int().cumsum(dim=1) # (B, L+1)
new_len = xt_len + total_ext # (B,)
xt_tmp = torch.full_like(xt, pad)
mask_fill = pos_idx_L < new_len.view(batch_size, 1)
xt_tmp[mask_fill] = mask
new_pos_orig = pos_idx_L + ext_ex[:, :max_length] # (B, L)
orig_mask = pos_idx_L < xt_len.view(batch_size, 1)
flat_b = batch_idx_L[orig_mask]
flat_p = new_pos_orig[orig_mask]
xt_tmp[flat_b, flat_p] = new_xt[orig_mask]
else:
xt_tmp = new_xt
if return_trace:
# Check if the token was changed
for i in range(batch_size):
for j in range(max_length):
if xt[i, j] != pad and xt[i, j] != new_xt[i, j]:
sampling_trace[i].append(
SamplingTraceDatapoint(
t=t[i].item(),
event_type="change",
position=j,
token=new_xt[i, j].item(),
)
)
# Check if a new token was inserted
for j in range(max_length):
id = max_length - j - 1
if ext[i, id]:
sampling_trace[i].append(
SamplingTraceDatapoint(
t=t[i].item(),
event_type="insertion",
position=id,
token=mask,
)
)
xt = xt_tmp
t = t + dt
return xt, sampling_trace
@torch.no_grad()
def mdm_tau_leaping_sampling(
model: MaskedDiffusionModule,
steps: int,
mask: int,
pad: int,
batch_size: int,
max_length: int,
return_trace: bool = False,
):
assert not return_trace, "Trace is not yet supported"
device = model.device
xt = torch.full((batch_size, max_length), mask, dtype=torch.int64, device=device)
dt = 1.0 / steps
t = torch.zeros(batch_size, device=device)
for i in range(steps):
# βββ predict and convert rates βββ
pred = model(xt, t)
pred = model.interpolant.to_actual_rate(xt, pred, t)
unmask_rate = pred.unmask_rate # (B, L, V)
if i == steps - 1:
# last step: deterministic unmask via argmax
mask_pos = xt == mask # (B, L)
new_token = unmask_rate.argmax(dim=2) # (B, L)
new_xt = xt.clone()
new_xt[mask_pos] = new_token[mask_pos]
new_xt = torch.where(xt != mask, xt, new_xt)
xt = new_xt
t = t + dt
continue
# tau-leaping via Poisson counts
counts = torch.poisson(unmask_rate * dt).long()
mask_pos = xt == mask # (B, L)
# zero out non-mask positions and maskβmask
counts[~mask_pos.unsqueeze(-1).expand_as(counts)] = 0
counts[..., mask] = 0
# only accept exactly one event
sum_c = counts.sum(dim=2) # (B, L)
one_event = sum_c == 1
new_token = counts.argmax(dim=2) # (B, L)
# build new xt
new_xt = xt.clone()
new_xt[one_event] = new_token[one_event]
# keep pads and already-unmasked tokens
new_xt = torch.where(xt != mask, xt, new_xt)
xt = new_xt
t = t + dt
return xt, []
# Not used in production, for debugging purposes
lengths = {4: 0.1, 16: 0.4, 32: 0.4, 64: 0.1}
def binomial_mass(k, n, p):
"""
Calculate the probability mass function (PMF) for a binomial distribution.
Args:
k (int): Number of successes
n (int): Number of trials
p (float): Probability of success in a single trial
Returns:
float: Probability mass P(X = k)
"""
import math
# Calculate binomial coefficient (n choose k)
try:
binom_coef = math.factorial(n) / (math.factorial(k) * math.factorial(n - k))
except ValueError:
# Handle cases where k > n or negative values
return 0.0
# Calculate probability mass
return binom_coef * (p ** k) * ((1 - p) ** (n - k))
def calculate_rate_batch(alpha_t, len_t):
"""
Calculate rate for a batch of alpha_t and len_t values.
Args:
alpha_t (torch.Tensor): Tensor of shape (batch_size,)
len_t (torch.Tensor): Tensor of shape (batch_size,)
Returns:
torch.Tensor: Tensor of shape (batch_size,) containing calculated rates
"""
batch_size = alpha_t.shape[0]
device = alpha_t.device
# Initialize tensors for numerator and denominator
nom = torch.zeros(batch_size, device=device)
denom = torch.zeros(batch_size, device=device)
for length, probability in lengths.items():
# Create mask for valid entries where len_t <= length
valid_mask = (len_t <= length) & (len_t >= 0)
if not valid_mask.any():
continue
valid_indices = valid_mask.nonzero(as_tuple=True)[0]
valid_len_t = len_t[valid_indices]
valid_alpha_t = alpha_t[valid_indices]
# Calculate binomial probabilities efficiently using torch distribution
binom_dist = torch.distributions.Binomial(total_count=length, probs=valid_alpha_t)
binom_probs = binom_dist.log_prob(valid_len_t).exp()
# Update numerator and denominator for valid indices
nom[valid_indices] += (length - valid_len_t) * probability * binom_probs
denom[valid_indices] += probability * binom_probs
# Handle division by zero in a vectorized way
result = torch.zeros_like(nom)
div_mask = denom > 0
result[div_mask] = nom[div_mask] / (denom[div_mask])
return result
# Keep the original function for backward compatibility
def calculate_rate(alpha_t, len_t):
"""Legacy scalar version of calculate_rate"""
if isinstance(alpha_t, torch.Tensor) and alpha_t.ndim > 0:
return calculate_rate_batch(alpha_t, len_t)
nom, denom = 0, 0
for length, probability in lengths.items():
if length >= len_t:
nom += (length - len_t) * probability * binomial_mass(len_t, length, alpha_t)
denom += probability * binomial_mass(len_t, length, alpha_t)
if denom == 0:
return 0.0
return nom /denom
@torch.no_grad()
@torch.compile(mode="reduce-overhead")
def any_order_mask_insertion_tau_leaping_sampling(
model: torch.nn.Module,
steps: int,
mask: int,
pad: int,
batch_size: int,
max_length: int,
return_trace: bool = False,
confidence_based_sampling: bool = True, # whether to use confidence-based decoding
alpha: float = 5.0, # hyperparameter for window size calculation
max_window: int = 32, # Maximum window size for sliding window
confidence_method: str = "prob_diff", # "position", "top_prob", "prob_diff", "entropy"
use_sliding_window: bool = False, # whether to use sliding window for position selection
) -> SamplingResult:
device = model.device
xt = torch.full((batch_size, max_length), pad, dtype=torch.int64, device=device)
sampling_trace = []
dt = 1.0 / steps
t = torch.zeros(batch_size, device=device)
# Precompute row indices for scatter
batch_idx_L = (
torch.arange(batch_size, device=device)
.view(batch_size, 1)
.expand(batch_size, max_length)
)
pos_idx_L = (
torch.arange(max_length, device=device)
.view(1, max_length)
.expand(batch_size, max_length)
)
for i in range(steps):
# --- predict rates ---
pred = model(xt, t)
xt_len = (xt != pad).sum(dim=1)
pred = model.interpolant.to_actual_rate(xt, pred, t)
unmask_rate = pred.unmask_rate # (B, L, V)
len_rate = pred.length_rate # (B, L+1)
if i == steps - 1:
# last step: deterministic unmask via argmax
mask_pos = xt == mask
new_token = unmask_rate.argmax(dim=2)
new_xt = xt.clone()
new_xt[mask_pos] = new_token[mask_pos]
new_xt = torch.where(xt == pad, pad, new_xt)
new_xt = torch.where((xt != mask) & (xt != pad), xt, new_xt)
xt = new_xt
t = t + dt
continue
# --- confidence-based decoding ---
if confidence_based_sampling > 0.0:
# Confidence-based unmasking (vectorized)
mask_positions = (xt == mask) # (B, L)
num_mask_positions = mask_positions.sum(dim=1) # (B,)
# 1. Determine number of tokens to unmask using Poisson
unmask_counts = torch.poisson(num_mask_positions.float() * dt).long() # (B,)
# 2. Calculate confidence based on selected method
if confidence_method == "position":
# Position-based confidence: position i / len(xt)
xt_len = (xt != pad).sum(dim=1) # (B,) - current sequence lengths
position_indices = torch.arange(max_length, device=device).unsqueeze(0).expand(batch_size, -1) # (B, L)
confidence = 1.0 - (position_indices.float() / xt_len.unsqueeze(1).float().clamp(min=1)) # (B, L)
elif confidence_method == "top_prob":
# Top probability confidence
import torch.nn.functional as F
token_logits = unmask_rate # (B, L, V) - use the unmask_rate as logits
unmask_probs = F.softmax(token_logits, dim=-1) # (B, L, V)
confidence = unmask_probs.max(dim=-1)[0] # (B, L)
elif confidence_method == "prob_diff":
# Probability difference confidence (top - second top)
import torch.nn.functional as F
token_logits = unmask_rate # (B, L, V)
unmask_probs = F.softmax(token_logits, dim=-1) # (B, L, V)
top2_probs, _ = torch.topk(unmask_probs, k=2, dim=-1) # (B, L, 2)
confidence = top2_probs[:, :, 0] - top2_probs[:, :, 1] # (B, L)
elif confidence_method == "entropy":
# Entropy-based confidence (lower entropy = higher confidence)
import torch.nn.functional as F
token_logits = unmask_rate # (B, L, V)
unmask_probs = F.softmax(token_logits, dim=-1) # (B, L, V)
entropy = -torch.sum(unmask_probs * torch.log(unmask_probs + 1e-10), dim=-1) # (B, L)
confidence = -entropy # (B, L) - negative entropy so lower entropy gives higher confidence
else:
raise ValueError(f"Unknown confidence_method: {confidence_method}")
# 3. Apply window constraint if enabled
if use_sliding_window:
# Calculate dynamic k for each batch
k_values = torch.minimum(
torch.minimum(
(alpha * unmask_counts).long(),
torch.tensor(max_window, device=device)
), num_mask_positions) # (B,)
# Get cumulative count of mask positions
mask_cumsum = mask_positions.cumsum(dim=1) # (B, L)
# Create window mask: position is eligible if it's a mask and within first k masks
is_within_window = mask_cumsum <= k_values.unsqueeze(1) # (B, L)
window_mask = mask_positions & is_within_window # (B, L)
# Set confidence to -inf for positions outside the window or non-mask positions
confidence = torch.where(window_mask, confidence, torch.tensor(-float('inf'), device=device))
else:
# No window constraint - only mask positions are eligible
confidence = torch.where(mask_positions, confidence, torch.tensor(-float('inf'), device=device))
new_xt = xt.clone()
# Vectorized unmasking
max_unmask = unmask_counts.max().item()
if max_unmask > 0:
# Get top-k indices for all batches
_, all_top_indices = torch.topk(confidence, k=max_unmask, dim=1, largest=True) # (B, max_unmask)
# Create mask for valid unmask operations
unmask_mask = torch.arange(max_unmask, device=device).unsqueeze(0) < unmask_counts.unsqueeze(1) # (B, max_unmask)
# Get most likely tokens
most_likely_tokens = unmask_rate.argmax(dim=-1) # (B, L)
# Gather the tokens to place at selected positions
selected_positions = all_top_indices[unmask_mask] # Flattened valid positions
batch_indices = torch.arange(batch_size, device=device).unsqueeze(1).expand(-1, max_unmask)[unmask_mask] # Corresponding batch indices
# Apply unmasking with sampled tokens
new_xt[batch_indices, selected_positions] = most_likely_tokens[batch_indices, selected_positions]
else:
# --- tau-leaping unmask via Poisson ---
counts = torch.poisson(unmask_rate * dt).long()
mask_pos = xt == mask
counts[~mask_pos.unsqueeze(-1).expand_as(counts)] = 0
counts[..., mask] = 0
sum_c = counts.sum(dim=2)
one_event = sum_c == 1
new_token = counts.argmax(dim=2)
new_xt = xt.clone()
new_xt[one_event] = new_token[one_event]
new_xt = torch.where(xt == pad, pad, new_xt)
new_xt = torch.where((xt != mask) & (xt != pad), xt, new_xt)
# insertion only on non-last
if i != steps - 1:
# --- Poisson insertion, compute new lengths and fill masks ---
ext = torch.poisson(len_rate * dt).long() # (B, L+1)
xt_len = xt.ne(pad).sum(dim=1) # (B,)
gaps = torch.arange(max_length + 1, device=device).view(1, -1)
ext = ext * (gaps <= xt_len.view(batch_size, 1)).long()
total_ext = ext.sum(dim=1)
valid = xt_len + total_ext <= max_length
ext = ext * valid.view(batch_size, 1).long()
# compute prefix sums of insertions
ext_ex = ext.int().cumsum(dim=1) # (B, L+1)
new_len = xt_len + total_ext # (B,)
# initialize with pads, then fill mask up to new_len
xt_tmp = torch.full_like(xt, pad)
mask_pos = pos_idx_L < new_len.view(batch_size, 1)
xt_tmp[mask_pos] = mask
# shift and scatter original tokens
new_pos_orig = pos_idx_L + ext_ex[:, :max_length] # (B, L)
orig_mask = pos_idx_L < xt_len.view(batch_size, 1)
flat_b = batch_idx_L[orig_mask]
flat_p = new_pos_orig[orig_mask]
xt_tmp[flat_b, flat_p] = new_xt[orig_mask]
else:
xt_tmp = new_xt
xt = xt_tmp
t = t + dt
if return_trace:
sampling_trace.append(xt)
return xt, sampling_trace
|