sequence.py 51 KB

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