Elffuss BraidHub

kikocis/llama-stack public

6513a722f4e4 · 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 termcolor import cprint
32
33from llama_toolchain.common.model_utils import model_local_dir
34from llama_toolchain.inference.api import QuantizationType
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 if not model_parallel_is_initialized():
84 initialize_model_parallel(model_parallel_size)
85
86 local_rank = int(os.environ.get("LOCAL_RANK", 0))
87 torch.cuda.set_device(local_rank)
88
89 # seed must be the same in all processes
90 if config.torch_seed is not None:
91 torch.manual_seed(config.torch_seed)
92
93 if local_rank > 0:
94 sys.stdout = open(os.devnull, "w")
95
96 start_time = time.time()
97 ckpt_dir = model_checkpoint_dir(model)
98
99 checkpoints = sorted(Path(ckpt_dir).glob("*.pth"))
100 assert len(checkpoints) > 0, f"no checkpoint files found in {ckpt_dir}"
101 assert model_parallel_size == len(
102 checkpoints
103 ), f"Loading a checkpoint for MP={len(checkpoints)} but world size is {model_parallel_size}"
104 ckpt_path = checkpoints[get_model_parallel_rank()]
105 state_dict = torch.load(ckpt_path, map_location="cpu", weights_only=True)
106 with open(Path(ckpt_dir) / "params.json", "r") as f:
107 params = json.loads(f.read())
108
109 if "model" in params:
110 params = params["model"]
111
112 model_args: ModelArgs = ModelArgs(
113 max_seq_len=config.max_seq_len,
114 max_batch_size=config.max_batch_size,
115 **params,
116 )
117
118 tokenizer_path = os.path.join(ckpt_dir, "tokenizer.model")
119 tokenizer = Tokenizer(model_path=tokenizer_path)
120
121 assert (
122 model_args.vocab_size == tokenizer.n_words
123 ), f"model_args vocab = {model_args.vocab_size} but tokenizer vocab = {tokenizer.n_words}"
124
125 fp8 = (
126 config.quantization
127 and config.quantization.type == QuantizationType.fp8.value
128 )
129
130 if fp8:
131 from .quantization.loader import convert_to_quantized_model
132
133 # load on CPU in bf16 so that fp8 conversion does not find an
134 # unexpected (fp32, e.g.) datatype
135 torch.set_default_tensor_type(torch.BFloat16Tensor)
136 model = Transformer(model_args)
137 model.load_state_dict(state_dict, strict=False)
138 model = convert_to_quantized_model(model, config)
139 else:
140 if torch.cuda.is_bf16_supported():
141 torch.set_default_tensor_type(torch.cuda.BFloat16Tensor)
142 else:
143 torch.set_default_tensor_type(torch.cuda.HalfTensor)
144 model = Transformer(model_args)
145 model.load_state_dict(state_dict, strict=False)
146
147 print(f"Loaded in {time.time() - start_time:.2f} seconds")
148 return Llama(model, tokenizer, model_args)
149
150 def __init__(self, model: Transformer, tokenizer: Tokenizer, args: ModelArgs):
151 self.args = args
152 self.model = model
153 self.tokenizer = tokenizer
154 self.formatter = ChatFormat(tokenizer)
155
156 @torch.inference_mode()
157 def generate(
158 self,
159 model_input: ModelInput,
160 max_gen_len: int,
161 temperature: float = 0.6,
162 top_p: float = 0.9,
163 logprobs: bool = False,
164 echo: bool = False,
165 include_stop_token: bool = False,
166 ) -> Generator:
167 params = self.model.params
168
169 # cprint("Input to model -> " + self.tokenizer.decode(model_input.tokens), "red")
170 prompt_tokens = [model_input.tokens]
171
172 bsz = 1
173 assert bsz <= params.max_batch_size, (bsz, params.max_batch_size)
174
175 min_prompt_len = min(len(t) for t in prompt_tokens)
176 max_prompt_len = max(len(t) for t in prompt_tokens)
177
178 if max_prompt_len >= params.max_seq_len:
179 cprint(
180 f"Out of token budget {max_prompt_len} vs {params.max_seq_len}", "red"
181 )
182 return
183
184 total_len = min(max_gen_len + max_prompt_len, params.max_seq_len)
185 pad_id = self.tokenizer.pad_id
186 tokens = torch.full((bsz, total_len), pad_id, dtype=torch.long, device="cuda")
187 for k, t in enumerate(prompt_tokens):
188 tokens[k, : len(t)] = torch.tensor(t, dtype=torch.long, device="cuda")
189 if logprobs:
190 token_logprobs = torch.zeros_like(tokens, dtype=torch.float)
191
192 prev_pos = 0
193 eos_reached = torch.tensor([False] * bsz, device="cuda")
194 input_text_mask = tokens != pad_id
195 if min_prompt_len == total_len:
196 # TODO(ashwin): unify this branch with the one below and figure out multimodal crap
197 logits = self.model.forward(tokens, prev_pos)
198 token_logprobs = -F.cross_entropy(
199 input=logits.transpose(1, 2),
200 target=tokens,
201 reduction="none",
202 ignore_index=pad_id,
203 )
204
205 stop_tokens = torch.tensor(self.tokenizer.stop_tokens)
206
207 for cur_pos in range(min_prompt_len, total_len):
208 logits = self.model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
209
210 if temperature > 0:
211 probs = torch.softmax(logits[:, -1] / temperature, dim=-1)
212 next_token = sample_top_p(probs, top_p)
213 else:
214 next_token = torch.argmax(logits[:, -1], dim=-1)
215
216 next_token = next_token.reshape(-1)
217 # only replace token if prompt has already been generated
218 next_token = torch.where(
219 input_text_mask[:, cur_pos], tokens[:, cur_pos], next_token
220 )
221 tokens[:, cur_pos] = next_token
222
223 target = tokens[:, prev_pos + 1 : cur_pos + 1]
224 if logprobs:
225 token_logprobs[:, prev_pos + 1 : cur_pos + 1] = -F.cross_entropy(
226 input=logits.transpose(1, 2),
227 target=tokens[:, prev_pos + 1 : cur_pos + 1],
228 reduction="none",
229 ignore_index=pad_id,
230 )
231 eos_reached |= (~input_text_mask[:, cur_pos]) & (
232 torch.isin(next_token, stop_tokens)
233 )
234 yield TokenResult(
235 token=next_token[0].item(),
236 text=self.tokenizer.decode(next_token.tolist()),
237 logprobs=(
238 token_logprobs[:, prev_pos + 1 : cur_pos + 1][0].tolist()
239 if logprobs
240 else None
241 ),
242 )
243
244 prev_pos = cur_pos
245 if all(eos_reached):
246 break
247
248 def text_completion(
249 self,
250 prompt: str,
251 temperature: float = 0.6,
252 top_p: float = 0.9,
253 max_gen_len: Optional[int] = None,
254 logprobs: bool = False,
255 echo: bool = False,
256 ) -> Generator:
257 if (
258 max_gen_len is None
259 or max_gen_len == 0
260 or max_gen_len >= self.model.params.max_seq_len
261 ):
262 max_gen_len = self.model.params.max_seq_len - 1
263
264 prompt_tokens = self.tokenizer.encode(prompt, bos=True, eos=False)
265
266 yield from self.generate(
267 model_input=ModelInput(tokens=prompt_tokens),
268 max_gen_len=max_gen_len,
269 temperature=temperature,
270 top_p=top_p,
271 logprobs=logprobs,
272 echo=echo,
273 )
274
275 def chat_completion(
276 self,
277 messages: List[Message],
278 temperature: float = 0.6,
279 top_p: float = 0.9,
280 max_gen_len: Optional[int] = None,
281 logprobs: bool = False,
282 tool_prompt_format: ToolPromptFormat = ToolPromptFormat.json,
283 ) -> Generator:
284 if (
285 max_gen_len is None
286 or max_gen_len == 0
287 or max_gen_len >= self.model.params.max_seq_len
288 ):
289 max_gen_len = self.model.params.max_seq_len - 1
290
291 yield from self.generate(
292 model_input=self.formatter.encode_dialog_prompt(
293 messages,
294 tool_prompt_format,
295 ),
296 max_gen_len=max_gen_len,
297 temperature=temperature,
298 top_p=top_p,
299 logprobs=logprobs,
300 include_stop_token=True,
301 )
302
303
304def sample_top_p(probs, p):
305 """
306 Perform top-p (nucleus) sampling on a probability distribution.
307
308 Args:
309 probs (torch.Tensor): Probability distribution tensor.
310 p (float): Probability threshold for top-p sampling.
311
312 Returns:
313 torch.Tensor: Sampled token indices.
314
315 Note:
316 Top-p sampling selects the smallest set of tokens whose cumulative probability mass
317 exceeds the threshold p. The distribution is renormalized based on the selected tokens.
318 """
319 probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
320 probs_sum = torch.cumsum(probs_sort, dim=-1)
321 mask = probs_sum - probs_sort > p
322 probs_sort[mask] = 0.0
323 probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
324 next_token = torch.multinomial(probs_sort, num_samples=1)
325 next_token = torch.gather(probs_idx, -1, next_token)
326 return next_token