sequence.py 52 KB

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