Elffuss BraidHub

kikocis/llama-stack public

842c3e3bbdd0 · 11.3 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7# Copyright (c) Meta Platforms, Inc. and affiliates.
8# This software may be used and distributed in accordance with the terms of the Llama 3 Community License Agreement.
9
10import json
11import os
12import sys
13import time
14from dataclasses import dataclass
15from pathlib import Path
16from typing import Generator, List, Optional
17
18import torch
19import torch.nn.functional as F
20from fairscale.nn.model_parallel.initialize import (
21 get_model_parallel_rank,
22 initialize_model_parallel,
23 model_parallel_is_initialized,
24)
25from llama_models.llama3.api.args import ModelArgs
26from llama_models.llama3.api.chat_format import ChatFormat, ModelInput
27from llama_models.llama3.api.datatypes import Message, ToolPromptFormat
28from llama_models.llama3.api.tokenizer import Tokenizer
29from llama_models.llama3.reference_impl.model import Transformer
30from llama_models.sku_list import resolve_model
31from llama_stack.apis.inference import QuantizationType
32
33from llama_stack.distribution.utils.model_utils import model_local_dir
34from termcolor import cprint
35
36from .config import MetaReferenceImplConfig
37
38
39def model_checkpoint_dir(model) -> str:
40 checkpoint_dir = Path(model_local_dir(model.descriptor()))
41 if not Path(checkpoint_dir / "consolidated.00.pth").exists():
42 checkpoint_dir = checkpoint_dir / "original"
43
44 assert checkpoint_dir.exists(), (
45 f"Could not find checkpoint dir: {checkpoint_dir}."
46 f"Please download model using `llama download {model.descriptor()}`"
47 )
48 return str(checkpoint_dir)
49
50
51@dataclass
52class TokenResult:
53 token: int
54 text: str
55 logprobs: Optional[List[float]] = None
56
57
58class Llama:
59 @staticmethod
60 def build(config: MetaReferenceImplConfig):
61 """
62 Build a Llama instance by initializing and loading a model checkpoint.
63
64 Note:
65 This method initializes the distributed process group, sets the device to CUDA,
66 and loads the pre-trained model and tokenizer.
67 """
68 model = resolve_model(config.model)
69
70 if (
71 config.quantization
72 and config.quantization.type == QuantizationType.fp8.value
73 ):
74 from .quantization.loader import is_fbgemm_available
75
76 if not is_fbgemm_available():
77 raise ImportError("fbgemm-gpu is required for FP8 quantization")
78
79 if not torch.distributed.is_initialized():
80 torch.distributed.init_process_group("nccl")
81
82 model_parallel_size = config.model_parallel_size
83
84 if not model_parallel_is_initialized():
85 initialize_model_parallel(model_parallel_size)
86
87 local_rank = int(os.environ.get("LOCAL_RANK", 0))
88 torch.cuda.set_device(local_rank)
89
90 # seed must be the same in all processes
91 if config.torch_seed is not None:
92 torch.manual_seed(config.torch_seed)
93
94 if local_rank > 0:
95 sys.stdout = open(os.devnull, "w")
96
97 start_time = time.time()
98 ckpt_dir = model_checkpoint_dir(model)
99
100 checkpoints = sorted(Path(ckpt_dir).glob("*.pth"))
101 assert len(checkpoints) > 0, f"no checkpoint files found in {ckpt_dir}"
102 assert model_parallel_size == len(
103 checkpoints
104 ), f"Loading a checkpoint for MP={len(checkpoints)} but world size is {model_parallel_size}"
105 ckpt_path = checkpoints[get_model_parallel_rank()]
106 state_dict = torch.load(ckpt_path, map_location="cpu", weights_only=True)
107 with open(Path(ckpt_dir) / "params.json", "r") as f:
108 params = json.loads(f.read())
109
110 if "model" in params:
111 params = params["model"]
112
113 model_args: ModelArgs = ModelArgs(
114 max_seq_len=config.max_seq_len,
115 max_batch_size=config.max_batch_size,
116 **params,
117 )
118
119 tokenizer_path = os.path.join(ckpt_dir, "tokenizer.model")
120 tokenizer = Tokenizer(model_path=tokenizer_path)
121
122 assert (
123 model_args.vocab_size == tokenizer.n_words
124 ), f"model_args vocab = {model_args.vocab_size} but tokenizer vocab = {tokenizer.n_words}"
125
126 fp8 = (
127 config.quantization
128 and config.quantization.type == QuantizationType.fp8.value
129 )
130
131 if fp8:
132 from .quantization.loader import convert_to_quantized_model
133
134 # load on CPU in bf16 so that fp8 conversion does not find an
135 # unexpected (fp32, e.g.) datatype
136 torch.set_default_tensor_type(torch.BFloat16Tensor)
137 model = Transformer(model_args)
138 model.load_state_dict(state_dict, strict=False)
139 model = convert_to_quantized_model(model, config)
140 else:
141 if torch.cuda.is_bf16_supported():
142 torch.set_default_tensor_type(torch.cuda.BFloat16Tensor)
143 else:
144 torch.set_default_tensor_type(torch.cuda.HalfTensor)
145 model = Transformer(model_args)
146 model.load_state_dict(state_dict, strict=False)
147
148 print(f"Loaded in {time.time() - start_time:.2f} seconds")
149 return Llama(model, tokenizer, model_args)
150
151 def __init__(self, model: Transformer, tokenizer: Tokenizer, args: ModelArgs):
152 self.args = args
153 self.model = model
154 self.tokenizer = tokenizer
155 self.formatter = ChatFormat(tokenizer)
156
157 @torch.inference_mode()
158 def generate(
159 self,
160 model_input: ModelInput,
161 max_gen_len: int,
162 temperature: float = 0.6,
163 top_p: float = 0.9,
164 logprobs: bool = False,
165 echo: bool = False,
166 include_stop_token: bool = False,
167 ) -> Generator:
168 params = self.model.params
169
170 # cprint("Input to model -> " + self.tokenizer.decode(model_input.tokens), "red")
171 prompt_tokens = [model_input.tokens]
172
173 bsz = 1
174 assert bsz <= params.max_batch_size, (bsz, params.max_batch_size)
175
176 min_prompt_len = min(len(t) for t in prompt_tokens)
177 max_prompt_len = max(len(t) for t in prompt_tokens)
178
179 if max_prompt_len >= params.max_seq_len:
180 cprint(
181 f"Out of token budget {max_prompt_len} vs {params.max_seq_len}", "red"
182 )
183 return
184
185 total_len = min(max_gen_len + max_prompt_len, params.max_seq_len)
186 pad_id = self.tokenizer.pad_id
187 tokens = torch.full((bsz, total_len), pad_id, dtype=torch.long, device="cuda")
188 for k, t in enumerate(prompt_tokens):
189 tokens[k, : len(t)] = torch.tensor(t, dtype=torch.long, device="cuda")
190 if logprobs:
191 token_logprobs = torch.zeros_like(tokens, dtype=torch.float)
192
193 prev_pos = 0
194 eos_reached = torch.tensor([False] * bsz, device="cuda")
195 input_text_mask = tokens != pad_id
196 if min_prompt_len == total_len:
197 # TODO(ashwin): unify this branch with the one below and figure out multimodal crap
198 logits = self.model.forward(tokens, prev_pos)
199 token_logprobs = -F.cross_entropy(
200 input=logits.transpose(1, 2),
201 target=tokens,
202 reduction="none",
203 ignore_index=pad_id,
204 )
205
206 stop_tokens = torch.tensor(self.tokenizer.stop_tokens)
207
208 for cur_pos in range(min_prompt_len, total_len):
209 logits = self.model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
210
211 if temperature > 0:
212 probs = torch.softmax(logits[:, -1] / temperature, dim=-1)
213 next_token = sample_top_p(probs, top_p)
214 else:
215 next_token = torch.argmax(logits[:, -1], dim=-1)
216
217 next_token = next_token.reshape(-1)
218 # only replace token if prompt has already been generated
219 next_token = torch.where(
220 input_text_mask[:, cur_pos], tokens[:, cur_pos], next_token
221 )
222 tokens[:, cur_pos] = next_token
223
224 target = tokens[:, prev_pos + 1 : cur_pos + 1]
225 if logprobs:
226 token_logprobs[:, prev_pos + 1 : cur_pos + 1] = -F.cross_entropy(
227 input=logits.transpose(1, 2),
228 target=tokens[:, prev_pos + 1 : cur_pos + 1],
229 reduction="none",
230 ignore_index=pad_id,
231 )
232 eos_reached |= (~input_text_mask[:, cur_pos]) & (
233 torch.isin(next_token, stop_tokens)
234 )
235 yield TokenResult(
236 token=next_token[0].item(),
237 text=self.tokenizer.decode(next_token.tolist()),
238 logprobs=(
239 token_logprobs[:, prev_pos + 1 : cur_pos + 1][0].tolist()
240 if logprobs
241 else None
242 ),
243 )
244
245 prev_pos = cur_pos
246 if all(eos_reached):
247 break
248
249 def text_completion(
250 self,
251 prompt: str,
252 temperature: float = 0.6,
253 top_p: float = 0.9,
254 max_gen_len: Optional[int] = None,
255 logprobs: bool = False,
256 echo: bool = False,
257 ) -> Generator:
258 if (
259 max_gen_len is None
260 or max_gen_len == 0
261 or max_gen_len >= self.model.params.max_seq_len
262 ):
263 max_gen_len = self.model.params.max_seq_len - 1
264
265 prompt_tokens = self.tokenizer.encode(prompt, bos=True, eos=False)
266
267 yield from self.generate(
268 model_input=ModelInput(tokens=prompt_tokens),
269 max_gen_len=max_gen_len,
270 temperature=temperature,
271 top_p=top_p,
272 logprobs=logprobs,
273 echo=echo,
274 )
275
276 def chat_completion(
277 self,
278 messages: List[Message],
279 temperature: float = 0.6,
280 top_p: float = 0.9,
281 max_gen_len: Optional[int] = None,
282 logprobs: bool = False,
283 tool_prompt_format: ToolPromptFormat = ToolPromptFormat.json,
284 ) -> Generator:
285 if (
286 max_gen_len is None
287 or max_gen_len == 0
288 or max_gen_len >= self.model.params.max_seq_len
289 ):
290 max_gen_len = self.model.params.max_seq_len - 1
291
292 yield from self.generate(
293 model_input=self.formatter.encode_dialog_prompt(
294 messages,
295 tool_prompt_format,
296 ),
297 max_gen_len=max_gen_len,
298 temperature=temperature,
299 top_p=top_p,
300 logprobs=logprobs,
301 include_stop_token=True,
302 )
303
304
305def sample_top_p(probs, p):
306 """
307 Perform top-p (nucleus) sampling on a probability distribution.
308
309 Args:
310 probs (torch.Tensor): Probability distribution tensor.
311 p (float): Probability threshold for top-p sampling.
312
313 Returns:
314 torch.Tensor: Sampled token indices.
315
316 Note:
317 Top-p sampling selects the smallest set of tokens whose cumulative probability mass
318 exceeds the threshold p. The distribution is renormalized based on the selected tokens.
319 """
320 probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
321 probs_sum = torch.cumsum(probs_sort, dim=-1)
322 mask = probs_sum - probs_sort > p
323 probs_sort[mask] = 0.0
324 probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
325 next_token = torch.multinomial(probs_sort, num_samples=1)
326 next_token = torch.gather(probs_idx, -1, next_token)
327 return next_token