sequence.py 14 KB

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