sequence.py 50 KB

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