sequence.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. is_encoder_decoder: bool,
  118. lora_request: Optional[LoRARequest] = None,
  119. ) -> None:
  120. self.seq_id = seq_id
  121. self.prompt = prompt
  122. self.block_size = block_size
  123. self.lora_request = lora_request
  124. self.data = SequenceData(prompt_token_ids)
  125. self.output_logprobs: SampleLogprobs = []
  126. self.output_text = ""
  127. self.logical_token_blocks: List[LogicalTokenBlock] = []
  128. initial_token_ids = prompt_token_ids
  129. if is_encoder_decoder:
  130. # We need to separate the prompt and generated tokens for
  131. # encoder-decoder models.
  132. num_prompt_blocks = (len(prompt_token_ids) + block_size -
  133. 1) // block_size
  134. padded_prompt_len = num_prompt_blocks * block_size
  135. initial_token_ids = prompt_token_ids + [0] * (
  136. padded_prompt_len - len(prompt_token_ids))
  137. # Also need to append decoder_start_token_id
  138. initial_token_ids.append(0)
  139. # Initialize the logical token blocks with the prompt token ids.
  140. self._append_tokens_to_blocks(initial_token_ids)
  141. self.status = SequenceStatus.WAITING
  142. # Used for incremental detokenization
  143. self.prefix_offset = 0
  144. self.read_offset = 0
  145. # Input + output tokens
  146. self.tokens: Optional[List[str]] = None
  147. self.persistent_data = {}
  148. self.persistent_data = {}
  149. @property
  150. def lora_int_id(self) -> int:
  151. return self.lora_request.lora_int_id if self.lora_request else 0
  152. def hash_of_block(self, logical_idx: int) -> int:
  153. # Compute the number of tokens in the sequence
  154. # TODO: The current hashing function is O(L^2). We should optimize
  155. # this in the future.
  156. num_tokens = self.num_hashed_tokens_of_block(logical_idx)
  157. return hash(
  158. (tuple(self.data.get_token_ids()[0:num_tokens]), self.lora_int_id))
  159. def num_hashed_tokens_of_block(self, logical_idx: int):
  160. return logical_idx * self.block_size + self.block_size
  161. def _append_logical_block(self) -> None:
  162. block = LogicalTokenBlock(
  163. block_number=len(self.logical_token_blocks),
  164. block_size=self.block_size,
  165. )
  166. self.logical_token_blocks.append(block)
  167. def _append_tokens_to_blocks(self, token_ids: List[int]) -> None:
  168. cursor = 0
  169. while cursor < len(token_ids):
  170. if not self.logical_token_blocks:
  171. self._append_logical_block()
  172. last_block = self.logical_token_blocks[-1]
  173. if last_block.is_full():
  174. self._append_logical_block()
  175. last_block = self.logical_token_blocks[-1]
  176. num_empty_slots = last_block.get_num_empty_slots()
  177. last_block.append_tokens(token_ids[cursor:cursor +
  178. num_empty_slots])
  179. cursor += num_empty_slots
  180. def append_token_id(
  181. self,
  182. token_id: int,
  183. logprobs: Dict[int, Logprob],
  184. ) -> None:
  185. assert token_id in logprobs
  186. self._append_tokens_to_blocks([token_id])
  187. self.output_logprobs.append(logprobs)
  188. self.data.append_token_id(token_id, logprobs[token_id].logprob)
  189. def get_len(self) -> int:
  190. return self.data.get_len()
  191. def get_prompt_len(self) -> int:
  192. return self.data.get_prompt_len()
  193. def get_output_len(self) -> int:
  194. return self.data.get_output_len()
  195. def get_token_ids(self) -> List[int]:
  196. return self.data.get_token_ids()
  197. def get_last_token_id(self) -> int:
  198. return self.data.get_last_token_id()
  199. def get_output_token_ids(self) -> List[int]:
  200. return self.data.output_token_ids
  201. def get_cumulative_logprob(self) -> float:
  202. return self.data.cumulative_logprob
  203. def get_beam_search_score(self,
  204. length_penalty: float = 0.0,
  205. seq_len: Optional[int] = None,
  206. eos_token_id: Optional[int] = None) -> float:
  207. """Calculate the beam search score with length penalty.
  208. Adapted from
  209. https://github.com/huggingface/transformers/blob/ccb92be23def445f2afdea94c31286f84b89eb5b/src/transformers/generation/beam_search.py#L938
  210. """
  211. if seq_len is None:
  212. seq_len = self.get_len()
  213. # NOTE: HF implementation does not count the EOS token
  214. # towards the length, we align with that here for testing.
  215. if (eos_token_id is not None
  216. and self.get_last_token_id() == eos_token_id):
  217. seq_len -= 1
  218. return self.get_cumulative_logprob() / (seq_len**length_penalty)
  219. def is_finished(self) -> bool:
  220. return SequenceStatus.is_finished(self.status)
  221. def fork(self, new_seq_id: int) -> "Sequence":
  222. new_seq = copy.deepcopy(self)
  223. new_seq.seq_id = new_seq_id
  224. return new_seq
  225. def __repr__(self) -> str:
  226. return (f"Sequence(seq_id={self.seq_id}, "
  227. f"status={self.status.name}, "
  228. f"num_blocks={len(self.logical_token_blocks)})")
  229. @dataclass
  230. class SequenceGroupState:
  231. """Mutable state tied to a specific sequence group"""
  232. # torch.Generator used in seeded sampling
  233. generator: Optional = None
  234. class SequenceGroup:
  235. """A group of sequences that are generated from the same prompt.
  236. Args:
  237. request_id: The ID of the request.
  238. seqs: The list of sequences.
  239. sampling_params: The sampling parameters used to generate the outputs.
  240. arrival_time: The arrival time of the request.
  241. lora_request: LoRA request.
  242. """
  243. def __init__(
  244. self,
  245. request_id: str,
  246. seqs: List[Sequence],
  247. sampling_params: SamplingParams,
  248. arrival_time: float,
  249. lora_request: Optional[LoRARequest] = None,
  250. ) -> None:
  251. self.request_id = request_id
  252. self.seqs_dict = {seq.seq_id: seq for seq in seqs}
  253. self.sampling_params = sampling_params
  254. self.metrics = RequestMetrics(arrival_time=arrival_time,
  255. last_token_time=arrival_time,
  256. first_scheduled_time=None,
  257. first_token_time=None,
  258. time_in_queue=None)
  259. self.lora_request = lora_request
  260. self.prompt_logprobs: Optional[PromptLogprobs] = None
  261. self.state = SequenceGroupState()
  262. @property
  263. def prompt(self) -> str:
  264. # All sequences in the group should have the same prompt.
  265. # We use the prompt of an arbitrary sequence.
  266. return next(iter(self.seqs_dict.values())).prompt
  267. @property
  268. def prompt_token_ids(self) -> List[int]:
  269. # All sequences in the group should have the same prompt.
  270. # We use the prompt of an arbitrary sequence.
  271. return next(iter(self.seqs_dict.values())).data.prompt_token_ids
  272. @property
  273. def lora_int_id(self) -> int:
  274. return self.lora_request.lora_int_id if self.lora_request else 0
  275. def get_last_latency(self, now: float) -> float:
  276. """Gets last token latency for Request level timings."""
  277. latency = now - self.metrics.last_token_time
  278. self.metrics.last_token_time = now
  279. return latency
  280. def maybe_set_first_token_time(self, time: float) -> None:
  281. """Sets the first token time for Request level timings."""
  282. if self.metrics.first_token_time is None:
  283. self.metrics.first_token_time = time
  284. def maybe_set_first_scheduled_time(self, time: float) -> None:
  285. """Sets the first scheduled time and time in queue for Request level
  286. timings."""
  287. if self.metrics.first_scheduled_time is None:
  288. self.metrics.first_scheduled_time = time
  289. self.metrics.time_in_queue = time - self.metrics.arrival_time
  290. def set_finished_time(self, time: Optional[float]) -> None:
  291. """Sets the finished time for Request level timings."""
  292. self.metrics.finished_time = time
  293. def get_max_num_running_seqs(self) -> int:
  294. """The maximum number of sequences running in parallel in the remaining
  295. lifetime of the request."""
  296. if self.sampling_params.use_beam_search:
  297. # For beam search, maximally there will always be `best_of` beam
  298. # candidates running in the future.
  299. return self.sampling_params.best_of
  300. else:
  301. if self.sampling_params.best_of > self.num_seqs():
  302. # At prompt stage, the sequence group is not yet filled up
  303. # and only have one sequence running. However, in the
  304. # generation stage, we will have `best_of` sequences running.
  305. return self.sampling_params.best_of
  306. # At sampling stages, return the number of actual sequences
  307. # that are not finished yet.
  308. return self.num_unfinished_seqs()
  309. def get_seqs(
  310. self,
  311. status: Optional[SequenceStatus] = None,
  312. ) -> List[Sequence]:
  313. if status is None:
  314. return list(self.seqs_dict.values())
  315. else:
  316. return [
  317. seq for seq in self.seqs_dict.values() if seq.status == status
  318. ]
  319. def get_unfinished_seqs(self) -> List[Sequence]:
  320. return [
  321. seq for seq in self.seqs_dict.values() if not seq.is_finished()
  322. ]
  323. def get_finished_seqs(self) -> List[Sequence]:
  324. return [seq for seq in self.seqs_dict.values() if seq.is_finished()]
  325. def num_seqs(self, status: Optional[SequenceStatus] = None) -> int:
  326. return len(self.get_seqs(status))
  327. def num_unfinished_seqs(self) -> int:
  328. return len(self.get_unfinished_seqs())
  329. def num_finished_seqs(self) -> int:
  330. return len(self.get_finished_seqs())
  331. def find(self, seq_id: int) -> Sequence:
  332. if seq_id not in self.seqs_dict:
  333. raise ValueError(f"Sequence {seq_id} not found.")
  334. return self.seqs_dict[seq_id]
  335. def add(self, seq: Sequence) -> None:
  336. if seq.seq_id in self.seqs_dict:
  337. raise ValueError(f"Sequence {seq.seq_id} already exists.")
  338. self.seqs_dict[seq.seq_id] = seq
  339. def remove(self, seq_id: int) -> None:
  340. if seq_id not in self.seqs_dict:
  341. raise ValueError(f"Sequence {seq_id} not found.")
  342. del self.seqs_dict[seq_id]
  343. def is_finished(self) -> bool:
  344. return all(seq.is_finished() for seq in self.get_seqs())
  345. def __repr__(self) -> str:
  346. return (f"SequenceGroup(request_id={self.request_id}, "
  347. f"sampling_params={self.sampling_params}, "
  348. f"num_seqs={len(self.seqs_dict)})")
  349. class SequenceGroupMetadata:
  350. """Metadata for a sequence group. Used to create `InputMetadata`.
  351. Args:
  352. request_id: The ID of the request.
  353. is_prompt: Whether the request is at prompt stage.
  354. seq_data: The sequence data. (Seq id -> sequence data)
  355. sampling_params: The sampling parameters used to generate the outputs.
  356. block_tables: The block tables. (Seq id -> list of physical block
  357. numbers)
  358. state: Internal state tied to this sequence group.
  359. lora_request: LoRA request.
  360. persistent_data: The persistent data of the sequence group.
  361. """
  362. def __init__(
  363. self,
  364. request_id: str,
  365. is_prompt: bool,
  366. seq_data: Dict[int, SequenceData],
  367. sampling_params: SamplingParams,
  368. block_tables: Dict[int, List[int]],
  369. persistent_data: Dict[int, dict],
  370. lora_request: Optional[LoRARequest] = None,
  371. computed_block_nums: Optional[List[int]] = None,
  372. state: Optional[SequenceGroupState] = None,
  373. ) -> None:
  374. self.request_id = request_id
  375. self.is_prompt = is_prompt
  376. self.seq_data = seq_data
  377. self.sampling_params = sampling_params
  378. self.block_tables = block_tables
  379. self.persistent_data = persistent_data
  380. self.lora_request = lora_request
  381. self.computed_block_nums = computed_block_nums
  382. self.state = SequenceGroupState() if state is None else state
  383. @property
  384. def lora_int_id(self) -> int:
  385. return self.lora_request.lora_int_id if self.lora_request else 0
  386. class SequenceOutput:
  387. """The model output associated with a sequence.
  388. Args:
  389. parent_seq_id: The ID of the parent sequence (for forking in beam
  390. search).
  391. output_token: The output token ID.
  392. logprobs: The logprobs of the output token.
  393. (Token id -> logP(x_i+1 | x_0, ..., x_i))
  394. persistent_data: The persistent data of the sequence.
  395. """
  396. def __init__(
  397. self,
  398. parent_seq_id: int,
  399. output_token: int,
  400. logprobs: Dict[int, Logprob],
  401. persistent_data: dict,
  402. ) -> None:
  403. self.parent_seq_id = parent_seq_id
  404. self.output_token = output_token
  405. self.logprobs = logprobs
  406. self.persistent_data = persistent_data
  407. def __repr__(self) -> str:
  408. return (f"SequenceOutput(parent_seq_id={self.parent_seq_id}, "
  409. f"output_token={self.output_token}, "
  410. f"logprobs={self.logprobs}, "
  411. f"persistent_data={self.persistent_data})")
  412. def __eq__(self, other: object) -> bool:
  413. if not isinstance(other, SequenceOutput):
  414. raise NotImplementedError()
  415. equal = (self.parent_seq_id == other.parent_seq_id
  416. and self.output_token == other.output_token)
  417. log_probs_equal = other.logprobs == self.logprobs
  418. return equal and log_probs_equal
  419. class SequenceGroupOutput:
  420. """The model output associated with a sequence group."""
  421. def __init__(
  422. self,
  423. samples: List[SequenceOutput],
  424. prompt_logprobs: Optional[PromptLogprobs],
  425. ) -> None:
  426. self.samples = samples
  427. self.prompt_logprobs = prompt_logprobs
  428. def __repr__(self) -> str:
  429. return (f"SequenceGroupOutput(samples={self.samples}, "
  430. f"prompt_logprobs={self.prompt_logprobs})")
  431. def __eq__(self, other: object) -> bool:
  432. if not isinstance(other, SequenceGroupOutput):
  433. raise NotImplementedError()
  434. return (self.samples == other.samples
  435. and self.prompt_logprobs == other.prompt_logprobs)
  436. # For each sequence group, we generate a list of SequenceOutput object,
  437. # each of which contains one possible candidate for the next token.
  438. SamplerOutput = List[SequenceGroupOutput]