File size: 4,678 Bytes
643267a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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())


@torch.inference_mode()
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()