Add batched generation support to model/ package
Browse files- model/kv_cache.py +33 -5
- model/pycraft_model.py +124 -2
model/kv_cache.py
CHANGED
|
@@ -172,20 +172,28 @@ def build_attn_mask(
|
|
| 172 |
q_len: int,
|
| 173 |
offset: int,
|
| 174 |
device,
|
|
|
|
| 175 |
) -> torch.Tensor | None:
|
| 176 |
"""
|
| 177 |
Build a bottom-right-aligned causal mask for cached attention.
|
| 178 |
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
offset == 0 caller passes is_causal=True (square, so PyTorch's
|
| 182 |
upper-left alignment is already correct)
|
| 183 |
q_len == 1 the single newest query may attend to every cached
|
| 184 |
key, so causality holds structurally — no mask needed
|
| 185 |
|
| 186 |
-
Otherwise returns (1, 1, q_len, offset + q_len)
|
|
|
|
| 187 |
|
| 188 |
-
mask[i, j] = (j <= offset + i)
|
| 189 |
|
| 190 |
WHY THIS EXISTS: PyTorch builds is_causal as torch.ones(L, S).tril() —
|
| 191 |
UPPER-LEFT aligned. With L=1, S=N that mask contains exactly one True
|
|
@@ -194,13 +202,33 @@ def build_attn_mask(
|
|
| 194 |
that ignores the prompt and collapses into repetition. Hence the explicit
|
| 195 |
dispatch rather than a blanket is_causal=True.
|
| 196 |
"""
|
| 197 |
-
if offset == 0 or q_len == 1:
|
| 198 |
return None
|
| 199 |
|
| 200 |
kv_len = offset + q_len
|
| 201 |
q_pos = torch.arange(offset, kv_len, device=device).unsqueeze(1) # (T, 1)
|
| 202 |
k_pos = torch.arange(0, kv_len, device=device).unsqueeze(0) # (1, S)
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
|
| 206 |
# ------------------------------------------------------------------ #
|
|
|
|
| 172 |
q_len: int,
|
| 173 |
offset: int,
|
| 174 |
device,
|
| 175 |
+
padding_mask: torch.Tensor | None = None,
|
| 176 |
) -> torch.Tensor | None:
|
| 177 |
"""
|
| 178 |
Build a bottom-right-aligned causal mask for cached attention.
|
| 179 |
|
| 180 |
+
Args:
|
| 181 |
+
padding_mask: optional (batch, offset + q_len) bool marking real
|
| 182 |
+
tokens True and padding False. Required for batched generation,
|
| 183 |
+
where shorter prompts are left-padded to a common length.
|
| 184 |
+
|
| 185 |
+
With no padding mask, returns None for the two cases SDPA handles on its
|
| 186 |
+
own:
|
| 187 |
|
| 188 |
offset == 0 caller passes is_causal=True (square, so PyTorch's
|
| 189 |
upper-left alignment is already correct)
|
| 190 |
q_len == 1 the single newest query may attend to every cached
|
| 191 |
key, so causality holds structurally — no mask needed
|
| 192 |
|
| 193 |
+
Otherwise returns bool "may attend", (1, 1, q_len, offset + q_len) or
|
| 194 |
+
(batch, 1, q_len, offset + q_len) when padding is involved:
|
| 195 |
|
| 196 |
+
mask[i, j] = (j <= offset + i) and not padding[j]
|
| 197 |
|
| 198 |
WHY THIS EXISTS: PyTorch builds is_causal as torch.ones(L, S).tril() —
|
| 199 |
UPPER-LEFT aligned. With L=1, S=N that mask contains exactly one True
|
|
|
|
| 202 |
that ignores the prompt and collapses into repetition. Hence the explicit
|
| 203 |
dispatch rather than a blanket is_causal=True.
|
| 204 |
"""
|
| 205 |
+
if padding_mask is None and (offset == 0 or q_len == 1):
|
| 206 |
return None
|
| 207 |
|
| 208 |
kv_len = offset + q_len
|
| 209 |
q_pos = torch.arange(offset, kv_len, device=device).unsqueeze(1) # (T, 1)
|
| 210 |
k_pos = torch.arange(0, kv_len, device=device).unsqueeze(0) # (1, S)
|
| 211 |
+
mask = (k_pos <= q_pos)[None, None, :, :] # (1,1,T,S)
|
| 212 |
+
|
| 213 |
+
if padding_mask is not None:
|
| 214 |
+
if padding_mask.shape[-1] != kv_len:
|
| 215 |
+
raise ValueError(
|
| 216 |
+
f"padding_mask covers {padding_mask.shape[-1]} positions but "
|
| 217 |
+
f"the key length is {kv_len} (offset {offset} + q_len {q_len})"
|
| 218 |
+
)
|
| 219 |
+
# (B,1,1,S) broadcast against the causal (1,1,T,S) -> (B,1,T,S)
|
| 220 |
+
mask = mask & padding_mask[:, None, None, :].to(torch.bool)
|
| 221 |
+
|
| 222 |
+
# A fully-masked query row makes softmax(all -inf) = NaN, which then
|
| 223 |
+
# spreads through the residual stream. Left-padded rows hit this: a
|
| 224 |
+
# pad token's own row can have every key masked. Letting each query
|
| 225 |
+
# attend to at least its own position costs nothing (those outputs are
|
| 226 |
+
# discarded) and keeps the tensor finite.
|
| 227 |
+
qi = torch.arange(q_len, device=device)
|
| 228 |
+
mask = mask.clone()
|
| 229 |
+
mask[:, :, qi, offset + qi] = True
|
| 230 |
+
|
| 231 |
+
return mask
|
| 232 |
|
| 233 |
|
| 234 |
# ------------------------------------------------------------------ #
|
model/pycraft_model.py
CHANGED
|
@@ -84,6 +84,7 @@ class PyCraftModel(nn.Module):
|
|
| 84 |
use_cache: bool | None = None, # None = auto (on iff a cache given)
|
| 85 |
num_logits_to_keep: int = 0, # 0 = all positions
|
| 86 |
ignore_index: int = -100, # label value excluded from loss
|
|
|
|
| 87 |
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 88 |
"""
|
| 89 |
Args:
|
|
@@ -118,8 +119,10 @@ class PyCraftModel(nn.Module):
|
|
| 118 |
|
| 119 |
# 2. Build the causal mask ONCE and share it across all blocks.
|
| 120 |
# Returns None on the two fast paths (offset 0, or single-token
|
| 121 |
-
# decode) where SDPA needs no explicit mask
|
| 122 |
-
|
|
|
|
|
|
|
| 123 |
|
| 124 |
# 3. Pass through transformer blocks
|
| 125 |
for block in self.blocks:
|
|
@@ -304,6 +307,125 @@ class PyCraftModel(nn.Module):
|
|
| 304 |
device=prepared.device)
|
| 305 |
return torch.cat([prepared, tail], dim=1)
|
| 306 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
def param_count(self) -> dict:
|
| 308 |
total = sum(p.numel() for p in self.parameters())
|
| 309 |
trainable = sum(p.numel()
|
|
|
|
| 84 |
use_cache: bool | None = None, # None = auto (on iff a cache given)
|
| 85 |
num_logits_to_keep: int = 0, # 0 = all positions
|
| 86 |
ignore_index: int = -100, # label value excluded from loss
|
| 87 |
+
attention_mask: torch.Tensor | None = None, # (batch, offset + seq_len)
|
| 88 |
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 89 |
"""
|
| 90 |
Args:
|
|
|
|
| 119 |
|
| 120 |
# 2. Build the causal mask ONCE and share it across all blocks.
|
| 121 |
# Returns None on the two fast paths (offset 0, or single-token
|
| 122 |
+
# decode) where SDPA needs no explicit mask — but never when
|
| 123 |
+
# padding is present, since padded keys must be excluded.
|
| 124 |
+
attn_mask = build_attn_mask(seq_len, offset, x.device,
|
| 125 |
+
padding_mask=attention_mask)
|
| 126 |
|
| 127 |
# 3. Pass through transformer blocks
|
| 128 |
for block in self.blocks:
|
|
|
|
| 307 |
device=prepared.device)
|
| 308 |
return torch.cat([prepared, tail], dim=1)
|
| 309 |
|
| 310 |
+
@torch.no_grad()
|
| 311 |
+
def generate_batch(
|
| 312 |
+
self,
|
| 313 |
+
prompts: list[list[int]], # one token-id list per sequence
|
| 314 |
+
max_new_tokens: int = 128,
|
| 315 |
+
temperature: float = 0.8,
|
| 316 |
+
top_k: int = 50,
|
| 317 |
+
top_p: float = 1.0,
|
| 318 |
+
repetition_penalty: float = 1.0,
|
| 319 |
+
eos_token_id: int | list[int] | None = 0,
|
| 320 |
+
pad_token_id: int = 4,
|
| 321 |
+
seed: int | None = None,
|
| 322 |
+
device=None,
|
| 323 |
+
) -> list[list[int]]:
|
| 324 |
+
"""
|
| 325 |
+
Generate for several prompts in one set of forward passes.
|
| 326 |
+
|
| 327 |
+
Returns the NEW tokens per prompt (the prompt is not echoed back),
|
| 328 |
+
each already truncated at its own EOS.
|
| 329 |
+
|
| 330 |
+
Prompts are LEFT-padded so every sequence ends at the same column,
|
| 331 |
+
which keeps logits[:, -1] valid for every row. Right padding would
|
| 332 |
+
put junk at that position and silently sample from it.
|
| 333 |
+
|
| 334 |
+
Left padding is safe for RoPE specifically because RoPE is relative:
|
| 335 |
+
shifting a whole sequence forward by k positions leaves every pairwise
|
| 336 |
+
distance within it unchanged, so a uniform offset costs nothing as
|
| 337 |
+
long as the pad columns are masked out. The key-padding mask handles
|
| 338 |
+
that, and also guarantees no query row is fully masked (which would
|
| 339 |
+
make softmax produce NaN).
|
| 340 |
+
"""
|
| 341 |
+
was_training = self.training
|
| 342 |
+
self.eval()
|
| 343 |
+
try:
|
| 344 |
+
if not prompts:
|
| 345 |
+
return []
|
| 346 |
+
device = device or self.token_embedding.weight.device
|
| 347 |
+
max_len = self.config.max_seq_len
|
| 348 |
+
|
| 349 |
+
# Truncate over-long prompts, then left-pad to a common width
|
| 350 |
+
prompts = [p[-(max_len - 1):] if len(p) >= max_len else list(p)
|
| 351 |
+
for p in prompts]
|
| 352 |
+
batch = len(prompts)
|
| 353 |
+
width = max(len(p) for p in prompts)
|
| 354 |
+
budget = min(max_new_tokens, max_len - width)
|
| 355 |
+
if budget <= 0:
|
| 356 |
+
return [[] for _ in prompts]
|
| 357 |
+
|
| 358 |
+
padded, pad_mask = [], []
|
| 359 |
+
for p in prompts:
|
| 360 |
+
gap = width - len(p)
|
| 361 |
+
padded.append([pad_token_id] * gap + p)
|
| 362 |
+
pad_mask.append([False] * gap + [True] * len(p))
|
| 363 |
+
|
| 364 |
+
input_ids = torch.tensor(padded, dtype=torch.long, device=device)
|
| 365 |
+
mask = torch.tensor(pad_mask, dtype=torch.bool, device=device)
|
| 366 |
+
|
| 367 |
+
eos_ids = ([] if eos_token_id is None
|
| 368 |
+
else [eos_token_id] if isinstance(eos_token_id, int)
|
| 369 |
+
else list(eos_token_id))
|
| 370 |
+
eos_set = set(eos_ids)
|
| 371 |
+
|
| 372 |
+
generator = None
|
| 373 |
+
if seed is not None:
|
| 374 |
+
generator = torch.Generator(device=device)
|
| 375 |
+
generator.manual_seed(seed)
|
| 376 |
+
|
| 377 |
+
cache = KVCache.from_model(
|
| 378 |
+
self, batch_size=batch, max_len=width + budget,
|
| 379 |
+
device=device, dtype=self.token_embedding.weight.dtype,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
logits, _ = self(input_ids, past_key_values=cache, use_cache=True,
|
| 383 |
+
num_logits_to_keep=1, attention_mask=mask)
|
| 384 |
+
next_logits = logits[:, -1, :]
|
| 385 |
+
|
| 386 |
+
out = input_ids
|
| 387 |
+
results: list[list[int]] = [[] for _ in range(batch)]
|
| 388 |
+
finished = [False] * batch
|
| 389 |
+
|
| 390 |
+
for _ in range(budget):
|
| 391 |
+
next_token = sample_next_token(
|
| 392 |
+
next_logits, out, temperature, top_k, top_p,
|
| 393 |
+
repetition_penalty, generator=generator,
|
| 394 |
+
) # (batch, 1)
|
| 395 |
+
|
| 396 |
+
for row in range(batch):
|
| 397 |
+
if finished[row]:
|
| 398 |
+
# Keep the row in the batch but stop recording it;
|
| 399 |
+
# feeding pad keeps shapes rectangular.
|
| 400 |
+
next_token[row, 0] = pad_token_id
|
| 401 |
+
continue
|
| 402 |
+
token = int(next_token[row, 0])
|
| 403 |
+
if token in eos_set:
|
| 404 |
+
finished[row] = True
|
| 405 |
+
next_token[row, 0] = pad_token_id
|
| 406 |
+
else:
|
| 407 |
+
results[row].append(token)
|
| 408 |
+
|
| 409 |
+
if all(finished):
|
| 410 |
+
break
|
| 411 |
+
|
| 412 |
+
out = torch.cat([out, next_token], dim=1)
|
| 413 |
+
# Newly written cache positions are real columns for every
|
| 414 |
+
# row; a finished row only ever attends to itself, so its
|
| 415 |
+
# filler cannot affect any other sequence.
|
| 416 |
+
mask = torch.cat(
|
| 417 |
+
[mask, torch.ones(batch, 1, dtype=torch.bool, device=device)],
|
| 418 |
+
dim=1,
|
| 419 |
+
)
|
| 420 |
+
logits, _ = self(next_token, past_key_values=cache,
|
| 421 |
+
use_cache=True, num_logits_to_keep=1,
|
| 422 |
+
attention_mask=mask)
|
| 423 |
+
next_logits = logits[:, -1, :]
|
| 424 |
+
|
| 425 |
+
return results
|
| 426 |
+
finally:
|
| 427 |
+
self.train(was_training)
|
| 428 |
+
|
| 429 |
def param_count(self) -> dict:
|
| 430 |
total = sum(p.numel() for p in self.parameters())
|
| 431 |
trainable = sum(p.numel()
|