multi_step_model_runner.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. import dataclasses
  2. import functools
  3. from dataclasses import dataclass, field
  4. from typing import (TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple,
  5. Union)
  6. try:
  7. from aphrodite.attention.backends.flash_attn import FlashAttentionMetadata
  8. except ModuleNotFoundError:
  9. # aphrodite_flash_attn is not installed, use the identical ROCm FA metadata
  10. from aphrodite.attention.backends.rocm_flash_attn import (
  11. ROCmFlashAttentionMetadata as FlashAttentionMetadata,
  12. )
  13. import torch
  14. from aphrodite import _custom_ops as ops
  15. from aphrodite.common.sequence import (CompletionSequenceGroupOutput,
  16. IntermediateTensors, Logprob,
  17. SequenceGroupMetadata, SequenceOutput)
  18. from aphrodite.distributed import get_pp_group
  19. from aphrodite.modeling.layers.sampler import (PromptLogprobs, SampleLogprobs,
  20. SamplerOutput, SamplingMetadata,
  21. get_logprobs,
  22. get_pythonized_sample_results)
  23. from aphrodite.modeling.model_loader.tensorizer import TensorizerConfig
  24. from aphrodite.task_handler.model_runner import (
  25. GPUModelRunnerBase, ModelInputForGPUWithSamplingMetadata)
  26. from aphrodite.task_handler.model_runner_base import (
  27. BroadcastableModelInput, _init_attn_metadata_from_tensor_dict,
  28. _init_frozen_model_input_from_tensor_dict,
  29. _init_sampling_metadata_from_tensor_dict)
  30. if TYPE_CHECKING:
  31. from aphrodite.attention.backends.abstract import AttentionBackend
  32. @dataclass
  33. class ModelOutput:
  34. """The output of a single model forward pass.
  35. The sampler_output_ready_event is set when the tensors in
  36. sampler_output are ready (the model+sampler forward pass has
  37. completed). We use the event to synchronize the GPU->CPU transfer,
  38. which we want to only run when the data has been written to the
  39. GPU tensors. Until the event is ready, the tensors in sampler_output
  40. will have garbage data.
  41. There are two scenarios:
  42. 1. The output tensors are ready and we can pythonize them immediately.
  43. 2. The output tensors are not ready and we need to wait for the event to be
  44. ready.
  45. """
  46. sampler_output: SamplerOutput
  47. sampler_output_ready_event: torch.cuda.Event
  48. sampled_token_ids: Optional[torch.Tensor] = None
  49. pythonized: bool = False
  50. # On-device tensor containing the logprobs of each token.
  51. logprobs: Optional["torch.Tensor"] = None
  52. def pythonize(
  53. self,
  54. input_metadata: "StatefulModelInput",
  55. copy_stream: torch.cuda.Stream,
  56. pinned_sampled_token_buffer: torch.Tensor,
  57. ) -> None:
  58. """Pythonize the output. Blocking."""
  59. if not self.pythonized:
  60. self._pythonize_sampler_output(
  61. input_metadata, copy_stream, pinned_sampled_token_buffer, True
  62. )
  63. self.pythonized = True
  64. def maybe_pythonize(
  65. self,
  66. input_metadata: "StatefulModelInput",
  67. copy_stream: torch.cuda.Stream,
  68. pinned_sampled_token_buffer: torch.Tensor,
  69. ) -> None:
  70. """Pythonize the output if ready, else return None. Non-blocking."""
  71. if not self.pythonized:
  72. self.pythonized = self._pythonize_sampler_output(
  73. input_metadata, copy_stream, pinned_sampled_token_buffer, False
  74. )
  75. def _pythonize_sampler_output(
  76. self,
  77. input_metadata: "StatefulModelInput",
  78. copy_stream: torch.cuda.Stream,
  79. pinned_sampled_token_buffer: torch.Tensor,
  80. blocking: bool,
  81. ) -> bool:
  82. """
  83. If blocking is set, will block until the forward pass for the output is
  84. ready and pythonize the output. Upon completing Pythonization, erases
  85. self.logprobs (note that a non-blocking call that is performed when
  86. the sampler output is not yet ready, will not erase self.logprobs.)
  87. """
  88. assert self.sampled_token_ids is not None
  89. if not blocking and not self.sampler_output_ready_event.query():
  90. return False
  91. if blocking:
  92. self.sampler_output_ready_event.synchronize()
  93. with torch.cuda.stream(copy_stream):
  94. _pythonize_sampler_output(
  95. input_metadata,
  96. self.sampler_output,
  97. pinned_sampled_token_buffer,
  98. self.sampled_token_ids, self.logprobs)
  99. # Erase the logprobs GPU-side tensor.
  100. # Note that although _pythonize_sampler_output() runs in its
  101. # own CUDA stream, nonetheless _pythonize_sampler_output()
  102. # cannot return until Pythonization is complete; therefore
  103. # we know that by the time the CPU reaches this point,
  104. # `self.logprobs` is no longer needed.
  105. self.logprobs = None
  106. return True
  107. @dataclass(frozen=False)
  108. class StatefulModelInput(BroadcastableModelInput):
  109. # actual frozen model input dataclass passed to _base_model_runner
  110. frozen_model_input: Optional[ModelInputForGPUWithSamplingMetadata] = None
  111. # list of model outputs for each step, may not be all pythonized
  112. cached_outputs: List[ModelOutput] = field(default_factory=list)
  113. # used to pass sampled token ids from the last step to the current step for
  114. # TP workers. Used to append to end of outputs and used by advance_step
  115. last_sampled_token_ids: Optional[torch.Tensor] = None
  116. current_step: int = 0
  117. is_multi_step: bool = True
  118. is_last_step: bool = False
  119. is_first_multi_step: bool = False
  120. # ping-pong data structures for multi-step to wait on the previous step
  121. step_cuda_events: List[torch.cuda.Event] = field(
  122. default_factory=lambda: [torch.cuda.Event(blocking=True)] * 2
  123. )
  124. num_seqs: int = -1
  125. num_queries: int = -1
  126. def as_broadcastable_tensor_dict(self) -> Dict[str, Any]:
  127. assert self.frozen_model_input is not None
  128. tensor_dict = self.frozen_model_input.as_broadcastable_tensor_dict()
  129. new_tensor_dict = {
  130. "last_sampled_token_ids": self.last_sampled_token_ids,
  131. "current_step": self.current_step,
  132. "is_multi_step": self.is_multi_step,
  133. "is_last_step": self.is_last_step,
  134. "is_first_multi_step": self.is_first_multi_step,
  135. "num_seqs": self.num_seqs,
  136. "num_queries": self.num_queries,
  137. }
  138. tensor_dict.update(new_tensor_dict)
  139. return tensor_dict
  140. @classmethod
  141. def from_broadcasted_tensor_dict(
  142. cls,
  143. tensor_dict: Dict[str, Any],
  144. attn_backend: Optional["AttentionBackend"] = None,
  145. ) -> "StatefulModelInput":
  146. tensor_dict = _init_sampling_metadata_from_tensor_dict(tensor_dict)
  147. if attn_backend is not None:
  148. tensor_dict = _init_attn_metadata_from_tensor_dict(
  149. attn_backend, tensor_dict
  150. )
  151. tensor_dict = _init_frozen_model_input_from_tensor_dict(
  152. ModelInputForGPUWithSamplingMetadata, tensor_dict
  153. )
  154. return cls(**tensor_dict)
  155. def record_step_event(self, current_stream: torch.cuda.Stream):
  156. # record the event for the current step so that the next step can sync
  157. # on it. We modulo by 2 to keep the events in a circular buffer and
  158. # support any attn backends that may be supported in the future. ie
  159. # Flashinfer would want two DecodeWrappers to overlap the CPU and GPU.
  160. self.step_cuda_events[self.current_step & 1] = torch.cuda.Event(
  161. blocking=True
  162. )
  163. self.step_cuda_events[self.current_step & 1].record(current_stream)
  164. def wait_previous_step(self):
  165. # These cuda events are an explicit synchronization to ensure that
  166. # advance_step() (for other attn backends that may be supported in the
  167. # future) do not clobber any data structures that is also used by any
  168. # enqueued forwards steps. For distributed case, only a single event is
  169. # needed, but for single GPU case, since we can let the CPU run much
  170. # further ahead, two events allow us to overlap the advance_step with
  171. # the previous forward (ie using two DecodeWrappers for flashinfer
  172. # backend)
  173. self.step_cuda_events[(self.current_step + 1) & 1].wait()
  174. def add_sampler_output(
  175. self,
  176. sampler_output: SamplerOutput,
  177. sampled_token_ids: Optional[torch.Tensor] = None,
  178. ):
  179. self.cached_outputs.append(
  180. ModelOutput(
  181. sampler_output=sampler_output,
  182. sampler_output_ready_event=None,
  183. sampled_token_ids=sampled_token_ids,
  184. pythonized=False,
  185. )
  186. )
  187. # MutableModelInputForGPUWithMultiStepMetadata is not subclass of
  188. # ModelInputForGPU but it wraps the actual input dataclass and adds multi-step
  189. # metadata
  190. # mypy: disable-error-code=type-var
  191. class MultiStepModelRunner(GPUModelRunnerBase[StatefulModelInput]):
  192. # mypy: enable-error-code=type-var
  193. def __init__(self, base_model_runner: GPUModelRunnerBase, *args, **kwargs):
  194. super().__init__(*args, **kwargs)
  195. # uses the base model runner to execute the model and wraps it with
  196. # multi-step logic
  197. self._base_model_runner: GPUModelRunnerBase = base_model_runner
  198. self.is_multi_step = self.scheduler_config.is_multi_step
  199. # used to copy tensors from GPU to CPU asynchronously
  200. self._copy_stream = torch.cuda.Stream()
  201. self.pinned_sampled_token_ids: Optional[torch.Tensor] = None
  202. def make_model_input_from_broadcasted_tensor_dict(
  203. self, tensor_dict: Dict[str, Any]
  204. ) -> StatefulModelInput:
  205. model_input = StatefulModelInput.from_broadcasted_tensor_dict(
  206. tensor_dict,
  207. attn_backend=self.attn_backend,
  208. )
  209. return model_input
  210. def prepare_model_input(
  211. self,
  212. seq_group_metadata_list: List[SequenceGroupMetadata],
  213. virtual_engine: int = 0,
  214. finished_requests_ids: Optional[List[str]] = None,
  215. ) -> StatefulModelInput:
  216. frozen_model_input = self._base_model_runner.prepare_model_input(
  217. seq_group_metadata_list, virtual_engine, finished_requests_ids
  218. )
  219. model_input = StatefulModelInput(
  220. frozen_model_input=frozen_model_input,
  221. num_seqs=len(frozen_model_input.seq_lens),
  222. num_queries=len(frozen_model_input.query_lens),
  223. )
  224. return model_input
  225. def _async_process_outputs(self, model_input: StatefulModelInput,
  226. output_proc_callback: Callable):
  227. # Proceed with pythonization and output_proc in order.
  228. # Stop on the first one that fails to pythonize
  229. cont = True
  230. for model_output in model_input.cached_outputs:
  231. if not model_output.pythonized:
  232. model_output.maybe_pythonize(model_input, self._copy_stream,
  233. self.pinned_sampled_token_ids)
  234. if model_output.pythonized:
  235. output_proc_callback(
  236. sampler_output=model_output.sampler_output)
  237. else:
  238. cont = False
  239. if not cont:
  240. break
  241. def _final_process_outputs(self, model_input: StatefulModelInput,
  242. output_proc_callback: Optional[Callable]):
  243. assert model_input.frozen_model_input is not None
  244. outputs = []
  245. for output_id in range(len(model_input.cached_outputs)):
  246. is_last_output = output_id == len(model_input.cached_outputs) - 1
  247. output = model_input.cached_outputs[output_id]
  248. if not output.pythonized:
  249. output.pythonize(model_input, self._copy_stream,
  250. self.pinned_sampled_token_ids)
  251. if model_input.frozen_model_input.use_async_and_multi_step:
  252. assert output_proc_callback is not None
  253. output_proc_callback(sampler_output=output.sampler_output,
  254. is_last_output=is_last_output)
  255. outputs.append(output.sampler_output)
  256. return outputs
  257. @torch.inference_mode()
  258. def execute_model(
  259. self,
  260. model_input: StatefulModelInput,
  261. kv_caches: List[torch.Tensor],
  262. intermediate_tensors: Optional[IntermediateTensors] = None,
  263. num_steps: int = 1,
  264. ) -> Optional[Union[List[SamplerOutput], IntermediateTensors]]:
  265. """
  266. Execute the model for a single step and update multi-step
  267. metadata
  268. """
  269. assert num_steps == 1, "MultiStepModelRunner only supports num_steps=1"
  270. frozen_model_input = model_input.frozen_model_input
  271. assert frozen_model_input is not None
  272. # path for warm up runs
  273. if not model_input.is_multi_step:
  274. return self._base_model_runner.execute_model(
  275. frozen_model_input, kv_caches, intermediate_tensors, num_steps
  276. )
  277. # make sure we skip the sampler on the lask rank and only pythonize
  278. # if CPU is ahead.
  279. if self.is_driver_worker and get_pp_group().is_last_rank:
  280. if self.pinned_sampled_token_ids is None:
  281. self.pinned_sampled_token_ids = torch.zeros(
  282. (self.scheduler_config.max_num_seqs, 1),
  283. dtype=torch.long,
  284. device="cpu",
  285. pin_memory=True,
  286. )
  287. self._base_model_runner.model.sampler.include_gpu_probs_tensor = (
  288. True
  289. )
  290. if frozen_model_input.sampling_metadata:
  291. frozen_model_input.sampling_metadata.skip_sampler_cpu_output = (
  292. True
  293. )
  294. # some pre-execute model logic for multi-step:
  295. # - if it's the first step, we need to reset the sampling tensors
  296. # - if it's not the first step, we need to advance the step using the
  297. # appended sampler output from last iteration
  298. # - also maybe pythonize if CPU is ahead of GPU
  299. current_stream = torch.cuda.current_stream()
  300. if not model_input.is_first_multi_step:
  301. # Explicitly block on the previous step's forward to make sure we
  302. # don't clobber any GPU tensors still in use.
  303. # This is not needed for flashattn backend, but for other attn
  304. # backends such as flashinfer that performs extra CPU operations on
  305. # input metadata we may need to synchronize any CPU operations that
  306. # might clobber enqueued forwards. (prevents CPU from running too
  307. # far ahead if needed)
  308. model_input.wait_previous_step()
  309. model_input = self._advance_step(
  310. model_input, model_input.cached_outputs[-1].sampler_output
  311. )
  312. output_proc_callback = None
  313. if frozen_model_input.use_async_and_multi_step:
  314. output_proc_callback = frozen_model_input.async_callback
  315. assert output_proc_callback is not None
  316. async_callback = functools.partial(
  317. self._async_process_outputs,
  318. model_input=model_input,
  319. output_proc_callback=output_proc_callback)
  320. frozen_model_input = dataclasses.replace( # type: ignore
  321. model_input.frozen_model_input,
  322. async_callback=async_callback)
  323. assert frozen_model_input is not None
  324. # Execute the model
  325. output = self._base_model_runner.execute_model(
  326. frozen_model_input, kv_caches, intermediate_tensors, num_steps=1
  327. )
  328. # record the event for the current step so that the next step can sync
  329. model_input.record_step_event(current_stream)
  330. if get_pp_group().is_last_rank and self.is_driver_worker:
  331. assert (
  332. len(output) == 1
  333. ), "MultiStepModelRunner requires single-step base_models"
  334. # event for the pythonization so that we only pythonize if the
  335. # tensors are ready. May be able to be combined with the step event
  336. output_ready_event = torch.cuda.Event()
  337. output_ready_event.record(current_stream)
  338. if self.parallel_config.pipeline_parallel_size > 1:
  339. output[0].sampled_token_ids_cpu = output[
  340. 0
  341. ].sampled_token_ids.cpu()
  342. model_input.cached_outputs.append(
  343. ModelOutput(
  344. output[0],
  345. output_ready_event,
  346. output[0].sampled_token_ids, False,
  347. output[0].logprobs))
  348. # These GPU tensors are not required by multi-step;
  349. # erase them to ensure they are not pythonized or
  350. # transferred to CPU
  351. output[0].sampled_token_ids = None
  352. output[0].sampled_token_probs = None
  353. output[0].logprobs = None
  354. # Pythonize the output if CPU is ahead and the previous step is
  355. # ready.
  356. if not frozen_model_input.use_async_and_multi_step:
  357. for model_output in model_input.cached_outputs:
  358. model_output.maybe_pythonize(model_input,
  359. self._copy_stream,
  360. self.pinned_sampled_token_ids)
  361. model_input.current_step += 1
  362. if not get_pp_group().is_last_rank:
  363. # Should be IntermediateTensors
  364. assert isinstance(output, IntermediateTensors)
  365. return output
  366. if not self.is_driver_worker:
  367. return []
  368. # Pythonize the output and block if needed since it is the last step
  369. if model_input.is_last_step:
  370. outputs = self._final_process_outputs(model_input,
  371. output_proc_callback)
  372. return outputs
  373. # should be [SamplerOutput]
  374. return output
  375. def _update_sampling_metadata(
  376. self, sampling_metadata, num_seqs, num_queries
  377. ):
  378. assert sampling_metadata.num_prompts == 0
  379. assert len(sampling_metadata.seq_groups) == num_queries
  380. assert sampling_metadata.selected_token_indices.shape == (num_queries,)
  381. # assert sampling_metadata.categorized_sample_indices == TODO: Add if needed # noqa: E501
  382. # Verify that all sequences are decodes
  383. for i in range(num_queries):
  384. seq_group = sampling_metadata.seq_groups[i]
  385. assert seq_group.is_prompt is False # No prompt
  386. assert seq_group.prompt_logprob_indices == [] # No prompt
  387. assert seq_group.sample_indices == [i] # Simple
  388. assert seq_group.seq_len is None # Decode
  389. assert seq_group.query_len is None # Decode
  390. def _advance_step(
  391. self, model_input: StatefulModelInput, out: SamplerOutput
  392. ) -> StatefulModelInput:
  393. frozen_model_input = model_input.frozen_model_input
  394. assert frozen_model_input is not None
  395. assert frozen_model_input.attn_metadata is not None
  396. num_seqs = model_input.num_seqs
  397. num_queries = model_input.num_queries
  398. assert num_seqs > 0
  399. assert num_queries > 0
  400. assert num_seqs >= num_queries
  401. attn_metadata = frozen_model_input.attn_metadata
  402. assert isinstance(attn_metadata, FlashAttentionMetadata)
  403. attn_metadata.advance_step(num_seqs, num_queries)
  404. # Update GPU tensors
  405. ops.advance_step(
  406. num_seqs=num_seqs,
  407. num_queries=num_queries,
  408. block_size=self.block_size,
  409. input_tokens=frozen_model_input.input_tokens,
  410. sampled_token_ids=model_input.cached_outputs[-1].sampled_token_ids,
  411. input_positions=frozen_model_input.input_positions,
  412. seq_lens=attn_metadata.seq_lens_tensor,
  413. slot_mapping=attn_metadata.slot_mapping,
  414. block_tables=attn_metadata.block_tables,
  415. )
  416. if frozen_model_input.seq_lens is not None:
  417. for i in range(num_queries):
  418. frozen_model_input.seq_lens[i] = attn_metadata.seq_lens[i]
  419. return model_input
  420. def load_model(self) -> None:
  421. return self._base_model_runner.load_model()
  422. def save_sharded_state(
  423. self,
  424. path: str,
  425. pattern: Optional[str] = None,
  426. max_size: Optional[int] = None,
  427. ) -> None:
  428. return self._base_model_runner.save_sharded_state(
  429. path, pattern, max_size
  430. )
  431. def save_tensorized_model(
  432. self, tensorizer_config: TensorizerConfig
  433. ) -> None:
  434. return self._base_model_runner.save_tensorized_model(tensorizer_config)
  435. def profile_run(self) -> None:
  436. return self._base_model_runner.profile_run()
  437. def remove_all_loras(self):
  438. return self._base_model_runner.remove_all_loras()
  439. def capture_model(self, kv_caches: List[List]) -> None:
  440. return self._base_model_runner.capture_model(kv_caches)
  441. @property
  442. def vocab_size(self) -> int:
  443. return self._base_model_runner.vocab_size
  444. DeferredLogprobsReturnType = Tuple[Optional[List[Optional[PromptLogprobs]]],
  445. Optional[List[SampleLogprobs]]]
  446. def deferred_pythonize_logprobs(
  447. output: SamplerOutput,
  448. sampling_metadata: SamplingMetadata,
  449. logprobs_tensor: Optional[torch.Tensor],
  450. ) -> DeferredLogprobsReturnType:
  451. """Perform deferred logprob Pythonization.
  452. 1. Pythonize GPU-side sampler result tensors into CPU-side sampler result.
  453. 2. Pythonize GPU-side logprobs tensor into CPU-side logprobs lists,
  454. utilizing the Pythonized sampler result computed in step 1.
  455. These deferred computations are not required for single-step scheduling
  456. or the `profile_run()` phase of multi-step scheduling.
  457. Args:
  458. output: sampler output (under deferred Pythonization)
  459. sampling_metadata
  460. Returns:
  461. prompt_logprobs (CPU), sample_logprobs (CPU)
  462. """
  463. # - Deferred pythonization of sample result
  464. sampler_result = get_pythonized_sample_results(
  465. output.deferred_sample_results_args)
  466. # - Erase the GPU-side deferred sample_result
  467. # computation args to ensure it is never
  468. # pythonized or transferred to CPU
  469. output.deferred_sample_results_args = None
  470. # - Deferred pythonization of logprobs
  471. (
  472. prompt_logprobs,
  473. sample_logprobs,
  474. ) = get_logprobs(logprobs_tensor, sampling_metadata, sampler_result)
  475. assert len(prompt_logprobs) == len(sampling_metadata.seq_groups)
  476. assert len(sample_logprobs) == len(sampling_metadata.seq_groups)
  477. return prompt_logprobs, sample_logprobs
  478. def _pythonize_sampler_output(
  479. model_input: StatefulModelInput,
  480. output: SamplerOutput,
  481. pinned_sampled_token_buffer: torch.Tensor,
  482. sampled_token_ids: torch.Tensor,
  483. logprobs_tensor: Optional[torch.Tensor],
  484. ) -> None:
  485. """ This function is only called when the output tensors are ready.
  486. See :class:`ModelOutput`.
  487. Modifies `output.outputs` and `pinned_sampled_token_buffer` in-place,
  488. adding a Pythonized output data structure
  489. (:class:`CompletionSequenceGroupOutput`) for each :class:`SequenceGroup`.
  490. Args:
  491. model_input
  492. output: sampler output
  493. pinned_sampled_token_token_buffer: CPU-side pinned memory
  494. (receives copy of
  495. GPU-side token buffer.)
  496. sampled_token_ids: GPU-side token buffer
  497. logprobs_tensor: GPU-side tensor containing
  498. logprobs computed during sampling
  499. """
  500. assert model_input.frozen_model_input is not None
  501. frozen_model_input = model_input.frozen_model_input
  502. assert frozen_model_input.sampling_metadata is not None
  503. # samples generation should have been skipped
  504. assert not output.outputs
  505. pinned_buffer = pinned_sampled_token_buffer[: model_input.num_queries]
  506. # CPU GPU sync
  507. pinned_buffer = pinned_buffer.copy_(sampled_token_ids, non_blocking=False)
  508. # this will not block as the tensors are already on CPU
  509. samples_list = pinned_buffer.tolist()
  510. sampling_metadata = frozen_model_input.sampling_metadata
  511. skip_sampler_cpu_output = (
  512. frozen_model_input.sampling_metadata.skip_sampler_cpu_output)
  513. # We are guaranteed output tensors are ready, so it is safe to
  514. # pythonize the sampler output & obtain CPU-side logprobs.
  515. #
  516. # However this computation may be skipped entirely
  517. # if no pythonization was deferred.
  518. seq_groups = sampling_metadata.seq_groups
  519. logprobs_are_requested = any([
  520. sg.sampling_params.logprobs is not None
  521. or sg.sampling_params.prompt_logprobs is not None for sg in seq_groups
  522. ])
  523. do_pythonize_logprobs = (skip_sampler_cpu_output
  524. and logprobs_are_requested)
  525. (
  526. prompt_logprobs,
  527. sample_logprobs,
  528. ) = (deferred_pythonize_logprobs(output, sampling_metadata,
  529. logprobs_tensor)
  530. if do_pythonize_logprobs else (None, None))
  531. for sgdx, (seq_group,
  532. sample_result) in enumerate(zip(seq_groups, samples_list)):
  533. if do_pythonize_logprobs:
  534. assert prompt_logprobs is not None
  535. assert sample_logprobs is not None
  536. (
  537. group_prompt_logprobs,
  538. group_sample_logprobs,
  539. ) = ( # Utilize deferred pythonization results
  540. prompt_logprobs[sgdx],
  541. sample_logprobs[sgdx],
  542. )
  543. elif logprobs_are_requested:
  544. (
  545. group_prompt_logprobs,
  546. group_sample_logprobs,
  547. ) = (
  548. # profile_run: use already-computed logprobs
  549. output.outputs[sgdx].prompt_logprobs,
  550. [sample.logprobs for sample in output.outputs[sgdx].samples])
  551. seq_ids = seq_group.seq_ids
  552. next_token_ids = sample_result
  553. parent_ids = [0]
  554. seq_outputs: List[SequenceOutput] = []
  555. if seq_group.sampling_params.logits_processors:
  556. assert len(seq_group.sampling_params.logits_processors) == 0, (
  557. "Logits Processors are not supported in multi-step decoding")
  558. for tdx, (parent_id,
  559. next_token_id) in enumerate(zip(parent_ids, next_token_ids)):
  560. seq_outputs.append(
  561. SequenceOutput(seq_ids[parent_id], next_token_id,
  562. (group_sample_logprobs[tdx]
  563. if logprobs_are_requested else {
  564. next_token_id:
  565. Logprob(logprob=float('inf'),
  566. rank=None,
  567. decoded_token=None)
  568. })))
  569. output.outputs.append(
  570. CompletionSequenceGroupOutput(
  571. seq_outputs,
  572. (group_prompt_logprobs if logprobs_are_requested else None)))
  573. assert len(output.outputs) > 0