1
0

sampler.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  1. """A layer that samples the next tokens from the model's outputs."""
  2. import itertools
  3. from typing import Dict, List, Optional, Tuple
  4. import torch
  5. import torch.nn as nn
  6. from aphrodite.common.sampling_params import SamplingType
  7. from aphrodite.common.sequence import (CompletionSequenceGroupOutput, Logprob,
  8. PromptLogprobs, SampleLogprobs,
  9. SamplerOutput, SequenceOutput)
  10. from aphrodite.modeling.layers.ops.sample import sample as sample_triton
  11. from aphrodite.modeling.sampling_metadata import (SamplingMetadata,
  12. SamplingTensors,
  13. SequenceGroupToSample)
  14. # (num_token_ids, num_parent_ids) per sequence group.
  15. SampleResultType = List[Tuple[List[int], List[int]]]
  16. class Sampler(nn.Module):
  17. """Samples the next tokens from the model's outputs.
  18. This layer does the following:
  19. 1. Discard the hidden states that are not used for sampling (i.e., all
  20. tokens except the final one in each prompt).
  21. 2. Compute the logits for the next tokens.
  22. 3. Apply presence, frequency and repetition penalties.
  23. 4. Apply temperature scaling.
  24. 5. Apply top-p and top-k truncation.
  25. 6. Sample the next tokens.
  26. Here, each sequence group within the batch can have different sampling
  27. parameters (e.g., sampling method, temperature, top-p, top-k, etc.).
  28. The structure of the logits tensor is coupled with the seq_groups in
  29. sampling_metadata. Typically, each sequence in each seq_group has one row in
  30. logits for the next token to be sampled; however, for a seq_group with a
  31. prompt request with the prompt_logprobs sampling parameter, there are rows
  32. in logits for each token in the input prompt.
  33. """
  34. def __init__(self):
  35. super().__init__()
  36. # Whether or not the SamplerOutput should have on-device tensors
  37. # containing the sampled token ids and probabilities. This is used by
  38. # speculative decoding.
  39. self.include_gpu_probs_tensor = False
  40. def _init_sampling_tensors(
  41. self,
  42. logits: torch.Tensor,
  43. sampling_metadata: SamplingMetadata,
  44. ):
  45. """The goal here is to reuse sampling tensors between similar decode
  46. runs. This is possible because sampling logic does not change between
  47. decodes of the same sequences.
  48. """
  49. _, vocab_size = logits.shape
  50. # First free any existing stored sampling tensors.
  51. # This is necessary because some sampling tensors may
  52. # have pinned memory.
  53. self._sampling_tensors = None
  54. # Initialize new sampling tensors
  55. (sampling_tensors, do_penalties, do_top_p_top_k, do_top_as, do_min_p,
  56. do_tfss, do_eta_cutoffs, do_epsilon_cutoffs, do_typical_ps,
  57. do_quadratic) = SamplingTensors.from_sampling_metadata(
  58. sampling_metadata, vocab_size, logits.device, logits.dtype)
  59. self._sampling_tensors = sampling_tensors
  60. self._do_penalties = do_penalties
  61. self._do_top_p_top_k = do_top_p_top_k
  62. self._do_top_as = do_top_as
  63. self._do_min_p = do_min_p
  64. self._do_tfss = do_tfss
  65. self._do_eta_cutoffs = do_eta_cutoffs
  66. self._do_epsilon_cutoffs = do_epsilon_cutoffs
  67. self._do_typical_ps = do_typical_ps
  68. self._do_quadratic = do_quadratic
  69. def forward(
  70. self,
  71. logits: torch.Tensor,
  72. sampling_metadata: SamplingMetadata,
  73. ) -> Optional[SamplerOutput]:
  74. """
  75. Args:
  76. logits: (num_tokens, vocab_size).
  77. sampling_metadata: Metadata for sampling.
  78. """
  79. assert logits is not None
  80. _, vocab_size = logits.shape
  81. # Prepare sampling tensors with pinned memory to avoid blocking.
  82. if not sampling_metadata.reuse_sampling_tensors:
  83. self._init_sampling_tensors(logits, sampling_metadata)
  84. elif self._do_penalties:
  85. # In this case, the sampling tensors logic depends on
  86. # "output_tokens" of a sequence. As a result, we cannot
  87. # reuse sampling tensors, since "output_tokens" changes
  88. # between decode runs.
  89. self._init_sampling_tensors(logits, sampling_metadata)
  90. assert self._sampling_tensors is not None
  91. sampling_tensors = self._sampling_tensors
  92. do_penalties = self._do_penalties
  93. do_top_p_top_k = self._do_top_p_top_k
  94. do_top_as = self._do_top_as
  95. do_min_p = self._do_min_p
  96. do_tfss = self._do_tfss
  97. do_eta_cutoffs = self._do_eta_cutoffs
  98. do_epsilon_cutoffs = self._do_epsilon_cutoffs
  99. do_typical_ps = self._do_typical_ps
  100. do_quadratic = self._do_quadratic
  101. logits = _apply_min_tokens_penalty(logits, sampling_metadata)
  102. # Apply presence and frequency penalties.
  103. if do_penalties:
  104. logits = _apply_penalties(logits, sampling_tensors.prompt_tokens,
  105. sampling_tensors.output_tokens,
  106. sampling_tensors.presence_penalties,
  107. sampling_tensors.frequency_penalties,
  108. sampling_tensors.repetition_penalties)
  109. # Apply temperature scaling.
  110. # Use in-place division to avoid creating a new tensor.
  111. logits.div_(sampling_tensors.temperatures.unsqueeze(dim=1))
  112. if do_top_p_top_k:
  113. logits = _apply_top_k_top_p(logits, sampling_tensors.top_ps,
  114. sampling_tensors.top_ks)
  115. if do_top_as:
  116. logits = _apply_top_a(logits, sampling_tensors.top_as)
  117. if do_min_p:
  118. logits = _apply_min_p(logits, sampling_tensors.min_ps)
  119. if do_tfss:
  120. logits = _apply_tfs(logits, sampling_tensors.tfss)
  121. if do_eta_cutoffs:
  122. logits = _apply_eta_cutoff(logits, sampling_tensors.eta_cutoffs)
  123. if do_epsilon_cutoffs:
  124. logits = _apply_epsilon_cutoff(logits,
  125. sampling_tensors.epsilon_cutoffs)
  126. if do_typical_ps:
  127. logits = _apply_typical_sampling(logits,
  128. sampling_tensors.typical_ps)
  129. if do_quadratic:
  130. logits = _apply_quadratic_sampling(
  131. logits, sampling_tensors.smoothing_factors,
  132. sampling_tensors.smoothing_curves)
  133. # banned_tokens = _get_custom_token_bans(sampling_metadata)
  134. # logits = _apply_token_bans(logits, banned_tokens)
  135. # We use float32 for probabilities and log probabilities.
  136. # Compute the probabilities.
  137. probs = torch.softmax(logits, dim=-1, dtype=torch.float)
  138. # Compute the log probabilities.
  139. logprobs = torch.log_softmax(logits, dim=-1, dtype=torch.float)
  140. # Sample the next tokens.
  141. sample_results, maybe_sampled_tokens_tensor = _sample(
  142. probs,
  143. logprobs,
  144. sampling_metadata,
  145. sampling_tensors,
  146. include_gpu_probs_tensor=self.include_gpu_probs_tensor,
  147. modify_greedy_probs=self._should_modify_greedy_probs_inplace,
  148. )
  149. if self.include_gpu_probs_tensor:
  150. assert maybe_sampled_tokens_tensor is not None
  151. on_device_tensors = (probs, logprobs, maybe_sampled_tokens_tensor)
  152. else:
  153. on_device_tensors = None
  154. # Get the logprobs query results.
  155. prompt_logprobs = None
  156. sample_logprobs = None
  157. if not sampling_metadata.skip_sampler_cpu_output:
  158. prompt_logprobs, sample_logprobs = _get_logprobs(
  159. logprobs, sampling_metadata, sample_results)
  160. return _build_sampler_output(
  161. sample_results,
  162. sampling_metadata,
  163. prompt_logprobs,
  164. sample_logprobs,
  165. on_device_tensors=on_device_tensors,
  166. skip_sampler_cpu_output=sampling_metadata.skip_sampler_cpu_output)
  167. @property
  168. def _should_modify_greedy_probs_inplace(self) -> bool:
  169. """Whether or not the sampler should modify the probability distribution
  170. of greedily-sampled tokens such that multinomial sampling would sample
  171. the greedily-sampled token.
  172. In other words, if True then we set the probability of the greedily-
  173. sampled token to 1.
  174. This is used by speculative decoding, which requires that the sampling
  175. method be encoded into the probability distribution.
  176. """
  177. # Modify greedy probs if include_gpu_probs_tensor is set.
  178. return self.include_gpu_probs_tensor
  179. def _get_bin_counts_and_mask(
  180. tokens: torch.Tensor,
  181. vocab_size: int,
  182. num_seqs: int,
  183. ) -> Tuple[torch.Tensor, torch.Tensor]:
  184. # Compute the bin counts for the tokens.
  185. # vocab_size + 1 for padding.
  186. bin_counts = torch.zeros((num_seqs, vocab_size + 1),
  187. dtype=torch.long,
  188. device=tokens.device)
  189. bin_counts.scatter_add_(1, tokens, torch.ones_like(tokens))
  190. bin_counts = bin_counts[:, :vocab_size]
  191. mask = bin_counts > 0
  192. return bin_counts, mask
  193. def _get_custom_token_bans(
  194. sampling_metadata: SamplingMetadata) -> List[List[int]]:
  195. assert sampling_metadata.seq_groups is not None
  196. banned_tokens: List[List[int]] = []
  197. for i, seq_group in enumerate(sampling_metadata.seq_groups):
  198. sampling_params = sampling_metadata.seq_groups[i].sampling_params
  199. seq_ids = seq_group.seq_ids
  200. custom_token_bans = sampling_params.custom_token_bans
  201. if (i < sampling_metadata.num_prompts
  202. and sampling_params.prompt_logprobs is not None):
  203. prompt_len = len(seq_group.prompt_logprob_indices)
  204. banned_tokens += [custom_token_bans] * (prompt_len - 1)
  205. banned_tokens += [custom_token_bans] * len(seq_ids)
  206. return banned_tokens
  207. def _apply_penalties(logits: torch.Tensor, prompt_tokens_tensor: torch.Tensor,
  208. output_tokens_tensor: torch.Tensor,
  209. presence_penalties: torch.Tensor,
  210. frequency_penalties: torch.Tensor,
  211. repetition_penalties: torch.Tensor) -> torch.Tensor:
  212. num_seqs, vocab_size = logits.shape
  213. _, prompt_mask = _get_bin_counts_and_mask(prompt_tokens_tensor, vocab_size,
  214. num_seqs)
  215. output_bin_counts, output_mask = _get_bin_counts_and_mask(
  216. output_tokens_tensor, vocab_size, num_seqs)
  217. repetition_penalties = repetition_penalties[:, None].repeat(1, vocab_size)
  218. repetition_penalties[~(prompt_mask | output_mask)] = 1.0
  219. logits = torch.where(logits > 0, logits / repetition_penalties,
  220. logits * repetition_penalties)
  221. # We follow the definition in OpenAI API.
  222. # Refer to https://platform.openai.com/docs/api-reference/parameter-details
  223. logits -= frequency_penalties.unsqueeze_(dim=1) * output_bin_counts
  224. logits -= presence_penalties.unsqueeze_(dim=1) * output_mask
  225. return logits
  226. def _apply_token_bans(logits: torch.Tensor,
  227. banned_tokens: List[List[int]]) -> torch.Tensor:
  228. for i, banned_token_ids in enumerate(banned_tokens):
  229. if not banned_token_ids:
  230. continue
  231. logits[i, banned_token_ids] = -float("inf")
  232. return logits
  233. def _apply_min_tokens_penalty(
  234. logits: torch.Tensor,
  235. sampling_metadata: SamplingMetadata,
  236. ) -> torch.Tensor:
  237. """Apply min_tokens penalty which sets stop tokens to -inf if min_tokens
  238. have not been generated yet
  239. """
  240. # list of indices in logits that will be set to -inf
  241. logits_to_penalize = []
  242. logits_applied = 0
  243. for seq_group in sampling_metadata.seq_groups:
  244. seq_ids = seq_group.seq_ids
  245. sampling_params = seq_group.sampling_params
  246. sample_indices = seq_group.sample_indices
  247. logits_applied += len(sample_indices) + len(
  248. seq_group.prompt_logprob_indices)
  249. if not seq_group.do_sample:
  250. continue
  251. start_idx = sample_indices[0]
  252. min_tokens = sampling_params.min_tokens
  253. token_ids_to_penalize = sampling_params.all_stop_token_ids
  254. if min_tokens > 0 and token_ids_to_penalize:
  255. seqs_to_penalize = []
  256. for j, seq_id in enumerate(seq_ids):
  257. seq_data = seq_group.seq_data[seq_id]
  258. if len(seq_data.output_token_ids) < min_tokens:
  259. seqs_to_penalize.append(j)
  260. if seqs_to_penalize:
  261. # convert to the index into logits
  262. seqs_to_penalize = [start_idx + j for j in seqs_to_penalize]
  263. # itertools.product pairs each seq index with every token id
  264. logits_to_penalize.extend(
  265. itertools.product(seqs_to_penalize, token_ids_to_penalize))
  266. if logits_to_penalize:
  267. # use zip and * to group indices along each dimension
  268. # eg. [ (1,2), (1,3), (5,6) ] -> ( (1,1,5), (2,3,6) )
  269. logits[tuple(zip(*logits_to_penalize))] = -float("inf")
  270. # verifies that no rows in logits were missed unexpectedly
  271. assert logits_applied == logits.shape[0]
  272. return logits
  273. def _apply_top_k_top_p(
  274. logits: torch.Tensor,
  275. p: torch.Tensor,
  276. k: torch.Tensor,
  277. ) -> torch.Tensor:
  278. logits_sort, logits_idx = logits.sort(dim=-1, descending=False)
  279. # Apply top-k.
  280. top_k_mask = logits_sort.size(1) - k.to(torch.long)
  281. # Get all the top_k values.
  282. top_k_mask = logits_sort.gather(1, top_k_mask.unsqueeze(dim=1))
  283. top_k_mask = logits_sort < top_k_mask
  284. logits_sort.masked_fill_(top_k_mask, -float("inf"))
  285. # Apply top-p.
  286. probs_sort = logits_sort.softmax(dim=-1)
  287. probs_sum = probs_sort.cumsum(dim=-1)
  288. top_p_mask = probs_sum <= 1 - p.unsqueeze(dim=1)
  289. # at least one
  290. top_p_mask[:, -1] = False
  291. logits_sort.masked_fill_(top_p_mask, -float("inf"))
  292. # Re-sort the probabilities.
  293. src = torch.arange(logits_idx.shape[-1],
  294. device=logits_idx.device).expand_as(logits_idx)
  295. logits_idx_inv = torch.empty_like(logits_idx).scatter_(dim=-1,
  296. index=logits_idx,
  297. src=src)
  298. logits = torch.gather(logits_sort, dim=-1, index=logits_idx_inv)
  299. return logits
  300. def _apply_min_p(
  301. logits: torch.Tensor,
  302. min_p: torch.Tensor,
  303. ) -> torch.Tensor:
  304. """
  305. Adapted from
  306. https://github.com/oobabooga/text-generation-webui/blob/3146124ec01f02c8fb1650a6517cf1b60b537aaf/modules/sampler_hijack.py#L16C17-L16C17
  307. """
  308. probs = torch.softmax(logits, dim=-1)
  309. top_probs, _ = probs.max(dim=-1, keepdim=True)
  310. scaled_min_p = min_p.unsqueeze_(dim=1) * top_probs
  311. tokens_to_remove = probs < scaled_min_p
  312. logits = logits.masked_fill_(tokens_to_remove, -float("inf"))
  313. return logits
  314. def _apply_top_a(
  315. logits: torch.Tensor,
  316. top_a: torch.Tensor,
  317. ) -> torch.Tensor:
  318. probs = torch.softmax(logits, dim=-1)
  319. top_probs, _ = probs.max(dim=-1, keepdim=True)
  320. threshold = torch.pow(top_probs, 2) * top_a.unsqueeze_(dim=1)
  321. tokens_to_remove = probs < threshold
  322. logits = logits.masked_fill_(tokens_to_remove, -float("inf"))
  323. return logits
  324. def _apply_tfs(
  325. logits: torch.Tensor,
  326. tfs: torch.Tensor,
  327. ) -> torch.Tensor:
  328. logits_sort, logits_idx = logits.sort(dim=-1, descending=True)
  329. d2 = logits_sort.softmax(dim=-1).diff().diff().abs()
  330. normalized_d2 = d2 / torch.sum(d2, dim=-1, keepdim=True)
  331. curvature_cdf = torch.cumsum(normalized_d2, dim=-1)
  332. tfs_mask = curvature_cdf > tfs.unsqueeze(dim=-1)
  333. tfs_mask = torch.cat(
  334. (
  335. torch.zeros(
  336. logits.shape[0], 1, dtype=torch.bool, device=logits.device),
  337. tfs_mask,
  338. torch.ones(
  339. logits.shape[0], 1, dtype=torch.bool, device=logits.device),
  340. ),
  341. dim=-1,
  342. )
  343. logits_sort[tfs_mask] = -float("inf")
  344. logits = torch.gather(logits_sort,
  345. dim=-1,
  346. index=torch.argsort(logits_idx, dim=-1))
  347. return logits
  348. def _apply_eta_cutoff(
  349. logits: torch.Tensor,
  350. eta_cutoff: torch.Tensor,
  351. ) -> torch.Tensor:
  352. shifted_logits = torch.log_softmax(logits, dim=-1)
  353. probs = shifted_logits.exp()
  354. neg_entropy = (probs * shifted_logits).nansum(dim=-1)
  355. eps = torch.min(eta_cutoff,
  356. torch.sqrt(eta_cutoff) *
  357. torch.exp(neg_entropy)).unsqueeze(dim=1)
  358. eta_mask = probs < eps
  359. # guard against nulling out all the logits
  360. top_idx = torch.argmax(probs, dim=1, keepdim=True)
  361. eta_mask.scatter_(dim=1, index=top_idx, value=False)
  362. logits[eta_mask] = -float("inf")
  363. return logits
  364. def _apply_epsilon_cutoff(
  365. logits: torch.Tensor,
  366. epsilon_cutoff: torch.Tensor,
  367. ) -> torch.Tensor:
  368. probs = logits.softmax(dim=-1)
  369. eps_mask = probs < epsilon_cutoff.unsqueeze(dim=1)
  370. # guard against nulling out all the logits
  371. top_idx = torch.argmax(probs, dim=1, keepdim=True)
  372. eps_mask.scatter_(dim=1, index=top_idx, value=False)
  373. logits[eps_mask] = -float("inf")
  374. return logits
  375. def _apply_typical_sampling(
  376. logits: torch.Tensor,
  377. typical_p: torch.Tensor,
  378. ) -> torch.Tensor:
  379. shifted_logits = torch.log_softmax(logits, dim=-1)
  380. probs = shifted_logits.exp()
  381. neg_entropy = (probs * shifted_logits).nansum(dim=-1, keepdim=True)
  382. surprisal_deviations = (neg_entropy - shifted_logits).abs()
  383. _, indices = torch.sort(surprisal_deviations)
  384. reordered_probs = probs.gather(-1, indices)
  385. typ_mask_sorted = reordered_probs.cumsum(dim=-1) >= typical_p.unsqueeze(
  386. dim=1)
  387. min_tokens_to_keep = 1
  388. # Keep at least min_tokens_to_keep
  389. typ_mask_sorted[..., :min_tokens_to_keep] = 0
  390. typ_mask = typ_mask_sorted.scatter(1, indices, typ_mask_sorted)
  391. logits[typ_mask] = -float("inf")
  392. return logits
  393. def _apply_quadratic_sampling(
  394. logits: torch.Tensor,
  395. smoothing_factor: torch.Tensor,
  396. smoothing_curve: torch.Tensor,
  397. ) -> torch.Tensor:
  398. """
  399. Applies a quadratic transformation to the logits based on the
  400. provided smoothing factors and curves. The transformation is
  401. centered around the maximum logit value in the batch.
  402. The transformation involves a quadratic and cubic term, with the
  403. cubic term controlled by the smoothing curve. The quadratic term is
  404. scaled by the smoothing factor, and the cubic term is scaled by the
  405. product of the smoothing factor and the smoothing curve.
  406. params:
  407. logits (torch.Tensor): The logits to be transformed.
  408. smoothing_factors (torch.Tensor): The factors to scale the quadratic
  409. term in the transformation.
  410. smoothing_curves (torch.Tensor): The factors to scale the cubic term
  411. in the transformation.
  412. returns:
  413. torch.Tensor: The transformed logits.
  414. Credits: @kalomaze
  415. """
  416. max_logits = logits.max(dim=-1, keepdim=True).values
  417. diff = logits - max_logits
  418. smoothing_factor.unsqueeze_(dim=1)
  419. smoothing_curve.unsqueeze_(dim=1)
  420. k = (3 - smoothing_curve) / 2
  421. s = (smoothing_curve - 1) / 2
  422. mask = smoothing_factor > 0
  423. mask = mask.flatten()
  424. transformed_logits = torch.where(
  425. logits != float('-inf'), -(k * smoothing_factor * diff**2) +
  426. (s * smoothing_factor * diff**3) + max_logits, logits)
  427. logits[mask, :] = transformed_logits[mask, :]
  428. return logits
  429. def _greedy_sample(
  430. selected_seq_groups: List[SequenceGroupToSample],
  431. samples: torch.Tensor,
  432. ) -> List[Tuple[List[int], List[int]]]:
  433. """Run greedy sampling on a given samples.
  434. Args:
  435. selected_seq_groups: A list of sequence groups batched.
  436. samples: (num_selected_samples,) A tensor of samples. The length of
  437. samples could be smaller than selected_seq_groups if
  438. seq_group.do_sample is False.
  439. Returns:
  440. Tuple of (next_token_ids, parent_ids). The length of returned list is
  441. same as the length of selected_seq_groups. If the corresponding
  442. seq_group has do_sample=False, tuple contains ([], [])
  443. """
  444. samples = samples.tolist()
  445. sample_idx = 0
  446. results = []
  447. for seq_group in selected_seq_groups:
  448. if not seq_group.do_sample:
  449. results.append(([], []))
  450. continue
  451. seq_ids = seq_group.seq_ids
  452. num_parent_seqs = len(seq_ids)
  453. assert num_parent_seqs == 1, (
  454. "Greedy sampling should have only one seq.")
  455. parent_ids = list(range(num_parent_seqs))
  456. next_token_ids = [samples[sample_idx]]
  457. results.append((next_token_ids, parent_ids))
  458. sample_idx += num_parent_seqs
  459. return results
  460. def _random_sample(
  461. selected_seq_groups: List[SequenceGroupToSample],
  462. random_samples: torch.Tensor,
  463. ) -> List[Tuple[List[int], List[int]]]:
  464. """Run random sampling on a given samples.
  465. Args:
  466. selected_seq_groups: A list of sequence groups batched.
  467. random_samples: (num_selected_samples,) A tensor of samples. The
  468. length of samples could be smaller than selected_seq_groups if
  469. seq_group.do_sample is False.
  470. Returns:
  471. Tuple of (next_token_ids, parent_ids). The length of returned list is
  472. same as the length of selected_seq_groups. If the corresponding
  473. seq_group has do_sample=False, tuple contains ([], [])
  474. """
  475. # Find the maximum best_of value of the prompt phase requests.
  476. random_samples = random_samples.cpu()
  477. sample_idx = 0
  478. results = []
  479. for seq_group in selected_seq_groups:
  480. if not seq_group.do_sample:
  481. results.append(([], []))
  482. continue
  483. seq_ids = seq_group.seq_ids
  484. sampling_params = seq_group.sampling_params
  485. is_prompt = seq_group.is_prompt
  486. num_parent_seqs = len(seq_ids)
  487. if is_prompt:
  488. # Prompt phase.
  489. parent_ids = [0] * sampling_params.best_of
  490. next_token_ids = random_samples[
  491. sample_idx, :sampling_params.best_of].tolist()
  492. else:
  493. # Generation phase.
  494. parent_ids = list(range(num_parent_seqs))
  495. next_token_ids = random_samples[sample_idx:sample_idx +
  496. num_parent_seqs, 0].tolist()
  497. results.append((next_token_ids, parent_ids))
  498. sample_idx += num_parent_seqs
  499. return results
  500. def _beam_search_sample(
  501. selected_seq_groups: List[SequenceGroupToSample],
  502. logprobs: torch.Tensor,
  503. ) -> List[Tuple[List[int], List[int]]]:
  504. """Run beam sampling on a given samples.
  505. Args:
  506. selected_seq_groups: A list of sequence groups batched.
  507. logprobs: (num_selected_samples, vocab_size,) A tensor of logprob
  508. on selected sample indices.
  509. Returns:
  510. Tuple of (next_token_ids, parent_ids). The length of returned list is
  511. same as the length of selected_seq_groups. If the corresponding
  512. seq_group has do_sample=False, tuple contains ([], [])
  513. """
  514. # We sample 2 * beam_width candidates to make sure that with high
  515. # probability we can get `beam_width` candidates in addition to
  516. # the finished sequences for the next iteration. See
  517. # https://github.com/tensorflow/tensor2tensor/blob/bafdc1b67730430d38d6ab802cbd51f9d053ba2e/tensor2tensor/utils/beam_search.py#L557-L563
  518. # for details. See also HF reference:
  519. # https://github.com/huggingface/transformers/blob/a4dd53d88e4852f023332d284ff07a01afcd5681/src/transformers/generation/utils.py#L3063-L3065
  520. #
  521. # NOTE: Beam search is not vectorized, so its speed can be slower than
  522. # other sampling methods.
  523. sample_idx = 0
  524. results = []
  525. for seq_group in selected_seq_groups:
  526. if not seq_group.do_sample:
  527. results.append(([], []))
  528. continue
  529. is_prompt = seq_group.is_prompt
  530. seq_ids, sampling_params = seq_group.seq_ids, seq_group.sampling_params
  531. num_parent_seqs = len(seq_ids)
  532. beam_width = sampling_params.best_of
  533. seq_group_logprobs = logprobs[sample_idx:sample_idx + num_parent_seqs]
  534. if is_prompt:
  535. # Prompt phase.
  536. assert num_parent_seqs == 1, (
  537. "Prompt input should have only one seq.")
  538. parent_ids = [0] * (2 * beam_width)
  539. _, next_token_ids = torch.topk(seq_group_logprobs[0],
  540. 2 * beam_width)
  541. next_token_ids = next_token_ids.tolist()
  542. else:
  543. # Generation phase.
  544. cumulative_logprobs = [
  545. seq_group.seq_data[seq_id].cumulative_logprob
  546. for seq_id in seq_ids
  547. ]
  548. cumulative_logprobs = torch.tensor(
  549. cumulative_logprobs,
  550. dtype=torch.float,
  551. device=seq_group_logprobs.device)
  552. seq_group_logprobs = (seq_group_logprobs +
  553. cumulative_logprobs.unsqueeze(dim=1))
  554. _, topk_ids = torch.topk(seq_group_logprobs.flatten(),
  555. 2 * beam_width)
  556. topk_ids = topk_ids.tolist()
  557. vocab_size = seq_group_logprobs.size(-1)
  558. parent_ids = [i // vocab_size for i in topk_ids]
  559. next_token_ids = [i % vocab_size for i in topk_ids]
  560. results.append((next_token_ids, parent_ids))
  561. sample_idx += num_parent_seqs
  562. assert sample_idx == logprobs.size(0)
  563. return results
  564. # torch.multinomial forces a GPU<->CPU sync.
  565. # Therefore, we use an optimized implementation instead.
  566. # Note that we always sample with replacement.
  567. # probs will be modified in place, but this is fine, as we pass
  568. # in a copy already.
  569. def _multinomial(
  570. probs: torch.Tensor,
  571. num_samples: int,
  572. seq_groups: Optional[List[SequenceGroupToSample]] = None,
  573. ) -> torch.Tensor:
  574. if num_samples > 1:
  575. # This is equivalent to torch.repeat_interleaved (which also
  576. # forces a GPU<->CPU sync).
  577. # This allows us to do sampling with replacement by creating
  578. # num_samples copies of each row in the tensor, and then
  579. # batch sampling the resulting tensor.
  580. probs = probs[:, None, :].expand(probs.shape[0], num_samples,
  581. probs.shape[1]).contiguous().view(
  582. -1, probs.shape[1])
  583. q = torch.empty_like(probs)
  584. if seq_groups is None:
  585. q.exponential_()
  586. else:
  587. sample_idx = 0
  588. for seq_group in seq_groups:
  589. seq_ids = seq_group.seq_ids
  590. next_sample_idx = sample_idx + len(seq_ids) * num_samples
  591. q[sample_idx:next_sample_idx].exponential_(
  592. generator=seq_group.generator)
  593. sample_idx = next_sample_idx
  594. return probs.div_(q).argmax(dim=1).view(-1, num_samples)
  595. def _sample_with_torch(
  596. probs: torch.Tensor,
  597. logprobs: torch.Tensor,
  598. sampling_metadata: SamplingMetadata,
  599. include_gpu_probs_tensor: bool,
  600. modify_greedy_probs: bool,
  601. ) -> Tuple[List[Tuple[List[int], List[int]]], Optional[torch.Tensor]]:
  602. categorized_seq_group_ids = {t: [] for t in SamplingType}
  603. categorized_sample_indices = sampling_metadata.categorized_sample_indices
  604. for i, seq_group in enumerate(sampling_metadata.seq_groups):
  605. sampling_params = seq_group.sampling_params
  606. sampling_type = sampling_params.sampling_type
  607. categorized_seq_group_ids[sampling_type].append(i)
  608. sample_results_dict: Dict[int, Tuple[List[int], List[int]]] = {}
  609. sample_metadata = {}
  610. multinomial_samples = {}
  611. # Create output tensor for sampled token ids.
  612. if include_gpu_probs_tensor:
  613. sampled_token_ids_tensor = torch.empty(logprobs.shape[0],
  614. 1,
  615. dtype=torch.long,
  616. device=logprobs.device)
  617. else:
  618. sampled_token_ids_tensor = None
  619. # Counterintuitively, having two loops here is actually faster.
  620. # The first loop can run without waiting on GPU<->CPU sync.
  621. for sampling_type in SamplingType:
  622. sample_indices = categorized_sample_indices[sampling_type][:, 0]
  623. num_tokens = len(sample_indices)
  624. if num_tokens == 0:
  625. continue
  626. seq_group_id = categorized_seq_group_ids[sampling_type]
  627. seq_groups = [sampling_metadata.seq_groups[i] for i in seq_group_id]
  628. sample_metadata[sampling_type] = (seq_group_id, seq_groups)
  629. long_sample_indices = sample_indices.long()
  630. if sampling_type == SamplingType.GREEDY:
  631. greedy_samples = torch.argmax(logprobs[long_sample_indices],
  632. dim=-1)
  633. if include_gpu_probs_tensor:
  634. # Store sampled tokens in output tensor.
  635. sampled_token_ids_tensor[
  636. long_sample_indices] = greedy_samples.unsqueeze(-1)
  637. if modify_greedy_probs:
  638. # If required, modify the probabilities such that sampling from
  639. # the modified distribution would always sample the argmax
  640. # token id.
  641. _modify_greedy_probs_inplace(logprobs, probs,
  642. long_sample_indices,
  643. greedy_samples)
  644. elif sampling_type in (SamplingType.RANDOM, SamplingType.RANDOM_SEED):
  645. max_best_of_in_batch = 1
  646. for seq_group in seq_groups:
  647. if seq_group.is_prompt:
  648. sampling_params = seq_group.sampling_params
  649. max_best_of_in_batch = max(max_best_of_in_batch,
  650. sampling_params.best_of)
  651. seeded_args = {} if sampling_type == SamplingType.RANDOM else {
  652. "seq_groups": seq_groups,
  653. }
  654. multinomial_samples[sampling_type] = _multinomial(
  655. probs[long_sample_indices], max_best_of_in_batch,
  656. **seeded_args)
  657. if include_gpu_probs_tensor:
  658. # Store sampled tokens in output tensor.
  659. sampled_token_ids_tensor[
  660. long_sample_indices] = multinomial_samples[sampling_type]
  661. elif sampling_type == SamplingType.BEAM:
  662. beam_search_logprobs = logprobs[sample_indices]
  663. else:
  664. raise ValueError(f"Unsupported sampling type: {sampling_type}")
  665. # GPU<->CPU sync happens in the loop below.
  666. # This also converts the sample output to Python objects.
  667. if not sampling_metadata.skip_sampler_cpu_output:
  668. for sampling_type in SamplingType:
  669. if sampling_type not in sample_metadata:
  670. continue
  671. (seq_group_id, seq_groups) = sample_metadata[sampling_type]
  672. if sampling_type == SamplingType.GREEDY:
  673. sample_results = _greedy_sample(seq_groups, greedy_samples)
  674. elif sampling_type in (SamplingType.RANDOM,
  675. SamplingType.RANDOM_SEED):
  676. sample_results = _random_sample(
  677. seq_groups, multinomial_samples[sampling_type])
  678. elif sampling_type == SamplingType.BEAM:
  679. sample_results = _beam_search_sample(seq_groups,
  680. beam_search_logprobs)
  681. sample_results_dict.update(zip(seq_group_id, sample_results))
  682. sample_results = [
  683. sample_results_dict.get(i, ([], []))
  684. for i in range(len(sampling_metadata.seq_groups))
  685. ]
  686. else:
  687. sample_results = []
  688. return sample_results, sampled_token_ids_tensor
  689. def _sample_with_triton_kernel(
  690. probs: torch.Tensor,
  691. logprobs: torch.Tensor,
  692. sampling_metadata: SamplingMetadata,
  693. sampling_tensors: SamplingTensors,
  694. ) -> List[Tuple[List[int], List[int]]]:
  695. categorized_seq_group_ids = {t: [] for t in SamplingType}
  696. categorized_sample_indices = sampling_metadata.categorized_sample_indices
  697. for i, seq_group in enumerate(sampling_metadata.seq_groups):
  698. sampling_params = seq_group.sampling_params
  699. sampling_type = sampling_params.sampling_type
  700. categorized_seq_group_ids[sampling_type].append(i)
  701. sample_results_dict: Dict[int, Tuple[List[int], List[int]]] = {}
  702. sample_metadata = {}
  703. max_best_of_in_batch = 1
  704. # Counterintuitively, having two loops here is actually faster.
  705. # The first loop can run without waiting on GPU<->CPU sync.
  706. for sampling_type in SamplingType:
  707. sample_indices = categorized_sample_indices[sampling_type][:, 0]
  708. sampled_token_indices = categorized_sample_indices[sampling_type][:, 1]
  709. num_tokens = len(sample_indices)
  710. if num_tokens == 0:
  711. continue
  712. seq_group_id = categorized_seq_group_ids[sampling_type]
  713. seq_groups = [sampling_metadata.seq_groups[i] for i in seq_group_id]
  714. sample_metadata[sampling_type] = (seq_group_id, seq_groups,
  715. sample_indices,
  716. sampled_token_indices)
  717. if sampling_type in (SamplingType.GREEDY, SamplingType.RANDOM,
  718. SamplingType.RANDOM_SEED):
  719. for seq_group in seq_groups:
  720. if seq_group.is_prompt:
  721. sampling_params = seq_group.sampling_params
  722. max_best_of_in_batch = max(max_best_of_in_batch,
  723. sampling_params.best_of)
  724. elif sampling_type == SamplingType.BEAM:
  725. beam_search_logprobs = logprobs[sample_indices]
  726. else:
  727. raise ValueError(f"Unsupported sampling type: {sampling_type}")
  728. sampled_tokens, _, _ = sample_triton(
  729. probs=probs,
  730. seeds=sampling_tensors.sampling_seeds,
  731. max_best_of=max_best_of_in_batch,
  732. sample_indices=sampling_tensors.sample_indices,
  733. logprobs=logprobs,
  734. # don't save logprobs because we have logic for that below
  735. # TODO: use this instead of the CPU-based logic below
  736. save_logprobs=False,
  737. )
  738. # GPU<->CPU sync happens in the loop below.
  739. for sampling_type in SamplingType:
  740. if sampling_type not in sample_metadata:
  741. continue
  742. (seq_group_id, seq_groups, sample_indices,
  743. sampled_token_indices) = sample_metadata[sampling_type]
  744. if sampling_type == SamplingType.GREEDY:
  745. sample_results = _greedy_sample(
  746. seq_groups, sampled_tokens[sampled_token_indices][:, 0])
  747. elif sampling_type in (SamplingType.RANDOM, SamplingType.RANDOM_SEED):
  748. sample_results = _random_sample(
  749. seq_groups, sampled_tokens[sampled_token_indices])
  750. elif sampling_type == SamplingType.BEAM:
  751. sample_results = _beam_search_sample(seq_groups,
  752. beam_search_logprobs)
  753. sample_results_dict.update(zip(seq_group_id, sample_results))
  754. sample_results = [
  755. sample_results_dict.get(i, ([], []))
  756. for i in range(len(sampling_metadata.seq_groups))
  757. ]
  758. return sample_results
  759. def _sample(
  760. probs: torch.Tensor, logprobs: torch.Tensor,
  761. sampling_metadata: SamplingMetadata, sampling_tensors: SamplingTensors,
  762. include_gpu_probs_tensor: bool, modify_greedy_probs: bool
  763. ) -> Tuple[List[Tuple[List[int], List[int]]], Optional[torch.Tensor]]:
  764. """
  765. Args:
  766. probs: (num_query_tokens_in_batch, num_vocab)
  767. logprobs: (num_query_tokens_in_batch, num_vocab)
  768. sampling_metadata: The metadata for a batch for sampling.
  769. sampling_tensors: Tensors that include sampling related metadata.
  770. Returns:
  771. (next_token_ids, parent_seq_ids) for each seq group in a batch.
  772. If sampling is skipped, it returns ([], [])
  773. sampled_token_ids_tensor: A tensor of sampled token ids.
  774. """
  775. return _sample_with_torch(
  776. probs,
  777. logprobs,
  778. sampling_metadata,
  779. include_gpu_probs_tensor=include_gpu_probs_tensor,
  780. modify_greedy_probs=modify_greedy_probs,
  781. )
  782. # TODO: Enable once Triton kernel & associated code is faster.
  783. # return _sample_with_triton_kernel(probs, logprobs, sampling_metadata,
  784. # sampling_tensors)
  785. def _get_ranks(x: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
  786. """
  787. This function calculates the ranks of the chosen tokens in a logprob tensor.
  788. Args:
  789. x (torch.Tensor): 2D logprob tensor of shape (N, M)
  790. where N is the no. of tokens and M is the vocab dim.
  791. indices (torch.Tensor): List of chosen token indices.
  792. Returns:
  793. torch.Tensor: 1D tensor of shape (N,) where N is the no. of tokens.
  794. Each element in the returned tensor represents the rank
  795. of the chosen token in the input logprob tensor.
  796. """
  797. vals = x[torch.arange(0, len(x), device=x.device, dtype=indices.dtype),
  798. indices]
  799. return (x > vals[:, None]).long().sum(1).add_(1)
  800. def _get_logprobs(
  801. logprobs: torch.Tensor,
  802. sampling_metadata: SamplingMetadata,
  803. sample_results: List[Tuple[List[int], List[int]]],
  804. ) -> Tuple[List[Optional[PromptLogprobs]], List[SampleLogprobs]]:
  805. """Return sample lobprobs and prompt logprobs.
  806. The logic consists of 3 parts.
  807. - Select indices to compute logprob from, ranks of token ids, and
  808. the top k token ids from logprobs.
  809. - Compute prompt logprobs if required.
  810. - Compute sample logprobs if required.
  811. Args:
  812. logprobs: (num_query_tokens_across_batch, num_vocab). Each query token's
  813. logprob per vocab. Sequence groups' query tokens are batched in a
  814. single flattened tensor. For example, assuming there are N
  815. seq groups, it is sorted by prefill tokens for seq_group_1 (if
  816. prompt logprob is enabled), decode tokens for seq_group_1 (if
  817. sampling is required), prefill tokens for seq_group_2, ...
  818. sampling_metadata: The sampling metadata.
  819. sample_results: (num_seq_groups) The tuple of (next_token_ids,
  820. parent_ids) for each sequence group. When beam search is enabled,
  821. sample_results can contain different number of seq_ids from
  822. sampling_metadata.seq_groups. It is because beam search creates
  823. 2 * BEAM_WIDTH number of samples (whereas there are only up to
  824. BEAM_WIDTH number of seq_ids).
  825. Returns:
  826. A tuple of prompt and sample logprobs per sequence group in a batch.
  827. """
  828. # The index of query token to calculate logprobs. It includes both
  829. # prompt and sample logprob indices.
  830. query_indices: List[int] = []
  831. # The next token ids to get the logprob value from.
  832. next_token_ids: List[int] = []
  833. # The largest requested number of logprobs. We find logprobs as many as the
  834. # largest num logprobs in this API.
  835. largest_num_logprobs = 1
  836. # Select indices to compute logprob from, ranks of token ids, and the top
  837. # k token ids from logprobs.
  838. for (seq_group, sample_result) in zip(sampling_metadata.seq_groups,
  839. sample_results):
  840. sampling_params = seq_group.sampling_params
  841. # Update indices and tokens for prompt logprobs.
  842. if (seq_group.is_prompt
  843. and sampling_params.prompt_logprobs is not None):
  844. largest_num_logprobs = max(largest_num_logprobs,
  845. sampling_params.prompt_logprobs)
  846. next_prompt_tokens = _get_next_prompt_tokens(seq_group)
  847. query_indices.extend(seq_group.prompt_logprob_indices)
  848. next_token_ids.extend(next_prompt_tokens)
  849. # Update indices and next tokenes for sample logprob.
  850. if seq_group.do_sample:
  851. token_ids, parent_seq_ids = sample_result
  852. # NOTE: We cannot directly use sample_indices because
  853. # sample_indices only contain parent seq_ids of a previous step.
  854. # The current step may have different number of seq_ids, and
  855. # we can obtain it from `sample_result[1]`.
  856. query_idx = seq_group.sample_indices[0]
  857. query_indices.extend(
  858. [query_idx + parent_id for parent_id in parent_seq_ids])
  859. next_token_ids.extend(token_ids)
  860. if sampling_params.logprobs is not None:
  861. largest_num_logprobs = max(largest_num_logprobs,
  862. sampling_params.logprobs)
  863. assert len(next_token_ids) == len(query_indices)
  864. if len(query_indices) == 0:
  865. empty_sampled_logprob = []
  866. empty_prompt_logprob = None
  867. return [empty_prompt_logprob], [empty_sampled_logprob]
  868. query_indices_gpu = torch.tensor(query_indices, device=logprobs.device)
  869. next_token_ids_gpu = torch.tensor(next_token_ids, device=logprobs.device)
  870. # (num_selected_query_tokens, num_logprobs). Note that query_indices can
  871. # contain duplicates if beam search is enabled.
  872. selected_logprobs = logprobs[[
  873. query_indices_gpu,
  874. next_token_ids_gpu,
  875. ]]
  876. ranks = _get_ranks(
  877. logprobs[query_indices_gpu],
  878. next_token_ids_gpu,
  879. )
  880. assert selected_logprobs.shape[0] == ranks.shape[0]
  881. # Logprobs of topk tokens for a batch of sequence groups.
  882. # (num_query_tokens_across_batch).
  883. if largest_num_logprobs > 0:
  884. top_logprobs, top_token_ids = torch.topk(logprobs,
  885. largest_num_logprobs,
  886. dim=-1)
  887. else:
  888. top_logprobs, top_token_ids = None, None
  889. selected_logprobs = selected_logprobs.to('cpu')
  890. ranks = ranks.to('cpu')
  891. if top_logprobs is not None and top_token_ids is not None:
  892. top_logprobs = top_logprobs.to('cpu')
  893. top_token_ids = top_token_ids.to('cpu')
  894. # Find prompt/sample logprobs.
  895. prompt_logprobs_per_seq_group: List[Optional[PromptLogprobs]] = []
  896. sample_logprobs_per_seq_group: List[SampleLogprobs] = []
  897. top_logprob_idx = 0
  898. selected_logprobs_idx = 0
  899. for seq_group, sample_result in zip(sampling_metadata.seq_groups,
  900. sample_results):
  901. (prompt_logprobs, top_logprob_idx,
  902. selected_logprobs_idx) = _get_prompt_logprob_if_needed(
  903. seq_group, selected_logprobs, ranks, top_token_ids, top_logprobs,
  904. selected_logprobs_idx, top_logprob_idx)
  905. prompt_logprobs_per_seq_group.append(prompt_logprobs)
  906. (sampled_logprobs, top_logprob_idx,
  907. selected_logprobs_idx) = _get_sampled_logprob_if_needed(
  908. seq_group, sample_result, selected_logprobs, ranks, top_token_ids,
  909. top_logprobs, selected_logprobs_idx, top_logprob_idx)
  910. sample_logprobs_per_seq_group.append(sampled_logprobs)
  911. return prompt_logprobs_per_seq_group, sample_logprobs_per_seq_group
  912. def _get_prompt_logprob_if_needed(
  913. seq_group: SequenceGroupToSample,
  914. selected_logprobs: torch.Tensor,
  915. ranks: torch.Tensor,
  916. top_token_ids: torch.Tensor,
  917. top_logprobs: torch.Tensor,
  918. selected_logprobs_idx: int,
  919. top_logprob_idx: int,
  920. ):
  921. """Compute the prompt logprob from a sequence group if needed."""
  922. sampling_params = seq_group.sampling_params
  923. is_prompt = seq_group.is_prompt
  924. # Find prompt logprobs
  925. prompt_logprobs: Optional[PromptLogprobs] = None
  926. if is_prompt and sampling_params.prompt_logprobs is not None:
  927. prompt_logprobs = []
  928. num_logprobs = sampling_params.prompt_logprobs
  929. next_prompt_tokens = _get_next_prompt_tokens(seq_group)
  930. # Pre-select indexes and create a list. It is faster than calling .item
  931. # repetitively.
  932. selected_logprob_items = selected_logprobs[
  933. selected_logprobs_idx:selected_logprobs_idx +
  934. len(next_prompt_tokens)].tolist()
  935. rank_items = ranks[selected_logprobs_idx:selected_logprobs_idx +
  936. len(next_prompt_tokens)].tolist()
  937. for idx, token_id in enumerate(next_prompt_tokens):
  938. # Calculate the prompt logprob of the real prompt tokens.
  939. # {token_id: (logprob, rank_from_vocab)}
  940. prompt_logprobs_dict: Dict[int, Tuple[float, int]] = {
  941. token_id: (selected_logprob_items[idx], rank_items[idx])
  942. }
  943. # Add top K prompt logprobs along with its rank.
  944. if num_logprobs > 0:
  945. top_ids = top_token_ids[
  946. top_logprob_idx, :num_logprobs].tolist()
  947. top_probs = top_logprobs[
  948. top_logprob_idx, :num_logprobs].tolist()
  949. # Top K is already sorted by rank, so we can use 1 ~
  950. # num_logprobs + 1 for rank.
  951. top_ranks = range(1, num_logprobs + 1)
  952. prompt_logprobs_dict.update({
  953. top_id: (top_prob, rank)
  954. for top_id, top_prob, rank in zip(top_ids, top_probs,
  955. top_ranks)
  956. })
  957. prompt_logprobs.append({
  958. token_id: Logprob(*logprob_and_rank)
  959. for token_id, logprob_and_rank in prompt_logprobs_dict.items()
  960. })
  961. # + 1 to go to the next prompt token.
  962. top_logprob_idx += 1
  963. # + len(next_prompt_tokens) to go to the next prompt.
  964. selected_logprobs_idx += len(next_prompt_tokens)
  965. return prompt_logprobs, top_logprob_idx, selected_logprobs_idx
  966. def _get_sampled_logprob_if_needed(
  967. seq_group: SequenceGroupToSample,
  968. sample_result: Tuple[List[int], List[int]],
  969. selected_logprobs: torch.Tensor,
  970. ranks: torch.Tensor,
  971. top_token_ids: torch.Tensor,
  972. top_logprobs: torch.Tensor,
  973. selected_logprobs_idx: int,
  974. top_logprob_idx: int,
  975. ):
  976. """Compute the sample logprob if needed."""
  977. seq_ids = seq_group.seq_ids
  978. num_logprobs = seq_group.sampling_params.logprobs or 0
  979. sampled_logprobs: SampleLogprobs = []
  980. next_token_ids, parent_seq_ids = sample_result
  981. if seq_group.do_sample:
  982. assert len(next_token_ids) > 0
  983. # Pre-select items from tensor. tolist() is faster than repetitive
  984. # `.item()` calls.
  985. selected_logprob_items = selected_logprobs[
  986. selected_logprobs_idx:selected_logprobs_idx +
  987. len(next_token_ids)].tolist()
  988. rank_items = ranks[selected_logprobs_idx:selected_logprobs_idx +
  989. len(next_token_ids)].tolist()
  990. for idx, (next_token_id,
  991. parent_id) in enumerate(zip(next_token_ids, parent_seq_ids)):
  992. # Get the logprob of a sampled token.
  993. sampled_logprobs_dict = {
  994. next_token_id: (selected_logprob_items[idx], rank_items[idx])
  995. }
  996. # Get top K logprobs.
  997. if num_logprobs > 0:
  998. top_ids = top_token_ids[top_logprob_idx +
  999. parent_id, :num_logprobs].tolist()
  1000. top_probs = top_logprobs[top_logprob_idx +
  1001. parent_id, :num_logprobs].tolist()
  1002. # Top K is already sorted by rank, so we can use 1 ~
  1003. # num_logprobs + 1 for rank.
  1004. top_ranks = range(1, num_logprobs + 1)
  1005. sampled_logprobs_dict.update({
  1006. top_id: (top_prob, rank)
  1007. for top_id, top_prob, rank in zip(top_ids, top_probs,
  1008. top_ranks)
  1009. })
  1010. sampled_logprobs.append({
  1011. token_id: Logprob(*logprob_and_rank)
  1012. for token_id, logprob_and_rank in
  1013. sampled_logprobs_dict.items()
  1014. })
  1015. # NOTE: This part of code is not intuitive. `selected_logprobs` include
  1016. # logprobs for the current step, which has len(next_token_ids) tokens
  1017. # per sequence group. `logprobs` includes logprobs from the previous
  1018. # steps, which has len(seq_ids) tokens per sequence group.
  1019. # Iterate to the next sequence group in a batch.
  1020. selected_logprobs_idx += len(next_token_ids)
  1021. # Iterate to the next sequence group in a batch.
  1022. top_logprob_idx += len(seq_ids)
  1023. return sampled_logprobs, top_logprob_idx, selected_logprobs_idx
  1024. def _modify_greedy_probs_inplace(logprobs: torch.Tensor, probs: torch.Tensor,
  1025. sample_indices: torch.Tensor,
  1026. greedy_samples: torch.Tensor) -> None:
  1027. """Modify the probability distributions of the greedily-sampled tokens such
  1028. that each sampled token has a "probability" of 1.0. This is required by
  1029. speculative decoding, which depends on the sampling method being encoded
  1030. within the probability distribution for correctness.
  1031. # Why do we only need to do this for greedy sampling?
  1032. Aphrodite's sampler performs the following steps for greedy or multinomial
  1033. (random) sampling:
  1034. 1. Get logits from model.
  1035. 2. Modify logits according to per-sequence sampling parameters.
  1036. - Multiply by temperature, top-k and top-p masking, penalize tokens
  1037. according to their frequency, etc.
  1038. 3. Sample a token.
  1039. - Random sampling simply samples from the modified probability
  1040. distribution.
  1041. - Greedy sampling performs `argmax` to obtain the token with the
  1042. highest likelihood.
  1043. Ignoring greedy sampling for a moment, we find that the computed probability
  1044. distribution has the following property: we can sample from it independently
  1045. and find that the token sampled by the Sampler has a frequency corresponding
  1046. to how often we see it in our sampling. In other words, for tokens sampled
  1047. with Aphrodite's random SamplingType, the computed probability distribution
  1048. encodes the sampling methodology completely.
  1049. Greedy sampling does not normally have this property. Aphrodite modifies
  1050. logits according to sampling params, then performs `argmax`, then returns
  1051. the sampled token and the computed probability distribution. If we sample
  1052. from the distribution, we'll find the likelihood of the greedily-sampled
  1053. token is not always 1.0.
  1054. Since lossless speculative decoding requires that the sampling methodology
  1055. be encoded within the probability distribution, we are motivated to modify
  1056. the probability distribution such that the sampled token has probability 1
  1057. when speculative decoding is used.
  1058. NOTE: Alternatively, we could use an extremely low temperature to achieve
  1059. greedy sampling using multinomial computation and unite the codepaths. This
  1060. has implications on the overall design of the sampler, e.g. how to record
  1061. accurate logprobs for the user, so this improvement is deferred to later.
  1062. """
  1063. # NOTE: logprobs are not modified so they can be returned to the user.
  1064. probs[sample_indices, :] = 0
  1065. probs[sample_indices, greedy_samples] = 1.0
  1066. def _build_sampler_output(
  1067. sample_results: SampleResultType,
  1068. sampling_metadata: SamplingMetadata,
  1069. prompt_logprobs: Optional[List[Optional[PromptLogprobs]]],
  1070. sample_logprobs: Optional[List[SampleLogprobs]],
  1071. on_device_tensors: Optional[Tuple[torch.Tensor, torch.Tensor,
  1072. torch.Tensor]],
  1073. skip_sampler_cpu_output: bool = False,
  1074. ) -> SamplerOutput:
  1075. """Construct Python objects with the output of sampling.
  1076. Args:
  1077. on_device_tensors: Tuple containing on-device tensors with the
  1078. probabilities used in sampling and the sampled token ids. This
  1079. allows post-processing without copies to CPU/serialization, e.g. in
  1080. speculative decoding rejection sampling.
  1081. """
  1082. sampler_output: List[CompletionSequenceGroupOutput] = []
  1083. if not skip_sampler_cpu_output:
  1084. assert prompt_logprobs is not None
  1085. assert sample_logprobs is not None
  1086. for (seq_group, sample_result, group_prompt_logprobs,
  1087. group_sample_logprobs) in zip(sampling_metadata.seq_groups,
  1088. sample_results, prompt_logprobs,
  1089. sample_logprobs):
  1090. seq_ids = seq_group.seq_ids
  1091. next_token_ids, parent_ids = sample_result
  1092. seq_outputs: List[SequenceOutput] = []
  1093. for parent_id, next_token_id, logprobs in zip(
  1094. parent_ids, next_token_ids, group_sample_logprobs):
  1095. seq_outputs.append(
  1096. SequenceOutput(seq_ids[parent_id], next_token_id,
  1097. logprobs))
  1098. sampler_output.append(
  1099. CompletionSequenceGroupOutput(seq_outputs,
  1100. group_prompt_logprobs))
  1101. # If not specified, store None values in SamplerOutput.
  1102. if on_device_tensors is not None:
  1103. (sampled_token_probs, logprobs_tensor,
  1104. sampled_token_ids) = on_device_tensors
  1105. else:
  1106. sampled_token_probs, logprobs_tensor, sampled_token_ids = (None, None,
  1107. None)
  1108. return SamplerOutput(
  1109. outputs=sampler_output,
  1110. sampled_token_probs=sampled_token_probs,
  1111. sampled_token_ids=sampled_token_ids,
  1112. logprobs=logprobs_tensor,
  1113. )
  1114. def _get_next_prompt_tokens(seq_group: SequenceGroupToSample) -> List[str]:
  1115. """Get a list of next prompt tokens to compute logprob from a
  1116. given sequence group.
  1117. It is used to compute prompt logprob. Imagine you have logprob for each
  1118. query token. Query token needs to know the next prompt token id to compute
  1119. prompt logprob. This is a helper to obtain next prompt token ids.
  1120. This API has to be used only when the caller knows seq_group is in prefill
  1121. stage.
  1122. Returns:
  1123. A list of next prompt tokens to compute logprob.
  1124. """
  1125. assert seq_group.is_prompt, (
  1126. "Caller should ensure the sequence group is in a prefill stage.")
  1127. seq_ids = seq_group.seq_ids
  1128. query_len = seq_group.query_len
  1129. assert query_len is not None
  1130. # prompt has only 1 seq id.
  1131. assert len(seq_ids) == 1
  1132. seq_data = seq_group.seq_data[seq_ids[0]]
  1133. computed_len = seq_data.get_num_computed_tokens()
  1134. prompt_tokens = seq_data.prompt_token_ids
  1135. # +1 because we are looking for a next prompt token.
  1136. next_token_index_start = computed_len + 1
  1137. next_token_index_end = min(computed_len + query_len + 1,
  1138. len(prompt_tokens))
  1139. next_prompt_tokens = prompt_tokens[
  1140. next_token_index_start:next_token_index_end]
  1141. return next_prompt_tokens
  1142. # def _apply_mirostat_v2(logits: torch.Tensor,
  1143. # sampling_tensors: SamplingTensors) -> torch.Tensor:
  1144. # # Reduce our view to just the affected logits
  1145. # logit_view = logits[sampling_tensors.miro_indices]
  1146. # # Calculate surprise value per token
  1147. # # Convert nats to bits for compatibility with ooba/kobold parameters.
  1148. # logit_surprise = torch.log_softmax(logit_view, dim=-1) / -math.log(2)
  1149. # # Mask out "too-surprising" tokens (surprisal > mu)
  1150. # mus = sampling_tensors.miro_mus
  1151. # miro_mask = logit_surprise > mus.unsqueeze(dim=-1)
  1152. # # Unmask most-likely logit to guarantee a selection.
  1153. # maxinds = torch.argmax(logit_view, dim=-1, keepdim=True)
  1154. # miro_mask.scatter_(dim=1, index=maxinds, value=False)
  1155. # # Apply logit mask (effectively a top-k filter).
  1156. # logit_view[miro_mask] = -float("inf")
  1157. # # Project logit changes made to the view onto the original.
  1158. # # I think this step might be redundant.
  1159. # logits[sampling_tensors.miro_indices] = logit_view
  1160. # return logits
  1161. # def _mirostat_store_args(logits: torch.Tensor, args: SamplingTensors,
  1162. # sample_results: List[Tuple[List[int], List[int]]],
  1163. # sampling_metadata: SamplingMetadata,
  1164. # output_metadata: OutputMetadata) -> None:
  1165. # """Based on whichever token was finally sampled, we calculate the
  1166. # final surprisal values to update the mus.
  1167. # Because a single sequence can have multiple samples, we must fork
  1168. # the mu accordingly."""
  1169. # assert sampling_metadata.seq_groups is not None
  1170. # seqid_to_tokens = {}
  1171. # seqid_to_indices = {}
  1172. # for (sids, _), (toks, parents) in zip(sampling_metadata.seq_groups,
  1173. # sample_results):
  1174. # for idx, (token, parent) in enumerate(zip(toks, parents)):
  1175. # seqid_to_tokens.setdefault(sids[parent], []).append(token)
  1176. # seqid_to_indices.setdefault(sids[parent], []).append(idx)
  1177. # seqids = args.miro_seqids
  1178. # picked_tokens = torch.tensor([seqid_to_tokens[x] for x in seqids],
  1179. # device=logits.device,
  1180. # dtype=torch.long)
  1181. # # Clumsily, we recalculate token surprisals.
  1182. # logits_view = logits[args.miro_indices]
  1183. # picked_surprise = torch.gather(torch.log_softmax(logits_view, dim=-1),
  1184. # dim=-1,
  1185. # index=picked_tokens) / -math.log(2)
  1186. # taus = args.miro_taus.unsqueeze(dim=-1) # AKA target surprisals
  1187. # etas = args.miro_etas.unsqueeze(dim=-1) # AKA accumulation rates
  1188. # mus = args.miro_mus.unsqueeze(dim=-1) # AKA surprisal accumulators
  1189. # nu_mus = mus - (picked_surprise - taus) * etas
  1190. # # Record updated mu values for use in the next iteration
  1191. # # Note how each mu is split into multiple based on the number of samples.
  1192. # for seqid, seq_mus in zip(seqids, nu_mus):
  1193. # for sample_idx, mu in zip(seqid_to_indices[seqid], seq_mus):
  1194. # output_metadata.add(seqid, sample_idx, "miro_mu", mu)