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