sequence.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. """Sequence and its related classes."""
  2. import copy
  3. import enum
  4. from typing import Dict, List, Optional, Union
  5. from aphrodite.common.block import LogicalTokenBlock
  6. from aphrodite.common.prefix import Prefix
  7. from aphrodite.common.sampling_params import SamplingParams
  8. from aphrodite.lora.request import LoRARequest
  9. PromptLogprobs = List[Optional[Dict[int, float]]]
  10. SampleLogprobs = List[Dict[int, float]]
  11. class SequenceStatus(enum.Enum):
  12. """Status of a sequence."""
  13. WAITING = enum.auto()
  14. RUNNING = enum.auto()
  15. SWAPPED = enum.auto()
  16. FINISHED_STOPPED = enum.auto()
  17. FINISHED_LENGTH_CAPPED = enum.auto()
  18. FINISHED_ABORTED = enum.auto()
  19. FINISHED_IGNORED = enum.auto()
  20. @staticmethod
  21. def is_finished(status: "SequenceStatus") -> bool:
  22. return status in [
  23. SequenceStatus.FINISHED_STOPPED,
  24. SequenceStatus.FINISHED_LENGTH_CAPPED,
  25. SequenceStatus.FINISHED_ABORTED,
  26. SequenceStatus.FINISHED_IGNORED,
  27. ]
  28. @staticmethod
  29. def get_finished_reason(status: "SequenceStatus") -> Union[str, None]:
  30. if status == SequenceStatus.FINISHED_STOPPED:
  31. finish_reason = "stop"
  32. elif status == SequenceStatus.FINISHED_LENGTH_CAPPED:
  33. finish_reason = "length"
  34. elif status == SequenceStatus.FINISHED_ABORTED:
  35. finish_reason = "abort"
  36. elif status == SequenceStatus.FINISHED_IGNORED:
  37. # The ignored sequences are the sequences whose prompt lengths
  38. # are longer than the model's length cap. Therefore, the stop
  39. # reason should also be "length" as in OpenAI API.
  40. finish_reason = "length"
  41. else:
  42. finish_reason = None
  43. return finish_reason
  44. class SequenceData:
  45. """Data associated with a sequence.
  46. Args:
  47. prompt_token_ids: The token IDs of the prompt.
  48. Attributes:
  49. prompt_token_ids: The token IDs of the prompt.
  50. output_token_ids: The token IDs of the output.
  51. cumulative_logprob: The cumulative log probability of the output.
  52. """
  53. def __init__(
  54. self,
  55. prompt_token_ids: List[int],
  56. ) -> None:
  57. self.prompt_token_ids = prompt_token_ids
  58. self.output_token_ids: List[int] = []
  59. self.cumulative_logprob = 0.0
  60. def append_token_id(self, token_id: int, logprob: float) -> None:
  61. self.output_token_ids.append(token_id)
  62. self.cumulative_logprob += logprob
  63. def get_len(self) -> int:
  64. return len(self.output_token_ids) + len(self.prompt_token_ids)
  65. def get_prompt_len(self) -> int:
  66. return len(self.prompt_token_ids)
  67. def get_output_len(self) -> int:
  68. return len(self.output_token_ids)
  69. def get_token_ids(self) -> List[int]:
  70. return self.prompt_token_ids + self.output_token_ids
  71. def get_last_token_id(self) -> int:
  72. if not self.output_token_ids:
  73. return self.prompt_token_ids[-1]
  74. return self.output_token_ids[-1]
  75. def __repr__(self) -> str:
  76. return (f"SequenceData("
  77. f"prompt_token_ids={self.prompt_token_ids}, "
  78. f"output_token_ids={self.output_token_ids}, "
  79. f"cumulative_logprob={self.cumulative_logprob})")
  80. class Sequence:
  81. """Stores the data, status, and block information of a sequence.
  82. Args:
  83. seq_id: The ID of the sequence.
  84. prompt: The prompt of the sequence.
  85. prompt_token_ids: The token IDs of the prompt.
  86. block_size: The block size of the sequence. Should be the same as the
  87. block size used by the block manager and cache engine.
  88. lora_request: LoRA request.
  89. """
  90. def __init__(
  91. self,
  92. seq_id: int,
  93. prompt: str,
  94. prompt_token_ids: List[int],
  95. block_size: int,
  96. lora_request: Optional[LoRARequest] = None,
  97. ) -> None:
  98. self.seq_id = seq_id
  99. self.prompt = prompt
  100. self.block_size = block_size
  101. self.lora_request = lora_request
  102. self.data = SequenceData(prompt_token_ids)
  103. self.output_logprobs: SampleLogprobs = []
  104. self.output_text = ""
  105. self.logical_token_blocks: List[LogicalTokenBlock] = []
  106. # Initialize the logical token blocks with the prompt token ids.
  107. self._append_tokens_to_blocks(prompt_token_ids)
  108. self.status = SequenceStatus.WAITING
  109. # Used for incremental detokenization
  110. self.prefix_offset = 0
  111. self.read_offset = 0
  112. # Input + output tokens
  113. self.tokens: Optional[List[str]] = None
  114. self.persistent_data = {}
  115. @property
  116. def lora_int_id(self) -> int:
  117. return self.lora_request.lora_int_id if self.lora_request else 0
  118. def _append_logical_block(self) -> None:
  119. block = LogicalTokenBlock(
  120. block_number=len(self.logical_token_blocks),
  121. block_size=self.block_size,
  122. )
  123. self.logical_token_blocks.append(block)
  124. def _append_tokens_to_blocks(self, token_ids: List[int]) -> None:
  125. cursor = 0
  126. while cursor < len(token_ids):
  127. if not self.logical_token_blocks:
  128. self._append_logical_block()
  129. last_block = self.logical_token_blocks[-1]
  130. if last_block.is_full():
  131. self._append_logical_block()
  132. last_block = self.logical_token_blocks[-1]
  133. num_empty_slots = last_block.get_num_empty_slots()
  134. last_block.append_tokens(token_ids[cursor:cursor +
  135. num_empty_slots])
  136. cursor += num_empty_slots
  137. def append_token_id(
  138. self,
  139. token_id: int,
  140. logprobs: Dict[int, float],
  141. ) -> None:
  142. assert token_id in logprobs
  143. self._append_tokens_to_blocks([token_id])
  144. self.output_logprobs.append(logprobs)
  145. self.data.append_token_id(token_id, logprobs[token_id])
  146. def get_len(self) -> int:
  147. return self.data.get_len()
  148. def get_prompt_len(self) -> int:
  149. return self.data.get_prompt_len()
  150. def get_output_len(self) -> int:
  151. return self.data.get_output_len()
  152. def get_token_ids(self) -> List[int]:
  153. return self.data.get_token_ids()
  154. def get_last_token_id(self) -> int:
  155. return self.data.get_last_token_id()
  156. def get_output_token_ids(self) -> List[int]:
  157. return self.data.output_token_ids
  158. def get_cumulative_logprob(self) -> float:
  159. return self.data.cumulative_logprob
  160. def get_beam_search_score(self,
  161. length_penalty: float = 0.0,
  162. seq_len: Optional[int] = None,
  163. eos_token_id: Optional[int] = None) -> float:
  164. """Calculate the beam search score with length penalty.
  165. Adapted from
  166. https://github.com/huggingface/transformers/blob/ccb92be23def445f2afdea94c31286f84b89eb5b/src/transformers/generation/beam_search.py#L938
  167. """
  168. if seq_len is None:
  169. seq_len = self.get_len()
  170. # NOTE: HF implementation does not count the EOS token
  171. # towards the length, we align with that here for testing.
  172. if (eos_token_id is not None
  173. and self.get_last_token_id() == eos_token_id):
  174. seq_len -= 1
  175. return self.get_cumulative_logprob() / (seq_len**length_penalty)
  176. def is_finished(self) -> bool:
  177. return SequenceStatus.is_finished(self.status)
  178. def fork(self, new_seq_id: int) -> "Sequence":
  179. new_seq = copy.deepcopy(self)
  180. new_seq.seq_id = new_seq_id
  181. return new_seq
  182. def __repr__(self) -> str:
  183. return (f"Sequence(seq_id={self.seq_id}, "
  184. f"status={self.status.name}, "
  185. f"num_blocks={len(self.logical_token_blocks)})")
  186. class SequenceGroup:
  187. """A group of sequences that are generated from the same prompt.
  188. Args:
  189. request_id: The ID of the request.
  190. seqs: The list of sequences.
  191. sampling_params: The sampling parameters used to generate the outputs.
  192. arrival_time: The arrival time of the request.
  193. lora_request: LoRA request.
  194. prefix: The prefix of the prompt of the sequence group.
  195. """
  196. def __init__(
  197. self,
  198. request_id: str,
  199. seqs: List[Sequence],
  200. sampling_params: SamplingParams,
  201. arrival_time: float,
  202. lora_request: Optional[LoRARequest] = None,
  203. prefix: Optional[Prefix] = None,
  204. ) -> None:
  205. self.request_id = request_id
  206. self.seqs_dict = {seq.seq_id: seq for seq in seqs}
  207. self.sampling_params = sampling_params
  208. self.arrival_time = arrival_time
  209. self.last_token_time = arrival_time
  210. self.lora_request = lora_request
  211. self.prefix: Optional[Prefix] = prefix
  212. self.prompt_logprobs: Optional[PromptLogprobs] = None
  213. @property
  214. def prompt(self) -> str:
  215. # All sequences in the group should have the same prompt.
  216. # We use the prompt of an arbitrary sequence.
  217. return next(iter(self.seqs_dict.values())).prompt
  218. @property
  219. def prompt_token_ids(self) -> List[int]:
  220. # All sequences in the group should have the same prompt.
  221. # We use the prompt of an arbitrary sequence.
  222. return next(iter(self.seqs_dict.values())).data.prompt_token_ids
  223. @property
  224. def lora_int_id(self) -> int:
  225. return self.lora_request.lora_int_id if self.lora_request else 0
  226. def get_last_latency(self, now: float) -> float:
  227. """Gets last token latency for Request level timings."""
  228. latency = now - self.last_token_time
  229. self.last_token_time = now
  230. return latency
  231. def get_max_num_running_seqs(self) -> int:
  232. """The maximum number of sequences running in parallel in the remaining
  233. lifetime of the request."""
  234. if self.sampling_params.use_beam_search:
  235. # For beam search, maximally there will always be `best_of` beam
  236. # candidates running in the future.
  237. return self.sampling_params.best_of
  238. else:
  239. if self.sampling_params.best_of > self.num_seqs():
  240. # At prompt stage, the sequence group is not yet filled up
  241. # and only have one sequence running. However, in the
  242. # generation stage, we will have `best_of` sequences running.
  243. return self.sampling_params.best_of
  244. # At sampling stages, return the number of actual sequences
  245. # that are not finished yet.
  246. return self.num_unfinished_seqs()
  247. def get_seqs(
  248. self,
  249. status: Optional[SequenceStatus] = None,
  250. ) -> List[Sequence]:
  251. if status is None:
  252. return list(self.seqs_dict.values())
  253. else:
  254. return [
  255. seq for seq in self.seqs_dict.values() if seq.status == status
  256. ]
  257. def get_unfinished_seqs(self) -> List[Sequence]:
  258. return [
  259. seq for seq in self.seqs_dict.values() if not seq.is_finished()
  260. ]
  261. def get_finished_seqs(self) -> List[Sequence]:
  262. return [seq for seq in self.seqs_dict.values() if seq.is_finished()]
  263. def num_seqs(self, status: Optional[SequenceStatus] = None) -> int:
  264. return len(self.get_seqs(status))
  265. def num_unfinished_seqs(self) -> int:
  266. return len(self.get_unfinished_seqs())
  267. def num_finished_seqs(self) -> int:
  268. return len(self.get_finished_seqs())
  269. def find(self, seq_id: int) -> Sequence:
  270. if seq_id not in self.seqs_dict:
  271. raise ValueError(f"Sequence {seq_id} not found.")
  272. return self.seqs_dict[seq_id]
  273. def add(self, seq: Sequence) -> None:
  274. if seq.seq_id in self.seqs_dict:
  275. raise ValueError(f"Sequence {seq.seq_id} already exists.")
  276. self.seqs_dict[seq.seq_id] = seq
  277. def remove(self, seq_id: int) -> None:
  278. if seq_id not in self.seqs_dict:
  279. raise ValueError(f"Sequence {seq_id} not found.")
  280. del self.seqs_dict[seq_id]
  281. def is_finished(self) -> bool:
  282. return all(seq.is_finished() for seq in self.get_seqs())
  283. def __repr__(self) -> str:
  284. return (f"SequenceGroup(request_id={self.request_id}, "
  285. f"sampling_params={self.sampling_params}, "
  286. f"num_seqs={len(self.seqs_dict)})")
  287. class SequenceGroupMetadata:
  288. """Metadata for a sequence group. Used to create `InputMetadata`.
  289. Args:
  290. request_id: The ID of the request.
  291. is_prompt: Whether the request is at prompt stage.
  292. seq_data: The sequence data. (Seq id -> sequence data)
  293. sampling_params: The sampling parameters used to generate the outputs.
  294. block_tables: The block tables. (Seq id -> list of physical block
  295. numbers)
  296. lora_request: LoRA request.
  297. prefix: The prefix of the prompt of the sequence group.
  298. persistent_data: The persistent data of the sequence group.
  299. """
  300. def __init__(
  301. self,
  302. request_id: str,
  303. is_prompt: bool,
  304. seq_data: Dict[int, SequenceData],
  305. sampling_params: SamplingParams,
  306. block_tables: Dict[int, List[int]],
  307. persistent_data: Dict[int, dict],
  308. lora_request: Optional[LoRARequest] = None,
  309. prefix: Optional[Prefix] = None,
  310. ) -> None:
  311. self.request_id = request_id
  312. self.is_prompt = is_prompt
  313. self.seq_data = seq_data
  314. self.sampling_params = sampling_params
  315. self.block_tables = block_tables
  316. self.persistent_data = persistent_data
  317. self.lora_request = lora_request
  318. self.prefix = prefix
  319. @property
  320. def lora_int_id(self) -> int:
  321. return self.lora_request.lora_int_id if self.lora_request else 0
  322. class SequenceOutput:
  323. """The model output associated with a sequence.
  324. Args:
  325. parent_seq_id: The ID of the parent sequence (for forking in beam
  326. search).
  327. output_token: The output token ID.
  328. logprobs: The logprobs of the output token.
  329. (Token id -> logP(x_i+1 | x_0, ..., x_i))
  330. persistent_data: The persistent data of the sequence.
  331. """
  332. def __init__(
  333. self,
  334. parent_seq_id: int,
  335. output_token: int,
  336. logprobs: Dict[int, float],
  337. persistent_data: dict,
  338. ) -> None:
  339. self.parent_seq_id = parent_seq_id
  340. self.output_token = output_token
  341. self.logprobs = logprobs
  342. self.persistent_data = persistent_data
  343. def __repr__(self) -> str:
  344. return (f"SequenceOutput(parent_seq_id={self.parent_seq_id}, "
  345. f"output_token={self.output_token}, "
  346. f"logprobs={self.logprobs}, "
  347. f"persistent_data={self.persistent_data})")
  348. def __eq__(self, other: object) -> bool:
  349. if not isinstance(other, SequenceOutput):
  350. raise NotImplementedError()
  351. return (self.parent_seq_id == other.parent_seq_id
  352. and self.output_token == other.output_token
  353. and self.logprobs == other.logprobs
  354. and self.persistent_data == other.persistent_data)
  355. class SequenceGroupOutput:
  356. """The model output associated with a sequence group."""
  357. def __init__(
  358. self,
  359. samples: List[SequenceOutput],
  360. prompt_logprobs: Optional[PromptLogprobs],
  361. ) -> None:
  362. self.samples = samples
  363. self.prompt_logprobs = prompt_logprobs
  364. def __repr__(self) -> str:
  365. return (f"SequenceGroupOutput(samples={self.samples}, "
  366. f"prompt_logprobs={self.prompt_logprobs})")
  367. def __eq__(self, other: object) -> bool:
  368. if not isinstance(other, SequenceGroupOutput):
  369. raise NotImplementedError()
  370. return (self.samples == other.samples
  371. and self.prompt_logprobs == other.prompt_logprobs)
  372. # For each sequence group, we generate a list of SequenceOutput object,
  373. # each of which contains one possible candidate for the next token.
  374. SamplerOutput = List[SequenceGroupOutput]