Text Generation
PyTorch
English
File size: 4,005 Bytes
2d1f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import json
from pathlib import Path

import torch
from tokenizers import Tokenizer

from model import SupernovaTinyArc


def sample_next_token(logits, temperature=0.8, top_k=50, top_p=0.9):
    if temperature <= 0:
        return torch.argmax(logits, dim=-1, keepdim=True)

    logits = logits / temperature

    if top_k > 0:
        k = min(top_k, logits.size(-1))
        threshold = torch.topk(logits, k).values[..., -1, None]
        logits = logits.masked_fill(logits < threshold, float("-inf"))

    if 0 < top_p < 1:
        sorted_logits, sorted_indices = torch.sort(
            logits, descending=True, dim=-1
        )
        cumulative_probs = torch.softmax(
            sorted_logits, dim=-1
        ).cumsum(dim=-1)

        sorted_indices_to_remove = cumulative_probs > top_p
        sorted_indices_to_remove[..., 1:] = (
            sorted_indices_to_remove[..., :-1].clone()
        )
        sorted_indices_to_remove[..., 0] = False

        indices_to_remove = torch.zeros_like(
            logits, dtype=torch.bool
        )
        indices_to_remove.scatter_(
            -1, sorted_indices, sorted_indices_to_remove
        )
        logits = logits.masked_fill(
            indices_to_remove, float("-inf")
        )

    probabilities = torch.softmax(logits, dim=-1)
    return torch.multinomial(probabilities, num_samples=1)


def generate(
    model,
    tokenizer,
    prompt,
    device,
    max_new_tokens=200,
    temperature=0.8,
    top_k=50,
    top_p=0.9,
):
    input_ids = tokenizer.encode(prompt).ids

    if not input_ids:
        raise ValueError("The prompt produced no tokens.")

    ids = torch.tensor(
        [input_ids], dtype=torch.long, device=device
    )

    eos_id = tokenizer.token_to_id("[EOS]")
    max_seq_len = model.config["max_seq_len"]

    model.eval()

    with torch.no_grad():
        for _ in range(max_new_tokens):
            context = ids[:, -max_seq_len:]
            logits, _ = model(context)

            next_token = sample_next_token(
                logits[:, -1, :],
                temperature=temperature,
                top_k=top_k,
                top_p=top_p,
            )

            ids = torch.cat([ids, next_token], dim=1)

            if eos_id is not None and next_token.item() == eos_id:
                break

    return tokenizer.decode(
        ids[0].tolist(),
        skip_special_tokens=True
    )


def main():
    parser = argparse.ArgumentParser(
        description="Generate text with Supernova-tinyArc."
    )
    parser.add_argument("--prompt", required=True)
    parser.add_argument("--checkpoint", default="checkpoints/base/best.pt")
    parser.add_argument("--max-new-tokens", type=int, default=200)
    parser.add_argument("--temperature", type=float, default=0.8)
    parser.add_argument("--top-k", type=int, default=50)
    parser.add_argument("--top-p", type=float, default=0.9)
    parser.add_argument("--device", default=None)

    args = parser.parse_args()

    root = Path(__file__).resolve().parent
    device = args.device or (
        "cuda" if torch.cuda.is_available() else "cpu"
    )

    with open(root / "config/model.json", encoding="utf-8") as f:
        config = json.load(f)

    tokenizer = Tokenizer.from_file(
        str(root / "tokenizer/tokenizer.json")
    )

    checkpoint_path = Path(args.checkpoint)
    if not checkpoint_path.is_absolute():
        checkpoint_path = root / checkpoint_path

    checkpoint = torch.load(
        checkpoint_path,
        map_location="cpu",
        weights_only=False,
    )

    model = SupernovaTinyArc(config)
    model.load_state_dict(checkpoint["model"], strict=True)
    model.to(device)
    model.eval()

    print(generate(
        model=model,
        tokenizer=tokenizer,
        prompt=args.prompt,
        device=device,
        max_new_tokens=args.max_new_tokens,
        temperature=args.temperature,
        top_k=args.top_k,
        top_p=args.top_p,
    ))


if __name__ == "__main__":
    main()