sequence.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. """Sequence and its related classes."""
  2. import copy
  3. import enum
  4. from abc import ABC, abstractmethod
  5. from array import array
  6. from collections import defaultdict
  7. from dataclasses import dataclass, field
  8. from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union, cast
  9. import torch
  10. from aphrodite.common.pooling_params import PoolingParams
  11. from aphrodite.common.sampling_params import SamplingParams
  12. from aphrodite.inputs.parse import is_valid_encoder_decoder_llm_inputs
  13. from aphrodite.lora.request import LoRARequest
  14. from aphrodite.prompt_adapter.request import PromptAdapterRequest
  15. if TYPE_CHECKING:
  16. from aphrodite.inputs import LLMInputs
  17. from aphrodite.multimodal import MultiModalDataDict
  18. from aphrodite.spec_decode.metrics import SpecDecodeWorkerMetrics
  19. @dataclass
  20. class Logprob:
  21. """Infos for supporting OpenAI compatible logprobs and token ranks.
  22. Attributes:
  23. logprob: The logprob of chosen token
  24. rank: The vocab rank of chosen token (>=1)
  25. decoded_token: The decoded chosen token index
  26. """
  27. logprob: float
  28. rank: Optional[int] = None
  29. decoded_token: Optional[str] = None
  30. # {token_id -> logprob} per each sequence group. None if the corresponding
  31. # sequence group doesn't require prompt logprob.
  32. PromptLogprobs = List[Optional[Dict[int, Logprob]]]
  33. # {token_id -> logprob} for each sequence group.
  34. SampleLogprobs = List[Dict[int, Logprob]]
  35. class SequenceStatus(enum.IntEnum):
  36. """Status of a sequence."""
  37. WAITING = 0
  38. RUNNING = 1
  39. SWAPPED = 2
  40. # Note: anything after SWAPPED (2) will be considered
  41. # as a finished status.
  42. FINISHED_STOPPED = 3
  43. FINISHED_LENGTH_CAPPED = 4
  44. FINISHED_ABORTED = 5
  45. FINISHED_IGNORED = 6
  46. @staticmethod
  47. def is_finished(status: "SequenceStatus") -> bool:
  48. return status > SequenceStatus.SWAPPED
  49. @staticmethod
  50. def get_finished_reason(status: "SequenceStatus") -> Union[str, None]:
  51. if status == SequenceStatus.FINISHED_STOPPED:
  52. finish_reason = "stop"
  53. elif status == SequenceStatus.FINISHED_LENGTH_CAPPED:
  54. finish_reason = "length"
  55. elif status == SequenceStatus.FINISHED_ABORTED:
  56. finish_reason = "abort"
  57. elif status == SequenceStatus.FINISHED_IGNORED:
  58. # The ignored sequences are the sequences whose prompt lengths
  59. # are longer than the model's length cap. Therefore, the stop
  60. # reason should also be "length" as in OpenAI API.
  61. finish_reason = "length"
  62. else:
  63. finish_reason = None
  64. return finish_reason
  65. class SequenceStage(enum.Enum):
  66. PREFILL = enum.auto()
  67. DECODE = enum.auto()
  68. @dataclass
  69. class RequestMetrics:
  70. """Metrics associated with a request.
  71. Attributes:
  72. arrival_time: The time when the request arrived.
  73. first_scheduled_time: The time when the request was first scheduled.
  74. first_token_time: The time when the first token was generated.
  75. time_in_queue: The time the request spent in the queue.
  76. finished_time: The time when the request was finished.
  77. """
  78. arrival_time: float
  79. last_token_time: float
  80. first_scheduled_time: Optional[float]
  81. first_token_time: Optional[float]
  82. time_in_queue: Optional[float]
  83. finished_time: Optional[float] = None
  84. class SequenceData:
  85. """Data associated with a sequence.
  86. Args:
  87. prompt_token_ids: The token IDs of the prompt.
  88. output_token_ids: The token IDs of the output. Set to an empty list if
  89. None.
  90. Attributes:
  91. prompt_token_ids: The token IDs of the prompt.
  92. output_token_ids: The token IDs of the output.
  93. cumulative_logprob: The cumulative log probability of the output.
  94. """
  95. def __init__(
  96. self,
  97. prompt_token_ids: List[int],
  98. output_token_ids: Optional[List[int]] = None,
  99. ) -> None:
  100. self._prompt_token_ids = array('l', prompt_token_ids)
  101. self._prompt_token_ids_tuple: Tuple[int, ...] = tuple(prompt_token_ids)
  102. self._output_token_ids = array(
  103. 'l', output_token_ids if output_token_ids is not None else [])
  104. self.cumulative_logprob = 0.0
  105. # The number of tokens that are computed (that run against the model).
  106. self._num_computed_tokens = 0
  107. self._stage: SequenceStage = SequenceStage.PREFILL
  108. self._update_cached_all_tokens()
  109. def _update_cached_all_tokens(self):
  110. self._cached_all_token_ids: List[int] = list(self._prompt_token_ids +
  111. self._output_token_ids)
  112. @property
  113. def prompt_token_ids(self) -> Tuple[int, ...]:
  114. return self._prompt_token_ids_tuple
  115. @prompt_token_ids.setter
  116. def prompt_token_ids(self, new_prompt_token_ids) -> None:
  117. self._prompt_token_ids = array('l', new_prompt_token_ids)
  118. self._prompt_token_ids_tuple = tuple(new_prompt_token_ids)
  119. self._update_cached_all_tokens()
  120. @property
  121. def prompt_token_ids_array(self) -> array:
  122. return self._prompt_token_ids
  123. @property
  124. def output_token_ids(self) -> Tuple[int, ...]:
  125. return tuple(self._output_token_ids)
  126. @output_token_ids.setter
  127. def output_token_ids(self, new_output_token_ids) -> None:
  128. self._output_token_ids = array('l', new_output_token_ids)
  129. self._update_cached_all_tokens()
  130. @property
  131. def output_token_ids_array(self) -> array:
  132. return self._output_token_ids
  133. def append_token_id(self, token_id: int, logprob: float) -> None:
  134. self._output_token_ids.append(token_id)
  135. self._cached_all_token_ids.append(token_id)
  136. self.cumulative_logprob += logprob
  137. def get_len(self) -> int:
  138. return len(self._output_token_ids) + len(self._prompt_token_ids)
  139. def get_prompt_len(self) -> int:
  140. return len(self._prompt_token_ids)
  141. def get_output_len(self) -> int:
  142. return len(self._output_token_ids)
  143. def get_token_ids(self) -> List[int]:
  144. return self._cached_all_token_ids
  145. def get_prefix_token_ids(
  146. self, num_tokens: int
  147. ) -> Tuple[Tuple[int, ...], Optional[Tuple[int, ...]]]:
  148. """Get prefix tokens, and make the return value hashable"""
  149. prompt_length = self.get_prompt_len()
  150. if num_tokens > prompt_length:
  151. return (self._prompt_token_ids_tuple,
  152. tuple(self._output_token_ids[:num_tokens - prompt_length]))
  153. else:
  154. return (self._prompt_token_ids_tuple[:num_tokens], None)
  155. def get_num_computed_tokens(self) -> int:
  156. """Return the number of prefill tokens that are already computed."""
  157. return self._num_computed_tokens
  158. def update_num_computed_tokens(self, num_new_computed_tokens: int):
  159. """Update number of tokens computed so far."""
  160. self._num_computed_tokens += num_new_computed_tokens
  161. assert self._num_computed_tokens <= self.get_len(), (
  162. self._num_computed_tokens, self.get_len())
  163. # If all tokens are computed, it means it is in decoding phase.
  164. if self.get_num_uncomputed_tokens() == 0:
  165. self._stage = SequenceStage.DECODE
  166. def reset_state_for_recompute(self) -> None:
  167. """Reset the number of computed tokens from this sequence. It is
  168. supposed to be called when a sequence needs to be started from
  169. the beginning again (e.g., sequence is preempted).
  170. """
  171. self._num_computed_tokens = 0
  172. self._stage = SequenceStage.PREFILL
  173. def get_num_uncomputed_tokens(self) -> int:
  174. """Return the number of prefill tokens that are not computed."""
  175. # we use `get_len()` which includes prompt_len + output_len instead
  176. # of prompt_len here. This is because during recompute we need to
  177. # prefill for both prompt and output.
  178. return self.get_len() - self.get_num_computed_tokens()
  179. def get_last_token_id(self) -> int:
  180. if not self._output_token_ids:
  181. return self._prompt_token_ids[-1]
  182. return self._output_token_ids[-1]
  183. def get_prompt_token_ids(self) -> Tuple[int, ...]:
  184. return self.prompt_token_ids
  185. def get_output_token_ids(self) -> Tuple[int, ...]:
  186. return self.output_token_ids
  187. @property
  188. def stage(self) -> SequenceStage:
  189. return self._stage
  190. def __repr__(self) -> str:
  191. return (f"SequenceData("
  192. f"prompt_token_ids={self._prompt_token_ids}, "
  193. f"output_token_ids={self._output_token_ids}, "
  194. f"cumulative_logprob={self.cumulative_logprob})")
  195. class Sequence:
  196. """Stores the data, status, and block information of a sequence.
  197. The sequence is constructed from the LLMInputs instance passed
  198. in through the `inputs` constructor argument.
  199. For encoder/decoder models, LLMInputs encapsulates both a
  200. decoder and encoder prompt, creating an ambiguity about which
  201. prompt to construct the sequence from. The `from_decoder_prompt`
  202. constructor argument signals whether to construct the Sequence
  203. from the LLMInputs decoder prompt, or encoder prompt.
  204. Args:
  205. seq_id: The ID of the sequence.
  206. inputs: The inputs of the sequence.
  207. block_size: The block size of the sequence. Should be the same as the
  208. block size used by the block manager and cache engine.
  209. eos_token_id: The end-of-sequence (EOS) token id recognized by this LLM.
  210. lora_request: LoRA request.
  211. prompt_adapter_request: Prompt Adapter request.
  212. from_decoder_prompt: Construct Sequence from LLMInputs decoder prompt
  213. (True) or encoder prompt (False.) Must be True
  214. for decoder-only model.
  215. """
  216. def __init__(
  217. self,
  218. seq_id: int,
  219. inputs: "LLMInputs",
  220. block_size: int,
  221. eos_token_id: Optional[int] = None,
  222. lora_request: Optional[LoRARequest] = None,
  223. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  224. from_decoder_prompt: bool = True,
  225. ) -> None:
  226. self.seq_id = seq_id
  227. self.inputs = inputs
  228. self.block_size = block_size
  229. self.eos_token_id = eos_token_id
  230. self.lora_request = lora_request
  231. self.prompt_adapter_request = prompt_adapter_request
  232. self.from_decoder_prompt = from_decoder_prompt
  233. self._prompt: Optional[str] = None
  234. self._prompt_token_ids: Optional[List[int]] = None
  235. # For decoder-only models, a Sequence is constructed
  236. # from an LLMInputs instance (the `inputs` arg.)
  237. #
  238. # For encoder/decoder models the same `inputs`
  239. # instance could be utilized to construct either an
  240. # encoder sequence or a decoder sequence, because
  241. # `LLMInputs` has both decoder- and encoder-oriented
  242. # member variables (i.e. it encapsulates both an encoder
  243. # and a decoder prompt.) The decision of which type of sequence
  244. # to generate is determined by the `from_decoder_prompt` argument.
  245. #
  246. # When constructing a encoder sequence
  247. # (`from_decoder_prompt` False) it matters that
  248. # the `LLMInputs` instance stored in `inputs` is valid
  249. # in the sense that its encoder-related member variables are
  250. # populated; below, an exception is raised if this is
  251. # not the case.
  252. #
  253. # When constructing a decoder sequence (`from_decoder_prompt` True)
  254. # it does not matter whether `inputs` has its encoder-related
  255. # member variables populated.
  256. if not (from_decoder_prompt
  257. or is_valid_encoder_decoder_llm_inputs(inputs)):
  258. raise ValueError("Cannot extract encoder input prompt from "
  259. f"invalid input {inputs}; did you forget the "
  260. "encoder input prompt fields?")
  261. self.data = SequenceData(self.prompt_token_ids)
  262. self.output_logprobs: SampleLogprobs = []
  263. self.output_text = ""
  264. self.status = SequenceStatus.WAITING
  265. self.stop_reason: Union[int, str, None] = None
  266. # Used for incremental detokenization
  267. self.prefix_offset = 0
  268. self.read_offset = 0
  269. # Input + output tokens
  270. self.tokens: Optional[List[str]] = None
  271. @property
  272. def n_blocks(self) -> int:
  273. return (self.get_len() + self.block_size - 1) // self.block_size
  274. @property
  275. def prompt(self) -> Optional[str]:
  276. if self._prompt is not None:
  277. # Reuse precomputed prompt string
  278. return self._prompt
  279. # Select decoder or encoder input prompt str,
  280. # as appropriate
  281. prompt_key: str = ("prompt"
  282. if self.from_decoder_prompt else "encoder_prompt")
  283. # Cache prompt
  284. self._prompt = cast(Optional[str], self.inputs.get(prompt_key))
  285. return self._prompt
  286. @property
  287. def prompt_token_ids(self) -> List[int]:
  288. if self._prompt_token_ids is not None:
  289. # Reuse precomputed prompt token ids
  290. return self._prompt_token_ids
  291. # Select decoder or encoder input prompt
  292. # token ids, as appropriate
  293. prompt_token_ids_key: str = ("prompt_token_ids"
  294. if self.from_decoder_prompt else
  295. "encoder_prompt_token_ids")
  296. # Cache computed prompt token ids
  297. self._prompt_token_ids = cast(List[int],
  298. self.inputs.get(prompt_token_ids_key))
  299. return self._prompt_token_ids
  300. @property
  301. def multi_modal_data(self) -> Optional["MultiModalDataDict"]:
  302. return self.inputs.get("multi_modal_data")
  303. @property
  304. def lora_int_id(self) -> int:
  305. return self.lora_request.lora_int_id if self.lora_request else 0
  306. @property
  307. def prompt_adapter_id(self) -> int:
  308. return self.prompt_adapter_request.prompt_adapter_id \
  309. if self.prompt_adapter_request else 0
  310. def get_output_text_to_return(self, buffer_length: int):
  311. # We return the full output text if the sequence is finished.
  312. truncate = buffer_length and not self.is_finished()
  313. return self.output_text[:-buffer_length] if truncate else (
  314. self.output_text)
  315. def hash_of_block(self, logical_idx: int) -> int:
  316. # TODO This can produce incorrect hash when block size > prompt size
  317. # Compute the number of tokens in the sequence
  318. # TODO: The current hashing function is O(L^2). We should optimize
  319. # this in the future.
  320. num_tokens = self.num_hashed_tokens_of_block(logical_idx)
  321. hashed_tokens = self.data.get_prefix_token_ids(num_tokens)
  322. return hash((hashed_tokens, self.lora_int_id))
  323. def num_hashed_tokens_of_block(self, logical_idx: int):
  324. return logical_idx * self.block_size + self.block_size
  325. def reset_state_for_recompute(self):
  326. """Reset the sequence states for recomputation."""
  327. self.data.reset_state_for_recompute()
  328. def append_token_id(
  329. self,
  330. token_id: int,
  331. logprobs: Dict[int, Logprob],
  332. ) -> None:
  333. assert token_id in logprobs
  334. self.output_logprobs.append(logprobs)
  335. self.data.append_token_id(token_id, logprobs[token_id].logprob)
  336. def get_len(self) -> int:
  337. return self.data.get_len()
  338. def get_prompt_len(self) -> int:
  339. return self.data.get_prompt_len()
  340. def get_output_len(self) -> int:
  341. return self.data.get_output_len()
  342. def get_token_ids(self) -> List[int]:
  343. return self.data.get_token_ids()
  344. def get_prompt_token_ids(self) -> Tuple[int, ...]:
  345. return self.data.get_prompt_token_ids()
  346. def get_last_token_id(self) -> int:
  347. return self.data.get_last_token_id()
  348. def get_output_token_ids(self) -> Tuple[int, ...]:
  349. return self.data.get_output_token_ids()
  350. def get_cumulative_logprob(self) -> float:
  351. return self.data.cumulative_logprob
  352. def get_beam_search_score(self,
  353. length_penalty: float = 1.0,
  354. seq_len: Optional[int] = None,
  355. eos_token_id: Optional[int] = None) -> float:
  356. """Calculate the beam search score with length penalty.
  357. Adapted from
  358. https://github.com/huggingface/transformers/blob/ccb92be23def445f2afdea94c31286f84b89eb5b/src/transformers/generation/beam_search.py#L938
  359. """
  360. if seq_len is None:
  361. seq_len = self.get_len()
  362. # NOTE: HF implementation does not count the EOS token
  363. # towards the length, we align with that here for testing.
  364. if (eos_token_id is not None
  365. and self.get_last_token_id() == eos_token_id):
  366. seq_len -= 1
  367. return self.get_cumulative_logprob() / (seq_len**length_penalty)
  368. def is_finished(self) -> bool:
  369. return SequenceStatus.is_finished(self.status)
  370. def fork(self, new_seq_id: int) -> "Sequence":
  371. new_seq = copy.deepcopy(self)
  372. new_seq.seq_id = new_seq_id
  373. return new_seq
  374. def get_num_new_tokens(self) -> int:
  375. """Get the number of new tokens to be computed.
  376. Returns:
  377. The new number of tokens to be computed. I.e., 1 for decode, or
  378. the remaining prompt size for prefill.
  379. """
  380. if self.data.stage == SequenceStage.DECODE:
  381. return 1
  382. return self.data.get_num_uncomputed_tokens()
  383. def is_prefill(self) -> bool:
  384. return self.data.stage == SequenceStage.PREFILL
  385. def __repr__(self) -> str:
  386. return (f"Sequence(seq_id={self.seq_id}, "
  387. f"status={self.status.name}, "
  388. f"num_blocks={self.n_blocks}, ")
  389. class SequenceGroup:
  390. """A group of sequences that are generated from the same prompt.
  391. Args:
  392. request_id: The ID of the request.
  393. seqs: The list of sequences.
  394. sampling_params: The sampling parameters used to generate the outputs.
  395. arrival_time: The arrival time of the request.
  396. lora_request: LoRA request.
  397. embeddings: The embeddings vectors of the prompt of the sequence group
  398. for an embedding model.
  399. pooling_params: The pooling parameters used to generate the pooling
  400. for an embedding model.
  401. encoder_seq: Optional, the single encoder sequence. Should be None
  402. unless you are working with an encoder/decoder model.
  403. prompt_adapter_request: Prompt adapter request.
  404. """
  405. def __init__(
  406. self,
  407. request_id: str,
  408. seqs: List[Sequence],
  409. arrival_time: float,
  410. sampling_params: Optional[SamplingParams] = None,
  411. lora_request: Optional[LoRARequest] = None,
  412. embeddings: Optional[List[float]] = None,
  413. pooling_params: Optional[PoolingParams] = None,
  414. encoder_seq: Optional[Sequence] = None,
  415. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  416. ) -> None:
  417. self.request_id = request_id
  418. self.seqs = seqs
  419. self.is_single_seq = len(seqs) == 1
  420. self.seqs_dict = {seq.seq_id: seq for seq in seqs}
  421. self.sampling_params = sampling_params
  422. self.metrics = RequestMetrics(arrival_time=arrival_time,
  423. last_token_time=arrival_time,
  424. first_scheduled_time=None,
  425. first_token_time=None,
  426. time_in_queue=None)
  427. self.lora_request = lora_request
  428. self.prompt_logprobs: Optional[PromptLogprobs] = None
  429. self.embeddings = embeddings
  430. self.pooling_params = pooling_params
  431. self.prompt_adapter_request = prompt_adapter_request
  432. self.encoder_seq = encoder_seq
  433. @property
  434. def prompt(self) -> Optional[str]:
  435. # All sequences in the group should have the same prompt.
  436. # We use the prompt of an arbitrary sequence.
  437. return self.seqs[0].prompt
  438. @property
  439. def prompt_token_ids(self) -> List[int]:
  440. # All sequences in the group should have the same prompt.
  441. # We use the prompt of an arbitrary sequence.
  442. return self.seqs[0].prompt_token_ids
  443. @property
  444. def encoder_prompt(self) -> Optional[str]:
  445. # There are either 0 or 1 encoder sequences
  446. # If one is present, its prompt is distinct
  447. # from the decoder's.
  448. return (self.encoder_seq.prompt
  449. if self.encoder_seq is not None else None)
  450. @property
  451. def encoder_prompt_token_ids(self) -> Optional[List[int]]:
  452. # There are either 0 or 1 encoder sequences
  453. # If one is present, its prompt token ids are
  454. # distinct from the decoder's.
  455. return (self.encoder_seq.prompt_token_ids
  456. if self.encoder_seq is not None else None)
  457. @property
  458. def multi_modal_data(self) -> "MultiModalDataDict":
  459. # All sequences in the group should have the same multi-modal data.
  460. # We use the multi-modal data of an arbitrary sequence.
  461. return self.seqs[0].multi_modal_data
  462. @property
  463. def lora_int_id(self) -> int:
  464. return self.lora_request.lora_int_id if self.lora_request else 0
  465. @property
  466. def prompt_adapter_id(self) -> int:
  467. return self.prompt_adapter_request.prompt_adapter_id \
  468. if self.prompt_adapter_request else 0
  469. @property
  470. def prompt_adapter_num_virtual_tokens(self) -> int:
  471. return self.prompt_adapter_request.prompt_adapter_num_virtual_tokens\
  472. if self.prompt_adapter_request else 0
  473. def get_last_latency(self, now: float) -> Optional[float]:
  474. """Sets the last token time for Request level timings."""
  475. # If still in prefill phase, raise Error.
  476. if self.is_prefill():
  477. raise ValueError(
  478. "seq_group.get_last_latency() should not be called "
  479. "if the seq_group is in prefill phase.")
  480. # Otherwise return token latency.
  481. latency = now - self.metrics.last_token_time
  482. self.metrics.last_token_time = now
  483. return latency
  484. def maybe_set_first_token_time(self, time: float) -> None:
  485. """Sets the first token time for Request level timings."""
  486. # NOTE: in a case where a sequence_group is swapped and
  487. # recomputed, the time between iterations is counted
  488. # in TPOT, rather than recalculating TTFT (since from the )
  489. # POV of the user, there is simply a long generation delay.
  490. if (self.metrics.first_token_time is None
  491. and self.seqs[0].get_output_len() == 1):
  492. self.metrics.first_token_time = time
  493. def maybe_set_first_scheduled_time(self, time: float) -> None:
  494. """Sets the first scheduled time and time in queue for Request
  495. level timings."""
  496. if self.metrics.first_scheduled_time is None:
  497. self.metrics.first_scheduled_time = time
  498. self.metrics.time_in_queue = time - self.metrics.arrival_time
  499. def set_finished_time(self, time: Optional[float]) -> None:
  500. """Sets the finished time for Request level timings."""
  501. self.metrics.finished_time = time
  502. def get_max_num_running_seqs(self) -> int:
  503. """The maximum number of sequences running in parallel in the remaining
  504. lifetime of the request."""
  505. if self.sampling_params and self.sampling_params.use_beam_search:
  506. # For beam search, maximally there will always be `best_of` beam
  507. # candidates running in the future.
  508. return self.sampling_params.best_of
  509. else:
  510. if (self.sampling_params
  511. and self.sampling_params.best_of > self.num_seqs()):
  512. # At prompt stage, the sequence group is not yet filled up
  513. # and only have one sequence running. However, in the
  514. # generation stage, we will have `best_of` sequences running.
  515. return self.sampling_params.best_of
  516. # At sampling stages, return the number of actual sequences
  517. # that are not finished yet.
  518. return self.num_unfinished_seqs()
  519. def get_seqs(
  520. self,
  521. status: Optional[SequenceStatus] = None,
  522. ) -> List[Sequence]:
  523. if status is None:
  524. return self.seqs
  525. if self.is_single_seq:
  526. return self.seqs if self.seqs[0].status == status else []
  527. return [seq for seq in self.seqs if seq.status == status]
  528. def is_encoder_decoder(self) -> bool:
  529. return self.encoder_seq is not None
  530. def get_encoder_seq(self) -> Optional[Sequence]:
  531. return self.encoder_seq
  532. def get_unfinished_seqs(self) -> List[Sequence]:
  533. if self.is_single_seq:
  534. return self.seqs if not self.seqs[0].is_finished() else []
  535. return [seq for seq in self.seqs if not seq.is_finished()]
  536. def get_finished_seqs(self) -> List[Sequence]:
  537. if self.is_single_seq:
  538. return self.seqs if self.seqs[0].is_finished() else []
  539. return [seq for seq in self.seqs if seq.is_finished()]
  540. def update_num_computed_tokens(self, num_new_computed_tokens: int):
  541. """Update number of tokens computed so far."""
  542. for seq in self.seqs:
  543. if not seq.is_finished():
  544. seq.data.update_num_computed_tokens(num_new_computed_tokens)
  545. def get_num_uncomputed_tokens(self) -> int:
  546. num_uncomputed_tokens = 0
  547. for seq in self.seqs:
  548. if not seq.is_finished():
  549. num_uncomputed_tokens += seq.data.get_num_uncomputed_tokens()
  550. return num_uncomputed_tokens
  551. def num_seqs(self, status: Optional[SequenceStatus] = None) -> int:
  552. # Optimization. We don't need to call get_seqs if we don't need to
  553. # filter by states.
  554. if status is None:
  555. return len(self.seqs)
  556. if self.is_single_seq:
  557. return 1 if self.seqs[0].status == status else 0
  558. return len(self.get_seqs(status))
  559. def num_unfinished_seqs(self) -> int:
  560. if self.is_single_seq:
  561. return 1 if not self.seqs[0].is_finished() else 0
  562. return len(self.get_unfinished_seqs())
  563. def num_finished_seqs(self) -> int:
  564. if self.is_single_seq:
  565. return 1 if self.seqs[0].is_finished() else 0
  566. return len(self.get_finished_seqs())
  567. def find(self, seq_id: int) -> Sequence:
  568. if seq_id not in self.seqs_dict:
  569. raise ValueError(f"Sequence {seq_id} not found.")
  570. return self.seqs_dict[seq_id]
  571. def add(self, seq: Sequence) -> None:
  572. if seq.seq_id in self.seqs_dict:
  573. raise ValueError(f"Sequence {seq.seq_id} already exists.")
  574. self.seqs_dict[seq.seq_id] = seq
  575. self.seqs.append(seq)
  576. self.is_single_seq = len(self.seqs) == 1
  577. def remove(self, seq_id: int) -> None:
  578. seq = self.seqs_dict.pop(seq_id, None)
  579. if seq is None:
  580. raise ValueError(f"Sequence {seq_id} not found.")
  581. self.seqs.remove(seq)
  582. self.is_single_seq = len(self.seqs) == 1
  583. def is_finished(self) -> bool:
  584. return all(seq.is_finished() for seq in self.seqs)
  585. def is_prefill(self) -> bool:
  586. # Every sequence should be in the same stage.
  587. return self.seqs[0].is_prefill()
  588. def __repr__(self) -> str:
  589. return (f"SequenceGroup(request_id={self.request_id}, "
  590. f"sampling_params={self.sampling_params}, "
  591. f"num_seqs={len(self.seqs)})")
  592. class SequenceGroupMetadata:
  593. """Metadata for a sequence group. Used to create `AttentionMetadata`.
  594. Args:
  595. request_id: The ID of the request.
  596. is_prompt: Whether the request is at prompt stage.
  597. seq_data: The sequence data. (Seq id -> sequence data)
  598. sampling_params: The sampling parameters used to generate the outputs.
  599. block_tables: The block tables. (Seq id -> list of physical block
  600. numbers)
  601. do_sample: True if sampling is required. Sampling is not required when
  602. e.g., prefill is chunked, and the current iteration only computes
  603. query tokens for prefill, we don't need sampling.
  604. token_chunk_size: The number of tokens to be processed (per sequence).
  605. None if chunking is not required.
  606. lora_request: LoRA request.
  607. computed_block_nums: The block numbers that are already computed,
  608. used in prefix caching.
  609. multi_modal_data: Multi modal data.
  610. encoder_seq_data: Optional sequence data for encoder prompt
  611. (SequenceGroup.encoder_seq). Should be None
  612. unless you are working with an encoder/decoder
  613. model.
  614. cross_block_table: Optional cross-attention block table associated
  615. with the encoder prompt
  616. (SequenceGroup.encoder_seq). Should be None
  617. unless you are working with an encoder/decoder
  618. model.
  619. prompt_adapter_request: Prompt Adapter request.
  620. """
  621. def __init__(
  622. self,
  623. request_id: str,
  624. is_prompt: bool,
  625. seq_data: Dict[int, SequenceData],
  626. sampling_params: SamplingParams,
  627. block_tables: Dict[int, List[int]],
  628. do_sample: bool = True,
  629. pooling_params: Optional[PoolingParams] = None,
  630. token_chunk_size: Optional[int] = None,
  631. lora_request: Optional[LoRARequest] = None,
  632. computed_block_nums: Optional[List[int]] = None,
  633. multi_modal_data: Optional["MultiModalDataDict"] = None,
  634. encoder_seq_data: Optional[SequenceData] = None,
  635. cross_block_table: Optional[List[int]] = None,
  636. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  637. ) -> None:
  638. self.request_id = request_id
  639. self.is_prompt = is_prompt
  640. self.seq_data = seq_data
  641. self.sampling_params = sampling_params
  642. self.block_tables = block_tables
  643. self.pooling_params = pooling_params
  644. self.lora_request = lora_request
  645. self.prompt_adapter_request = prompt_adapter_request
  646. self.computed_block_nums = computed_block_nums
  647. self.multi_modal_data = multi_modal_data
  648. self.encoder_seq_data = encoder_seq_data
  649. self.cross_block_table = cross_block_table
  650. self._token_chunk_size = token_chunk_size
  651. self.do_sample = do_sample
  652. # The number of speculative tokens adopted in this request.
  653. # None means specuative decoding is not used.
  654. # Zero means speculative decoding is disabled for some reasons.
  655. # TODO: We should maintain this states out of the sequence group.
  656. self.num_speculative_tokens = None
  657. if seq_data is not None and self._token_chunk_size is None:
  658. if is_prompt:
  659. self._token_chunk_size = next(iter(
  660. seq_data.values())).get_len()
  661. else:
  662. self._token_chunk_size = 1
  663. @property
  664. def lora_int_id(self) -> int:
  665. return self.lora_request.lora_int_id if self.lora_request else 0
  666. @property
  667. def prompt_adapter_id(self) -> int:
  668. return self.prompt_adapter_request.prompt_adapter_id \
  669. if self.prompt_adapter_request else 0
  670. @property
  671. def prompt_adapter_num_virtual_tokens(self) -> int:
  672. return self.prompt_adapter_request.prompt_adapter_num_virtual_tokens \
  673. if self.prompt_adapter_request else 0
  674. @property
  675. def token_chunk_size(self) -> int:
  676. """Return the number of tokens to be processed (chunk size)."""
  677. assert self._token_chunk_size is not None
  678. return self._token_chunk_size
  679. class SequenceOutput:
  680. """The model output associated with a sequence.
  681. Args:
  682. parent_seq_id: The ID of the parent sequence (for forking in beam
  683. search).
  684. output_token: The output token ID.
  685. logprobs: The logprobs of the output token.
  686. (Token id -> logP(x_i+1 | x_0, ..., x_i))
  687. """
  688. def __init__(
  689. self,
  690. parent_seq_id: int,
  691. output_token: int,
  692. logprobs: Dict[int, Logprob],
  693. ) -> None:
  694. self.parent_seq_id = parent_seq_id
  695. self.output_token = output_token
  696. self.logprobs = logprobs
  697. def __repr__(self) -> str:
  698. return (f"SequenceOutput(parent_seq_id={self.parent_seq_id}, "
  699. f"output_token={self.output_token}, "
  700. f"logprobs={self.logprobs})")
  701. def __eq__(self, other: object) -> bool:
  702. if not isinstance(other, SequenceOutput):
  703. raise NotImplementedError()
  704. equal = (self.parent_seq_id == other.parent_seq_id
  705. and self.output_token == other.output_token)
  706. log_probs_equal = other.logprobs == self.logprobs
  707. return equal and log_probs_equal
  708. class SequenceGroupOutput(ABC):
  709. """The base class for model outputs associated with a sequence group."""
  710. @abstractmethod
  711. def __repr__(self) -> str:
  712. pass
  713. @abstractmethod
  714. def __eq__(self, other: object) -> bool:
  715. pass
  716. class CompletionSequenceGroupOutput(SequenceGroupOutput):
  717. """The model output associated with a completion sequence group."""
  718. def __init__(
  719. self,
  720. samples: List[SequenceOutput],
  721. prompt_logprobs: Optional[PromptLogprobs],
  722. ) -> None:
  723. self.samples = samples
  724. # Prompt logprob for each prompt query token.
  725. self.prompt_logprobs = prompt_logprobs
  726. def __repr__(self) -> str:
  727. return (f"CompletionSequenceGroupOutput(samples={self.samples}, "
  728. f"prompt_logprobs={self.prompt_logprobs})")
  729. def __eq__(self, other: object) -> bool:
  730. if not isinstance(other, CompletionSequenceGroupOutput):
  731. raise NotImplementedError()
  732. return (self.samples == other.samples
  733. and self.prompt_logprobs == other.prompt_logprobs)
  734. class EmbeddingSequenceGroupOutput(SequenceGroupOutput):
  735. """The model output associated with an embedding sequence group."""
  736. def __init__(
  737. self,
  738. embeddings: List[float],
  739. ) -> None:
  740. self.embeddings = embeddings
  741. def __repr__(self) -> str:
  742. return (f"EmbeddingSequenceGroupOutput("
  743. f"embeddings_shape={len(self.embeddings)})")
  744. def __eq__(self, other: object) -> bool:
  745. if not isinstance(other, EmbeddingSequenceGroupOutput):
  746. raise NotImplementedError()
  747. return self.embeddings == other.embeddings
  748. @dataclass
  749. class IntermediateTensors:
  750. """For all pipeline stages except the last, we need to return the hidden
  751. states and residuals to be sent to the next stage. This data structure
  752. contains the hidden states and residuals for a request.
  753. """
  754. tensors: Dict[str, torch.Tensor]
  755. def __getitem__(self, key: Union[str, slice]):
  756. if isinstance(key, str):
  757. return self.tensors[key]
  758. elif isinstance(key, slice):
  759. return self.__class__({k: v[key] for k, v in self.tensors.items()})
  760. def __setitem__(self, key: str, value):
  761. self.tensors[key] = value
  762. def __len__(self):
  763. return len(self.tensors)
  764. def __eq__(self, other: object):
  765. return isinstance(other, self.__class__) and self
  766. def __repr__(self) -> str:
  767. return f"IntermediateTensors(tensors={self.tensors})"
  768. @dataclass
  769. class SamplerOutput:
  770. """For each sequence group, we generate a list of SequenceOutput object,
  771. each of which contains one possible candidate for the next token.
  772. This data structure implements methods, so it can be used like a list, but
  773. also has optional fields for device tensors.
  774. """
  775. outputs: List[CompletionSequenceGroupOutput]
  776. # On-device tensor containing probabilities of each token.
  777. sampled_token_probs: Optional[torch.Tensor] = None
  778. # On-device tensor containing the logprobs of each token.
  779. logprobs: Optional["torch.Tensor"] = None
  780. # On-device tensor containing the sampled token ids.
  781. sampled_token_ids: Optional[torch.Tensor] = None
  782. # Spec decode metrics populated by workers.
  783. spec_decode_worker_metrics: Optional["SpecDecodeWorkerMetrics"] = None
  784. # Optional last hidden states from the model.
  785. hidden_states: Optional[torch.Tensor] = None
  786. def __getitem__(self, idx: int):
  787. return self.outputs[idx]
  788. def __setitem__(self, idx: int, value):
  789. self.outputs[idx] = value
  790. def __len__(self):
  791. return len(self.outputs)
  792. def __eq__(self, other: object):
  793. return isinstance(other,
  794. self.__class__) and self.outputs == other.outputs
  795. def __repr__(self) -> str:
  796. """Show the shape of a tensor instead of its values to reduce noise.
  797. """
  798. sampled_token_probs_repr = ("None" if self.sampled_token_probs is None
  799. else self.sampled_token_probs.shape)
  800. sampled_token_ids_repr = ("None" if self.sampled_token_ids is None else
  801. self.sampled_token_ids.shape)
  802. return (
  803. f"SamplerOutput(outputs={self.outputs}, "
  804. f"sampled_token_probs={sampled_token_probs_repr}, "
  805. f"sampled_token_ids={sampled_token_ids_repr}, "
  806. f"spec_decode_worker_metrics={self.spec_decode_worker_metrics})")
  807. @dataclass
  808. class PoolerOutput:
  809. """The output from a pooling operation in the embedding model."""
  810. outputs: List[EmbeddingSequenceGroupOutput]
  811. spec_decode_worker_metrics: Optional["SpecDecodeWorkerMetrics"] = None
  812. def __getitem__(self, idx: int):
  813. return self.outputs[idx]
  814. def __setitem__(self, idx: int, value):
  815. self.outputs[idx] = value
  816. def __len__(self):
  817. return len(self.outputs)
  818. def __eq__(self, other: object):
  819. return isinstance(other,
  820. self.__class__) and self.outputs == other.outputs
  821. def get_all_seq_ids(
  822. seq_group_metadata_list: List[SequenceGroupMetadata]) -> List[int]:
  823. """Given a list of SequenceGroupMetadata, create a list of all
  824. sequence ids.
  825. """
  826. return [seq_id for sg in seq_group_metadata_list for seq_id in sg.seq_data]
  827. def get_all_seq_ids_and_request_ids(
  828. seq_group_metadata_list: List[SequenceGroupMetadata]
  829. ) -> Tuple[List[int], Dict[str, Set[int]]]:
  830. """Given a list of SequenceGroupMetadata, create a list of all
  831. sequence ids.
  832. """
  833. seq_ids: List[int] = []
  834. request_id_seq_ids_mapping: Dict[str, Set[int]] = defaultdict(set)
  835. for sg in seq_group_metadata_list:
  836. for seq_id in sg.seq_data:
  837. seq_ids.append(seq_id)
  838. request_id_seq_ids_mapping[sg.request_id].add(seq_id)
  839. return seq_ids, request_id_seq_ids_mapping
  840. class HiddenStates:
  841. """Hidden states corresponding to in-progress sequences.
  842. Used in speculative decoding to pass hidden states from
  843. the target model to the proposer model in the subsequent step.
  844. seq_ids are the sequence ids of each entry of the batch
  845. dimension of the hidden_states tensor"""
  846. def __init__(self, seq_group_metadata_list: List[SequenceGroupMetadata],
  847. hidden_states: torch.Tensor):
  848. assert len(seq_group_metadata_list) == len(hidden_states)
  849. self.seq_ids: List[int] = get_all_seq_ids(seq_group_metadata_list)
  850. self.hidden_states: torch.Tensor = hidden_states
  851. def update(self, seq_group_metadata_list: List[SequenceGroupMetadata],
  852. hidden_states: torch.Tensor) -> None:
  853. """Update hidden states from target model invocation."""
  854. assert len(seq_group_metadata_list) == len(hidden_states)
  855. self.seq_ids.extend(get_all_seq_ids(seq_group_metadata_list))
  856. self.hidden_states = torch.cat([self.hidden_states, hidden_states])
  857. def prune(self,
  858. seq_group_metadata_list: List[SequenceGroupMetadata]) -> None:
  859. """Prune to provided list of sequence ids."""
  860. seq_ids = get_all_seq_ids(seq_group_metadata_list)
  861. if seq_ids != self.seq_ids:
  862. # Batch contents changed - prune removed sequences.
  863. index = [self.seq_ids.index(seq_id) for seq_id in seq_ids]
  864. self.hidden_states = self.hidden_states[index]
  865. self.seq_ids = seq_ids
  866. @dataclass
  867. class ExecuteModelRequest:
  868. """The model execution request, containing CPU metadata only. The LLM
  869. engine should create an instance of this class for each request batch."""
  870. # The sequence group metadata list.
  871. seq_group_metadata_list: List[SequenceGroupMetadata]
  872. # Blocks to swap in. List of CPU -> GPU block number.
  873. blocks_to_swap_in: List[Tuple[int, int]] = field(default_factory=list)
  874. # Blocks to swap out. List of GPU -> CPU block number.
  875. blocks_to_swap_out: List[Tuple[int, int]] = field(default_factory=list)
  876. # Blocks to copy. Source to dest block.
  877. blocks_to_copy: List[Tuple[int, int]] = field(default_factory=list)
  878. # Virtual engine ID for pipeline parallel.
  879. virtual_engine: int = 0
  880. # The number of slots for lookahead decoding.
  881. num_lookahead_slots: int = 0
  882. # The number of requests in the running queue.
  883. running_queue_size: int = 0
  884. # Optional hidden states from prior step.
  885. previous_hidden_states: Optional[HiddenStates] = None
  886. # The number of forward steps to run.
  887. num_steps: int = 1
  888. # Finished request ids since last step.
  889. finished_requests_ids: List[str] = field(default_factory=list)
  890. def clone(
  891. self, seq_group_metadata_list: List[SequenceGroupMetadata]
  892. ) -> "ExecuteModelRequest":
  893. """Clone the request with a new sequence group metadata list."""
  894. return ExecuteModelRequest(
  895. seq_group_metadata_list=seq_group_metadata_list,
  896. blocks_to_swap_in=self.blocks_to_swap_in.copy(),
  897. blocks_to_swap_out=self.blocks_to_swap_out.copy(),
  898. blocks_to_copy=self.blocks_to_copy.copy(),
  899. virtual_engine=self.virtual_engine,
  900. num_lookahead_slots=self.num_lookahead_slots,
  901. running_queue_size=self.running_queue_size,
  902. previous_hidden_states=self.previous_hidden_states,
  903. num_steps=self.num_steps,
  904. finished_requests_ids=self.finished_requests_ids,
  905. )