sequence.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. """Sequence and its related classes."""
  2. import copy
  3. import enum
  4. from dataclasses import dataclass
  5. from typing import Dict, List, Optional, Union, TYPE_CHECKING
  6. from aphrodite.common.block import LogicalTokenBlock
  7. from aphrodite.common.sampling_params import SamplingParams
  8. from aphrodite.lora.request import LoRARequest
  9. if TYPE_CHECKING:
  10. import torch
  11. from aphrodite.spec_decode.metrics import SpecDecodeWorkerMetrics
  12. @dataclass
  13. class Logprob:
  14. """Infos for supporting OpenAI compatible logprobs and token ranks.
  15. Attributes:
  16. logprob: The logprob of chosen token
  17. rank: The vocab rank of chosen token (>=1)
  18. decoded_token: The decoded chosen token index
  19. """
  20. logprob: float
  21. rank: Optional[int] = None
  22. decoded_token: Optional[str] = None
  23. PromptLogprobs = List[Optional[Dict[int, Logprob]]]
  24. SampleLogprobs = List[Dict[int, Logprob]]
  25. class SequenceStatus(enum.Enum):
  26. """Status of a sequence."""
  27. WAITING = enum.auto()
  28. RUNNING = enum.auto()
  29. SWAPPED = enum.auto()
  30. FINISHED_STOPPED = enum.auto()
  31. FINISHED_LENGTH_CAPPED = enum.auto()
  32. FINISHED_ABORTED = enum.auto()
  33. FINISHED_IGNORED = enum.auto()
  34. @staticmethod
  35. def is_finished(status: "SequenceStatus") -> bool:
  36. return status in [
  37. SequenceStatus.FINISHED_STOPPED,
  38. SequenceStatus.FINISHED_LENGTH_CAPPED,
  39. SequenceStatus.FINISHED_ABORTED,
  40. SequenceStatus.FINISHED_IGNORED,
  41. ]
  42. @staticmethod
  43. def get_finished_reason(status: "SequenceStatus") -> Union[str, None]:
  44. if status == SequenceStatus.FINISHED_STOPPED:
  45. finish_reason = "stop"
  46. elif status == SequenceStatus.FINISHED_LENGTH_CAPPED:
  47. finish_reason = "length"
  48. elif status == SequenceStatus.FINISHED_ABORTED:
  49. finish_reason = "abort"
  50. elif status == SequenceStatus.FINISHED_IGNORED:
  51. # The ignored sequences are the sequences whose prompt lengths
  52. # are longer than the model's length cap. Therefore, the stop
  53. # reason should also be "length" as in OpenAI API.
  54. finish_reason = "length"
  55. else:
  56. finish_reason = None
  57. return finish_reason
  58. class SequenceStage(enum.Enum):
  59. PREFILL = enum.auto()
  60. DECODE = enum.auto()
  61. @dataclass
  62. class RequestMetrics:
  63. """Metrics associated with a request.
  64. Args:
  65. arrival_time: The time when the request arrived.
  66. first_scheduled_time: The time when the request was first scheduled.
  67. first_token_time: The time when the first token was generated.
  68. time_in_queue: The time the request spent in the queue.
  69. finished_time: The time when the request was finished.
  70. """
  71. arrival_time: float
  72. last_token_time: float
  73. first_scheduled_time: Optional[float]
  74. first_token_time: Optional[float]
  75. time_in_queue: Optional[float]
  76. finished_time: Optional[float] = None
  77. class SequenceData:
  78. """Data associated with a sequence.
  79. Args:
  80. prompt_token_ids: The token IDs of the prompt.
  81. output_token_ids: The token IDs of the output. Set to an empty list if
  82. None.
  83. Attributes:
  84. prompt_token_ids: The token IDs of the prompt.
  85. output_token_ids: The token IDs of the output.
  86. cumulative_logprob: The cumulative log probability of the output.
  87. """
  88. def __init__(
  89. self,
  90. prompt_token_ids: List[int],
  91. output_token_ids: Optional[List[int]] = None,
  92. ) -> None:
  93. if output_token_ids is None:
  94. output_token_ids = []
  95. self.prompt_token_ids = prompt_token_ids
  96. self.output_token_ids = output_token_ids
  97. self.cumulative_logprob = 0.0
  98. # The number of tokens that are computed (that run against the model).
  99. self._num_computed_tokens = 0
  100. self._stage: SequenceStage = SequenceStage.PREFILL
  101. def append_token_id(self, token_id: int, logprob: float) -> None:
  102. self.output_token_ids.append(token_id)
  103. self.cumulative_logprob += logprob
  104. def get_len(self) -> int:
  105. return len(self.output_token_ids) + len(self.prompt_token_ids)
  106. def get_prompt_len(self) -> int:
  107. return len(self.prompt_token_ids)
  108. def get_output_len(self) -> int:
  109. return len(self.output_token_ids)
  110. def get_token_ids(self) -> List[int]:
  111. return self.prompt_token_ids + self.output_token_ids
  112. def get_num_computed_tokens(self) -> int:
  113. """Return the number of prefill tokens that are already computed."""
  114. return self._num_computed_tokens
  115. def update_num_computed_tokens(self, num_new_computed_tokens: int):
  116. """Update number of tokens computed so far."""
  117. self._num_computed_tokens += num_new_computed_tokens
  118. assert self._num_computed_tokens <= self.get_len(), (
  119. self._num_computed_tokens, self.get_len())
  120. # If all tokens are computed, it means it is in decoding phase.
  121. if self.get_num_uncomputed_tokens() == 0:
  122. self._stage = SequenceStage.DECODE
  123. def reset_state_for_recompute(self) -> None:
  124. """Reset the number of computed tokens from this sequence. It is
  125. supposed to be called when a sequence needs to be started from
  126. the beginning again (e.g., sequence is preempted).
  127. """
  128. self._num_computed_tokens = 0
  129. self._stage = SequenceStage.PREFILL
  130. def get_num_uncomputed_tokens(self) -> int:
  131. """Return the number of prefil tokens that are not computed."""
  132. # we use `get_len()` which includes prompt_len + output_len instead
  133. # of prompt_len here. This is because during recompute we need to
  134. # prefill for both prompt and output.
  135. return self.get_len() - self.get_num_computed_tokens()
  136. def get_last_token_id(self) -> int:
  137. if not self.output_token_ids:
  138. return self.prompt_token_ids[-1]
  139. return self.output_token_ids[-1]
  140. def get_prompt_token_ids(self) -> int:
  141. return self.prompt_token_ids
  142. def get_output_token_ids(self) -> int:
  143. return self.output_token_ids
  144. @property
  145. def stage(self) -> SequenceStage:
  146. return self._stage
  147. def __repr__(self) -> str:
  148. return (f"SequenceData("
  149. f"prompt_token_ids={self.prompt_token_ids}, "
  150. f"output_token_ids={self.output_token_ids}, "
  151. f"cumulative_logprob={self.cumulative_logprob})")
  152. class Sequence:
  153. """Stores the data, status, and block information of a sequence.
  154. Args:
  155. seq_id: The ID of the sequence.
  156. prompt: The prompt of the sequence.
  157. prompt_token_ids: The token IDs of the prompt.
  158. block_size: The block size of the sequence. Should be the same as the
  159. block size used by the block manager and cache engine.
  160. lora_request: LoRA request.
  161. """
  162. def __init__(
  163. self,
  164. seq_id: int,
  165. prompt: str,
  166. prompt_token_ids: List[int],
  167. block_size: int,
  168. eos_token_id: Optional[int] = None,
  169. lora_request: Optional[LoRARequest] = None,
  170. ) -> None:
  171. self.seq_id = seq_id
  172. self.prompt = prompt
  173. self.block_size = block_size
  174. self.eos_token_id = eos_token_id
  175. self.lora_request = lora_request
  176. self.data = SequenceData(prompt_token_ids)
  177. self.output_logprobs: SampleLogprobs = []
  178. self.output_text = ""
  179. self.logical_token_blocks: List[LogicalTokenBlock] = []
  180. # Initialize the logical token blocks with the prompt token ids.
  181. self._append_tokens_to_blocks(prompt_token_ids)
  182. self.status = SequenceStatus.WAITING
  183. self.stop_reason: Union[int, str, None] = None
  184. # Used for incremental detokenization
  185. self.prefix_offset = 0
  186. self.read_offset = 0
  187. # Input + output tokens
  188. self.tokens: Optional[List[str]] = None
  189. self.persistent_data = {}
  190. @property
  191. def lora_int_id(self) -> int:
  192. return self.lora_request.lora_int_id if self.lora_request else 0
  193. def get_output_text_to_return(self, buffer_length: int):
  194. # We return the full output text if the sequence is finished.
  195. truncate = buffer_length and not self.is_finished()
  196. return self.output_text[:-buffer_length] if truncate else (
  197. self.output_text)
  198. def hash_of_block(self, logical_idx: int) -> int:
  199. # Compute the number of tokens in the sequence
  200. # TODO: The current hashing function is O(L^2). We should optimize
  201. # this in the future.
  202. num_tokens = self.num_hashed_tokens_of_block(logical_idx)
  203. return hash(
  204. (tuple(self.data.get_token_ids()[0:num_tokens]), self.lora_int_id))
  205. def num_hashed_tokens_of_block(self, logical_idx: int):
  206. return logical_idx * self.block_size + self.block_size
  207. def reset_state_for_recompute(self):
  208. """Reset the sequence states for recomputation."""
  209. self.data.reset_state_for_recompute()
  210. def _append_logical_block(self) -> None:
  211. block = LogicalTokenBlock(
  212. block_number=len(self.logical_token_blocks),
  213. block_size=self.block_size,
  214. )
  215. self.logical_token_blocks.append(block)
  216. def _append_tokens_to_blocks(self, token_ids: List[int]) -> None:
  217. cursor = 0
  218. while cursor < len(token_ids):
  219. if not self.logical_token_blocks:
  220. self._append_logical_block()
  221. last_block = self.logical_token_blocks[-1]
  222. if last_block.is_full():
  223. self._append_logical_block()
  224. last_block = self.logical_token_blocks[-1]
  225. num_empty_slots = last_block.get_num_empty_slots()
  226. last_block.append_tokens(token_ids[cursor:cursor +
  227. num_empty_slots])
  228. cursor += num_empty_slots
  229. def append_token_id(
  230. self,
  231. token_id: int,
  232. logprobs: Dict[int, Logprob],
  233. ) -> None:
  234. assert token_id in logprobs
  235. self._append_tokens_to_blocks([token_id])
  236. self.output_logprobs.append(logprobs)
  237. self.data.append_token_id(token_id, logprobs[token_id].logprob)
  238. def get_len(self) -> int:
  239. return self.data.get_len()
  240. def get_prompt_len(self) -> int:
  241. return self.data.get_prompt_len()
  242. def get_output_len(self) -> int:
  243. return self.data.get_output_len()
  244. def get_token_ids(self) -> List[int]:
  245. return self.data.get_token_ids()
  246. def get_prompt_token_ids(self) -> List[int]:
  247. return self.data.get_prompt_token_ids()
  248. def get_last_token_id(self) -> int:
  249. return self.data.get_last_token_id()
  250. def get_output_token_ids(self) -> List[int]:
  251. return self.data.output_token_ids
  252. def get_cumulative_logprob(self) -> float:
  253. return self.data.cumulative_logprob
  254. def get_beam_search_score(
  255. self,
  256. length_penalty: float = 1.0,
  257. seq_len: Optional[int] = None,
  258. eos_token_id: Optional[int] = None,
  259. ) -> float:
  260. """Calculate the beam search score with length penalty.
  261. Adapted from
  262. https://github.com/huggingface/transformers/blob/ccb92be23def445f2afdea94c31286f84b89eb5b/src/transformers/generation/beam_search.py#L938
  263. """
  264. if seq_len is None:
  265. seq_len = self.get_len()
  266. # NOTE: HF implementation does not count the EOS token
  267. # towards the length, we align with that here for testing.
  268. if (eos_token_id is not None
  269. and self.get_last_token_id() == eos_token_id):
  270. seq_len -= 1
  271. return self.get_cumulative_logprob() / (seq_len**length_penalty)
  272. def is_finished(self) -> bool:
  273. return SequenceStatus.is_finished(self.status)
  274. def fork(self, new_seq_id: int) -> "Sequence":
  275. new_seq = copy.deepcopy(self)
  276. new_seq.seq_id = new_seq_id
  277. return new_seq
  278. def get_num_new_tokens(self) -> int:
  279. """Get the number of new tokens to be computed.
  280. Args:
  281. remainig_token_budget: The remaining token budgets.
  282. Returns:
  283. The new number of tokens to be computed. I.e., 1 for decode, prompt
  284. size for prefill. If there's not enough remainig_token_budget, it
  285. can return the chunked number of new tokens.
  286. """
  287. if self.data.stage == SequenceStage.DECODE:
  288. return 1
  289. return self.data.get_num_uncomputed_tokens()
  290. def is_prefill(self) -> bool:
  291. return self.data.stage == SequenceStage.PREFILL
  292. def __repr__(self) -> str:
  293. return (f"Sequence(seq_id={self.seq_id}, "
  294. f"status={self.status.name}, "
  295. f"num_blocks={len(self.logical_token_blocks)})")
  296. @dataclass
  297. class SequenceGroupState:
  298. """Mutable state tied to a specific sequence group"""
  299. # torch.Generator used in seeded sampling
  300. generator: Optional = None
  301. class MultiModalData:
  302. """Multi modal request.
  303. Args:
  304. type: The data type.
  305. data: The actual data.
  306. The required shape and semantic meaning of it depends on the vision
  307. language config of the hosted model.
  308. See `VisionLanguageConfig` in `config.py`.
  309. """
  310. class Type(enum.Enum):
  311. IMAGE = enum.auto()
  312. def __init__(self, type: Type, data: "torch.Tensor"):
  313. self.type = type
  314. self.data = data
  315. class SequenceGroup:
  316. """A group of sequences that are generated from the same prompt.
  317. Args:
  318. request_id: The ID of the request.
  319. seqs: The list of sequences.
  320. sampling_params: The sampling parameters used to generate the outputs.
  321. arrival_time: The arrival time of the request.
  322. lora_request: LoRA request.
  323. multi_modal_requst: Multi modal data for the request.
  324. """
  325. def __init__(
  326. self,
  327. request_id: str,
  328. seqs: List[Sequence],
  329. sampling_params: SamplingParams,
  330. arrival_time: float,
  331. lora_request: Optional[LoRARequest] = None,
  332. multi_modal_data: Optional[MultiModalData] = None,
  333. ) -> None:
  334. self.request_id = request_id
  335. self.seqs_dict = {seq.seq_id: seq for seq in seqs}
  336. self.sampling_params = sampling_params
  337. self.metrics = RequestMetrics(
  338. arrival_time=arrival_time,
  339. last_token_time=arrival_time,
  340. first_scheduled_time=None,
  341. first_token_time=None,
  342. time_in_queue=None,
  343. )
  344. self.lora_request = lora_request
  345. self.prompt_logprobs: Optional[PromptLogprobs] = None
  346. self.state = SequenceGroupState()
  347. self.multi_modal_data = multi_modal_data
  348. @property
  349. def prompt(self) -> str:
  350. # All sequences in the group should have the same prompt.
  351. # We use the prompt of an arbitrary sequence.
  352. return next(iter(self.seqs_dict.values())).prompt
  353. @property
  354. def prompt_token_ids(self) -> List[int]:
  355. # All sequences in the group should have the same prompt.
  356. # We use the prompt of an arbitrary sequence.
  357. return next(iter(self.seqs_dict.values())).data.prompt_token_ids
  358. @property
  359. def lora_int_id(self) -> int:
  360. return self.lora_request.lora_int_id if self.lora_request else 0
  361. def get_last_latency(self, now: float) -> float:
  362. """Gets last token latency for Request level timings."""
  363. latency = now - self.metrics.last_token_time
  364. self.metrics.last_token_time = now
  365. return latency
  366. def maybe_set_first_token_time(self, time: float) -> None:
  367. """Sets the first token time for Request level timings."""
  368. if self.metrics.first_token_time is None:
  369. self.metrics.first_token_time = time
  370. def maybe_set_first_scheduled_time(self, time: float) -> None:
  371. """Sets the first scheduled time and time in queue for Request level
  372. timings."""
  373. if self.metrics.first_scheduled_time is None:
  374. self.metrics.first_scheduled_time = time
  375. self.metrics.time_in_queue = time - self.metrics.arrival_time
  376. def set_finished_time(self, time: Optional[float]) -> None:
  377. """Sets the finished time for Request level timings."""
  378. self.metrics.finished_time = time
  379. def get_max_num_running_seqs(self) -> int:
  380. """The maximum number of sequences running in parallel in the remaining
  381. lifetime of the request."""
  382. if self.sampling_params.use_beam_search:
  383. # For beam search, maximally there will always be `best_of` beam
  384. # candidates running in the future.
  385. return self.sampling_params.best_of
  386. else:
  387. if self.sampling_params.best_of > self.num_seqs():
  388. # At prompt stage, the sequence group is not yet filled up
  389. # and only have one sequence running. However, in the
  390. # generation stage, we will have `best_of` sequences running.
  391. return self.sampling_params.best_of
  392. # At sampling stages, return the number of actual sequences
  393. # that are not finished yet.
  394. return self.num_unfinished_seqs()
  395. def get_seqs(
  396. self,
  397. status: Optional[SequenceStatus] = None,
  398. ) -> List[Sequence]:
  399. return (list(self.seqs_dict.values()) if status is None else [
  400. seq for seq in self.seqs_dict.values() if seq.status == status
  401. ])
  402. def get_unfinished_seqs(self) -> List[Sequence]:
  403. return [
  404. seq for seq in self.seqs_dict.values() if not seq.is_finished()
  405. ]
  406. def get_finished_seqs(self) -> List[Sequence]:
  407. return [seq for seq in self.seqs_dict.values() if seq.is_finished()]
  408. def update_num_computed_tokens(self, num_new_computed_tokens: int):
  409. """Update number of tokens computed so far."""
  410. for seq in self.seqs_dict.values():
  411. if not seq.is_finished():
  412. seq.data.update_num_computed_tokens(num_new_computed_tokens)
  413. def get_num_uncomputed_tokens(self) -> int:
  414. num_uncomputed_tokens = 0
  415. for seq in self.get_seqs():
  416. if not seq.is_finished():
  417. num_uncomputed_tokens += seq.data.get_num_uncomputed_tokens()
  418. return num_uncomputed_tokens
  419. def num_seqs(self, status: Optional[SequenceStatus] = None) -> int:
  420. # Optimization. We don't need to call get_seqs if we don't need to
  421. # filter by states.
  422. if status is None:
  423. return len(self.seqs_dict)
  424. return len(self.get_seqs(status))
  425. def num_unfinished_seqs(self) -> int:
  426. return len(self.get_unfinished_seqs())
  427. def num_finished_seqs(self) -> int:
  428. return len(self.get_finished_seqs())
  429. def find(self, seq_id: int) -> Sequence:
  430. if seq_id not in self.seqs_dict:
  431. raise ValueError(f"Sequence {seq_id} not found.")
  432. return self.seqs_dict[seq_id]
  433. def add(self, seq: Sequence) -> None:
  434. if seq.seq_id in self.seqs_dict:
  435. raise ValueError(f"Sequence {seq.seq_id} already exists.")
  436. self.seqs_dict[seq.seq_id] = seq
  437. def remove(self, seq_id: int) -> None:
  438. if seq_id not in self.seqs_dict:
  439. raise ValueError(f"Sequence {seq_id} not found.")
  440. del self.seqs_dict[seq_id]
  441. def is_finished(self) -> bool:
  442. return all(seq.is_finished() for seq in self.get_seqs())
  443. def is_prefill(self) -> bool:
  444. # Every sequences should be in the same stage.
  445. return self.get_seqs()[0].is_prefill()
  446. def __repr__(self) -> str:
  447. return (f"SequenceGroup(request_id={self.request_id}, "
  448. f"sampling_params={self.sampling_params}, "
  449. f"num_seqs={len(self.seqs_dict)})")
  450. class SequenceGroupMetadata:
  451. """Metadata for a sequence group. Used to create `AttentionMetadata`.
  452. Args:
  453. request_id: The ID of the request.
  454. is_prompt: Whether the request is at prompt stage.
  455. seq_data: The sequence data. (Seq id -> sequence data)
  456. sampling_params: The sampling parameters used to generate the outputs.
  457. block_tables: The block tables. (Seq id -> list of physical block
  458. numbers)
  459. token_chunk_size: The number of tokens to be processed (per sequence).
  460. None if chunking is not required.
  461. state: Internal state tied to this sequence group.
  462. lora_request: LoRA request.
  463. multi_modal_data: Multi modal data for the request.
  464. persistent_data: The persistent data of the sequence group.
  465. """
  466. def __init__(
  467. self,
  468. request_id: str,
  469. is_prompt: bool,
  470. seq_data: Dict[int, SequenceData],
  471. sampling_params: SamplingParams,
  472. block_tables: Dict[int, List[int]],
  473. persistent_data: Dict[int, dict],
  474. token_chunk_size: Optional[int] = None,
  475. lora_request: Optional[LoRARequest] = None,
  476. computed_block_nums: Optional[List[int]] = None,
  477. state: Optional[SequenceGroupState] = None,
  478. multi_modal_data: Optional[MultiModalData] = None,
  479. ) -> None:
  480. self.request_id = request_id
  481. self.is_prompt = is_prompt
  482. self.seq_data = seq_data
  483. self.sampling_params = sampling_params
  484. self.block_tables = block_tables
  485. self.persistent_data = persistent_data
  486. self.lora_request = lora_request
  487. self.computed_block_nums = computed_block_nums
  488. self.state = SequenceGroupState() if state is None else state
  489. self.multi_modal_data = multi_modal_data
  490. self._token_chunk_size = token_chunk_size
  491. if self._token_chunk_size is None:
  492. if is_prompt:
  493. self._token_chunk_size = list(seq_data.values())[0].get_len()
  494. else:
  495. self._token_chunk_size = 1
  496. @property
  497. def lora_int_id(self) -> int:
  498. return self.lora_request.lora_int_id if self.lora_request else 0
  499. @property
  500. def token_chunk_size(self) -> int:
  501. """Return the number of tokens to be processed (chunk size)."""
  502. return self._token_chunk_size
  503. class SequenceOutput:
  504. """The model output associated with a sequence.
  505. Args:
  506. parent_seq_id: The ID of the parent sequence (for forking in beam
  507. search).
  508. output_token: The output token ID.
  509. logprobs: The logprobs of the output token.
  510. (Token id -> logP(x_i+1 | x_0, ..., x_i))
  511. persistent_data: The persistent data of the sequence.
  512. """
  513. def __init__(
  514. self,
  515. parent_seq_id: int,
  516. output_token: int,
  517. logprobs: Dict[int, Logprob],
  518. persistent_data: dict,
  519. ) -> None:
  520. self.parent_seq_id = parent_seq_id
  521. self.output_token = output_token
  522. self.logprobs = logprobs
  523. self.persistent_data = persistent_data
  524. def __repr__(self) -> str:
  525. return (f"SequenceOutput(parent_seq_id={self.parent_seq_id}, "
  526. f"output_token={self.output_token}, "
  527. f"logprobs={self.logprobs}, "
  528. f"persistent_data={self.persistent_data})")
  529. def __eq__(self, other: object) -> bool:
  530. if not isinstance(other, SequenceOutput):
  531. raise NotImplementedError()
  532. equal = (self.parent_seq_id == other.parent_seq_id
  533. and self.output_token == other.output_token)
  534. log_probs_equal = other.logprobs == self.logprobs
  535. return equal and log_probs_equal
  536. class SequenceGroupOutput:
  537. """The model output associated with a sequence group."""
  538. def __init__(
  539. self,
  540. samples: List[SequenceOutput],
  541. prompt_logprobs: Optional[PromptLogprobs],
  542. ) -> None:
  543. self.samples = samples
  544. self.prompt_logprobs = prompt_logprobs
  545. def __repr__(self) -> str:
  546. return (f"SequenceGroupOutput(samples={self.samples}, "
  547. f"prompt_logprobs={self.prompt_logprobs})")
  548. def __eq__(self, other: object) -> bool:
  549. if not isinstance(other, SequenceGroupOutput):
  550. raise NotImplementedError()
  551. return (self.samples == other.samples
  552. and self.prompt_logprobs == other.prompt_logprobs)
  553. @dataclass
  554. class SamplerOutput:
  555. """For each sequence group, we generate a list of SequenceOutput object,
  556. each of which contains one possible candidate for the next token.
  557. This datastructure implements methods so it can be used like a list, but
  558. also has optional fields for device tensors.
  559. """
  560. outputs: List[SequenceGroupOutput]
  561. # On-device tensor containing probabilities of each token.
  562. sampled_token_probs: Optional["torch.Tensor"] = None
  563. # On-device tensor containing the sampled token ids.
  564. sampled_token_ids: Optional["torch.Tensor"] = None
  565. # Spec decode metrics populated by workers.
  566. spec_decode_worker_metrics: Optional["SpecDecodeWorkerMetrics"] = None
  567. def __getitem__(self, idx: int):
  568. return self.outputs[idx]
  569. def __setitem__(self, idx: int, value):
  570. self.outputs[idx] = value
  571. def __len__(self):
  572. return len(self.outputs)
  573. def __eq__(self, other: object):
  574. return (isinstance(other, self.__class__)
  575. and self.outputs == other.outputs)
  576. def __repr__(self) -> str:
  577. """Show the shape of a tensor instead of its values to reduce noise.
  578. """
  579. sampled_token_probs_repr = ("None" if self.sampled_token_probs is None
  580. else self.sampled_token_probs.shape)
  581. sampled_token_ids_repr = ("None" if self.sampled_token_ids is None else
  582. self.sampled_token_ids.shape)
  583. return (
  584. f"SamplerOutput(outputs={self.outputs}, "
  585. f"sampled_token_probs={sampled_token_probs_repr}, "
  586. f"sampled_token_ids={sampled_token_ids_repr}, "
  587. f"spec_decode_worker_metrics={self.spec_decode_worker_metrics})")