sequence.py 18 KB

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