Add files using upload-large-folder tool
Browse files- inference/generate.py +137 -0
inference/generate.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
from argparse import ArgumentParser
|
4 |
+
from typing import List
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.distributed as dist
|
8 |
+
from transformers import AutoTokenizer
|
9 |
+
from safetensors.torch import load_model
|
10 |
+
|
11 |
+
from model import Transformer, ModelArgs
|
12 |
+
|
13 |
+
|
14 |
+
def sample(logits, temperature: float = 1.0):
|
15 |
+
logits = logits / max(temperature, 1e-5)
|
16 |
+
probs = torch.softmax(logits, dim=-1)
|
17 |
+
return probs.div_(torch.empty_like(probs).exponential_(1)).argmax(dim=-1)
|
18 |
+
|
19 |
+
|
20 |
+
@torch.inference_mode()
|
21 |
+
def generate(
|
22 |
+
model: Transformer,
|
23 |
+
prompt_tokens: List[List[int]],
|
24 |
+
max_new_tokens: int,
|
25 |
+
eos_id: int,
|
26 |
+
temperature: float = 1.0
|
27 |
+
) -> List[List[int]]:
|
28 |
+
prompt_lens = [len(t) for t in prompt_tokens]
|
29 |
+
assert max(prompt_lens) <= model.max_seq_len
|
30 |
+
total_len = min(model.max_seq_len, max_new_tokens + max(prompt_lens))
|
31 |
+
tokens = torch.full((len(prompt_tokens), total_len), -1, dtype=torch.long, device="cuda")
|
32 |
+
for i, t in enumerate(prompt_tokens):
|
33 |
+
tokens[i, :len(t)] = torch.tensor(t, dtype=torch.long, device="cuda")
|
34 |
+
prev_pos = 0
|
35 |
+
finished = torch.tensor([False] * len(prompt_tokens), device="cuda")
|
36 |
+
prompt_mask = tokens != -1
|
37 |
+
for cur_pos in range(min(prompt_lens), total_len):
|
38 |
+
logits = model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
|
39 |
+
if temperature > 0:
|
40 |
+
next_token = sample(logits, temperature)
|
41 |
+
else:
|
42 |
+
next_token = logits.argmax(dim=-1)
|
43 |
+
next_token = torch.where(prompt_mask[:, cur_pos], tokens[:, cur_pos], next_token)
|
44 |
+
tokens[:, cur_pos] = next_token
|
45 |
+
finished |= torch.logical_and(~prompt_mask[:, cur_pos], next_token == eos_id)
|
46 |
+
prev_pos = cur_pos
|
47 |
+
if finished.all():
|
48 |
+
break
|
49 |
+
completion_tokens = []
|
50 |
+
for i, toks in enumerate(tokens.tolist()):
|
51 |
+
toks = toks[prompt_lens[i]:prompt_lens[i]+max_new_tokens]
|
52 |
+
if eos_id in toks:
|
53 |
+
toks = toks[:toks.index(eos_id)]
|
54 |
+
completion_tokens.append(toks)
|
55 |
+
return completion_tokens
|
56 |
+
|
57 |
+
|
58 |
+
def main(
|
59 |
+
ckpt_path: str,
|
60 |
+
config: str,
|
61 |
+
input_file: str = "",
|
62 |
+
interactive: bool = True,
|
63 |
+
max_new_tokens: int = 100,
|
64 |
+
temperature: float = 1.0,
|
65 |
+
) -> None:
|
66 |
+
world_size = int(os.getenv("WORLD_SIZE", "1"))
|
67 |
+
rank = int(os.getenv("RANK", "0"))
|
68 |
+
local_rank = int(os.getenv("LOCAL_RANK", "0"))
|
69 |
+
if world_size > 1:
|
70 |
+
dist.init_process_group("nccl")
|
71 |
+
global print
|
72 |
+
if rank != 0:
|
73 |
+
print = lambda *_, **__: None
|
74 |
+
torch.cuda.set_device(local_rank)
|
75 |
+
torch.set_default_dtype(torch.bfloat16)
|
76 |
+
torch.set_num_threads(8)
|
77 |
+
torch.manual_seed(965)
|
78 |
+
with open(config) as f:
|
79 |
+
args = ModelArgs(**json.load(f))
|
80 |
+
print(args)
|
81 |
+
with torch.device("cuda"):
|
82 |
+
model = Transformer(args)
|
83 |
+
tokenizer = AutoTokenizer.from_pretrained(ckpt_path)
|
84 |
+
tokenizer.decode(generate(model, [tokenizer.encode("DeepSeek")], 2, -1, 1.)[0])
|
85 |
+
load_model(model, os.path.join(ckpt_path, f"model{rank}-mp{world_size}.safetensors"))
|
86 |
+
|
87 |
+
if interactive:
|
88 |
+
messages = []
|
89 |
+
while True:
|
90 |
+
if world_size == 1:
|
91 |
+
prompt = input(">>> ")
|
92 |
+
elif rank == 0:
|
93 |
+
prompt = input(">>> ")
|
94 |
+
objects = [prompt]
|
95 |
+
dist.broadcast_object_list(objects, 0)
|
96 |
+
else:
|
97 |
+
objects = [None]
|
98 |
+
dist.broadcast_object_list(objects, 0)
|
99 |
+
prompt = objects[0]
|
100 |
+
if prompt == "/exit":
|
101 |
+
break
|
102 |
+
elif prompt == "/clear":
|
103 |
+
messages.clear()
|
104 |
+
continue
|
105 |
+
messages.append({"role": "user", "content": prompt})
|
106 |
+
prompt_tokens = tokenizer.apply_chat_template(messages, add_generation_prompt=True)
|
107 |
+
completion_tokens = generate(model, [prompt_tokens], max_new_tokens, tokenizer.eos_token_id, temperature)
|
108 |
+
completion = tokenizer.decode(completion_tokens[0], skip_special_tokens=True)
|
109 |
+
print(completion)
|
110 |
+
messages.append({"role": "assistant", "content": completion})
|
111 |
+
else:
|
112 |
+
with open(input_file) as f:
|
113 |
+
prompts = [line.strip() for line in f.readlines()]
|
114 |
+
assert len(prompts) <= args.max_batch_size
|
115 |
+
prompt_tokens = [tokenizer.apply_chat_template([{"role": "user", "content": prompt}], add_generation_prompt=True) for prompt in prompts]
|
116 |
+
completion_tokens = generate(model, prompt_tokens, max_new_tokens, tokenizer.eos_token_id, temperature)
|
117 |
+
completions = tokenizer.batch_decode(completion_tokens, skip_special_tokens=True)
|
118 |
+
for prompt, completion in zip(prompts, completions):
|
119 |
+
print("Prompt:", prompt)
|
120 |
+
print("Completion:", completion)
|
121 |
+
print()
|
122 |
+
|
123 |
+
if world_size > 1:
|
124 |
+
dist.destroy_process_group()
|
125 |
+
|
126 |
+
|
127 |
+
if __name__ == "__main__":
|
128 |
+
parser = ArgumentParser()
|
129 |
+
parser.add_argument("--ckpt-path", type=str, required=True)
|
130 |
+
parser.add_argument("--config", type=str, required=True)
|
131 |
+
parser.add_argument("--input-file", type=str, default="")
|
132 |
+
parser.add_argument("--interactive", action="store_true")
|
133 |
+
parser.add_argument("--max-new-tokens", type=int, default=200)
|
134 |
+
parser.add_argument("--temperature", type=float, default=0.2)
|
135 |
+
args = parser.parse_args()
|
136 |
+
assert args.input_file or args.interactive
|
137 |
+
main(args.ckpt_path, args.config, args.input_file, args.interactive, args.max_new_tokens, args.temperature)
|