Elffuss BraidHub

kikocis/llama-stack public

bb9be718c121 · 13.7 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 (
28 InterleavedTextMedia,
29 Message,
30 ToolPromptFormat,
31)
32from llama_models.llama3.api.tokenizer import Tokenizer
33from llama_models.llama3.reference_impl.model import Transformer
34from llama_models.llama3.reference_impl.multimodal.model import (
35 CrossAttentionTransformer,
36)
37from llama_models.sku_list import resolve_model
38from termcolor import cprint
39
40from llama_stack.apis.inference import QuantizationType
41
42from llama_stack.distribution.utils.model_utils import model_local_dir
43
44from .config import MetaReferenceImplConfig
45
46
47def model_checkpoint_dir(model) -> str:
48 checkpoint_dir = Path(model_local_dir(model.descriptor()))
49
50 paths = [Path(checkpoint_dir / f"consolidated.{ext}") for ext in ["pth", "00.pth"]]
51 if not any(p.exists() for p in paths):
52 checkpoint_dir = checkpoint_dir / "original"
53
54 assert checkpoint_dir.exists(), (
55 f"Could not find checkpoint dir: {checkpoint_dir}."
56 f"Please download model using `llama download {model.descriptor()}`"
57 )
58 return str(checkpoint_dir)
59
60
61@dataclass
62class TokenResult:
63 token: int
64 text: str
65 logprobs: Optional[List[float]] = None
66
67
68class Llama:
69 @staticmethod
70 def build(config: MetaReferenceImplConfig):
71 """
72 Build a Llama instance by initializing and loading a model checkpoint.
73
74 Note:
75 This method initializes the distributed process group, sets the device to CUDA,
76 and loads the pre-trained model and tokenizer.
77 """
78 model = resolve_model(config.model)
79
80 if (
81 config.quantization
82 and config.quantization.type == QuantizationType.fp8.value
83 ):
84 from .quantization.loader import is_fbgemm_available
85
86 if not is_fbgemm_available():
87 raise ImportError("fbgemm-gpu is required for FP8 quantization")
88
89 if not torch.distributed.is_initialized():
90 torch.distributed.init_process_group("nccl")
91
92 model_parallel_size = config.model_parallel_size
93
94 if not model_parallel_is_initialized():
95 initialize_model_parallel(model_parallel_size)
96
97 local_rank = int(os.environ.get("LOCAL_RANK", 0))
98 torch.cuda.set_device(local_rank)
99
100 # seed must be the same in all processes
101 if config.torch_seed is not None:
102 torch.manual_seed(config.torch_seed)
103
104 if local_rank > 0:
105 sys.stdout = open(os.devnull, "w")
106
107 start_time = time.time()
108 ckpt_dir = model_checkpoint_dir(model)
109
110 checkpoints = sorted(Path(ckpt_dir).glob("*.pth"))
111 assert len(checkpoints) > 0, f"no checkpoint files found in {ckpt_dir}"
112 assert model_parallel_size == len(
113 checkpoints
114 ), f"Loading a checkpoint for MP={len(checkpoints)} but world size is {model_parallel_size}"
115 ckpt_path = checkpoints[get_model_parallel_rank()]
116 state_dict = torch.load(ckpt_path, map_location="cpu", weights_only=True)
117 with open(Path(ckpt_dir) / "params.json", "r") as f:
118 params = json.loads(f.read())
119
120 if "model" in params:
121 params = params["model"]
122
123 model_args: ModelArgs = ModelArgs(
124 max_seq_len=config.max_seq_len,
125 max_batch_size=config.max_batch_size,
126 **params,
127 )
128
129 tokenizer_path = os.path.join(ckpt_dir, "tokenizer.model")
130 tokenizer = Tokenizer(model_path=tokenizer_path)
131
132 assert (
133 model_args.vocab_size == tokenizer.n_words
134 ), f"model_args vocab = {model_args.vocab_size} but tokenizer vocab = {tokenizer.n_words}"
135
136 fp8 = (
137 config.quantization
138 and config.quantization.type == QuantizationType.fp8.value
139 )
140
141 if fp8:
142 from .quantization.loader import convert_to_quantized_model
143
144 # load on CPU in bf16 so that fp8 conversion does not find an
145 # unexpected (fp32, e.g.) datatype
146 torch.set_default_tensor_type(torch.BFloat16Tensor)
147 if model_args.vision_chunk_size > 0:
148 model = CrossAttentionTransformer(model_args)
149 model.setup_cache(model_args.max_batch_size, torch.bfloat16)
150 else:
151 model = Transformer(model_args)
152 model.load_state_dict(state_dict, strict=False)
153 model = convert_to_quantized_model(model, config)
154 else:
155 if torch.cuda.is_bf16_supported():
156 torch.set_default_tensor_type(torch.cuda.BFloat16Tensor)
157 else:
158 torch.set_default_tensor_type(torch.cuda.HalfTensor)
159 if model_args.vision_chunk_size > 0:
160 model = CrossAttentionTransformer(model_args)
161 model.setup_cache(model_args.max_batch_size, torch.bfloat16)
162 else:
163 model = Transformer(model_args)
164 model.load_state_dict(state_dict, strict=False)
165
166 print(f"Loaded in {time.time() - start_time:.2f} seconds")
167 return Llama(model, tokenizer, model_args)
168
169 def __init__(self, model: Transformer, tokenizer: Tokenizer, args: ModelArgs):
170 self.args = args
171 self.model = model
172 self.tokenizer = tokenizer
173 self.formatter = ChatFormat(tokenizer)
174
175 @torch.inference_mode()
176 def generate(
177 self,
178 model_input: ModelInput,
179 max_gen_len: int,
180 temperature: float = 0.6,
181 top_p: float = 0.9,
182 logprobs: bool = False,
183 echo: bool = False,
184 include_stop_token: bool = False,
185 ) -> Generator:
186 params = self.model.params
187
188 # input_tokens = [
189 # self.formatter.vision_token if t == 128256 else t
190 # for t in model_input.tokens
191 # ]
192 # cprint("Input to model -> " + self.tokenizer.decode(input_tokens), "red")
193 prompt_tokens = [model_input.tokens]
194
195 bsz = 1
196 assert bsz <= params.max_batch_size, (bsz, params.max_batch_size)
197
198 min_prompt_len = min(len(t) for t in prompt_tokens)
199 max_prompt_len = max(len(t) for t in prompt_tokens)
200
201 if max_prompt_len >= params.max_seq_len:
202 cprint(
203 f"Out of token budget {max_prompt_len} vs {params.max_seq_len}", "red"
204 )
205 return
206
207 total_len = min(max_gen_len + max_prompt_len, params.max_seq_len)
208
209 is_vision = isinstance(self.model, CrossAttentionTransformer)
210 if is_vision:
211 images = model_input.vision.images if model_input.vision is not None else []
212 mask = model_input.vision.mask if model_input.vision is not None else []
213
214 # the method works for bsz > 1 so add a batch dimension
215 xattn_caches, cross_attention_masks, full_text_row_masked_out_mask = (
216 self.model.compute_vision_tokens_masks(
217 batch_images=[images],
218 batch_masks=[mask],
219 total_len=total_len,
220 )
221 )
222
223 pad_id = self.tokenizer.pad_id
224 tokens = torch.full((bsz, total_len), pad_id, dtype=torch.long, device="cuda")
225 for k, t in enumerate(prompt_tokens):
226 tokens[k, : len(t)] = torch.tensor(t, dtype=torch.long, device="cuda")
227 if logprobs:
228 token_logprobs = torch.zeros_like(tokens, dtype=torch.float)
229
230 prev_pos = 0
231 eos_reached = torch.tensor([False] * bsz, device="cuda")
232 input_text_mask = tokens != pad_id
233 if min_prompt_len == total_len:
234 # TODO(ashwin): unify this branch with the one below and figure out multimodal crap
235 logits = self.model.forward(tokens, prev_pos)
236 token_logprobs = -F.cross_entropy(
237 input=logits.transpose(1, 2),
238 target=tokens,
239 reduction="none",
240 ignore_index=pad_id,
241 )
242
243 stop_tokens = torch.tensor(self.tokenizer.stop_tokens)
244
245 for cur_pos in range(min_prompt_len, total_len):
246 if is_vision:
247 position_ids = torch.arange(
248 prev_pos, cur_pos, dtype=torch.long, device="cuda"
249 )
250 logits = self.model.forward(
251 position_ids,
252 tokens,
253 cross_attention_masks,
254 full_text_row_masked_out_mask,
255 xattn_caches,
256 )
257 else:
258 logits = self.model.forward(tokens[:, prev_pos:cur_pos], prev_pos)
259
260 if temperature > 0:
261 probs = torch.softmax(logits[:, -1] / temperature, dim=-1)
262 next_token = sample_top_p(probs, top_p)
263 else:
264 next_token = torch.argmax(logits[:, -1], dim=-1)
265
266 next_token = next_token.reshape(-1)
267 # only replace token if prompt has already been generated
268 next_token = torch.where(
269 input_text_mask[:, cur_pos], tokens[:, cur_pos], next_token
270 )
271 tokens[:, cur_pos] = next_token
272
273 target = tokens[:, prev_pos + 1 : cur_pos + 1]
274 if is_vision:
275 # the logits space (num_classes) is designed to never contain a media_token
276 # however our input token stream does contain them. we need to nuke them here
277 # or else the CUDA kernels will crash with an illegal memory access
278 vision_tokens = [self.tokenizer.special_tokens["<|image|>"], 128256]
279 masks = [target.eq(t) for t in vision_tokens]
280 if len(masks) > 1:
281 mask = torch.logical_or(*masks)
282 else:
283 mask = masks[0]
284 target[mask] = 0
285
286 if logprobs:
287 token_logprobs[:, prev_pos + 1 : cur_pos + 1] = -F.cross_entropy(
288 input=logits.transpose(1, 2),
289 target=tokens[:, prev_pos + 1 : cur_pos + 1],
290 reduction="none",
291 ignore_index=pad_id,
292 )
293 eos_reached |= (~input_text_mask[:, cur_pos]) & (
294 torch.isin(next_token, stop_tokens)
295 )
296 yield TokenResult(
297 token=next_token[0].item(),
298 text=self.tokenizer.decode(next_token.tolist()),
299 logprobs=(
300 token_logprobs[:, prev_pos + 1 : cur_pos + 1][0].tolist()
301 if logprobs
302 else None
303 ),
304 )
305
306 prev_pos = cur_pos
307 if all(eos_reached):
308 break
309
310 def text_completion(
311 self,
312 content: InterleavedTextMedia,
313 temperature: float = 0.6,
314 top_p: float = 0.9,
315 max_gen_len: Optional[int] = None,
316 logprobs: bool = False,
317 echo: bool = False,
318 ) -> Generator:
319 if (
320 max_gen_len is None
321 or max_gen_len == 0
322 or max_gen_len >= self.model.params.max_seq_len
323 ):
324 max_gen_len = self.model.params.max_seq_len - 1
325
326 model_input = self.formatter.encode_content(content)
327
328 yield from self.generate(
329 model_input=model_input,
330 max_gen_len=max_gen_len,
331 temperature=temperature,
332 top_p=top_p,
333 logprobs=logprobs,
334 echo=echo,
335 )
336
337 def chat_completion(
338 self,
339 messages: List[Message],
340 temperature: float = 0.6,
341 top_p: float = 0.9,
342 max_gen_len: Optional[int] = None,
343 logprobs: bool = False,
344 tool_prompt_format: ToolPromptFormat = ToolPromptFormat.json,
345 ) -> Generator:
346 if (
347 max_gen_len is None
348 or max_gen_len == 0
349 or max_gen_len >= self.model.params.max_seq_len
350 ):
351 max_gen_len = self.model.params.max_seq_len - 1
352
353 yield from self.generate(
354 model_input=self.formatter.encode_dialog_prompt(
355 messages,
356 tool_prompt_format,
357 ),
358 max_gen_len=max_gen_len,
359 temperature=temperature,
360 top_p=top_p,
361 logprobs=logprobs,
362 include_stop_token=True,
363 )
364
365
366def sample_top_p(probs, p):
367 """
368 Perform top-p (nucleus) sampling on a probability distribution.
369
370 Args:
371 probs (torch.Tensor): Probability distribution tensor.
372 p (float): Probability threshold for top-p sampling.
373
374 Returns:
375 torch.Tensor: Sampled token indices.
376
377 Note:
378 Top-p sampling selects the smallest set of tokens whose cumulative probability mass
379 exceeds the threshold p. The distribution is renormalized based on the selected tokens.
380 """
381 probs_sort, probs_idx = torch.sort(probs, dim=-1, descending=True)
382 probs_sum = torch.cumsum(probs_sort, dim=-1)
383 mask = probs_sum - probs_sort > p
384 probs_sort[mask] = 0.0
385 probs_sort.div_(probs_sort.sum(dim=-1, keepdim=True))
386 next_token = torch.multinomial(probs_sort, num_samples=1)
387 next_token = torch.gather(probs_idx, -1, next_token)
388 return next_token