sequence.py 49 KB

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