tpu_model_runner.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. import time
  2. from dataclasses import dataclass
  3. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union
  4. from unittest.mock import patch
  5. import numpy as np
  6. import torch
  7. import torch.nn as nn
  8. import torch_xla.core.xla_model as xm
  9. import torch_xla.runtime as xr
  10. from loguru import logger
  11. from aphrodite.attention import AttentionMetadata, get_attn_backend
  12. from aphrodite.common.config import (CacheConfig, DeviceConfig, LoadConfig,
  13. ModelConfig, MultiModalConfig,
  14. ParallelConfig, SchedulerConfig)
  15. from aphrodite.common.sequence import (CompletionSequenceGroupOutput,
  16. IntermediateTensors, Logprob,
  17. SamplerOutput, SequenceGroupMetadata,
  18. SequenceOutput)
  19. from aphrodite.modeling.model_loader import get_model
  20. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  21. from aphrodite.task_handler.model_runner_base import (
  22. ModelRunnerBase, ModelRunnerInputBase,
  23. _add_attn_metadata_broadcastable_dict,
  24. _init_attn_metadata_from_tensor_dict)
  25. if TYPE_CHECKING:
  26. from aphrodite.attention.backends.abstract import AttentionBackend
  27. # Here we utilize the behavior that out-of-bound index is ignored.
  28. # FIXME: Find a more reliable way to prevent possible bugs.
  29. _PAD_SLOT_ID = 1_000_000_000
  30. # FIXME: Temporarily disabled top-p sampling since it's too slow.
  31. _ENABLE_TOP_P = False
  32. # FIXME: A temporary hack to support `n > 1`.
  33. # This can significantly affect the performance if too large.
  34. _MAX_NUM_SAMPLES = 128
  35. @dataclass(frozen=True)
  36. class ModelInputForTPU(ModelRunnerInputBase):
  37. token_ids: torch.Tensor
  38. position_ids: torch.Tensor
  39. attn_metadata: AttentionMetadata
  40. input_lens: torch.Tensor
  41. t: torch.Tensor
  42. p: torch.Tensor
  43. num_samples: int
  44. best_of: List[int]
  45. seq_groups: List[List[int]]
  46. def as_broadcastable_tensor_dict(
  47. self) -> Dict[str, Union[int, torch.Tensor]]:
  48. tensor_dict = {
  49. "token_ids": self.token_ids,
  50. "position_ids": self.position_ids,
  51. "input_lens": self.input_lens,
  52. "t": self.t,
  53. "p": self.p,
  54. "num_samples": self.num_samples,
  55. "best_of": self.best_of,
  56. "seq_groups": self.seq_groups,
  57. "virtual_engine": self.virtual_engine,
  58. }
  59. _add_attn_metadata_broadcastable_dict(tensor_dict, self.attn_metadata)
  60. return tensor_dict
  61. @classmethod
  62. def from_broadcasted_tensor_dict(
  63. cls: Type["ModelInputForTPU"],
  64. tensor_dict: Dict[str, Any],
  65. attn_backend: Optional["AttentionBackend"] = None,
  66. ) -> "ModelInputForTPU":
  67. if attn_backend is not None:
  68. tensor_dict = _init_attn_metadata_from_tensor_dict(
  69. attn_backend, tensor_dict)
  70. return cls(**tensor_dict)
  71. class TPUModelRunner(ModelRunnerBase[ModelInputForTPU]):
  72. def __init__(
  73. self,
  74. model_config: ModelConfig,
  75. parallel_config: ParallelConfig,
  76. scheduler_config: SchedulerConfig,
  77. device_config: DeviceConfig,
  78. cache_config: CacheConfig,
  79. load_config: LoadConfig,
  80. multimodal_config: Optional[MultiModalConfig] = None,
  81. is_driver_worker: bool = False,
  82. ):
  83. self.model_config = model_config
  84. self.parallel_config = parallel_config
  85. self.scheduler_config = scheduler_config
  86. self.device_config = device_config
  87. self.cache_config = cache_config
  88. self.load_config = load_config
  89. self.multimodal_config = multimodal_config
  90. self.is_driver_worker = is_driver_worker
  91. self.block_size = self.cache_config.block_size
  92. self.max_num_blocks_per_seq = (self.model_config.max_model_len //
  93. self.block_size)
  94. self.block_tables = np.zeros(
  95. (self.scheduler_config.max_num_seqs, self.max_num_blocks_per_seq),
  96. dtype=np.int32)
  97. self.attn_backend = get_attn_backend(
  98. self.model_config.get_num_attention_heads(self.parallel_config),
  99. self.model_config.get_head_size(),
  100. self.model_config.get_num_kv_heads(self.parallel_config),
  101. self.model_config.get_sliding_window(),
  102. self.model_config.dtype,
  103. self.cache_config.cache_dtype,
  104. self.block_size,
  105. False,
  106. )
  107. def load_model(self) -> None:
  108. self.device = self.device_config.device
  109. # NOTE: While the executor assigns the TP ranks to the worker
  110. # process, the ranks can be different from the ranks internally assigned
  111. # by the xm runtime. Therefore, there is a mismatch in the rank
  112. # assignment between the gloo (cpu) runtime and the xm (tpu) runtime.
  113. # This is not a problem in linear layers because all-reduce is
  114. # rank-agnostic. However, it matters for all-gather as the ranks
  115. # determine the order of concatenating the output tensors.
  116. # As a workaround, we use the xm's rank assignment only when loading
  117. # the embedding weights.
  118. xm_tp_rank = xr.global_ordinal()
  119. with patch(
  120. "vllm.model_executor.layers.vocab_parallel_embedding."
  121. "get_tensor_model_parallel_rank",
  122. return_value=xm_tp_rank):
  123. model = get_model(
  124. model_config=self.model_config,
  125. load_config=self.load_config,
  126. device_config=self.device_config,
  127. parallel_config=self.parallel_config,
  128. cache_config=self.cache_config,
  129. scheduler_config=self.scheduler_config,
  130. multimodal_config=self.multimodal_config,
  131. lora_config=None,
  132. )
  133. model = model.eval()
  134. xm.wait_device_ops()
  135. model = ModelWrapper(model)
  136. # NOTE: There are two stages of compilation: torch.compile and
  137. # XLA compilation. Setting dynamic=True can reduce the torch.compile
  138. # overhead by reusing the FX graph for different shapes.
  139. # However, the XLA graph will still require static shapes and needs to
  140. # be re-compiled for every different shapes. This overhead is inevitable
  141. # in the first run, but can be skipped afterwards as we cache the XLA
  142. # graphs in the disk (APHRODITE_XLA_CACHE_PATH).
  143. self.model = torch.compile(model,
  144. backend="openxla",
  145. fullgraph=True,
  146. dynamic=True)
  147. def _dummy_run(
  148. self,
  149. batch_size: int,
  150. seq_len: int,
  151. kv_caches: List[Tuple[torch.Tensor, torch.Tensor]],
  152. is_prompt: bool,
  153. ) -> None:
  154. if is_prompt:
  155. seq_len = (seq_len + 15) // 16 * 16
  156. token_ids = torch.zeros((batch_size, seq_len),
  157. dtype=torch.int32,
  158. device=self.device)
  159. position_ids = torch.zeros((batch_size, seq_len),
  160. dtype=torch.int32,
  161. device=self.device)
  162. slot_mapping = torch.zeros((batch_size, seq_len),
  163. dtype=torch.int64,
  164. device=self.device)
  165. attn_metadata = self.attn_backend.make_metadata(
  166. num_prefills=batch_size,
  167. num_prefill_tokens=batch_size * seq_len,
  168. num_decode_tokens=0,
  169. slot_mapping=slot_mapping,
  170. block_tables=None,
  171. context_lens=None,
  172. )
  173. input_lens = torch.ones((batch_size, ),
  174. dtype=torch.int32,
  175. device=self.device)
  176. else:
  177. assert seq_len == 1
  178. token_ids = torch.zeros((batch_size, seq_len),
  179. dtype=torch.int32,
  180. device=self.device)
  181. position_ids = torch.zeros((batch_size, seq_len),
  182. dtype=torch.int32,
  183. device=self.device)
  184. slot_mapping = torch.zeros((batch_size, seq_len),
  185. dtype=torch.int64,
  186. device=self.device)
  187. block_tables = torch.zeros(
  188. (batch_size, self.max_num_blocks_per_seq),
  189. dtype=torch.int32,
  190. device=self.device)
  191. context_lens = torch.ones((batch_size, ),
  192. dtype=torch.int32,
  193. device=self.device)
  194. input_lens = torch.ones((batch_size, ),
  195. dtype=torch.int32,
  196. device=self.device)
  197. attn_metadata = self.attn_backend.make_metadata(
  198. num_prefills=0,
  199. num_prefill_tokens=0,
  200. num_decode_tokens=batch_size * seq_len,
  201. slot_mapping=slot_mapping,
  202. block_tables=block_tables,
  203. context_lens=context_lens,
  204. )
  205. t = torch.ones((batch_size, ), dtype=torch.float32, device=self.device)
  206. p = torch.ones((batch_size, ), dtype=torch.float32, device=self.device)
  207. # Dummy run.
  208. num_samples = _MAX_NUM_SAMPLES if is_prompt else 1
  209. self.model(token_ids, position_ids, attn_metadata, input_lens, t, p,
  210. num_samples, kv_caches)
  211. def warmup_model(
  212. self,
  213. kv_caches: List[Tuple[torch.Tensor, torch.Tensor]],
  214. ) -> None:
  215. # Prefill
  216. logger.info("Compiling the model with different input shapes...")
  217. start = time.time()
  218. for batch_size in [1]:
  219. seq_len = 16
  220. while True:
  221. self._dummy_run(batch_size, seq_len, kv_caches, is_prompt=True)
  222. xm.wait_device_ops()
  223. logger.info(f"batch_size: {batch_size}, seq_len: {seq_len}")
  224. if seq_len >= self.model_config.max_model_len:
  225. break
  226. num_tokens = batch_size * seq_len
  227. if num_tokens >= self.scheduler_config.max_num_batched_tokens:
  228. break
  229. seq_len = seq_len * 2
  230. end = time.time()
  231. logger.info(f"Compilation for prefill done in {end - start:.2f} s.")
  232. # Decode
  233. start = time.time()
  234. seq_len = 1
  235. batch_size = 8 # Must be in sync with _get_padded_batch_size()
  236. while True:
  237. self._dummy_run(batch_size, seq_len, kv_caches, is_prompt=False)
  238. xm.wait_device_ops()
  239. logger.info(f"batch_size: {batch_size}, seq_len: {seq_len}")
  240. if batch_size >= self.scheduler_config.max_num_seqs:
  241. break
  242. batch_size = batch_size + 16 if batch_size >= 16 else batch_size * 2
  243. end = time.time()
  244. logger.info(f"Compilation for decode done in {end - start:.2f} s.")
  245. def _prepare_prompt(
  246. self,
  247. seq_group_metadata_list: List[SequenceGroupMetadata],
  248. ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata, torch.Tensor]:
  249. assert len(seq_group_metadata_list) > 0
  250. input_tokens: List[int] = []
  251. input_positions: List[int] = []
  252. prompt_lens: List[int] = []
  253. slot_mapping: List[int] = []
  254. for seq_group_metadata in seq_group_metadata_list:
  255. assert seq_group_metadata.is_prompt
  256. seq_ids = list(seq_group_metadata.seq_data.keys())
  257. assert len(seq_ids) == 1
  258. seq_id = seq_ids[0]
  259. seq_data = seq_group_metadata.seq_data[seq_id]
  260. # Could include output tokens when a request is preempted.
  261. prompt_tokens = seq_data.get_token_ids()
  262. prompt_len = len(prompt_tokens)
  263. prompt_lens.append(prompt_len)
  264. input_tokens.extend(prompt_tokens)
  265. input_positions.extend(list(range(prompt_len)))
  266. assert seq_group_metadata.block_tables is not None
  267. block_table = seq_group_metadata.block_tables[seq_id]
  268. for i in range(prompt_len):
  269. block_number = block_table[i // self.block_size]
  270. block_offset = i % self.block_size
  271. slot = block_number * self.block_size + block_offset
  272. slot_mapping.append(slot)
  273. # Add paddings to EACH prompt to the smallest power of 2 that is
  274. # greater than or equal to the prompt length.
  275. # We pad the seq_len to reduce the compilation overhead.
  276. # We execute each prompt individually (i.e., with batch_size 1)
  277. # because the FlashAttention kernel does not support ragged inputs.
  278. # TODO(woosuk): Use SplashAttention to support ragged inputs.
  279. padded_prompt_len = _get_padded_prefill_len(prompt_len)
  280. num_paddings = padded_prompt_len - prompt_len
  281. input_tokens += [0] * num_paddings
  282. input_positions += [0] * num_paddings
  283. slot_mapping += [_PAD_SLOT_ID] * num_paddings
  284. assert len(prompt_lens) > 0
  285. num_prefills = len(prompt_lens)
  286. input_tokens = torch.tensor(input_tokens,
  287. dtype=torch.int32,
  288. device="cpu")
  289. input_positions = torch.tensor(input_positions,
  290. dtype=torch.int32,
  291. device="cpu")
  292. slot_mapping = torch.tensor(slot_mapping,
  293. dtype=torch.int64,
  294. device="cpu")
  295. prompt_lens = torch.tensor(prompt_lens,
  296. dtype=torch.int32,
  297. device="cpu")
  298. attn_metadata = self.attn_backend.make_metadata(
  299. num_prefills=num_prefills,
  300. num_prefill_tokens=0, # NOTE: This is not used.
  301. num_decode_tokens=0,
  302. slot_mapping=slot_mapping,
  303. block_tables=None,
  304. context_lens=None,
  305. )
  306. return input_tokens, input_positions, attn_metadata, prompt_lens
  307. def _prepare_decode(
  308. self,
  309. seq_group_metadata_list: List[SequenceGroupMetadata],
  310. ) -> Tuple[torch.Tensor, torch.Tensor, AttentionMetadata, torch.Tensor]:
  311. assert len(seq_group_metadata_list) > 0
  312. input_tokens: List[List[int]] = []
  313. input_positions: List[List[int]] = []
  314. slot_mapping: List[List[int]] = []
  315. context_lens: List[int] = []
  316. batch_idx = 0
  317. for seq_group_metadata in seq_group_metadata_list:
  318. assert not seq_group_metadata.is_prompt
  319. seq_ids = list(seq_group_metadata.seq_data.keys())
  320. for seq_id in seq_ids:
  321. seq_data = seq_group_metadata.seq_data[seq_id]
  322. generation_token = seq_data.get_last_token_id()
  323. input_tokens.append([generation_token])
  324. seq_len = seq_data.get_len()
  325. position = seq_len - 1
  326. input_positions.append([position])
  327. context_lens.append(seq_len)
  328. assert seq_group_metadata.block_tables is not None
  329. block_table = seq_group_metadata.block_tables[seq_id]
  330. self.block_tables[batch_idx, :len(block_table)] = block_table
  331. batch_idx += 1
  332. block_number = block_table[position // self.block_size]
  333. block_offset = position % self.block_size
  334. slot = block_number * self.block_size + block_offset
  335. slot_mapping.append([slot])
  336. batch_size = _get_padded_batch_size(batch_idx)
  337. num_paddings = batch_size - batch_idx
  338. input_tokens = input_tokens + [[0]] * num_paddings
  339. input_positions = input_positions + [[0]] * num_paddings
  340. slot_mapping = slot_mapping + [[_PAD_SLOT_ID]] * num_paddings
  341. context_lens = context_lens + [0] * num_paddings
  342. input_tokens = torch.tensor(input_tokens,
  343. dtype=torch.int32,
  344. device="cpu")
  345. input_positions = torch.tensor(input_positions,
  346. dtype=torch.int32,
  347. device="cpu")
  348. slot_mapping = torch.tensor(slot_mapping,
  349. dtype=torch.int64,
  350. device="cpu")
  351. context_lens = torch.tensor(context_lens,
  352. dtype=torch.int32,
  353. device="cpu")
  354. block_tables = torch.tensor(self.block_tables[:batch_size],
  355. dtype=torch.int32,
  356. device="cpu")
  357. input_lens = torch.tensor([1] * batch_size,
  358. dtype=torch.int32,
  359. device="cpu")
  360. attn_metadata = self.attn_backend.make_metadata(
  361. num_prefills=0,
  362. num_prefill_tokens=0,
  363. num_decode_tokens=batch_size,
  364. slot_mapping=slot_mapping,
  365. block_tables=block_tables,
  366. context_lens=context_lens,
  367. )
  368. return input_tokens, input_positions, attn_metadata, input_lens
  369. def _prepare_sample(
  370. self,
  371. seq_group_metadata_list: List[SequenceGroupMetadata],
  372. padded_batch_size: int,
  373. ) -> Tuple[torch.Tensor, torch.Tensor, List[int]]:
  374. assert len(seq_group_metadata_list) > 0
  375. t = []
  376. p = []
  377. best_of = []
  378. for seq_group_metadata in seq_group_metadata_list:
  379. sampling_params = seq_group_metadata.sampling_params
  380. t.append(sampling_params.temperature)
  381. if sampling_params.top_p != 1 and not _ENABLE_TOP_P:
  382. raise NotImplementedError(
  383. "Top-p sampling is currently disabled for the TPU backend "
  384. "due to performance issues.")
  385. p.append(sampling_params.top_p)
  386. if sampling_params.top_k != -1:
  387. raise NotImplementedError(
  388. "Top-k sampling is currently disabled for the TPU backend "
  389. "due to performance issues.")
  390. if sampling_params.best_of > _MAX_NUM_SAMPLES:
  391. raise NotImplementedError(
  392. f"Best of > {_MAX_NUM_SAMPLES} is not supported by the TPU "
  393. "backend.")
  394. best_of.append(sampling_params.best_of)
  395. if sampling_params.use_beam_search:
  396. raise NotImplementedError(
  397. "Beam search is not supported by the TPU backend.")
  398. if sampling_params.logprobs is not None:
  399. raise NotImplementedError(
  400. "logprobs is not currently supported by the TPU backend.")
  401. if sampling_params.prompt_logprobs is not None:
  402. raise NotImplementedError(
  403. "prompt_logprobs is not currently supported by the TPU "
  404. "backend.")
  405. # Repeat the sampling params if the seq group has multiple seqs.
  406. num_seqs = len(seq_group_metadata.seq_data)
  407. t += [t[-1]] * (num_seqs - 1)
  408. p += [p[-1]] * (num_seqs - 1)
  409. best_of += [best_of[-1]] * (num_seqs - 1)
  410. num_paddings = padded_batch_size - len(t)
  411. t += [1.0] * num_paddings
  412. p += [1.0] * num_paddings
  413. t = torch.tensor(t, dtype=torch.float32, device="cpu")
  414. p = torch.tensor(p, dtype=torch.float32, device="cpu")
  415. return t, p, best_of
  416. def prepare_model_input(
  417. self,
  418. seq_group_metadata_list: List[SequenceGroupMetadata],
  419. virtual_engine: int = 0,
  420. finished_requests_ids: Optional[List[str]] = None,
  421. ) -> ModelInputForTPU:
  422. del finished_requests_ids # Unused.
  423. assert virtual_engine == 0
  424. assert len(seq_group_metadata_list) > 0
  425. # NOTE: We assume that all sequences in the group are all prompts or
  426. # all decodes.
  427. is_prompt = seq_group_metadata_list[0].is_prompt
  428. if is_prompt:
  429. inputs = self._prepare_prompt(seq_group_metadata_list)
  430. else:
  431. inputs = self._prepare_decode(seq_group_metadata_list)
  432. input_tokens, input_positions, attn_metadata, input_lens = inputs
  433. padded_batch_size = input_tokens.shape[0]
  434. t, p, best_of = self._prepare_sample(seq_group_metadata_list,
  435. padded_batch_size)
  436. num_samples = _MAX_NUM_SAMPLES if is_prompt else 1
  437. seq_groups = [
  438. list(metadata.seq_data.keys())
  439. for metadata in seq_group_metadata_list
  440. ]
  441. return ModelInputForTPU(input_tokens, input_positions, attn_metadata,
  442. input_lens, t, p, num_samples, best_of,
  443. seq_groups)
  444. def make_model_input_from_broadcasted_tensor_dict(
  445. self, tensor_dict: Dict[str, Any]) -> ModelInputForTPU:
  446. model_input = ModelInputForTPU.from_broadcasted_tensor_dict(
  447. tensor_dict, attn_backend=self.attn_backend)
  448. return model_input
  449. @torch.no_grad()
  450. def execute_model(
  451. self,
  452. model_input: ModelInputForTPU,
  453. kv_caches: Optional[List[Any]],
  454. intermediate_tensors: Optional[IntermediateTensors] = None,
  455. num_steps: int = 1,
  456. ) -> List[SamplerOutput]:
  457. assert intermediate_tensors is None
  458. if num_steps > 1:
  459. raise ValueError(
  460. "TPUModelRunner does not support multi-step execution.")
  461. def _execute_model(*args, clone: bool = False) -> torch.Tensor:
  462. """Move input args from CPU to device and execute the model."""
  463. def _copy_to_device(x: torch.Tensor) -> torch.Tensor:
  464. if clone:
  465. # When x is a slice of a CPU tensor, XLA may copy the whole
  466. # original tensor to TPU instead of only copying x.
  467. # To avoid this, we copy x after cloning.
  468. x = x.clone()
  469. return x.to(self.device)
  470. new_args = []
  471. for arg in args:
  472. if isinstance(arg, torch.Tensor):
  473. arg = _copy_to_device(arg)
  474. elif isinstance(arg, AttentionMetadata):
  475. arg.slot_mapping = _copy_to_device(arg.slot_mapping)
  476. if getattr(arg, "block_tables", None) is not None:
  477. arg.block_tables = _copy_to_device(arg.block_tables)
  478. if getattr(arg, "context_lens", None) is not None:
  479. arg.context_lens = _copy_to_device(arg.context_lens)
  480. new_args.append(arg)
  481. return self.model(*new_args)
  482. num_prefills = model_input.attn_metadata.num_prefills
  483. is_prompt = num_prefills > 0
  484. if is_prompt:
  485. # NOTE: Since the FlashAttention kernel does not support
  486. # ragged inputs, we split the prompts into different batches and
  487. # process them separately. This is a temporary hack that should be
  488. # optimized by using SplashAttention.
  489. next_token_ids = []
  490. orig_slot_mapping = model_input.attn_metadata.slot_mapping
  491. batch_size = model_input.input_lens.shape[0]
  492. start_idx = 0
  493. for i in range(batch_size):
  494. # Get the actual prefill_len.
  495. prefill_len = model_input.input_lens[i:i + 1].item()
  496. prefill_len = _get_padded_prefill_len(prefill_len)
  497. end_idx = start_idx + prefill_len
  498. model_input.attn_metadata.slot_mapping = orig_slot_mapping[
  499. None, start_idx:end_idx]
  500. model_input.attn_metadata.num_prefills = 1
  501. output_token_ids = _execute_model(
  502. model_input.token_ids[None, start_idx:end_idx],
  503. model_input.position_ids[None, start_idx:end_idx],
  504. model_input.attn_metadata,
  505. model_input.input_lens[i:i + 1],
  506. model_input.t[i:i + 1],
  507. model_input.p[i:i + 1],
  508. model_input.num_samples,
  509. kv_caches,
  510. clone=True)
  511. # Retrieve the outputs to CPU.
  512. next_token_ids += output_token_ids.cpu().tolist()
  513. start_idx = end_idx
  514. else:
  515. # Execute the model.
  516. output_token_ids = _execute_model(
  517. model_input.token_ids, model_input.position_ids,
  518. model_input.attn_metadata, model_input.input_lens,
  519. model_input.t, model_input.p, model_input.num_samples,
  520. kv_caches)
  521. # Retrieve the outputs to CPU.
  522. next_token_ids = output_token_ids.cpu().tolist()
  523. # NOTE: Minimal code to construct the sampler outputs.
  524. # The TPU backend does not reuse the sampler, since the TPU backend
  525. # does not support the advanced sampling parameters such as logprobs.
  526. zero_logprob = Logprob(0.0)
  527. batch_idx = 0
  528. sampler_outputs = []
  529. for seq_group in model_input.seq_groups:
  530. seq_ids = seq_group
  531. seq_outputs = []
  532. if is_prompt:
  533. assert len(seq_ids) == 1
  534. seq_id = seq_ids[0]
  535. for i in range(model_input.best_of[batch_idx]):
  536. next_token_id = next_token_ids[batch_idx][i]
  537. seq_outputs.append(
  538. SequenceOutput(seq_id, next_token_id,
  539. {next_token_id: zero_logprob}))
  540. batch_idx += 1
  541. else:
  542. for seq_id in seq_ids:
  543. next_token_id = next_token_ids[batch_idx][0]
  544. seq_outputs.append(
  545. SequenceOutput(seq_id, next_token_id,
  546. {next_token_id: zero_logprob}))
  547. batch_idx += 1
  548. sampler_outputs.append(
  549. CompletionSequenceGroupOutput(seq_outputs, None))
  550. return [SamplerOutput(sampler_outputs)]
  551. class ModelWrapper(nn.Module):
  552. def __init__(self, model: nn.Module):
  553. super().__init__()
  554. self.model = model
  555. def forward(
  556. self,
  557. token_ids: torch.Tensor,
  558. position_ids: torch.Tensor,
  559. attn_metadata: AttentionMetadata,
  560. input_lens: torch.Tensor,
  561. t: torch.Tensor,
  562. p: torch.Tensor,
  563. num_samples: int,
  564. kv_caches: List[Tuple[Optional[torch.Tensor], Optional[torch.Tensor]]],
  565. ) -> torch.Tensor:
  566. """Executes the forward pass of the model and samples the next token.
  567. Args:
  568. token_ids: The input token IDs of shape [batch_size, seq_len].
  569. position_ids: The input position IDs of shape [batch_size, seq_len].
  570. attn_metadata: The Pallas attention metadata.
  571. input_lens: The actual input lengths of shape [batch_size].
  572. t: The sampling temperature of shape [batch_size].
  573. p: The top-p probability of shape [batch_size].
  574. num_samples: Number of samples to draw from each logits vector.
  575. kv_caches: The key and value caches. They can be None during the
  576. memory profiling at initialization.
  577. """
  578. batch_size, seq_len = token_ids.shape
  579. # Calculate the positions to sample from.
  580. start_indicies = torch.arange(
  581. batch_size, dtype=torch.int32, device=input_lens.device) * seq_len
  582. logits_indices = start_indicies + input_lens - 1
  583. # FIXME: This is a temporary hack to avoid using the existing
  584. # sampler and sampling metadata.
  585. sampling_metadata = SamplingMetadata(
  586. seq_groups=[],
  587. selected_token_indices=logits_indices,
  588. categorized_sample_indices={},
  589. num_prompts=attn_metadata.num_prefills,
  590. )
  591. # Skip this in memory profiling at initialization.
  592. if kv_caches[0][0] is not None:
  593. # index_copy_(slot_mapping) only works when the inserted dimension
  594. # is 0. However, the KV cache in the Pallas backend has the shape
  595. # [num_kv_heads, num_blocks, block_size, head_size]. To make it
  596. # work, we need to flatten the first three dimensions and modify
  597. # the slot_mapping accordingly.
  598. num_kv_heads, num_blocks, block_size, _ = kv_caches[0][0].shape
  599. slot_mapping = attn_metadata.slot_mapping
  600. slot_mapping = slot_mapping.flatten()
  601. head_indicies = torch.arange(0,
  602. num_kv_heads,
  603. device=slot_mapping.device,
  604. dtype=slot_mapping.dtype)
  605. head_indicies *= block_size * num_blocks
  606. slot_mapping = slot_mapping.repeat_interleave(num_kv_heads).view(
  607. -1, num_kv_heads)
  608. slot_mapping = slot_mapping + head_indicies.view(1, -1)
  609. slot_mapping = slot_mapping.flatten()
  610. attn_metadata.slot_mapping = slot_mapping
  611. hidden_states = self.model(
  612. token_ids,
  613. position_ids,
  614. kv_caches,
  615. attn_metadata,
  616. )
  617. hidden_states = hidden_states.flatten(0, 1)
  618. logits = self.model.compute_logits(hidden_states, sampling_metadata)
  619. # Argmax sampling.
  620. argmax_token_ids = torch.argmax(logits, dim=-1, keepdim=True)
  621. argmax_token_ids = argmax_token_ids.repeat(1, num_samples)
  622. # Zero temperature means greedy decoding. Avoid division by zero.
  623. nonzero_t = torch.where(t != 0, t, 1.0)
  624. logits = logits / nonzero_t.unsqueeze(dim=1)
  625. if _ENABLE_TOP_P:
  626. logits = _apply_top_p(logits, p.unsqueeze(dim=1))
  627. # Random sampling.
  628. probs = torch.softmax(logits, dim=-1, dtype=torch.float32)
  629. sampled_token_ids = torch.multinomial(probs,
  630. num_samples,
  631. replacement=True)
  632. next_token_ids = torch.where(t != 0, sampled_token_ids,
  633. argmax_token_ids)
  634. return next_token_ids
  635. def _get_padded_prefill_len(x: int) -> int:
  636. # NOTE: The pallas FlashAttention kernel requires the sequence
  637. # length to be a multiple of 16. We pad the prompt length to the nearest
  638. # multiple of 16. This is also good for performance.
  639. if x <= 16:
  640. return 16
  641. return 1 << (x - 1).bit_length()
  642. def _get_padded_batch_size(batch_size: int) -> int:
  643. # The GMM Pallas kernel requires num_tokens * topk to be a multiple of 16.
  644. # To meet this requirement in the simplest way, we set the minimal batch
  645. # size to 8.
  646. if batch_size <= 8:
  647. return 8
  648. else:
  649. return ((batch_size + 15) // 16) * 16
  650. def _apply_top_p(logits: torch.Tensor, p: torch.Tensor) -> torch.Tensor:
  651. logits_sorted = torch.sort(logits, dim=-1, descending=True).values
  652. sorted_cum_probs = torch.cumsum(logits_sorted.softmax(dim=-1), dim=-1)
  653. cutoff_index = torch.sum(sorted_cum_probs < p, dim=-1, keepdim=True)
  654. cutoff_logit = torch.gather(logits_sorted, -1, cutoff_index)
  655. logits = logits.masked_fill_(logits < cutoff_logit, -float("inf"))
  656. return logits