sequence.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. """Sequence and its related classes."""
  2. import copy
  3. import enum
  4. import math
  5. from abc import ABC, abstractmethod
  6. from array import array
  7. from collections import defaultdict
  8. from dataclasses import dataclass, field
  9. from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, Union
  10. import torch
  11. from aphrodite.common.pooling_params import PoolingParams
  12. from aphrodite.common.sampling_params import SamplingParams
  13. from aphrodite.lora.request import LoRARequest
  14. from aphrodite.prompt_adapter.request import PromptAdapterRequest
  15. if TYPE_CHECKING:
  16. from aphrodite.inputs import LLMInputs
  17. from aphrodite.multimodal import MultiModalDataDict
  18. from aphrodite.spec_decode.metrics import SpecDecodeWorkerMetrics
  19. @dataclass
  20. class Logprob:
  21. """Infos for supporting OpenAI compatible logprobs and token ranks.
  22. Attributes:
  23. logprob: The logprob of chosen token
  24. rank: The vocab rank of chosen token (>=1)
  25. decoded_token: The decoded chosen token index
  26. """
  27. logprob: float
  28. rank: Optional[int] = None
  29. decoded_token: Optional[str] = None
  30. # {token_id -> logprob} per each sequence group. None if the corresponding
  31. # sequence group doesn't require prompt logprob.
  32. PromptLogprobs = List[Optional[Dict[int, Logprob]]]
  33. # {token_id -> logprob} for each sequence group.
  34. SampleLogprobs = List[Dict[int, Logprob]]
  35. class SequenceStatus(enum.IntEnum):
  36. """Status of a sequence."""
  37. WAITING = 0
  38. RUNNING = 1
  39. SWAPPED = 2
  40. # Note: anything after SWAPPED (2) will be considered
  41. # as a finished status.
  42. FINISHED_STOPPED = 3
  43. FINISHED_LENGTH_CAPPED = 4
  44. FINISHED_ABORTED = 5
  45. FINISHED_IGNORED = 6
  46. @staticmethod
  47. def is_finished(status: "SequenceStatus") -> bool:
  48. return status > SequenceStatus.SWAPPED
  49. @staticmethod
  50. def get_finished_reason(status: "SequenceStatus") -> Union[str, None]:
  51. if status == SequenceStatus.FINISHED_STOPPED:
  52. finish_reason = "stop"
  53. elif status == SequenceStatus.FINISHED_LENGTH_CAPPED:
  54. finish_reason = "length"
  55. elif status == SequenceStatus.FINISHED_ABORTED:
  56. finish_reason = "abort"
  57. elif status == SequenceStatus.FINISHED_IGNORED:
  58. # The ignored sequences are the sequences whose prompt lengths
  59. # are longer than the model's length cap. Therefore, the stop
  60. # reason should also be "length" as in OpenAI API.
  61. finish_reason = "length"
  62. else:
  63. finish_reason = None
  64. return finish_reason
  65. class SequenceStage(enum.Enum):
  66. PREFILL = enum.auto()
  67. DECODE = enum.auto()
  68. @dataclass
  69. class RequestMetrics:
  70. """Metrics associated with a request.
  71. Attributes:
  72. arrival_time: The time when the request arrived.
  73. first_scheduled_time: The time when the request was first scheduled.
  74. first_token_time: The time when the first token was generated.
  75. time_in_queue: The time the request spent in the queue.
  76. finished_time: The time when the request was finished.
  77. """
  78. arrival_time: float
  79. last_token_time: float
  80. first_scheduled_time: Optional[float]
  81. first_token_time: Optional[float]
  82. time_in_queue: Optional[float]
  83. finished_time: Optional[float] = None
  84. class SequenceData:
  85. """Data associated with a sequence.
  86. Args:
  87. prompt_token_ids: The token IDs of the prompt.
  88. output_token_ids: The token IDs of the output. Set to an empty list if
  89. None.
  90. Attributes:
  91. prompt_token_ids: The token IDs of the prompt.
  92. output_token_ids: The token IDs of the output.
  93. cumulative_logprob: The cumulative log probability of the output.
  94. """
  95. def __init__(
  96. self,
  97. prompt_token_ids: List[int],
  98. output_token_ids: Optional[List[int]] = None,
  99. ) -> None:
  100. self._prompt_token_ids = array('l', prompt_token_ids)
  101. self._prompt_token_ids_tuple: Tuple[int, ...] = tuple(prompt_token_ids)
  102. self._output_token_ids = array(
  103. 'l', output_token_ids if output_token_ids is not None else [])
  104. self.cumulative_logprob = 0.0
  105. # The number of tokens that are computed (that run against the model).
  106. self._num_computed_tokens = 0
  107. self._stage: SequenceStage = SequenceStage.PREFILL
  108. self._update_cached_all_tokens()
  109. def _update_cached_all_tokens(self):
  110. self._cached_all_token_ids: List[int] = list(self._prompt_token_ids +
  111. self._output_token_ids)
  112. @property
  113. def prompt_token_ids(self) -> Tuple[int, ...]:
  114. return self._prompt_token_ids_tuple
  115. @prompt_token_ids.setter
  116. def prompt_token_ids(self, new_prompt_token_ids) -> None:
  117. self._prompt_token_ids = array('l', new_prompt_token_ids)
  118. self._prompt_token_ids_tuple = tuple(new_prompt_token_ids)
  119. self._update_cached_all_tokens()
  120. @property
  121. def prompt_token_ids_array(self) -> array:
  122. return self._prompt_token_ids
  123. @property
  124. def output_token_ids(self) -> Tuple[int, ...]:
  125. return tuple(self._output_token_ids)
  126. @output_token_ids.setter
  127. def output_token_ids(self, new_output_token_ids) -> None:
  128. self._output_token_ids = array('l', new_output_token_ids)
  129. self._update_cached_all_tokens()
  130. @property
  131. def output_token_ids_array(self) -> array:
  132. return self._output_token_ids
  133. def append_token_id(self, token_id: int, logprob: float) -> None:
  134. self._output_token_ids.append(token_id)
  135. self._cached_all_token_ids.append(token_id)
  136. self.cumulative_logprob += logprob
  137. def get_len(self) -> int:
  138. return len(self._output_token_ids) + len(self._prompt_token_ids)
  139. def get_prompt_len(self) -> int:
  140. return len(self._prompt_token_ids)
  141. def get_output_len(self) -> int:
  142. return len(self._output_token_ids)
  143. def get_token_ids(self) -> List[int]:
  144. return self._cached_all_token_ids
  145. def get_prefix_token_ids(
  146. self, num_tokens: int
  147. ) -> Tuple[Tuple[int, ...], Optional[Tuple[int, ...]]]:
  148. """Get prefix tokens, and make the return value hashable"""
  149. prompt_length = self.get_prompt_len()
  150. if num_tokens > prompt_length:
  151. return (self._prompt_token_ids_tuple,
  152. tuple(self._output_token_ids[:num_tokens - prompt_length]))
  153. else:
  154. return (self._prompt_token_ids_tuple[:num_tokens], None)
  155. def get_num_computed_tokens(self) -> int:
  156. """Return the number of prefill tokens that are already computed."""
  157. return self._num_computed_tokens
  158. def update_num_computed_tokens(self, num_new_computed_tokens: int):
  159. """Update number of tokens computed so far."""
  160. self._num_computed_tokens += num_new_computed_tokens
  161. assert self._num_computed_tokens <= self.get_len(), (
  162. self._num_computed_tokens, self.get_len())
  163. # If all tokens are computed, it means it is in decoding phase.
  164. if self.get_num_uncomputed_tokens() == 0:
  165. self._stage = SequenceStage.DECODE
  166. def reset_state_for_recompute(self) -> None:
  167. """Reset the number of computed tokens from this sequence. It is
  168. supposed to be called when a sequence needs to be started from
  169. the beginning again (e.g., sequence is preempted).
  170. """
  171. self._num_computed_tokens = 0
  172. self._stage = SequenceStage.PREFILL
  173. def get_num_uncomputed_tokens(self) -> int:
  174. """Return the number of prefill tokens that are not computed."""
  175. # we use `get_len()` which includes prompt_len + output_len instead
  176. # of prompt_len here. This is because during recompute we need to
  177. # prefill for both prompt and output.
  178. return self.get_len() - self.get_num_computed_tokens()
  179. def get_last_token_id(self) -> int:
  180. if not self._output_token_ids:
  181. return self._prompt_token_ids[-1]
  182. return self._output_token_ids[-1]
  183. def get_prompt_token_ids(self) -> Tuple[int, ...]:
  184. return self.prompt_token_ids
  185. def get_output_token_ids(self) -> Tuple[int, ...]:
  186. return self.output_token_ids
  187. @property
  188. def stage(self) -> SequenceStage:
  189. return self._stage
  190. def __repr__(self) -> str:
  191. return (f"SequenceData("
  192. f"prompt_token_ids={self._prompt_token_ids}, "
  193. f"output_token_ids={self._output_token_ids}, "
  194. f"cumulative_logprob={self.cumulative_logprob})")
  195. class Sequence:
  196. """Stores the data, status, and block information of a sequence.
  197. Args:
  198. seq_id: The ID of the sequence.
  199. inputs: The inputs of the sequence.
  200. block_size: The block size of the sequence. Should be the same as the
  201. block size used by the block manager and cache engine.
  202. lora_request: LoRA request.
  203. prompt_adapter_request: Prompt adapter request.
  204. """
  205. def __init__(
  206. self,
  207. seq_id: int,
  208. inputs: "LLMInputs",
  209. block_size: int,
  210. eos_token_id: Optional[int] = None,
  211. lora_request: Optional[LoRARequest] = None,
  212. prompt_adapter_request: Optional[PromptAdapterRequest] = None
  213. ) -> None:
  214. self.seq_id = seq_id
  215. self.inputs = inputs
  216. self.block_size = block_size
  217. self.eos_token_id = eos_token_id
  218. self.lora_request = lora_request
  219. self.prompt_adapter_request = prompt_adapter_request
  220. self.data = SequenceData(self.prompt_token_ids)
  221. self.output_logprobs: SampleLogprobs = []
  222. self.output_text = ""
  223. self.status = SequenceStatus.WAITING
  224. self.stop_reason: Union[int, str, None] = None
  225. # Used for incremental detokenization
  226. self.prefix_offset = 0
  227. self.read_offset = 0
  228. # Input + output tokens
  229. self.tokens: Optional[List[str]] = None
  230. @property
  231. def n_blocks(self) -> int:
  232. return math.ceil(self.get_len() / self.block_size)
  233. @property
  234. def prompt(self) -> Optional[str]:
  235. return self.inputs.get("prompt")
  236. @property
  237. def prompt_token_ids(self) -> List[int]:
  238. return self.inputs["prompt_token_ids"]
  239. @property
  240. def multi_modal_data(self) -> Optional["MultiModalDataDict"]:
  241. return self.inputs.get("multi_modal_data")
  242. @property
  243. def lora_int_id(self) -> int:
  244. return self.lora_request.lora_int_id if self.lora_request else 0
  245. @property
  246. def prompt_adapter_id(self) -> int:
  247. return self.prompt_adapter_request.prompt_adapter_id \
  248. if self.prompt_adapter_request else 0
  249. def get_output_text_to_return(self, buffer_length: int):
  250. # We return the full output text if the sequence is finished.
  251. truncate = buffer_length and not self.is_finished()
  252. return self.output_text[:-buffer_length] if truncate else (
  253. self.output_text)
  254. def hash_of_block(self, logical_idx: int) -> int:
  255. # TODO This can produce incorrect hash when block size > prompt size
  256. # Compute the number of tokens in the sequence
  257. # TODO: The current hashing function is O(L^2). We should optimize
  258. # this in the future.
  259. num_tokens = self.num_hashed_tokens_of_block(logical_idx)
  260. hashed_tokens = self.data.get_prefix_token_ids(num_tokens)
  261. return hash((hashed_tokens, self.lora_int_id))
  262. def num_hashed_tokens_of_block(self, logical_idx: int):
  263. return logical_idx * self.block_size + self.block_size
  264. def reset_state_for_recompute(self):
  265. """Reset the sequence states for recomputation."""
  266. self.data.reset_state_for_recompute()
  267. def append_token_id(
  268. self,
  269. token_id: int,
  270. logprobs: Dict[int, Logprob],
  271. ) -> None:
  272. assert token_id in logprobs
  273. self.output_logprobs.append(logprobs)
  274. self.data.append_token_id(token_id, logprobs[token_id].logprob)
  275. def get_len(self) -> int:
  276. return self.data.get_len()
  277. def get_prompt_len(self) -> int:
  278. return self.data.get_prompt_len()
  279. def get_output_len(self) -> int:
  280. return self.data.get_output_len()
  281. def get_token_ids(self) -> List[int]:
  282. return self.data.get_token_ids()
  283. def get_prompt_token_ids(self) -> Tuple[int, ...]:
  284. return self.data.get_prompt_token_ids()
  285. def get_last_token_id(self) -> int:
  286. return self.data.get_last_token_id()
  287. def get_output_token_ids(self) -> Tuple[int, ...]:
  288. return self.data.get_output_token_ids()
  289. def get_cumulative_logprob(self) -> float:
  290. return self.data.cumulative_logprob
  291. def get_beam_search_score(self,
  292. length_penalty: float = 1.0,
  293. seq_len: Optional[int] = None,
  294. eos_token_id: Optional[int] = None) -> float:
  295. """Calculate the beam search score with length penalty.
  296. Adapted from
  297. https://github.com/huggingface/transformers/blob/ccb92be23def445f2afdea94c31286f84b89eb5b/src/transformers/generation/beam_search.py#L938
  298. """
  299. if seq_len is None:
  300. seq_len = self.get_len()
  301. # NOTE: HF implementation does not count the EOS token
  302. # towards the length, we align with that here for testing.
  303. if (eos_token_id is not None
  304. and self.get_last_token_id() == eos_token_id):
  305. seq_len -= 1
  306. return self.get_cumulative_logprob() / (seq_len**length_penalty)
  307. def is_finished(self) -> bool:
  308. return SequenceStatus.is_finished(self.status)
  309. def fork(self, new_seq_id: int) -> "Sequence":
  310. new_seq = copy.deepcopy(self)
  311. new_seq.seq_id = new_seq_id
  312. return new_seq
  313. def get_num_new_tokens(self) -> int:
  314. """Get the number of new tokens to be computed.
  315. Returns:
  316. The new number of tokens to be computed. I.e., 1 for decode, or
  317. the remaining prompt size for prefill.
  318. """
  319. if self.data.stage == SequenceStage.DECODE:
  320. return 1
  321. return self.data.get_num_uncomputed_tokens()
  322. def is_prefill(self) -> bool:
  323. return self.data.stage == SequenceStage.PREFILL
  324. def __repr__(self) -> str:
  325. return (f"Sequence(seq_id={self.seq_id}, "
  326. f"status={self.status.name}, "
  327. f"num_blocks={self.n_blocks}, ")
  328. class SequenceGroup:
  329. """A group of sequences that are generated from the same prompt.
  330. Args:
  331. request_id: The ID of the request.
  332. seqs: The list of sequences.
  333. sampling_params: The sampling parameters used to generate the outputs.
  334. arrival_time: The arrival time of the request.
  335. lora_request: LoRA request.
  336. embeddings: The embeddings vectors of the prompt of the sequence group
  337. for an embedding model.
  338. pooling_params: The pooling parameters used to generate the pooling
  339. for an embedding model.
  340. encoder_seq: Optional, the single encoder sequence. Should be None
  341. unless you are working with an encoder/decoder model.
  342. prompt_adapter_request: Prompt adapter request.
  343. """
  344. def __init__(
  345. self,
  346. request_id: str,
  347. seqs: List[Sequence],
  348. arrival_time: float,
  349. sampling_params: Optional[SamplingParams] = None,
  350. lora_request: Optional[LoRARequest] = None,
  351. embeddings: Optional[List[float]] = None,
  352. pooling_params: Optional[PoolingParams] = None,
  353. encoder_seq: Optional[Sequence] = None,
  354. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  355. ) -> None:
  356. self.request_id = request_id
  357. self.seqs = seqs
  358. self.seqs_dict = {seq.seq_id: seq for seq in seqs}
  359. self.sampling_params = sampling_params
  360. self.metrics = RequestMetrics(arrival_time=arrival_time,
  361. last_token_time=arrival_time,
  362. first_scheduled_time=None,
  363. first_token_time=None,
  364. time_in_queue=None)
  365. self.lora_request = lora_request
  366. self.prompt_logprobs: Optional[PromptLogprobs] = None
  367. self.embeddings = embeddings
  368. self.pooling_params = pooling_params
  369. self.prompt_adapter_request = prompt_adapter_request
  370. self.encoder_seq = encoder_seq
  371. @property
  372. def prompt(self) -> Optional[str]:
  373. # All sequences in the group should have the same prompt.
  374. # We use the prompt of an arbitrary sequence.
  375. return self.seqs[0].prompt
  376. @property
  377. def prompt_token_ids(self) -> List[int]:
  378. # All sequences in the group should have the same prompt.
  379. # We use the prompt of an arbitrary sequence.
  380. return self.seqs[0].prompt_token_ids
  381. @property
  382. def multi_modal_data(self) -> "MultiModalDataDict":
  383. # All sequences in the group should have the same multi-modal data.
  384. # We use the multi-modal data of an arbitrary sequence.
  385. return self.seqs[0].multi_modal_data
  386. @property
  387. def lora_int_id(self) -> int:
  388. return self.lora_request.lora_int_id if self.lora_request else 0
  389. @property
  390. def prompt_adapter_id(self) -> int:
  391. return self.prompt_adapter_request.prompt_adapter_id \
  392. if self.prompt_adapter_request else 0
  393. @property
  394. def prompt_adapter_num_virtual_tokens(self) -> int:
  395. return self.prompt_adapter_request.prompt_adapter_num_virtual_tokens\
  396. if self.prompt_adapter_request else 0
  397. def get_last_latency(self, now: float) -> Optional[float]:
  398. """Sets the last token time for Request level timings."""
  399. # If still in prefill phase, raise Error.
  400. if self.is_prefill():
  401. raise ValueError(
  402. "seq_group.get_last_latency() should not be called "
  403. "if the seq_group is in prefill phase.")
  404. # Otherwise return token latency.
  405. latency = now - self.metrics.last_token_time
  406. self.metrics.last_token_time = now
  407. return latency
  408. def maybe_set_first_token_time(self, time: float) -> None:
  409. """Sets the first token time for Request level timings."""
  410. # NOTE: in a case where a sequence_group is swapped and
  411. # recomputed, the time between iterations is counted
  412. # in TPOT, rather than recalculating TTFT (since from the )
  413. # POV of the user, there is simply a long generation delay.
  414. if (self.metrics.first_token_time is None
  415. and self.seqs[0].get_output_len() == 1):
  416. self.metrics.first_token_time = time
  417. def maybe_set_first_scheduled_time(self, time: float) -> None:
  418. """Sets the first scheduled time and time in queue for Request
  419. level timings."""
  420. if self.metrics.first_scheduled_time is None:
  421. self.metrics.first_scheduled_time = time
  422. self.metrics.time_in_queue = time - self.metrics.arrival_time
  423. def set_finished_time(self, time: Optional[float]) -> None:
  424. """Sets the finished time for Request level timings."""
  425. self.metrics.finished_time = time
  426. def get_max_num_running_seqs(self) -> int:
  427. """The maximum number of sequences running in parallel in the remaining
  428. lifetime of the request."""
  429. if self.sampling_params and self.sampling_params.use_beam_search:
  430. # For beam search, maximally there will always be `best_of` beam
  431. # candidates running in the future.
  432. return self.sampling_params.best_of
  433. else:
  434. if (self.sampling_params
  435. and self.sampling_params.best_of > self.num_seqs()):
  436. # At prompt stage, the sequence group is not yet filled up
  437. # and only have one sequence running. However, in the
  438. # generation stage, we will have `best_of` sequences running.
  439. return self.sampling_params.best_of
  440. # At sampling stages, return the number of actual sequences
  441. # that are not finished yet.
  442. return self.num_unfinished_seqs()
  443. def get_seqs(
  444. self,
  445. status: Optional[SequenceStatus] = None,
  446. ) -> List[Sequence]:
  447. if status is None:
  448. return self.seqs
  449. return [seq for seq in self.seqs if seq.status == status]
  450. def is_encoder_decoder(self) -> bool:
  451. return self.encoder_seq is not None
  452. def get_encoder_seq(self) -> Optional[Sequence]:
  453. return self.encoder_seq
  454. def get_unfinished_seqs(self) -> List[Sequence]:
  455. return [seq for seq in self.seqs if not seq.is_finished()]
  456. def get_finished_seqs(self) -> List[Sequence]:
  457. return [seq for seq in self.seqs if seq.is_finished()]
  458. def update_num_computed_tokens(self, num_new_computed_tokens: int):
  459. """Update number of tokens computed so far."""
  460. for seq in self.seqs:
  461. if not seq.is_finished():
  462. seq.data.update_num_computed_tokens(num_new_computed_tokens)
  463. def get_num_uncomputed_tokens(self) -> int:
  464. num_uncomputed_tokens = 0
  465. for seq in self.seqs:
  466. if not seq.is_finished():
  467. num_uncomputed_tokens += seq.data.get_num_uncomputed_tokens()
  468. return num_uncomputed_tokens
  469. def num_seqs(self, status: Optional[SequenceStatus] = None) -> int:
  470. # Optimization. We don't need to call get_seqs if we don't need to
  471. # filter by states.
  472. if status is None:
  473. return len(self.seqs)
  474. return len(self.get_seqs(status))
  475. def num_unfinished_seqs(self) -> int:
  476. return len(self.get_unfinished_seqs())
  477. def num_finished_seqs(self) -> int:
  478. return len(self.get_finished_seqs())
  479. def find(self, seq_id: int) -> Sequence:
  480. if seq_id not in self.seqs_dict:
  481. raise ValueError(f"Sequence {seq_id} not found.")
  482. return self.seqs_dict[seq_id]
  483. def add(self, seq: Sequence) -> None:
  484. if seq.seq_id in self.seqs_dict:
  485. raise ValueError(f"Sequence {seq.seq_id} already exists.")
  486. self.seqs_dict[seq.seq_id] = seq
  487. self.seqs.append(seq)
  488. def remove(self, seq_id: int) -> None:
  489. seq = self.seqs_dict.pop(seq_id, None)
  490. if seq is None:
  491. raise ValueError(f"Sequence {seq_id} not found.")
  492. self.seqs.remove(seq)
  493. def is_finished(self) -> bool:
  494. return all(seq.is_finished() for seq in self.seqs)
  495. def is_prefill(self) -> bool:
  496. # Every sequence should be in the same stage.
  497. return self.seqs[0].is_prefill()
  498. def __repr__(self) -> str:
  499. return (f"SequenceGroup(request_id={self.request_id}, "
  500. f"sampling_params={self.sampling_params}, "
  501. f"num_seqs={len(self.seqs)})")
  502. class SequenceGroupMetadata:
  503. """Metadata for a sequence group. Used to create `AttentionMetadata`.
  504. Args:
  505. request_id: The ID of the request.
  506. is_prompt: Whether the request is at prompt stage.
  507. seq_data: The sequence data. (Seq id -> sequence data)
  508. sampling_params: The sampling parameters used to generate the outputs.
  509. block_tables: The block tables. (Seq id -> list of physical block
  510. numbers)
  511. do_sample: True if sampling is required. Sampling is not required when
  512. e.g., prefill is chunked, and the current iteration only computes
  513. query tokens for prefill, we don't need sampling.
  514. token_chunk_size: The number of tokens to be processed (per sequence).
  515. None if chunking is not required.
  516. lora_request: LoRA request.
  517. computed_block_nums: The block numbers that are already computed,
  518. used in prefix caching.
  519. multi_modal_data: Multi modal data.
  520. encoder_seq_data: Optional sequence data for encoder prompt
  521. (SequenceGroup.encoder_seq). Should be None
  522. unless you are working with an encoder/decoder
  523. model.
  524. cross_block_table: Optional cross-attention block table associated
  525. with the encoder prompt
  526. (SequenceGroup.encoder_seq). Should be None
  527. unless you are working with an encoder/decoder
  528. model.
  529. prompt_adapter_request: Prompt Adapter request.
  530. """
  531. def __init__(
  532. self,
  533. request_id: str,
  534. is_prompt: bool,
  535. seq_data: Dict[int, SequenceData],
  536. sampling_params: SamplingParams,
  537. block_tables: Dict[int, List[int]],
  538. do_sample: bool = True,
  539. pooling_params: Optional[PoolingParams] = None,
  540. token_chunk_size: Optional[int] = None,
  541. lora_request: Optional[LoRARequest] = None,
  542. computed_block_nums: Optional[List[int]] = None,
  543. multi_modal_data: Optional["MultiModalDataDict"] = None,
  544. encoder_seq_data: Optional[SequenceData] = None,
  545. cross_block_table: Optional[List[int]] = None,
  546. prompt_adapter_request: Optional[PromptAdapterRequest] = None,
  547. ) -> None:
  548. self.request_id = request_id
  549. self.is_prompt = is_prompt
  550. self.seq_data = seq_data
  551. self.sampling_params = sampling_params
  552. self.block_tables = block_tables
  553. self.pooling_params = pooling_params
  554. self.lora_request = lora_request
  555. self.prompt_adapter_request = prompt_adapter_request
  556. self.computed_block_nums = computed_block_nums
  557. self.multi_modal_data = multi_modal_data
  558. self.encoder_seq_data = encoder_seq_data
  559. self.cross_block_table = cross_block_table
  560. self._token_chunk_size = token_chunk_size
  561. self.do_sample = do_sample
  562. # The number of speculative tokens adopted in this request.
  563. # None means specuative decoding is not used.
  564. # Zero means speculative decoding is disabled for some reasons.
  565. # TODO: We should maintain this states out of the sequence group.
  566. self.num_speculative_tokens = None
  567. if self._token_chunk_size is None:
  568. if is_prompt:
  569. self._token_chunk_size = list(seq_data.values())[0].get_len()
  570. else:
  571. self._token_chunk_size = 1
  572. @property
  573. def lora_int_id(self) -> int:
  574. return self.lora_request.lora_int_id if self.lora_request else 0
  575. @property
  576. def prompt_adapter_id(self) -> int:
  577. return self.prompt_adapter_request.prompt_adapter_id \
  578. if self.prompt_adapter_request else 0
  579. @property
  580. def prompt_adapter_num_virtual_tokens(self) -> int:
  581. return self.prompt_adapter_request.prompt_adapter_num_virtual_tokens \
  582. if self.prompt_adapter_request else 0
  583. @property
  584. def token_chunk_size(self) -> int:
  585. """Return the number of tokens to be processed (chunk size)."""
  586. assert self._token_chunk_size is not None
  587. return self._token_chunk_size
  588. class SequenceOutput:
  589. """The model output associated with a sequence.
  590. Args:
  591. parent_seq_id: The ID of the parent sequence (for forking in beam
  592. search).
  593. output_token: The output token ID.
  594. logprobs: The logprobs of the output token.
  595. (Token id -> logP(x_i+1 | x_0, ..., x_i))
  596. """
  597. def __init__(
  598. self,
  599. parent_seq_id: int,
  600. output_token: int,
  601. logprobs: Dict[int, Logprob],
  602. ) -> None:
  603. self.parent_seq_id = parent_seq_id
  604. self.output_token = output_token
  605. self.logprobs = logprobs
  606. def __repr__(self) -> str:
  607. return (f"SequenceOutput(parent_seq_id={self.parent_seq_id}, "
  608. f"output_token={self.output_token}, "
  609. f"logprobs={self.logprobs})")
  610. def __eq__(self, other: object) -> bool:
  611. if not isinstance(other, SequenceOutput):
  612. raise NotImplementedError()
  613. equal = (self.parent_seq_id == other.parent_seq_id
  614. and self.output_token == other.output_token)
  615. log_probs_equal = other.logprobs == self.logprobs
  616. return equal and log_probs_equal
  617. class SequenceGroupOutput(ABC):
  618. """The base class for model outputs associated with a sequence group."""
  619. @abstractmethod
  620. def __repr__(self) -> str:
  621. pass
  622. @abstractmethod
  623. def __eq__(self, other: object) -> bool:
  624. pass
  625. class CompletionSequenceGroupOutput(SequenceGroupOutput):
  626. """The model output associated with a completion sequence group."""
  627. def __init__(
  628. self,
  629. samples: List[SequenceOutput],
  630. prompt_logprobs: Optional[PromptLogprobs],
  631. ) -> None:
  632. self.samples = samples
  633. # Prompt logprob for each prompt query token.
  634. self.prompt_logprobs = prompt_logprobs
  635. def __repr__(self) -> str:
  636. return (f"CompletionSequenceGroupOutput(samples={self.samples}, "
  637. f"prompt_logprobs={self.prompt_logprobs})")
  638. def __eq__(self, other: object) -> bool:
  639. if not isinstance(other, CompletionSequenceGroupOutput):
  640. raise NotImplementedError()
  641. return (self.samples == other.samples
  642. and self.prompt_logprobs == other.prompt_logprobs)
  643. class EmbeddingSequenceGroupOutput(SequenceGroupOutput):
  644. """The model output associated with an embedding sequence group."""
  645. def __init__(
  646. self,
  647. embeddings: List[float],
  648. ) -> None:
  649. self.embeddings = embeddings
  650. def __repr__(self) -> str:
  651. return (f"EmbeddingSequenceGroupOutput("
  652. f"embeddings_shape={len(self.embeddings)})")
  653. def __eq__(self, other: object) -> bool:
  654. if not isinstance(other, EmbeddingSequenceGroupOutput):
  655. raise NotImplementedError()
  656. return self.embeddings == other.embeddings
  657. @dataclass
  658. class IntermediateTensors:
  659. """For all pipeline stages except the last, we need to return the hidden
  660. states and residuals to be sent to the next stage. This data structure
  661. contains the hidden states and residuals for a request.
  662. """
  663. tensors: Dict[str, torch.Tensor]
  664. def __getitem__(self, key: Union[str, slice]):
  665. if isinstance(key, str):
  666. return self.tensors[key]
  667. elif isinstance(key, slice):
  668. return self.__class__({k: v[key] for k, v in self.tensors.items()})
  669. def __setitem__(self, key: str, value):
  670. self.tensors[key] = value
  671. def __len__(self):
  672. return len(self.tensors)
  673. def __eq__(self, other: object):
  674. return isinstance(other, self.__class__) and self
  675. def __repr__(self) -> str:
  676. return f"IntermediateTensors(tensors={self.tensors})"
  677. @dataclass
  678. class SamplerOutput:
  679. """For each sequence group, we generate a list of SequenceOutput object,
  680. each of which contains one possible candidate for the next token.
  681. This data structure implements methods, so it can be used like a list, but
  682. also has optional fields for device tensors.
  683. """
  684. outputs: List[CompletionSequenceGroupOutput]
  685. # On-device tensor containing probabilities of each token.
  686. sampled_token_probs: Optional[torch.Tensor] = None
  687. # On-device tensor containing the logprobs of each token.
  688. logprobs: Optional["torch.Tensor"] = None
  689. # On-device tensor containing the sampled token ids.
  690. sampled_token_ids: Optional[torch.Tensor] = None
  691. # Spec decode metrics populated by workers.
  692. spec_decode_worker_metrics: Optional["SpecDecodeWorkerMetrics"] = None
  693. # Optional last hidden states from the model.
  694. hidden_states: Optional[torch.Tensor] = None
  695. def __getitem__(self, idx: int):
  696. return self.outputs[idx]
  697. def __setitem__(self, idx: int, value):
  698. self.outputs[idx] = value
  699. def __len__(self):
  700. return len(self.outputs)
  701. def __eq__(self, other: object):
  702. return isinstance(other,
  703. self.__class__) and self.outputs == other.outputs
  704. def __repr__(self) -> str:
  705. """Show the shape of a tensor instead of its values to reduce noise.
  706. """
  707. sampled_token_probs_repr = ("None" if self.sampled_token_probs is None
  708. else self.sampled_token_probs.shape)
  709. sampled_token_ids_repr = ("None" if self.sampled_token_ids is None else
  710. self.sampled_token_ids.shape)
  711. return (
  712. f"SamplerOutput(outputs={self.outputs}, "
  713. f"sampled_token_probs={sampled_token_probs_repr}, "
  714. f"sampled_token_ids={sampled_token_ids_repr}, "
  715. f"spec_decode_worker_metrics={self.spec_decode_worker_metrics})")
  716. @dataclass
  717. class PoolerOutput:
  718. """The output from a pooling operation in the embedding model."""
  719. outputs: List[EmbeddingSequenceGroupOutput]
  720. spec_decode_worker_metrics: Optional["SpecDecodeWorkerMetrics"] = None
  721. def __getitem__(self, idx: int):
  722. return self.outputs[idx]
  723. def __setitem__(self, idx: int, value):
  724. self.outputs[idx] = value
  725. def __len__(self):
  726. return len(self.outputs)
  727. def __eq__(self, other: object):
  728. return isinstance(other,
  729. self.__class__) and self.outputs == other.outputs
  730. def get_all_seq_ids(
  731. seq_group_metadata_list: List[SequenceGroupMetadata]) -> List[int]:
  732. """Given a list of SequenceGroupMetadata, create a list of all
  733. sequence ids.
  734. """
  735. return [seq_id for sg in seq_group_metadata_list for seq_id in sg.seq_data]
  736. def get_all_seq_ids_and_request_ids(
  737. seq_group_metadata_list: List[SequenceGroupMetadata]
  738. ) -> Tuple[List[int], Dict[str, Set[int]]]:
  739. """Given a list of SequenceGroupMetadata, create a list of all
  740. sequence ids.
  741. """
  742. seq_ids: List[int] = []
  743. request_id_seq_ids_mapping: Dict[str, Set[int]] = defaultdict(set)
  744. for sg in seq_group_metadata_list:
  745. for seq_id in sg.seq_data:
  746. seq_ids.append(seq_id)
  747. request_id_seq_ids_mapping[sg.request_id].add(seq_id)
  748. return seq_ids, request_id_seq_ids_mapping
  749. class HiddenStates:
  750. """Hidden states corresponding to in-progress sequences.
  751. Used in speculative decoding to pass hidden states from
  752. the target model to the proposer model in the subsequent step.
  753. seq_ids are the sequence ids of each entry of the batch
  754. dimension of the hidden_states tensor"""
  755. def __init__(self, seq_group_metadata_list: List[SequenceGroupMetadata],
  756. hidden_states: torch.Tensor):
  757. assert len(seq_group_metadata_list) == len(hidden_states)
  758. self.seq_ids: List[int] = get_all_seq_ids(seq_group_metadata_list)
  759. self.hidden_states: torch.Tensor = hidden_states
  760. def update(self, seq_group_metadata_list: List[SequenceGroupMetadata],
  761. hidden_states: torch.Tensor) -> None:
  762. """Update hidden states from target model invocation."""
  763. assert len(seq_group_metadata_list) == len(hidden_states)
  764. self.seq_ids.extend(get_all_seq_ids(seq_group_metadata_list))
  765. self.hidden_states = torch.cat([self.hidden_states, hidden_states])
  766. def prune(self,
  767. seq_group_metadata_list: List[SequenceGroupMetadata]) -> None:
  768. """Prune to provided list of sequence ids."""
  769. seq_ids = get_all_seq_ids(seq_group_metadata_list)
  770. if seq_ids != self.seq_ids:
  771. # Batch contents changed - prune removed sequences.
  772. index = [self.seq_ids.index(seq_id) for seq_id in seq_ids]
  773. self.hidden_states = self.hidden_states[index]
  774. self.seq_ids = seq_ids
  775. @dataclass
  776. class ExecuteModelRequest:
  777. """The model execution request, containing CPU metadata only. The LLM
  778. engine should create an instance of this class for each request batch."""
  779. # The sequence group metadata list.
  780. seq_group_metadata_list: List[SequenceGroupMetadata]
  781. # Blocks to swap in. List of CPU -> GPU block number.
  782. blocks_to_swap_in: List[Tuple[int, int]] = field(default_factory=list)
  783. # Blocks to swap out. List of GPU -> CPU block number.
  784. blocks_to_swap_out: List[Tuple[int, int]] = field(default_factory=list)
  785. # Blocks to copy. Source to dest block.
  786. blocks_to_copy: List[Tuple[int, int]] = field(default_factory=list)
  787. # Virtual engine ID for pipeline parallel.
  788. virtual_engine: int = 0
  789. # The number of slots for lookahead decoding.
  790. num_lookahead_slots: int = 0
  791. # The number of requests in the running queue.
  792. running_queue_size: int = 0
  793. # Optional hidden states from prior step.
  794. previous_hidden_states: Optional[HiddenStates] = None
  795. # The number of forward steps to run.
  796. num_steps: int = 1
  797. # Finished request ids since last step.
  798. finished_requests_ids: List[str] = field(default_factory=list)
  799. def clone(
  800. self, seq_group_metadata_list: List[SequenceGroupMetadata]
  801. ) -> "ExecuteModelRequest":
  802. """Clone the request with a new sequence group metadata list."""
  803. return ExecuteModelRequest(
  804. seq_group_metadata_list=seq_group_metadata_list,
  805. blocks_to_swap_in=self.blocks_to_swap_in.copy(),
  806. blocks_to_swap_out=self.blocks_to_swap_out.copy(),
  807. blocks_to_copy=self.blocks_to_copy.copy(),
  808. virtual_engine=self.virtual_engine,
  809. num_lookahead_slots=self.num_lookahead_slots,
  810. running_queue_size=self.running_queue_size,
  811. previous_hidden_states=self.previous_hidden_states,
  812. num_steps=self.num_steps,
  813. finished_requests_ids=self.finished_requests_ids,
  814. )