Spaces:
Sleeping
Sleeping
Commit ·
a3032cf
1
Parent(s): 6cd4a29
Update inference.py
Browse files- inference.py +46 -28
inference.py
CHANGED
|
@@ -67,7 +67,7 @@ def load_model(checkpoint_path: str, device: torch.device) -> tuple[GPT, GPTConf
|
|
| 67 |
)
|
| 68 |
|
| 69 |
model_config = GPTConfig(**checkpoint["model_config"])
|
| 70 |
-
model = GPT(model_config)
|
| 71 |
|
| 72 |
state_dict = checkpoint["model_state_dict"]
|
| 73 |
|
|
@@ -84,8 +84,15 @@ def load_model(checkpoint_path: str, device: torch.device) -> tuple[GPT, GPTConf
|
|
| 84 |
file=sys.stderr,
|
| 85 |
)
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
model.load_state_dict(state_dict)
|
| 88 |
-
model.to(device)
|
| 89 |
model.eval()
|
| 90 |
|
| 91 |
n_params = model.get_num_params() / 1e6
|
|
@@ -102,7 +109,7 @@ def _apply_repetition_penalty(
|
|
| 102 |
logits: torch.Tensor,
|
| 103 |
generated_ids: list[int],
|
| 104 |
penalty: float,
|
| 105 |
-
|
| 106 |
max_count: int = 6,
|
| 107 |
) -> torch.Tensor:
|
| 108 |
"""CTRL-style penalty, COUNT-SCALED: a token seen N times in the
|
|
@@ -136,12 +143,12 @@ def _apply_repetition_penalty(
|
|
| 136 |
already arrive at the first generation step with count >= 2-3, giving
|
| 137 |
them a standing penalty of penalty**3 before the model has emitted a
|
| 138 |
single token. That's not repetition suppression -- it's prompt
|
| 139 |
-
interference.
|
| 140 |
original prompt_ids) lets us count only within the generated portion.
|
| 141 |
"""
|
| 142 |
if penalty == 1.0 or not generated_ids:
|
| 143 |
return logits
|
| 144 |
-
if
|
| 145 |
# Count only tokens that appear in the generated suffix (after the
|
| 146 |
# prompt). generated_ids includes the prompt prefix, so we walk the
|
| 147 |
# list and tally only tokens not in the prompt -- tokens that the
|
|
@@ -149,8 +156,9 @@ def _apply_repetition_penalty(
|
|
| 149 |
# penalty**1 if they recur in the generated portion (they're not
|
| 150 |
# immune; we just don't pre-charge them for being in the prompt).
|
| 151 |
gen_counts: Counter[int] = Counter()
|
| 152 |
-
|
| 153 |
-
|
|
|
|
| 154 |
for tid in generated_ids:
|
| 155 |
if prompt_remaining.get(tid, 0) > 0:
|
| 156 |
prompt_remaining[tid] -= 1
|
|
@@ -223,6 +231,13 @@ def _top_p_filter(logits: torch.Tensor, top_p: float) -> torch.Tensor:
|
|
| 223 |
return torch.full_like(logits, float("-inf")).scatter(1, sorted_idx, sorted_logits)
|
| 224 |
|
| 225 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
|
| 227 |
def _clip_max_new_tokens(max_new_tokens: int, prompt_ids: list[int], block_size: int) -> int:
|
| 228 |
"""Prevent the generation loop from silently overwriting the prompt by
|
|
@@ -232,7 +247,14 @@ def _clip_max_new_tokens(max_new_tokens: int, prompt_ids: list[int], block_size:
|
|
| 232 |
return 0
|
| 233 |
available = block_size - len(prompt_ids)
|
| 234 |
if available <= 0:
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
return min(max_new_tokens, available)
|
| 237 |
|
| 238 |
|
|
@@ -262,13 +284,15 @@ def generate(
|
|
| 262 |
idx = torch.tensor([prompt_ids] * num_samples, dtype=torch.long, device=device)
|
| 263 |
block_size = model.config.block_size
|
| 264 |
eos_id = getattr(tokenizer, "eos_id", None)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
|
| 266 |
# Built once from the original prompt and kept as a multiset so
|
| 267 |
# repetition penalty excludes prompt tokens by duplicate-aware count.
|
| 268 |
-
|
| 269 |
-
# Counter built once here; _apply_repetition_penalty copies it per call
|
| 270 |
-
# (O(unique tokens)) instead of rebuilding from the list (O(prompt_len)).
|
| 271 |
-
prompt_counter: Counter[int] = Counter(prompt_ids_reference)
|
| 272 |
|
| 273 |
# Clip the requested budget to the remaining context budget so the
|
| 274 |
# context window never drops the prompt silently when max_new_tokens
|
|
@@ -300,7 +324,7 @@ def generate(
|
|
| 300 |
if finished[b]:
|
| 301 |
continue
|
| 302 |
row = logits[b:b + 1]
|
| 303 |
-
row = _apply_repetition_penalty(row, generated_ids[b], repetition_penalty,
|
| 304 |
row = _block_repeated_ngrams(row, generated_ids[b], no_repeat_ngram_size)
|
| 305 |
row = row / max(temperature, 1e-5)
|
| 306 |
if top_k is not None:
|
|
@@ -309,13 +333,11 @@ def generate(
|
|
| 309 |
row = _top_p_filter(row, top_p)
|
| 310 |
logits[b:b + 1] = row
|
| 311 |
|
| 312 |
-
# Guard: if any row is all -inf (over-aggressive filtering), reset it
|
| 313 |
-
# to uniform so multinomial doesn't receive NaN probabilities.
|
| 314 |
-
all_neg_inf = ~torch.isfinite(logits).any(dim=-1) # [B]
|
| 315 |
-
if all_neg_inf.any():
|
| 316 |
-
logits[all_neg_inf] = 0.0 # uniform before softmax
|
| 317 |
-
|
| 318 |
probs = torch.softmax(logits, dim=-1)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
next_ids = torch.multinomial(probs, num_samples=1) # (num_samples, 1)
|
| 320 |
|
| 321 |
# Once a sequence hits EOS, keep feeding it its own last token so the
|
|
@@ -325,22 +347,15 @@ def generate(
|
|
| 325 |
next_ids[b, 0] = idx[b, -1]
|
| 326 |
continue
|
| 327 |
tid = next_ids[b, 0].item()
|
|
|
|
| 328 |
if eos_id is not None and tid == eos_id:
|
| 329 |
finished[b] = True
|
| 330 |
-
else:
|
| 331 |
-
generated_ids[b].append(tid)
|
| 332 |
|
| 333 |
idx = torch.cat([idx, next_ids], dim=1)
|
| 334 |
|
| 335 |
if stream and num_samples == 1:
|
| 336 |
new_text = tokenizer.decode(generated_ids[0])
|
| 337 |
-
|
| 338 |
-
print(new_text[len(prev_text[0]):], end="", flush=True)
|
| 339 |
-
else:
|
| 340 |
-
# BPE decode is not prefix-stable (a new token can change how
|
| 341 |
-
# earlier bytes are decoded, e.g. completing a multi-byte char).
|
| 342 |
-
# Reprint the whole line to stay correct.
|
| 343 |
-
print("\r" + new_text, end="", flush=True)
|
| 344 |
prev_text[0] = new_text
|
| 345 |
|
| 346 |
if stream and num_samples == 1:
|
|
@@ -394,6 +409,9 @@ def _resolve_dtype(dtype_arg: str, device: torch.device) -> torch.dtype | None:
|
|
| 394 |
if dtype_arg == "fp32":
|
| 395 |
return None # no autocast
|
| 396 |
if dtype_arg == "fp16":
|
|
|
|
|
|
|
|
|
|
| 397 |
return torch.float16
|
| 398 |
if dtype_arg == "bf16":
|
| 399 |
return torch.bfloat16
|
|
|
|
| 67 |
)
|
| 68 |
|
| 69 |
model_config = GPTConfig(**checkpoint["model_config"])
|
| 70 |
+
model = GPT(model_config).to(device)
|
| 71 |
|
| 72 |
state_dict = checkpoint["model_state_dict"]
|
| 73 |
|
|
|
|
| 84 |
file=sys.stderr,
|
| 85 |
)
|
| 86 |
|
| 87 |
+
quant = checkpoint.get("quantization")
|
| 88 |
+
if quant:
|
| 89 |
+
import model as _m
|
| 90 |
+
fn = {"int8": _m.apply_int8_to_model, "nvfp4": _m.apply_nvfp4_to_model}.get(quant)
|
| 91 |
+
if fn is None:
|
| 92 |
+
raise RuntimeError(f"checkpoint quantized with {quant!r} but this build can't re-apply it")
|
| 93 |
+
fn(model)
|
| 94 |
+
model._quant_mode = quant
|
| 95 |
model.load_state_dict(state_dict)
|
|
|
|
| 96 |
model.eval()
|
| 97 |
|
| 98 |
n_params = model.get_num_params() / 1e6
|
|
|
|
| 109 |
logits: torch.Tensor,
|
| 110 |
generated_ids: list[int],
|
| 111 |
penalty: float,
|
| 112 |
+
prompt_id_set: "list[int] | set[int] | None" = None,
|
| 113 |
max_count: int = 6,
|
| 114 |
) -> torch.Tensor:
|
| 115 |
"""CTRL-style penalty, COUNT-SCALED: a token seen N times in the
|
|
|
|
| 143 |
already arrive at the first generation step with count >= 2-3, giving
|
| 144 |
them a standing penalty of penalty**3 before the model has emitted a
|
| 145 |
single token. That's not repetition suppression -- it's prompt
|
| 146 |
+
interference. prompt_id_set (built once per generate() call from the
|
| 147 |
original prompt_ids) lets us count only within the generated portion.
|
| 148 |
"""
|
| 149 |
if penalty == 1.0 or not generated_ids:
|
| 150 |
return logits
|
| 151 |
+
if prompt_id_set:
|
| 152 |
# Count only tokens that appear in the generated suffix (after the
|
| 153 |
# prompt). generated_ids includes the prompt prefix, so we walk the
|
| 154 |
# list and tally only tokens not in the prompt -- tokens that the
|
|
|
|
| 156 |
# penalty**1 if they recur in the generated portion (they're not
|
| 157 |
# immune; we just don't pre-charge them for being in the prompt).
|
| 158 |
gen_counts: Counter[int] = Counter()
|
| 159 |
+
prompt_remaining = _build_prompt_remaining(
|
| 160 |
+
list(prompt_id_set) if isinstance(prompt_id_set, set) else list(prompt_id_set)
|
| 161 |
+
)
|
| 162 |
for tid in generated_ids:
|
| 163 |
if prompt_remaining.get(tid, 0) > 0:
|
| 164 |
prompt_remaining[tid] -= 1
|
|
|
|
| 231 |
return torch.full_like(logits, float("-inf")).scatter(1, sorted_idx, sorted_logits)
|
| 232 |
|
| 233 |
|
| 234 |
+
def _build_prompt_remaining(prompt_ids: list[int]) -> Counter[int]:
|
| 235 |
+
"""Return the prompt token multiplicities needed by the repetition
|
| 236 |
+
penalty walker. A plain set hides duplicate counts, which underestimates
|
| 237 |
+
how many times a repeated prompt token should be available to the counter.
|
| 238 |
+
"""
|
| 239 |
+
return Counter(prompt_ids)
|
| 240 |
+
|
| 241 |
|
| 242 |
def _clip_max_new_tokens(max_new_tokens: int, prompt_ids: list[int], block_size: int) -> int:
|
| 243 |
"""Prevent the generation loop from silently overwriting the prompt by
|
|
|
|
| 247 |
return 0
|
| 248 |
available = block_size - len(prompt_ids)
|
| 249 |
if available <= 0:
|
| 250 |
+
raise ValueError(
|
| 251 |
+
f"prompt is {len(prompt_ids)} tokens >= block_size {block_size}; nothing "
|
| 252 |
+
f"left to generate. Shorten the prompt (this build has no sliding-window "
|
| 253 |
+
f"generation)."
|
| 254 |
+
)
|
| 255 |
+
if max_new_tokens > available:
|
| 256 |
+
print(f"[generate] NOTE: clipped max_new_tokens {max_new_tokens} -> {available} "
|
| 257 |
+
f"(block_size={block_size}, prompt={len(prompt_ids)}).", file=sys.stderr)
|
| 258 |
return min(max_new_tokens, available)
|
| 259 |
|
| 260 |
|
|
|
|
| 284 |
idx = torch.tensor([prompt_ids] * num_samples, dtype=torch.long, device=device)
|
| 285 |
block_size = model.config.block_size
|
| 286 |
eos_id = getattr(tokenizer, "eos_id", None)
|
| 287 |
+
if eos_id is None:
|
| 288 |
+
eos_id = getattr(tokenizer, "eos_token_id", None)
|
| 289 |
+
if eos_id is None:
|
| 290 |
+
print("[generate] WARNING: tokenizer exposes no eos_id/eos_token_id -- "
|
| 291 |
+
"early stopping disabled, generations run to budget.", file=sys.stderr)
|
| 292 |
|
| 293 |
# Built once from the original prompt and kept as a multiset so
|
| 294 |
# repetition penalty excludes prompt tokens by duplicate-aware count.
|
| 295 |
+
prompt_id_set: list[int] = list(prompt_ids)
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
# Clip the requested budget to the remaining context budget so the
|
| 298 |
# context window never drops the prompt silently when max_new_tokens
|
|
|
|
| 324 |
if finished[b]:
|
| 325 |
continue
|
| 326 |
row = logits[b:b + 1]
|
| 327 |
+
row = _apply_repetition_penalty(row, generated_ids[b], repetition_penalty, prompt_id_set=prompt_id_set)
|
| 328 |
row = _block_repeated_ngrams(row, generated_ids[b], no_repeat_ngram_size)
|
| 329 |
row = row / max(temperature, 1e-5)
|
| 330 |
if top_k is not None:
|
|
|
|
| 333 |
row = _top_p_filter(row, top_p)
|
| 334 |
logits[b:b + 1] = row
|
| 335 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
probs = torch.softmax(logits, dim=-1)
|
| 337 |
+
dead = ~torch.isfinite(probs).any(dim=-1) | (probs.sum(dim=-1) <= 0)
|
| 338 |
+
if dead.any():
|
| 339 |
+
logits[dead] = 0.0
|
| 340 |
+
probs = torch.softmax(logits, dim=-1)
|
| 341 |
next_ids = torch.multinomial(probs, num_samples=1) # (num_samples, 1)
|
| 342 |
|
| 343 |
# Once a sequence hits EOS, keep feeding it its own last token so the
|
|
|
|
| 347 |
next_ids[b, 0] = idx[b, -1]
|
| 348 |
continue
|
| 349 |
tid = next_ids[b, 0].item()
|
| 350 |
+
generated_ids[b].append(tid)
|
| 351 |
if eos_id is not None and tid == eos_id:
|
| 352 |
finished[b] = True
|
|
|
|
|
|
|
| 353 |
|
| 354 |
idx = torch.cat([idx, next_ids], dim=1)
|
| 355 |
|
| 356 |
if stream and num_samples == 1:
|
| 357 |
new_text = tokenizer.decode(generated_ids[0])
|
| 358 |
+
print(new_text[len(prev_text[0]):], end="", flush=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 359 |
prev_text[0] = new_text
|
| 360 |
|
| 361 |
if stream and num_samples == 1:
|
|
|
|
| 409 |
if dtype_arg == "fp32":
|
| 410 |
return None # no autocast
|
| 411 |
if dtype_arg == "fp16":
|
| 412 |
+
if device.type == "cpu":
|
| 413 |
+
print("[Inference] fp16 autocast unsupported on CPU -- using bf16 or fp32.", file=sys.stderr)
|
| 414 |
+
return torch.bfloat16
|
| 415 |
return torch.float16
|
| 416 |
if dtype_arg == "bf16":
|
| 417 |
return torch.bfloat16
|