Download src/pat/generate.py from ICLRPAT27/PAT-code: direct link, hf CLI and curl.
- Browser
- Download file 4.68 kB
-
https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/generate.py
- Command line
-
hf download hf://ICLRPAT27/PAT-code/src/pat/generate.py
-
curl -L -o generate.py https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/generate.py
4.68 kB
| """Text generation with explicit document boundaries and a fixed CUDA path.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| from pathlib import Path | |
| import torch | |
| from .checkpoint import load_checkpoint | |
| from .inference import create_cache | |
| from .tokenizer import EOD_ID, Tokenizer | |
| def sample(logits: torch.Tensor, temperature: float, top_p: float, generator) -> int: | |
| """Sample text or EOD; packing markers and unused rows are never emitted.""" | |
| if not math.isfinite(temperature) or temperature < 0 or not 0 < top_p <= 1: | |
| raise ValueError("temperature must be finite and nonnegative; top_p must be in (0, 1]") | |
| logits = logits.float().flatten()[: EOD_ID + 1] | |
| if not torch.isfinite(logits).all(): | |
| raise FloatingPointError("Nonfinite model logits") | |
| if temperature == 0: | |
| return int(logits.argmax().item()) | |
| probabilities = torch.softmax(logits / temperature, dim=-1) | |
| sorted_probs, indices = probabilities.sort(descending=True) | |
| # Retain the token which crosses the cumulative threshold, including at | |
| # least the most likely token. This avoids an empty distribution. | |
| remove = sorted_probs.cumsum(0) - sorted_probs > top_p | |
| sorted_probs[remove] = 0 | |
| chosen = torch.multinomial(sorted_probs, 1, generator=generator) | |
| return int(indices[chosen].item()) | |
| def generate( | |
| model, | |
| prompt: str, | |
| *, | |
| tokenizer: Tokenizer | None = None, | |
| max_new_tokens: int = 128, | |
| temperature: float = 0.0, | |
| top_p: float = 0.95, | |
| seed: int = 42, | |
| ) -> dict: | |
| """Prefill one document, then decode with the checkpoint's fixed KV cache. | |
| Context capacity includes BOS. PAT commits completed chunks to its memory | |
| internally; callers supply ordinary text without packing markers. | |
| """ | |
| tokenizer = tokenizer or Tokenizer() | |
| if type(max_new_tokens) is not int or max_new_tokens <= 0: | |
| raise ValueError("max_new_tokens must be a positive integer") | |
| if not math.isfinite(temperature) or temperature < 0 or not 0 < top_p <= 1: | |
| raise ValueError("Invalid sampling parameters") | |
| tokens = tokenizer.encode(prompt) | |
| if not tokens: | |
| raise ValueError("The prompt must contain at least one text token") | |
| if any(token >= EOD_ID for token in tokens): | |
| raise ValueError("The prompt contains reserved control tokens") | |
| if len(tokens) + max_new_tokens + 1 > model.config.context_length: | |
| raise ValueError("Prompt plus requested generation exceeds the configured context length") | |
| device = next(model.parameters()).device | |
| if device.type != "cuda": | |
| raise RuntimeError("PAT and FA generation require CUDA") | |
| generator = torch.Generator(device=device).manual_seed(seed) | |
| model.eval() | |
| generated = [] | |
| stop_reason = "length" | |
| with torch.autocast("cuda", dtype=torch.bfloat16): | |
| # The final selected token is returned without another forward pass. | |
| cache = create_cache(model, tokens, capacity=len(tokens) + max_new_tokens) | |
| for index in range(max_new_tokens): | |
| token = sample(cache.next_token_logits, temperature, top_p, generator) | |
| generated.append(token) | |
| if token == EOD_ID: | |
| stop_reason = "end_of_document" | |
| break | |
| if index + 1 < max_new_tokens: | |
| cache.append(token) | |
| return {"text": tokenizer.decode(generated), "token_ids": generated, | |
| "prompt_tokens": len(tokens), "generated_tokens": len(generated), "stop_reason": stop_reason} | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--checkpoint", type=Path, required=True, help="Verified released checkpoint directory") | |
| parser.add_argument("--prompt", required=True, help="Raw text prefix; no chat template is inserted") | |
| parser.add_argument("--max-new-tokens", type=int, default=128, help="Maximum generated tokens") | |
| parser.add_argument("--temperature", type=float, default=0.0, help="0 selects deterministic greedy decoding") | |
| parser.add_argument("--top-p", type=float, default=0.95, help="Nucleus mass for positive temperatures") | |
| parser.add_argument("--seed", type=int, default=42, help="Sampling seed") | |
| args = parser.parse_args() | |
| model = load_checkpoint(args.checkpoint, device="cuda") | |
| result = generate(model, args.prompt, tokenizer=Tokenizer(args.checkpoint / "tokenizer.json"), | |
| max_new_tokens=args.max_new_tokens, temperature=args.temperature, | |
| top_p=args.top_p, seed=args.seed) | |
| print(json.dumps(result, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |