sequence.py 51 KB

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