sampler.py 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989
  1. """A layer that samples the next tokens from the model's outputs."""
  2. import itertools
  3. import warnings
  4. from enum import IntEnum
  5. from math import inf
  6. from typing import Dict, List, Optional, Tuple
  7. import torch
  8. import torch.nn as nn
  9. from loguru import logger
  10. import aphrodite._custom_ops as ops
  11. import aphrodite.common.envs as envs
  12. from aphrodite.common.sampling_params import SamplingType
  13. from aphrodite.common.sequence import (CompletionSequenceGroupOutput, Logprob,
  14. PromptLogprobs, SampleLogprobs,
  15. SamplerOutput, SequenceOutput)
  16. from aphrodite.triton_utils import HAS_TRITON
  17. if HAS_TRITON:
  18. from aphrodite.modeling.layers.ops.sample import sample as sample_triton
  19. from aphrodite.modeling.sampling_metadata import (SamplingMetadata,
  20. SamplingTensors,
  21. SequenceGroupToSample)
  22. # (num_token_ids, num_parent_ids) per sequence group.
  23. SampleResultType = List[Tuple[List[int], List[int]]]
  24. # There isn't a "safe" temperature range for fp16 logits.
  25. # This value was chosen because 1/2e-5 is just under the 65k fp16 max, meaning
  26. # that this temperature well-uses the fp16 space after the logits are offset.
  27. _TEMPERATURE_MINIMUM = 2e-5
  28. # If enabled, we switch to a more performant implementation
  29. # of top-k and top-p
  30. APHRODITE_USE_SAMPLING_KERNELS = envs.APHRODITE_USE_SAMPLING_KERNELS
  31. class SamplerID(IntEnum):
  32. # Mirror these in aphrodite/common/sampling_params.py
  33. # Values out of order to keep backwards compatibility
  34. # with Koboldcpp values
  35. DRY = 7
  36. PENALTIES = 6
  37. NO_REPEAT_NGRAM = 8
  38. TEMPERATURE = 5
  39. TOP_NSIGMA = 9
  40. TOP_P_TOP_K = 0
  41. TOP_A = 1
  42. MIN_P = 2
  43. TFS = 3
  44. ETA_CUTOFF = 10
  45. EPSILON_CUTOFF = 11
  46. TYPICAL_P = 4
  47. QUADRATIC = 12
  48. XTC = 13
  49. class Sampler(nn.Module):
  50. """Samples the next tokens from the model's outputs.
  51. This layer does the following:
  52. 1. Discard the hidden states that are not used for sampling (i.e., all
  53. tokens except the final one in each prompt).
  54. 2. Compute the logits for the next tokens.
  55. 3. Apply presence, frequency and repetition penalties.
  56. 4. Apply temperature scaling.
  57. 5. Apply top-p and top-k truncation.
  58. 6. Sample the next tokens.
  59. Here, each sequence group within the batch can have different sampling
  60. parameters (e.g., sampling method, temperature, top-p, top-k, etc.).
  61. The structure of the logits tensor is coupled with the seq_groups in
  62. sampling_metadata. Typically, each sequence in each seq_group has one row in
  63. logits for the next token to be sampled; however, for a seq_group with a
  64. prompt request with the prompt_logprobs sampling parameter, there are rows
  65. in logits for each token in the input prompt.
  66. """
  67. def __init__(self):
  68. super().__init__()
  69. # Whether or not the SamplerOutput should have on-device tensors
  70. # containing the sampled token ids and probabilities. This is used by
  71. # speculative decoding.
  72. self.include_gpu_probs_tensor = False
  73. self.should_modify_greedy_probs_inplace = False
  74. def _init_sampling_tensors(
  75. self,
  76. logits: torch.Tensor,
  77. sampling_metadata: SamplingMetadata,
  78. ):
  79. """The goal here is to reuse sampling tensors between similar decode
  80. runs. This is possible because sampling logic does not change between
  81. decodes of the same sequences.
  82. """
  83. _, vocab_size = logits.shape
  84. # First free any existing stored sampling tensors.
  85. # This is necessary because some sampling tensors may
  86. # have pinned memory.
  87. self._sampling_tensors = None
  88. # Initialize new sampling tensors
  89. (sampling_tensors, do_penalties, do_no_repeat_ngrams, do_temperatures,
  90. do_top_p_top_k, do_top_as, do_min_p, do_tfss, do_eta_cutoffs,
  91. do_epsilon_cutoffs, do_typical_ps, do_quadratic, do_xtc, do_nsigmas,
  92. do_dry, do_skew, do_temp_last
  93. ) = SamplingTensors.from_sampling_metadata(
  94. sampling_metadata, vocab_size, logits.device, logits.dtype)
  95. self._sampling_tensors = sampling_tensors
  96. self._do_penalties = do_penalties
  97. self._do_no_repeat_ngrams = do_no_repeat_ngrams
  98. self._do_temperatures = do_temperatures
  99. self._do_top_p_top_k = do_top_p_top_k
  100. self._do_top_as = do_top_as
  101. self._do_min_p = do_min_p
  102. self._do_tfss = do_tfss
  103. self._do_eta_cutoffs = do_eta_cutoffs
  104. self._do_epsilon_cutoffs = do_epsilon_cutoffs
  105. self._do_typical_ps = do_typical_ps
  106. self._do_quadratic = do_quadratic
  107. self._do_xtc = do_xtc
  108. self._do_nsgimas = do_nsigmas
  109. self._do_dry = do_dry
  110. self._do_skew = do_skew
  111. self._do_temp_last = do_temp_last
  112. def forward(
  113. self,
  114. logits: torch.Tensor,
  115. sampling_metadata: SamplingMetadata,
  116. ) -> Optional[SamplerOutput]:
  117. """
  118. Args:
  119. logits: (num_tokens, vocab_size).
  120. sampling_metadata: Metadata for sampling.
  121. """
  122. assert logits is not None
  123. _, vocab_size = logits.shape
  124. # Prepare sampling tensors with pinned memory to avoid blocking.
  125. if not sampling_metadata.reuse_sampling_tensors:
  126. self._init_sampling_tensors(logits, sampling_metadata)
  127. elif self._do_penalties or self._do_dry:
  128. # In this case, the sampling tensors logic depends on
  129. # "output_tokens" of a sequence. As a result, we cannot
  130. # reuse sampling tensors, since "output_tokens" changes
  131. # between decode runs.
  132. self._init_sampling_tensors(logits, sampling_metadata)
  133. assert self._sampling_tensors is not None
  134. sampling_tensors = self._sampling_tensors
  135. do_penalties = self._do_penalties
  136. do_no_repeat_ngrams = self._do_no_repeat_ngrams
  137. do_temperatures = self._do_temperatures
  138. do_top_p_top_k = self._do_top_p_top_k
  139. do_top_as = self._do_top_as
  140. do_min_p = self._do_min_p
  141. do_tfss = self._do_tfss
  142. do_eta_cutoffs = self._do_eta_cutoffs
  143. do_epsilon_cutoffs = self._do_epsilon_cutoffs
  144. do_typical_ps = self._do_typical_ps
  145. do_quadratic = self._do_quadratic
  146. do_xtc = self._do_xtc
  147. do_nsigmas = self._do_nsgimas
  148. do_dry = self._do_dry
  149. do_skew = self._do_skew
  150. do_temp_last = self._do_temp_last
  151. logits = _apply_min_tokens_penalty(logits, sampling_metadata)
  152. banned_tokens = _get_custom_token_bans(sampling_metadata)
  153. logits = _apply_token_bans(logits, banned_tokens)
  154. sampler_order = None
  155. if sampling_metadata.seq_groups:
  156. sampler_order = sampling_metadata.seq_groups[
  157. 0].sampling_params.sampler_priority
  158. # Warn if both custom order and temp_last are specified
  159. if (sampling_metadata.seq_groups and
  160. sampling_metadata.seq_groups[0].is_prompt and
  161. sampler_order is not None and
  162. do_temp_last):
  163. logger.warning(
  164. "Both sampler_priority and temperature_last=True "
  165. "were specified. Using custom sampler_priority order "
  166. "and ignoring temperature_last.")
  167. if sampler_order is None:
  168. default_order = [
  169. SamplerID.DRY,
  170. SamplerID.PENALTIES,
  171. SamplerID.NO_REPEAT_NGRAM,
  172. SamplerID.TEMPERATURE,
  173. SamplerID.TOP_NSIGMA,
  174. SamplerID.TOP_P_TOP_K,
  175. SamplerID.TOP_A,
  176. SamplerID.MIN_P,
  177. SamplerID.TFS,
  178. SamplerID.ETA_CUTOFF,
  179. SamplerID.EPSILON_CUTOFF,
  180. SamplerID.TYPICAL_P,
  181. SamplerID.QUADRATIC,
  182. SamplerID.XTC,
  183. ]
  184. sampler_order = []
  185. for sampler_id in default_order:
  186. if sampler_id == SamplerID.TEMPERATURE and do_temp_last:
  187. continue
  188. sampler_order.append(sampler_id)
  189. if sampler_id == SamplerID.XTC and do_temp_last:
  190. sampler_order.append(SamplerID.TEMPERATURE)
  191. if sampling_metadata.seq_groups and sampling_metadata.seq_groups[
  192. 0].is_prompt:
  193. logger.debug("Sampler execution order: ")
  194. for i, sampler_id in enumerate(sampler_order, 1):
  195. logger.debug(f"{i}. {SamplerID(sampler_id).name}")
  196. enabled_samplers = []
  197. # ruff: noqa: E701
  198. if do_penalties: enabled_samplers.append("PENALTIES")
  199. if do_no_repeat_ngrams: enabled_samplers.append("NO_REPEAT_NGRAM")
  200. if do_temperatures: enabled_samplers.append("TEMPERATURE")
  201. if do_top_p_top_k: enabled_samplers.append("TOP_P_TOP_K")
  202. if do_top_as: enabled_samplers.append("TOP_A")
  203. if do_min_p: enabled_samplers.append("MIN_P")
  204. if do_tfss: enabled_samplers.append("TFS")
  205. if do_eta_cutoffs: enabled_samplers.append("ETA_CUTOFF")
  206. if do_epsilon_cutoffs: enabled_samplers.append("EPSILON_CUTOFF")
  207. if do_typical_ps: enabled_samplers.append("TYPICAL_P")
  208. if do_quadratic: enabled_samplers.append("QUADRATIC")
  209. if do_xtc: enabled_samplers.append("XTC")
  210. if do_nsigmas: enabled_samplers.append("TOP_NSIGMA")
  211. if do_dry: enabled_samplers.append("DRY")
  212. if do_skew: enabled_samplers.append("SKEW")
  213. logger.debug(f"Enabled samplers: {', '.join(enabled_samplers)}")
  214. for sampler_id in sampler_order:
  215. if sampler_id == SamplerID.DRY and do_dry:
  216. if (sampling_metadata.seq_groups and
  217. sampling_metadata.seq_groups[0].is_prompt):
  218. logger.debug(
  219. f"Applying DRY with dry_multiplier: "
  220. f"{sampling_tensors.dry_multipliers}.")
  221. logits = _apply_dry(
  222. logits,
  223. sampling_tensors.prompt_tokens,
  224. sampling_tensors.output_tokens,
  225. sampling_tensors.dry_multipliers,
  226. sampling_tensors.dry_bases,
  227. sampling_tensors.dry_allowed_lengths,
  228. sampling_tensors.dry_sequence_breaker_ids,
  229. sampling_tensors.dry_ranges)
  230. elif sampler_id == SamplerID.PENALTIES and do_penalties:
  231. if (sampling_metadata.seq_groups and
  232. sampling_metadata.seq_groups[0].is_prompt):
  233. logger.debug(
  234. "Applying penalties with "
  235. f"pres_pen: {sampling_tensors.presence_penalties}, "
  236. f"freq_pen: {sampling_tensors.frequency_penalties}, "
  237. f"rep_pen: {sampling_tensors.repetition_penalties}.")
  238. logits = _apply_penalties(
  239. logits, sampling_tensors.prompt_tokens,
  240. sampling_tensors.output_tokens,
  241. sampling_tensors.presence_penalties,
  242. sampling_tensors.frequency_penalties,
  243. sampling_tensors.repetition_penalties)
  244. elif sampler_id == SamplerID.NO_REPEAT_NGRAM and \
  245. do_no_repeat_ngrams:
  246. if (sampling_metadata.seq_groups and
  247. sampling_metadata.seq_groups[0].is_prompt):
  248. logger.debug(
  249. "Applying no_repeat_ngram with no_repeat_ngram_size: "
  250. f"{sampling_tensors.no_repeat_ngram_sizes}.")
  251. logits = _apply_no_repeat_ngram(
  252. logits,
  253. sampling_tensors.prompt_tokens,
  254. sampling_tensors.no_repeat_ngram_sizes)
  255. elif sampler_id == SamplerID.TEMPERATURE and do_temperatures:
  256. if (sampling_metadata.seq_groups and
  257. sampling_metadata.seq_groups[0].is_prompt):
  258. logger.debug(
  259. "Applying temperatures with temperature: "
  260. f"{sampling_tensors.temperatures}, "
  261. f"dynatemp_min: {sampling_tensors.dynatemp_mins}, "
  262. f"dynatemp_max: {sampling_tensors.dynatemp_maxs}, "
  263. f"dynamtep_exp: {sampling_tensors.dynatemp_exps}.")
  264. _apply_temperatures(
  265. logits, sampling_tensors.temperatures,
  266. sampling_tensors.dynatemp_mins,
  267. sampling_tensors.dynatemp_maxs,
  268. sampling_tensors.dynatemp_exps)
  269. elif sampler_id == SamplerID.TOP_NSIGMA and do_nsigmas:
  270. if (sampling_metadata.seq_groups and
  271. sampling_metadata.seq_groups[0].is_prompt):
  272. logger.debug(
  273. "Applying Top-Nsigma with nsigma: "
  274. f"{sampling_tensors.nsigmas}")
  275. logits = _apply_top_nsigma(
  276. logits, sampling_tensors.nsigmas)
  277. elif sampler_id == SamplerID.TOP_P_TOP_K and do_top_p_top_k and \
  278. not APHRODITE_USE_SAMPLING_KERNELS:
  279. if (sampling_metadata.seq_groups and
  280. sampling_metadata.seq_groups[0].is_prompt):
  281. logger.debug(
  282. "Applying Top-p and Top-k with top-p: "
  283. f"{sampling_tensors.top_ps}, top_k: "
  284. f"{sampling_tensors.top_ks}.")
  285. logits = _apply_top_k_top_p(
  286. logits, sampling_tensors.top_ps,
  287. sampling_tensors.top_ks)
  288. elif sampler_id == SamplerID.TOP_A and do_top_as:
  289. if (sampling_metadata.seq_groups and
  290. sampling_metadata.seq_groups[0].is_prompt):
  291. logger.debug(
  292. "Applying Top-a with Top-a: "
  293. f"{sampling_tensors.top_as}.")
  294. logits = _apply_top_a(
  295. logits, sampling_tensors.top_as)
  296. elif sampler_id == SamplerID.MIN_P and do_min_p:
  297. if (sampling_metadata.seq_groups and
  298. sampling_metadata.seq_groups[0].is_prompt):
  299. logger.debug(
  300. "Applying Min-p with Min-p: "
  301. f"{sampling_tensors.min_ps}.")
  302. logits = _apply_min_p(
  303. logits, sampling_tensors.min_ps)
  304. elif sampler_id == SamplerID.TFS and do_tfss:
  305. if (sampling_metadata.seq_groups and
  306. sampling_metadata.seq_groups[0].is_prompt):
  307. logger.debug(
  308. "Applying Tail-Free Sampling with tfs: "
  309. f"{sampling_tensors.tfss}.")
  310. logits = _apply_tfs(
  311. logits, sampling_tensors.tfss)
  312. elif sampler_id == SamplerID.ETA_CUTOFF and do_eta_cutoffs:
  313. if (sampling_metadata.seq_groups and
  314. sampling_metadata.seq_groups[0].is_prompt):
  315. logger.debug(
  316. "Applying ETA Cutoff with eta_cutoff: "
  317. f"{sampling_tensors.eta_cutoffs}.")
  318. logits = _apply_eta_cutoff(
  319. logits, sampling_tensors.eta_cutoffs)
  320. elif sampler_id == SamplerID.EPSILON_CUTOFF and do_epsilon_cutoffs:
  321. if (sampling_metadata.seq_groups and
  322. sampling_metadata.seq_groups[0].is_prompt):
  323. logger.debug(
  324. "Applying Epsilon Cutoff with epsilon_cutoff: "
  325. f"{sampling_tensors.epsilon_cutoffs}.")
  326. logits = _apply_epsilon_cutoff(
  327. logits, sampling_tensors.epsilon_cutoffs)
  328. elif sampler_id == SamplerID.TYPICAL_P and do_typical_ps:
  329. if (sampling_metadata.seq_groups and
  330. sampling_metadata.seq_groups[0].is_prompt):
  331. logger.debug(
  332. "Applying Locally Typical Sampling with typical_p: "
  333. f"{sampling_tensors.typical_ps}.")
  334. logits = _apply_typical_sampling(
  335. logits, sampling_tensors.typical_ps)
  336. elif sampler_id == SamplerID.QUADRATIC and do_quadratic:
  337. if (sampling_metadata.seq_groups and
  338. sampling_metadata.seq_groups[0].is_prompt):
  339. logger.debug(
  340. "Applying Quadratic and Cubic Sampling with "
  341. "smoothing_factors: "
  342. f"{sampling_tensors.smoothing_factors},"
  343. f" smoothing_curves: "
  344. f"{sampling_tensors.smoothing_curves}.")
  345. logits = _apply_quadratic_sampling(
  346. logits, sampling_tensors.smoothing_factors,
  347. sampling_tensors.smoothing_curves)
  348. elif sampler_id == SamplerID.XTC and do_xtc:
  349. if (sampling_metadata.seq_groups and
  350. sampling_metadata.seq_groups[0].is_prompt):
  351. logger.debug(
  352. "Applying Exclude Top Choices sampling with "
  353. f"xtc_threshold: {sampling_tensors.xtc_thresholds}, "
  354. "xtc_probability: "
  355. f"{sampling_tensors.xtc_probabilities}.")
  356. logits = _apply_xtc_sampling(
  357. logits, sampling_tensors.xtc_thresholds,
  358. sampling_tensors.xtc_probabilities)
  359. # Compute the probabilities.
  360. # No cast required, as softmaxes internally accumulate with >= fp32.
  361. # See https://github.com/pytorch/pytorch/blob/v2.4.0/aten/src/ATen/native/cuda/PersistentSoftmax.cuh#L62
  362. probs = torch.softmax(logits, dim=-1)
  363. # skew needs to be applied post-softmax
  364. if do_skew:
  365. if (sampling_metadata.seq_groups and
  366. sampling_metadata.seq_groups[0].is_prompt):
  367. logger.debug(
  368. "Applying Skew sampling with skew: "
  369. f"{sampling_tensors.skews}.")
  370. # reference: https://github.com/turboderp/exllamav2/commit/1de4cdd70b09208e7b4f17ee322c190e16f60efd
  371. cum_probs = torch.cumsum(probs, dim=-1)
  372. cum_probs = torch.pow(cum_probs, torch.exp(
  373. sampling_tensors.skews).unsqueeze(dim=1))
  374. probs = torch.diff(cum_probs, dim=-1,
  375. prepend=torch.zeros_like(cum_probs[..., :1]))
  376. logits = torch.log(probs)
  377. # Compute the log probabilities.
  378. logprobs = torch.log_softmax(logits, dim=-1)
  379. # Logits unused past this point. They are HUGE, for prompt_logprobs.
  380. del logits
  381. # Sample the next tokens.
  382. sample_results, maybe_sampled_tokens_tensor = _sample(
  383. probs,
  384. logprobs,
  385. sampling_metadata,
  386. sampling_tensors,
  387. include_gpu_probs_tensor=self.include_gpu_probs_tensor,
  388. modify_greedy_probs=self._should_modify_greedy_probs_inplace,
  389. )
  390. if self.include_gpu_probs_tensor:
  391. assert maybe_sampled_tokens_tensor is not None
  392. on_device_tensors = (probs, logprobs, maybe_sampled_tokens_tensor)
  393. else:
  394. on_device_tensors = None
  395. # Get the logprobs query results.
  396. prompt_logprobs = None
  397. sample_logprobs = None
  398. if not sampling_metadata.skip_sampler_cpu_output:
  399. prompt_logprobs, sample_logprobs = _get_logprobs(
  400. logprobs, sampling_metadata, sample_results)
  401. return _build_sampler_output(
  402. sample_results,
  403. sampling_metadata,
  404. prompt_logprobs,
  405. sample_logprobs,
  406. on_device_tensors=on_device_tensors,
  407. skip_sampler_cpu_output=sampling_metadata.skip_sampler_cpu_output)
  408. @property
  409. def _should_modify_greedy_probs_inplace(self) -> bool:
  410. """Whether or not the sampler should modify the probability distribution
  411. of greedily-sampled tokens such that multinomial sampling would sample
  412. the greedily-sampled token.
  413. In other words, if True then we set the probability of the greedily-
  414. sampled token to 1.
  415. This is used by speculative decoding, which requires that the sampling
  416. method be encoded into the probability distribution.
  417. """
  418. return self.should_modify_greedy_probs_inplace
  419. def _get_bin_counts_and_mask(
  420. tokens: torch.Tensor,
  421. vocab_size: int,
  422. num_seqs: int,
  423. ) -> Tuple[torch.Tensor, torch.Tensor]:
  424. # Compute the bin counts for the tokens.
  425. # vocab_size + 1 for padding.
  426. bin_counts = torch.zeros((num_seqs, vocab_size + 1),
  427. dtype=torch.long,
  428. device=tokens.device)
  429. bin_counts.scatter_add_(1, tokens, torch.ones_like(tokens))
  430. bin_counts = bin_counts[:, :vocab_size]
  431. mask = bin_counts > 0
  432. return bin_counts, mask
  433. def _get_custom_token_bans(
  434. sampling_metadata: SamplingMetadata) -> List[List[int]]:
  435. assert sampling_metadata.seq_groups is not None
  436. banned_tokens: List[List[int]] = []
  437. for i, seq_group in enumerate(sampling_metadata.seq_groups):
  438. sampling_params = sampling_metadata.seq_groups[i].sampling_params
  439. seq_ids = seq_group.seq_ids
  440. custom_token_bans = sampling_params.custom_token_bans
  441. if (i < sampling_metadata.num_prompts
  442. and sampling_params.prompt_logprobs is not None):
  443. prompt_len = len(seq_group.prompt_logprob_indices)
  444. banned_tokens += [custom_token_bans] * (prompt_len - 1)
  445. banned_tokens += [custom_token_bans] * len(seq_ids)
  446. return banned_tokens
  447. def _apply_penalties(logits: torch.Tensor, prompt_tokens_tensor: torch.Tensor,
  448. output_tokens_tensor: torch.Tensor,
  449. presence_penalties: torch.Tensor,
  450. frequency_penalties: torch.Tensor,
  451. repetition_penalties: torch.Tensor) -> torch.Tensor:
  452. num_seqs, vocab_size = logits.shape
  453. _, prompt_mask = _get_bin_counts_and_mask(prompt_tokens_tensor, vocab_size,
  454. num_seqs)
  455. output_bin_counts, output_mask = _get_bin_counts_and_mask(
  456. output_tokens_tensor, vocab_size, num_seqs)
  457. repetition_penalties = repetition_penalties[:, None].repeat(1, vocab_size)
  458. repetition_penalties[~(prompt_mask | output_mask)] = 1.0
  459. logits = torch.where(logits > 0, logits / repetition_penalties,
  460. logits * repetition_penalties)
  461. # We follow the definition in OpenAI API.
  462. # Refer to https://platform.openai.com/docs/api-reference/parameter-details
  463. logits -= frequency_penalties.unsqueeze_(dim=1) * output_bin_counts
  464. logits -= presence_penalties.unsqueeze_(dim=1) * output_mask
  465. return logits
  466. def _apply_temperatures(
  467. logits: torch.Tensor,
  468. temperatures: torch.Tensor,
  469. dynatemp_mins: torch.Tensor,
  470. dynatemp_maxs: torch.Tensor,
  471. dynatemp_exps: torch.Tensor,
  472. ) -> None:
  473. dynatemp_mask = (dynatemp_mins != 0) | (dynatemp_maxs != 0)
  474. dynatemp_mins = dynatemp_mins[dynatemp_mask]
  475. dynatemp_maxs = dynatemp_maxs[dynatemp_mask]
  476. dynatemp_exps = dynatemp_exps[dynatemp_mask]
  477. dynatemp_logits = logits[dynatemp_mask]
  478. dynatemp_shifted_logits = torch.log_softmax(dynatemp_logits, dim=-1)
  479. dynatemp_probs = dynatemp_shifted_logits.exp()
  480. dynatemp_entropies = -(dynatemp_probs *
  481. dynatemp_shifted_logits).nansum(dim=-1)
  482. dynatemp_max_entropies = torch.log_(
  483. (dynatemp_logits > float("-inf")).sum(dim=-1).float())
  484. normalized_entropies = dynatemp_entropies.div_(dynatemp_max_entropies)
  485. dyn_temp = (dynatemp_mins + (dynatemp_maxs - dynatemp_mins) *
  486. normalized_entropies.pow_(dynatemp_exps))
  487. temperatures[dynatemp_mask] = dyn_temp
  488. temperatures[temperatures.isnan()] = _TEMPERATURE_MINIMUM
  489. temperatures[temperatures <= _TEMPERATURE_MINIMUM] = _TEMPERATURE_MINIMUM
  490. # To prevent saturation of top logits, we shift the range to [-inf, 1]
  491. # Why align to 1, instead of 0? Because [0, 1] holds 25% of all floats.
  492. # Why mask? So we aren't potentially discarding data in milder temps.
  493. low_temps = temperatures < 0.1
  494. logits[low_temps] -= logits.max(dim=-1, keepdim=True).values[low_temps] - 1
  495. logits.div_(temperatures.unsqueeze(dim=1))
  496. def _apply_token_bans(logits: torch.Tensor,
  497. banned_tokens: List[List[int]]) -> torch.Tensor:
  498. for i, banned_token_ids in enumerate(banned_tokens):
  499. if i >= logits.size(0):
  500. break
  501. if not banned_token_ids:
  502. continue
  503. logits[i, banned_token_ids] = -float("inf")
  504. return logits
  505. def _apply_min_tokens_penalty(
  506. logits: torch.Tensor,
  507. sampling_metadata: SamplingMetadata,
  508. ) -> torch.Tensor:
  509. """Apply min_tokens penalty which sets stop tokens to -inf if min_tokens
  510. have not been generated yet
  511. """
  512. # list of indices in logits that will be set to -inf
  513. logits_to_penalize = []
  514. logits_applied = 0
  515. for seq_group in sampling_metadata.seq_groups:
  516. seq_ids = seq_group.seq_ids
  517. sampling_params = seq_group.sampling_params
  518. sample_indices = seq_group.sample_indices
  519. logits_applied += len(sample_indices) + len(
  520. seq_group.prompt_logprob_indices)
  521. if not seq_group.do_sample:
  522. continue
  523. start_idx = sample_indices[0]
  524. min_tokens = sampling_params.min_tokens
  525. token_ids_to_penalize = sampling_params.all_stop_token_ids
  526. if min_tokens > 0 and token_ids_to_penalize:
  527. seqs_to_penalize = []
  528. for j, seq_id in enumerate(seq_ids):
  529. seq_data = seq_group.seq_data[seq_id]
  530. if len(seq_data.output_token_ids_array) < min_tokens:
  531. seqs_to_penalize.append(j)
  532. if seqs_to_penalize:
  533. # convert to the index into logits
  534. seqs_to_penalize = [start_idx + j for j in seqs_to_penalize]
  535. # itertools.product pairs each seq index with every token id
  536. logits_to_penalize.extend(
  537. itertools.product(seqs_to_penalize, token_ids_to_penalize))
  538. if logits_to_penalize:
  539. # use zip and * to group indices along each dimension
  540. # eg. [ (1,2), (1,3), (5,6) ] -> ( (1,1,5), (2,3,6) )
  541. logits[tuple(zip(*logits_to_penalize))] = -float("inf")
  542. # verifies that no rows in logits were missed unexpectedly
  543. assert logits_applied == logits.shape[0]
  544. return logits
  545. def _apply_dry(
  546. logits: torch.Tensor,
  547. input_token_ids: torch.Tensor,
  548. output_token_ids: torch.Tensor,
  549. multipliers: torch.Tensor,
  550. bases: torch.Tensor,
  551. allowed_lengths: torch.Tensor,
  552. sequence_breakers_ids: torch.Tensor,
  553. ranges: torch.Tensor,
  554. ) -> torch.Tensor:
  555. """
  556. Apply Don't Repeat Yourself (DRY) sampling to the logits.
  557. Reference: https://github.com/oobabooga/text-generation-webui/pull/5677
  558. """
  559. VOCAB_SIZE = logits.size(-1)
  560. MAX_NGRAM = 100
  561. # Process each sequence that has a nonzero multiplier
  562. applies_to = multipliers.nonzero(as_tuple=True)[0]
  563. for irow in applies_to.tolist():
  564. # DRY applies to input AND output tokens, so concat w/o padding tokens
  565. prompt_len = (len(input_token_ids[irow]) -
  566. (input_token_ids[irow] == VOCAB_SIZE).sum().item())
  567. ouput_len = (len(output_token_ids[irow]) -
  568. (output_token_ids[irow] == VOCAB_SIZE).sum().item())
  569. token_seq = torch.cat((input_token_ids[irow][:prompt_len],
  570. output_token_ids[irow][:ouput_len]), dim=0)
  571. range_limit = ranges[irow].item()
  572. if range_limit: # could this be done in cat? yes. do i care? no.
  573. token_seq = token_seq[-range_limit:]
  574. last_token = token_seq[-1].item()
  575. if last_token in sequence_breakers_ids[irow]:
  576. continue # early out for everything up to the min_ngram check?
  577. # Build a mask of all the breaking tokens in the context
  578. break_mask = torch.zeros(len(token_seq), dtype=torch.bool,
  579. device=logits.device)
  580. for break_tok in sequence_breakers_ids[irow]:
  581. break_mask.logical_or_(token_seq == break_tok)
  582. # Find the most recent breaking token (sets ngram limit)
  583. max_ngram = 0
  584. for max_ngram in range(min(len(break_mask), MAX_NGRAM + 1)):
  585. if break_mask[-max_ngram - 1]:
  586. break
  587. min_ngram = allowed_lengths[irow].item()
  588. if max_ngram <= min_ngram: # Too close to a break to match anything
  589. continue
  590. # If [token] is picked, what's the longest ngram that would match?
  591. ngram_lens = torch.zeros(VOCAB_SIZE, dtype=torch.int32,
  592. device=logits.device)
  593. # Find all instances of the last token- potential ngrams!
  594. endpoint_indexes = torch.nonzero(token_seq == last_token,
  595. as_tuple=True)[0].tolist()
  596. # NOTE: This seems like the slow part. Haven't benchmarked.
  597. for idx in endpoint_indexes[:-1]: # Skip the last_token match
  598. unwind = 0
  599. # Check up to max_ngram tokens prior to idx (we know idx matches)
  600. for unwind in range(1, min(idx, max_ngram) + 1):
  601. if break_mask[idx - unwind]:
  602. break
  603. if token_seq[idx - unwind] != token_seq[-unwind - 1]:
  604. break
  605. next_tok = token_seq[idx+1]
  606. # The repeated tokens BEFORE next_tok (+1 to include [idx]).
  607. ngram_lens[next_tok] = max(ngram_lens[next_tok].item(), unwind + 1)
  608. # Convert ngram lengths to penalty exponents
  609. penalty_mask = ngram_lens > 0
  610. scales = bases[irow] ** (ngram_lens[penalty_mask] - min_ngram)
  611. # Calculate and apply penalties
  612. logits[irow][penalty_mask] -= multipliers[irow] * scales
  613. return logits
  614. def _apply_no_repeat_ngram(
  615. logits: torch.Tensor,
  616. input_ids: torch.Tensor,
  617. ngram_size: torch.Tensor,
  618. ) -> torch.Tensor:
  619. """Apply no-repeat-ngram penalty which sets logits to -inf for tokens that
  620. would create a repeated n-gram.
  621. """
  622. if torch.all(ngram_size == 0):
  623. return logits
  624. batch_size = logits.shape[0]
  625. for i in range(batch_size):
  626. size = int(ngram_size[i].item())
  627. if size == 0:
  628. continue
  629. cur_len = len(input_ids[i])
  630. if cur_len < size:
  631. continue
  632. banned_tokens = _calc_banned_ngram_tokens(
  633. ngram_size=size,
  634. prev_input_ids=input_ids[i],
  635. cur_len=cur_len-1
  636. )
  637. if banned_tokens:
  638. logits[i, banned_tokens] = -float("inf")
  639. return logits
  640. def _apply_top_k_top_p(
  641. logits: torch.Tensor,
  642. p: torch.Tensor,
  643. k: torch.Tensor,
  644. ) -> torch.Tensor:
  645. logits_sort, logits_idx = logits.sort(dim=-1, descending=False)
  646. # Apply top-k.
  647. top_k_mask = logits_sort.size(1) - k.to(torch.long)
  648. # Get all the top_k values.
  649. top_k_mask = logits_sort.gather(1, top_k_mask.unsqueeze(dim=1))
  650. top_k_mask = logits_sort < top_k_mask
  651. logits_sort.masked_fill_(top_k_mask, -float("inf"))
  652. # Apply top-p.
  653. probs_sort = logits_sort.softmax(dim=-1)
  654. probs_sum = probs_sort.cumsum(dim=-1)
  655. top_p_mask = probs_sum <= 1 - p.unsqueeze(dim=1)
  656. # at least one
  657. top_p_mask[:, -1] = False
  658. logits_sort.masked_fill_(top_p_mask, -float("inf"))
  659. # Re-sort the probabilities.
  660. src = torch.arange(logits_idx.shape[-1],
  661. device=logits_idx.device).expand_as(logits_idx)
  662. logits_idx_inv = torch.empty_like(logits_idx).scatter_(dim=-1,
  663. index=logits_idx,
  664. src=src)
  665. logits = torch.gather(logits_sort, dim=-1, index=logits_idx_inv)
  666. return logits
  667. def _apply_min_p(
  668. logits: torch.Tensor,
  669. min_p: torch.Tensor,
  670. ) -> torch.Tensor:
  671. """
  672. Adapted from
  673. https://github.com/oobabooga/text-generation-webui/blob/3146124ec01f02c8fb1650a6517cf1b60b537aaf/modules/sampler_hijack.py#L16C17-L16C17
  674. """
  675. probs = torch.softmax(logits, dim=-1)
  676. top_probs, _ = probs.max(dim=-1, keepdim=True)
  677. scaled_min_p = min_p.unsqueeze_(dim=1) * top_probs
  678. tokens_to_remove = probs < scaled_min_p
  679. logits = logits.masked_fill_(tokens_to_remove, -float("inf"))
  680. return logits
  681. def _apply_top_a(
  682. logits: torch.Tensor,
  683. top_a: torch.Tensor,
  684. ) -> torch.Tensor:
  685. probs = torch.softmax(logits, dim=-1)
  686. top_probs, _ = probs.max(dim=-1, keepdim=True)
  687. threshold = torch.pow(top_probs, 2) * top_a.unsqueeze_(dim=1)
  688. tokens_to_remove = probs < threshold
  689. logits = logits.masked_fill_(tokens_to_remove, -float("inf"))
  690. return logits
  691. def _apply_tfs(
  692. logits: torch.Tensor,
  693. tfs: torch.Tensor,
  694. ) -> torch.Tensor:
  695. logits_sort, logits_idx = logits.sort(dim=-1, descending=True)
  696. d2 = logits_sort.softmax(dim=-1).diff().diff().abs()
  697. normalized_d2 = d2 / torch.sum(d2, dim=-1, keepdim=True)
  698. curvature_cdf = torch.cumsum(normalized_d2, dim=-1)
  699. tfs_mask = curvature_cdf > tfs.unsqueeze(dim=-1)
  700. tfs_mask = torch.cat(
  701. (
  702. torch.zeros(
  703. logits.shape[0], 1, dtype=torch.bool, device=logits.device),
  704. tfs_mask,
  705. torch.ones(
  706. logits.shape[0], 1, dtype=torch.bool, device=logits.device),
  707. ),
  708. dim=-1,
  709. )
  710. logits_sort[tfs_mask] = -float("inf")
  711. logits = torch.gather(logits_sort,
  712. dim=-1,
  713. index=torch.argsort(logits_idx, dim=-1))
  714. return logits
  715. def _apply_eta_cutoff(
  716. logits: torch.Tensor,
  717. eta_cutoff: torch.Tensor,
  718. ) -> torch.Tensor:
  719. shifted_logits = torch.log_softmax(logits, dim=-1)
  720. probs = shifted_logits.exp()
  721. neg_entropy = (probs * shifted_logits).nansum(dim=-1)
  722. eps = torch.min(eta_cutoff,
  723. torch.sqrt(eta_cutoff) *
  724. torch.exp(neg_entropy)).unsqueeze(dim=1)
  725. eta_mask = probs < eps
  726. # guard against nulling out all the logits
  727. top_idx = torch.argmax(probs, dim=1, keepdim=True)
  728. eta_mask.scatter_(dim=1, index=top_idx, value=False)
  729. logits[eta_mask] = -float("inf")
  730. return logits
  731. def _apply_epsilon_cutoff(
  732. logits: torch.Tensor,
  733. epsilon_cutoff: torch.Tensor,
  734. ) -> torch.Tensor:
  735. probs = logits.softmax(dim=-1)
  736. eps_mask = probs < epsilon_cutoff.unsqueeze(dim=1)
  737. # guard against nulling out all the logits
  738. top_idx = torch.argmax(probs, dim=1, keepdim=True)
  739. eps_mask.scatter_(dim=1, index=top_idx, value=False)
  740. logits[eps_mask] = -float("inf")
  741. return logits
  742. def _apply_typical_sampling(
  743. logits: torch.Tensor,
  744. typical_p: torch.Tensor,
  745. ) -> torch.Tensor:
  746. shifted_logits = torch.log_softmax(logits, dim=-1)
  747. probs = shifted_logits.exp()
  748. neg_entropy = (probs * shifted_logits).nansum(dim=-1, keepdim=True)
  749. surprisal_deviations = (neg_entropy - shifted_logits).abs()
  750. _, indices = torch.sort(surprisal_deviations)
  751. reordered_probs = probs.gather(-1, indices)
  752. typ_mask_sorted = reordered_probs.cumsum(dim=-1) >= typical_p.unsqueeze(
  753. dim=1)
  754. min_tokens_to_keep = 1
  755. # Keep at least min_tokens_to_keep
  756. typ_mask_sorted[..., :min_tokens_to_keep] = 0
  757. typ_mask = typ_mask_sorted.scatter(1, indices, typ_mask_sorted)
  758. logits[typ_mask] = -float("inf")
  759. return logits
  760. def _apply_quadratic_sampling(
  761. logits: torch.Tensor,
  762. smoothing_factor: torch.Tensor,
  763. smoothing_curve: torch.Tensor,
  764. ) -> torch.Tensor:
  765. """
  766. Applies a quadratic transformation to the logits based on the
  767. provided smoothing factors and curves. The transformation is
  768. centered around the maximum logit value in the batch.
  769. The transformation involves a quadratic and cubic term, with the
  770. cubic term controlled by the smoothing curve. The quadratic term is
  771. scaled by the smoothing factor, and the cubic term is scaled by the
  772. product of the smoothing factor and the smoothing curve.
  773. params:
  774. logits (torch.Tensor): The logits to be transformed.
  775. smoothing_factors (torch.Tensor): The factors to scale the quadratic
  776. term in the transformation.
  777. smoothing_curves (torch.Tensor): The factors to scale the cubic term
  778. in the transformation.
  779. returns:
  780. torch.Tensor: The transformed logits.
  781. Credits: @kalomaze
  782. """
  783. mask = smoothing_factor != 0
  784. smoothing_factor.unsqueeze_(dim=1)
  785. smoothing_curve.unsqueeze_(dim=1)
  786. k = smoothing_factor * (3 - smoothing_curve) / 2
  787. s = smoothing_factor * (smoothing_curve - 1) / 2
  788. quadlogits = logits[mask] # limit to logits using this sampler
  789. max_logits = quadlogits.max(dim=-1, keepdim=True).values
  790. # Construct the delta from each logit to its new value
  791. diff = quadlogits - max_logits
  792. diff -= diff**2 * (s[mask] * diff - k[mask])
  793. diff[diff != diff] = 0 # Eliminate NaNs due to infs
  794. logits[mask] -= diff
  795. return logits
  796. def _apply_xtc_sampling(
  797. logits: torch.Tensor,
  798. xtc_thresholds: torch.Tensor,
  799. xtc_probabilities: torch.Tensor,
  800. ) -> torch.Tensor:
  801. """Apply Exclude Top Choices (XTC) sampling to the logits.
  802. Reference: https://github.com/oobabooga/text-generation-webui/pull/6335
  803. Args:
  804. logits: (num_tokens, vocab_size) The input logits.
  805. xtc_thresholds: (num_tokens,) The threshold for each token.
  806. xtc_probabilities: (num_tokens,) The probability of applying XTC
  807. for each token.
  808. Returns:
  809. torch.Tensor: The modified logits.
  810. """
  811. apply_xtc = torch.rand_like(xtc_probabilities) < xtc_probabilities
  812. if not apply_xtc.any():
  813. return logits
  814. probs = torch.softmax(logits, dim=-1)
  815. sorted_probs, sorted_indices = torch.sort(probs, descending=True, dim=-1)
  816. # Find indices where the next probability is above the threshold
  817. # Skips the top choice, which later on becomes skipping the last choice.
  818. above_threshold = sorted_probs[..., 1:] >= xtc_thresholds.unsqueeze(-1)
  819. # Apply XTC only to rows where it should be applied
  820. for i in range(logits.shape[0]):
  821. if apply_xtc[i]:
  822. # Count logits above the threshold (skipping the first)
  823. indices_to_remove = above_threshold[i].count_nonzero(dim=-1).item()
  824. if indices_to_remove > 0:
  825. # Implies the top logit and at least one other is >= threshold.
  826. # Mask out above_thresh logits except the last/lowest one.
  827. logits[i].scatter_(
  828. 0, sorted_indices[i, :indices_to_remove], -float('inf'))
  829. return logits
  830. def _apply_top_nsigma(
  831. logits: torch.Tensor,
  832. nsigma: torch.Tensor,
  833. ) -> torch.Tensor:
  834. """Apply top-nsigma truncation to the logits.
  835. Reference: https://arxiv.org/abs/2411.07641
  836. Args:
  837. logits: Logits of shape (num_tokens, vocab_size)
  838. nsigma: Number of standard deviations to use as threshold
  839. Returns:
  840. Modified logits with values below threshold set to -inf
  841. """
  842. std = logits.std(dim=-1, keepdim=True)
  843. threshold = (logits.max(dim=-1, keepdim=True).values -
  844. nsigma.unsqueeze(dim=1) * std)
  845. logits[logits < threshold] = float("-inf")
  846. return logits
  847. def _greedy_sample(
  848. selected_seq_groups: List[SequenceGroupToSample],
  849. samples: torch.Tensor,
  850. ) -> List[Tuple[List[int], List[int]]]:
  851. """Run greedy sampling on a given samples.
  852. Args:
  853. selected_seq_groups: A list of sequence groups batched.
  854. samples: (num_selected_samples,) A tensor of samples. The length of
  855. samples could be smaller than selected_seq_groups if
  856. seq_group.do_sample is False.
  857. Returns:
  858. Tuple of (next_token_ids, parent_ids). The length of returned list is
  859. same as the length of selected_seq_groups. If the corresponding
  860. seq_group has do_sample=False, tuple contains ([], [])
  861. """
  862. samples = samples.tolist()
  863. sample_idx = 0
  864. results = []
  865. for seq_group in selected_seq_groups:
  866. if not seq_group.do_sample:
  867. results.append(([], []))
  868. continue
  869. seq_ids = seq_group.seq_ids
  870. num_parent_seqs = len(seq_ids)
  871. assert num_parent_seqs == 1, (
  872. "Greedy sampling should have only one seq.")
  873. parent_ids = list(range(num_parent_seqs))
  874. next_token_ids = [samples[sample_idx]]
  875. results.append((next_token_ids, parent_ids))
  876. sample_idx += num_parent_seqs
  877. return results
  878. def _random_sample(
  879. selected_seq_groups: List[SequenceGroupToSample],
  880. random_samples: torch.Tensor,
  881. ) -> List[Tuple[List[int], List[int]]]:
  882. """Run random sampling on a given samples.
  883. Args:
  884. selected_seq_groups: A list of sequence groups batched.
  885. random_samples: (num_selected_samples,) A tensor of samples. The
  886. length of samples could be smaller than selected_seq_groups if
  887. seq_group.do_sample is False.
  888. Returns:
  889. Tuple of (next_token_ids, parent_ids). The length of returned list is
  890. same as the length of selected_seq_groups. If the corresponding
  891. seq_group has do_sample=False, tuple contains ([], [])
  892. """
  893. # Find the maximum best_of value of the prompt phase requests.
  894. random_samples = random_samples.cpu()
  895. sample_idx = 0
  896. results = []
  897. for seq_group in selected_seq_groups:
  898. if not seq_group.do_sample:
  899. results.append(([], []))
  900. continue
  901. seq_ids = seq_group.seq_ids
  902. sampling_params = seq_group.sampling_params
  903. is_prompt = seq_group.is_prompt
  904. num_parent_seqs = len(seq_ids)
  905. if is_prompt:
  906. # Prompt phase.
  907. parent_ids = [0] * sampling_params.best_of
  908. next_token_ids = random_samples[
  909. sample_idx, :sampling_params.best_of].tolist()
  910. else:
  911. # Generation phase.
  912. parent_ids = list(range(num_parent_seqs))
  913. next_token_ids = random_samples[sample_idx:sample_idx +
  914. num_parent_seqs, 0].tolist()
  915. results.append((next_token_ids, parent_ids))
  916. sample_idx += num_parent_seqs
  917. return results
  918. def _beam_search_sample(
  919. selected_seq_groups: List[SequenceGroupToSample],
  920. logprobs: torch.Tensor,
  921. ) -> List[Tuple[List[int], List[int]]]:
  922. """Run beam sampling on a given samples.
  923. Args:
  924. selected_seq_groups: A list of sequence groups batched.
  925. logprobs: (num_selected_samples, vocab_size,) A tensor of logprob
  926. on selected sample indices.
  927. Returns:
  928. Tuple of (next_token_ids, parent_ids). The length of returned list is
  929. same as the length of selected_seq_groups. If the corresponding
  930. seq_group has do_sample=False, tuple contains ([], [])
  931. """
  932. # We sample 2 * beam_width candidates to make sure that with high
  933. # probability we can get `beam_width` candidates in addition to
  934. # the finished sequences for the next iteration. See
  935. # https://github.com/tensorflow/tensor2tensor/blob/bafdc1b67730430d38d6ab802cbd51f9d053ba2e/tensor2tensor/utils/beam_search.py#L557-L563
  936. # for details. See also HF reference:
  937. # https://github.com/huggingface/transformers/blob/a4dd53d88e4852f023332d284ff07a01afcd5681/src/transformers/generation/utils.py#L3063-L3065
  938. #
  939. # NOTE: Beam search is not vectorized, so its speed can be slower than
  940. # other sampling methods.
  941. sample_idx = 0
  942. results = []
  943. for seq_group in selected_seq_groups:
  944. if not seq_group.do_sample:
  945. results.append(([], []))
  946. continue
  947. is_prompt = seq_group.is_prompt
  948. seq_ids, sampling_params = seq_group.seq_ids, seq_group.sampling_params
  949. num_parent_seqs = len(seq_ids)
  950. beam_width = sampling_params.best_of
  951. seq_group_logprobs = logprobs[sample_idx:sample_idx + num_parent_seqs]
  952. if is_prompt:
  953. # Prompt phase.
  954. assert num_parent_seqs == 1, (
  955. "Prompt input should have only one seq.")
  956. parent_ids = [0] * (2 * beam_width)
  957. _, next_token_ids = torch.topk(seq_group_logprobs[0],
  958. 2 * beam_width)
  959. next_token_ids = next_token_ids.tolist()
  960. else:
  961. # Generation phase.
  962. cumulative_logprobs = [
  963. seq_group.seq_data[seq_id].cumulative_logprob
  964. for seq_id in seq_ids
  965. ]
  966. cumulative_logprobs = torch.tensor(
  967. cumulative_logprobs,
  968. dtype=torch.float,
  969. device=seq_group_logprobs.device)
  970. seq_group_logprobs = (seq_group_logprobs +
  971. cumulative_logprobs.unsqueeze(dim=1))
  972. _, topk_ids = torch.topk(seq_group_logprobs.flatten(),
  973. 2 * beam_width)
  974. topk_ids = topk_ids.tolist()
  975. vocab_size = seq_group_logprobs.size(-1)
  976. parent_ids = [i // vocab_size for i in topk_ids]
  977. next_token_ids = [i % vocab_size for i in topk_ids]
  978. results.append((next_token_ids, parent_ids))
  979. sample_idx += num_parent_seqs
  980. assert sample_idx == logprobs.size(0)
  981. return results
  982. # torch.multinomial forces a GPU<->CPU sync.
  983. # Therefore, we use an optimized implementation instead.
  984. # Note that we always sample with replacement.
  985. # probs will be modified in place, but this is fine, as we pass
  986. # in a copy already.
  987. def _multinomial(
  988. probs: torch.Tensor,
  989. num_samples: int,
  990. seq_groups: Optional[List[SequenceGroupToSample]] = None,
  991. ) -> torch.Tensor:
  992. if num_samples > 1:
  993. probs = probs.repeat_interleave(num_samples, dim=0)
  994. q = torch.empty_like(probs)
  995. if seq_groups is None:
  996. q.exponential_()
  997. else:
  998. sample_idx = 0
  999. for seq_group in seq_groups:
  1000. seq_ids = seq_group.seq_ids
  1001. stride = len(seq_ids) * num_samples
  1002. assert seq_group.generator is not None
  1003. q[sample_idx:sample_idx +
  1004. stride].exponential_(generator=seq_group.generator)
  1005. sample_idx += stride
  1006. return probs.div_(q).argmax(dim=1).view(-1, num_samples)
  1007. def _top_k_top_p_multinomial_with_kernels(
  1008. probs: torch.Tensor, top_ks: torch.Tensor, top_ps: torch.Tensor,
  1009. num_samples: int, seq_groups: Optional[List[SequenceGroupToSample]]):
  1010. max_top_k_round = 32
  1011. if num_samples > 1:
  1012. probs = probs.repeat_interleave(num_samples, dim=0)
  1013. top_ks = top_ks.repeat_interleave(num_samples)
  1014. top_ps = top_ps.repeat_interleave(num_samples)
  1015. batch_size = probs.shape[0]
  1016. uniform_samples = torch.empty((max_top_k_round, batch_size),
  1017. device=probs.device)
  1018. if seq_groups is None:
  1019. uniform_samples.uniform_()
  1020. else:
  1021. sample_idx = 0
  1022. for seq_group in seq_groups:
  1023. seq_ids = seq_group.seq_ids
  1024. stride = len(seq_ids) * num_samples
  1025. assert seq_group.generator is not None
  1026. uniform_samples[:, sample_idx:sample_idx +
  1027. stride].uniform_(generator=seq_group.generator)
  1028. sample_idx += stride
  1029. batch_next_token_ids, success = ops.top_k_top_p_sampling_from_probs(
  1030. probs,
  1031. uniform_samples,
  1032. top_ks,
  1033. top_ps,
  1034. )
  1035. if not success.all():
  1036. warnings.warn("CUDA rejection sampling failed, fallback.",
  1037. stacklevel=1)
  1038. probs = ops.top_k_renorm_prob(probs, top_ks)
  1039. probs = ops.top_p_renorm_prob(probs, top_ps)
  1040. batch_next_token_ids = ops.sampling_from_probs(
  1041. probs, uniform_samples[0])
  1042. return batch_next_token_ids.view(-1, num_samples)
  1043. def _sample_with_torch(
  1044. probs: torch.Tensor,
  1045. logprobs: torch.Tensor,
  1046. sampling_metadata: SamplingMetadata,
  1047. sampling_tensors: SamplingTensors,
  1048. include_gpu_probs_tensor: bool,
  1049. modify_greedy_probs: bool,
  1050. ) -> Tuple[List[Tuple[List[int], List[int]]], Optional[torch.Tensor]]:
  1051. categorized_seq_group_ids = {t: [] for t in SamplingType}
  1052. categorized_sample_indices = sampling_metadata.categorized_sample_indices
  1053. for i, seq_group in enumerate(sampling_metadata.seq_groups):
  1054. sampling_params = seq_group.sampling_params
  1055. sampling_type = sampling_params.sampling_type
  1056. categorized_seq_group_ids[sampling_type].append(i)
  1057. sample_results_dict: Dict[int, Tuple[List[int], List[int]]] = {}
  1058. sample_metadata = {}
  1059. multinomial_samples = {}
  1060. # Create output tensor for sampled token ids.
  1061. if include_gpu_probs_tensor:
  1062. sampled_token_ids_tensor = torch.empty(logprobs.shape[0],
  1063. 1,
  1064. dtype=torch.long,
  1065. device=logprobs.device)
  1066. else:
  1067. sampled_token_ids_tensor = None
  1068. # Counterintuitively, having two loops here is actually faster.
  1069. # The first loop can run without waiting on GPU<->CPU sync.
  1070. for sampling_type in SamplingType:
  1071. sample_indices = categorized_sample_indices[sampling_type][:, 0]
  1072. num_tokens = len(sample_indices)
  1073. if num_tokens == 0:
  1074. continue
  1075. seq_group_id = categorized_seq_group_ids[sampling_type]
  1076. seq_groups = [sampling_metadata.seq_groups[i] for i in seq_group_id]
  1077. sample_metadata[sampling_type] = (seq_group_id, seq_groups)
  1078. long_sample_indices = sample_indices.long()
  1079. if sampling_type == SamplingType.GREEDY:
  1080. greedy_samples = torch.argmax(logprobs[long_sample_indices],
  1081. dim=-1)
  1082. if include_gpu_probs_tensor:
  1083. # Store sampled tokens in output tensor.
  1084. sampled_token_ids_tensor[
  1085. long_sample_indices] = greedy_samples.unsqueeze(-1)
  1086. if modify_greedy_probs:
  1087. # If required, modify the probabilities such that sampling from
  1088. # the modified distribution would always sample the argmax
  1089. # token id.
  1090. _modify_greedy_probs_inplace(logprobs, probs,
  1091. long_sample_indices,
  1092. greedy_samples)
  1093. elif sampling_type in (SamplingType.RANDOM, SamplingType.RANDOM_SEED):
  1094. max_best_of_in_batch = 1
  1095. for seq_group in seq_groups:
  1096. if seq_group.is_prompt:
  1097. sampling_params = seq_group.sampling_params
  1098. max_best_of_in_batch = max(max_best_of_in_batch,
  1099. sampling_params.best_of)
  1100. seq_groups_arg = (None if sampling_type == SamplingType.RANDOM else
  1101. seq_groups)
  1102. if APHRODITE_USE_SAMPLING_KERNELS is not None:
  1103. multinomial_samples[
  1104. sampling_type] = _top_k_top_p_multinomial_with_kernels(
  1105. probs[long_sample_indices],
  1106. sampling_tensors.top_ks[long_sample_indices],
  1107. sampling_tensors.top_ps[long_sample_indices],
  1108. max_best_of_in_batch,
  1109. seq_groups_arg,
  1110. )
  1111. else:
  1112. multinomial_samples[sampling_type] = _multinomial(
  1113. probs[long_sample_indices],
  1114. max_best_of_in_batch,
  1115. seq_groups=seq_groups_arg)
  1116. if sampled_token_ids_tensor is not None:
  1117. # Store sampled tokens in output tensor.
  1118. sampled_token_ids_tensor[long_sample_indices] = \
  1119. multinomial_samples[sampling_type].to(torch.long)
  1120. elif sampling_type == SamplingType.BEAM:
  1121. beam_search_logprobs = logprobs[sample_indices]
  1122. else:
  1123. raise ValueError(f"Unsupported sampling type: {sampling_type}")
  1124. # GPU<->CPU sync happens in the loop below.
  1125. # This also converts the sample output to Python objects.
  1126. if not sampling_metadata.skip_sampler_cpu_output:
  1127. for sampling_type in SamplingType:
  1128. if sampling_type not in sample_metadata:
  1129. continue
  1130. (seq_group_id, seq_groups) = sample_metadata[sampling_type]
  1131. if sampling_type == SamplingType.GREEDY:
  1132. sample_results = _greedy_sample(seq_groups, greedy_samples)
  1133. elif sampling_type in (SamplingType.RANDOM,
  1134. SamplingType.RANDOM_SEED):
  1135. sample_results = _random_sample(
  1136. seq_groups, multinomial_samples[sampling_type])
  1137. elif sampling_type == SamplingType.BEAM:
  1138. sample_results = _beam_search_sample(seq_groups,
  1139. beam_search_logprobs)
  1140. sample_results_dict.update(zip(seq_group_id, sample_results))
  1141. sample_results = [
  1142. sample_results_dict.get(i, ([], []))
  1143. for i in range(len(sampling_metadata.seq_groups))
  1144. ]
  1145. else:
  1146. sample_results = []
  1147. return sample_results, sampled_token_ids_tensor
  1148. def _sample_with_triton_kernel(
  1149. probs: torch.Tensor,
  1150. logprobs: torch.Tensor,
  1151. sampling_metadata: SamplingMetadata,
  1152. sampling_tensors: SamplingTensors,
  1153. ) -> List[Tuple[List[int], List[int]]]:
  1154. categorized_seq_group_ids = {t: [] for t in SamplingType}
  1155. categorized_sample_indices = sampling_metadata.categorized_sample_indices
  1156. for i, seq_group in enumerate(sampling_metadata.seq_groups):
  1157. sampling_params = seq_group.sampling_params
  1158. sampling_type = sampling_params.sampling_type
  1159. categorized_seq_group_ids[sampling_type].append(i)
  1160. sample_results_dict: Dict[int, Tuple[List[int], List[int]]] = {}
  1161. sample_metadata = {}
  1162. max_best_of_in_batch = 1
  1163. # Counterintuitively, having two loops here is actually faster.
  1164. # The first loop can run without waiting on GPU<->CPU sync.
  1165. for sampling_type in SamplingType:
  1166. sample_indices = categorized_sample_indices[sampling_type][:, 0]
  1167. sampled_token_indices = categorized_sample_indices[sampling_type][:, 1]
  1168. num_tokens = len(sample_indices)
  1169. if num_tokens == 0:
  1170. continue
  1171. seq_group_id = categorized_seq_group_ids[sampling_type]
  1172. seq_groups = [sampling_metadata.seq_groups[i] for i in seq_group_id]
  1173. sample_metadata[sampling_type] = (seq_group_id, seq_groups,
  1174. sample_indices,
  1175. sampled_token_indices)
  1176. if sampling_type in (SamplingType.GREEDY, SamplingType.RANDOM,
  1177. SamplingType.RANDOM_SEED):
  1178. for seq_group in seq_groups:
  1179. if seq_group.is_prompt:
  1180. sampling_params = seq_group.sampling_params
  1181. max_best_of_in_batch = max(max_best_of_in_batch,
  1182. sampling_params.best_of)
  1183. elif sampling_type == SamplingType.BEAM:
  1184. beam_search_logprobs = logprobs[sample_indices]
  1185. else:
  1186. raise ValueError(f"Unsupported sampling type: {sampling_type}")
  1187. sampled_tokens, _, _ = sample_triton(
  1188. probs=probs,
  1189. seeds=sampling_tensors.sampling_seeds,
  1190. max_best_of=max_best_of_in_batch,
  1191. sample_indices=sampling_tensors.sample_indices,
  1192. logprobs=logprobs,
  1193. # don't save logprobs because we have logic for that below
  1194. # TODO: use this instead of the CPU-based logic below
  1195. save_logprobs=False,
  1196. )
  1197. # GPU<->CPU sync happens in the loop below.
  1198. for sampling_type in SamplingType:
  1199. if sampling_type not in sample_metadata:
  1200. continue
  1201. (seq_group_id, seq_groups, sample_indices,
  1202. sampled_token_indices) = sample_metadata[sampling_type]
  1203. if sampling_type == SamplingType.GREEDY:
  1204. sample_results = _greedy_sample(
  1205. seq_groups, sampled_tokens[sampled_token_indices][:, 0])
  1206. elif sampling_type in (SamplingType.RANDOM, SamplingType.RANDOM_SEED):
  1207. sample_results = _random_sample(
  1208. seq_groups, sampled_tokens[sampled_token_indices])
  1209. elif sampling_type == SamplingType.BEAM:
  1210. sample_results = _beam_search_sample(seq_groups,
  1211. beam_search_logprobs)
  1212. sample_results_dict.update(zip(seq_group_id, sample_results))
  1213. sample_results = [
  1214. sample_results_dict.get(i, ([], []))
  1215. for i in range(len(sampling_metadata.seq_groups))
  1216. ]
  1217. return sample_results
  1218. def _sample(
  1219. probs: torch.Tensor, logprobs: torch.Tensor,
  1220. sampling_metadata: SamplingMetadata, sampling_tensors: SamplingTensors,
  1221. include_gpu_probs_tensor: bool, modify_greedy_probs: bool
  1222. ) -> Tuple[List[Tuple[List[int], List[int]]], Optional[torch.Tensor]]:
  1223. """
  1224. Args:
  1225. probs: (num_query_tokens_in_batch, num_vocab)
  1226. logprobs: (num_query_tokens_in_batch, num_vocab)
  1227. sampling_metadata: The metadata for a batch for sampling.
  1228. sampling_tensors: Tensors that include sampling related metadata.
  1229. Returns:
  1230. (next_token_ids, parent_seq_ids) for each seq group in a batch.
  1231. If sampling is skipped, it returns ([], [])
  1232. sampled_token_ids_tensor: A tensor of sampled token ids.
  1233. """
  1234. return _sample_with_torch(
  1235. probs,
  1236. logprobs,
  1237. sampling_metadata,
  1238. sampling_tensors,
  1239. include_gpu_probs_tensor=include_gpu_probs_tensor,
  1240. modify_greedy_probs=modify_greedy_probs,
  1241. )
  1242. # TODO: Enable once Triton kernel & associated code is faster.
  1243. # return _sample_with_triton_kernel(probs, logprobs, sampling_metadata,
  1244. # sampling_tensors)
  1245. def _get_ranks(logprobs: torch.Tensor, query_indices: torch.Tensor, indices: torch.Tensor) -> torch.Tensor:
  1246. """
  1247. This function calculates the ranks of the chosen tokens in a logprob tensor.
  1248. Args:
  1249. x (torch.Tensor): 2D logprob tensor of shape (N, M)
  1250. where N is the no. of tokens and M is the vocab dim.
  1251. indices (torch.Tensor): List of chosen token indices.
  1252. Returns:
  1253. torch.Tensor: 1D tensor of shape (N,) where N is the no. of tokens.
  1254. Each element in the returned tensor represents the rank
  1255. of the chosen token in the input logprob tensor.
  1256. """
  1257. expanded_indices = torch.zeros(logprobs.shape[0], dtype=indices.dtype, device=indices.device)
  1258. expanded_indices.scatter_(-1, query_indices, indices)
  1259. vals = torch.gather(logprobs, -1, expanded_indices.unsqueeze(dim=1))
  1260. # doing this in a single pass is not practical for prompt_logprobs.
  1261. outs = torch.zeros_like(indices)
  1262. for i in range(0, vals.shape[0], 10):
  1263. outs[i:i+10] = (logprobs[i:i+10] > vals[i:i+10]).sum(dim=-1, dtype=indices.dtype)
  1264. return outs[query_indices].add_(1)
  1265. def _get_logprobs(
  1266. logprobs: torch.Tensor,
  1267. sampling_metadata: SamplingMetadata,
  1268. sample_results: List[Tuple[List[int], List[int]]],
  1269. ) -> Tuple[List[Optional[PromptLogprobs]], List[SampleLogprobs]]:
  1270. """Return sample lobprobs and prompt logprobs.
  1271. The logic consists of 3 parts.
  1272. - Select indices to compute logprob from, ranks of token ids, and
  1273. the top k token ids from logprobs.
  1274. - Compute prompt logprobs if required.
  1275. - Compute sample logprobs if required.
  1276. Args:
  1277. logprobs: (num_query_tokens_across_batch, num_vocab). Each query token's
  1278. logprob per vocab. Sequence groups' query tokens are batched in a
  1279. single flattened tensor. For example, assuming there are N
  1280. seq groups, it is sorted by prefill tokens for seq_group_1 (if
  1281. prompt logprob is enabled), decode tokens for seq_group_1 (if
  1282. sampling is required), prefill tokens for seq_group_2, ...
  1283. sampling_metadata: The sampling metadata.
  1284. sample_results: (num_seq_groups) The tuple of (next_token_ids,
  1285. parent_ids) for each sequence group. When beam search is enabled,
  1286. sample_results can contain different number of seq_ids from
  1287. sampling_metadata.seq_groups. It is because beam search creates
  1288. 2 * BEAM_WIDTH number of samples (whereas there are only up to
  1289. BEAM_WIDTH number of seq_ids).
  1290. Returns:
  1291. A tuple of prompt and sample logprobs per sequence group in a batch.
  1292. """
  1293. # The index of query token to calculate logprobs. It includes both
  1294. # prompt and sample logprob indices.
  1295. query_indices: List[int] = []
  1296. # The next token ids to get the logprob value from.
  1297. next_token_ids: List[int] = []
  1298. # The largest requested number of logprobs. We find logprobs as many as the
  1299. # largest num logprobs in this API. If every logprobs is None, it will be
  1300. # set to -1.
  1301. largest_num_logprobs = -1
  1302. # If beam search is enabled.
  1303. use_beam_search = False
  1304. # Select indices to compute logprob from, ranks of token ids, and the top
  1305. # k token ids from logprobs.
  1306. for (seq_group, sample_result) in zip(sampling_metadata.seq_groups,
  1307. sample_results):
  1308. sampling_params = seq_group.sampling_params
  1309. # Update indices and tokens for prompt logprobs.
  1310. if (seq_group.is_prompt
  1311. and sampling_params.prompt_logprobs is not None):
  1312. largest_num_logprobs = max(largest_num_logprobs,
  1313. sampling_params.prompt_logprobs)
  1314. next_prompt_tokens = _get_next_prompt_tokens(seq_group)
  1315. query_indices.extend(seq_group.prompt_logprob_indices)
  1316. next_token_ids.extend(next_prompt_tokens)
  1317. # Update indices and next tokenes for sample logprob.
  1318. if seq_group.do_sample:
  1319. token_ids, parent_seq_ids = sample_result
  1320. # NOTE: We cannot directly use sample_indices because
  1321. # sample_indices only contain parent seq_ids of a previous step.
  1322. # The current step may have different number of seq_ids, and
  1323. # we can obtain it from `sample_result[1]`.
  1324. query_idx = seq_group.sample_indices[0]
  1325. query_indices.extend(
  1326. [query_idx + parent_id for parent_id in parent_seq_ids])
  1327. next_token_ids.extend(token_ids)
  1328. if sampling_params.logprobs is not None:
  1329. largest_num_logprobs = max(largest_num_logprobs,
  1330. sampling_params.logprobs)
  1331. use_beam_search = use_beam_search or sampling_params.use_beam_search
  1332. assert len(next_token_ids) == len(query_indices)
  1333. if len(query_indices) == 0:
  1334. empty_sampled_logprob = []
  1335. empty_prompt_logprob = None
  1336. return [empty_prompt_logprob], [empty_sampled_logprob]
  1337. selected_logprobs, ranks = None, None
  1338. top_logprobs, top_token_ids = None, None
  1339. # If largest_num_logprobs == -1, i.e. no logprobs are requested, we can
  1340. # skip the whole logprob calculation.
  1341. if largest_num_logprobs >= 0 or use_beam_search:
  1342. query_indices_gpu = torch.tensor(query_indices, device=logprobs.device)
  1343. next_token_ids_gpu = torch.tensor(next_token_ids,
  1344. device=logprobs.device)
  1345. # (num_selected_query_tokens, num_logprobs). Note that query_indices can
  1346. # contain duplicates if beam search is enabled.
  1347. selected_logprobs = logprobs[[
  1348. query_indices_gpu,
  1349. next_token_ids_gpu,
  1350. ]]
  1351. ranks = _get_ranks(
  1352. logprobs,
  1353. query_indices_gpu,
  1354. next_token_ids_gpu,
  1355. )
  1356. assert selected_logprobs.shape[0] == ranks.shape[0]
  1357. # We need to compute top k only if there exists logprobs > 0.
  1358. if largest_num_logprobs > 0:
  1359. # Logprobs of topk tokens for a batch of sequence groups.
  1360. # (num_query_tokens_across_batch).
  1361. top_logprobs, top_token_ids = torch.topk(logprobs,
  1362. largest_num_logprobs,
  1363. dim=-1)
  1364. top_logprobs = top_logprobs.to('cpu')
  1365. top_token_ids = top_token_ids.to('cpu')
  1366. selected_logprobs = selected_logprobs.to('cpu')
  1367. ranks = ranks.to('cpu')
  1368. # Find prompt/sample logprobs.
  1369. prompt_logprobs_per_seq_group: List[Optional[PromptLogprobs]] = []
  1370. sample_logprobs_per_seq_group: List[SampleLogprobs] = []
  1371. top_logprob_idx = 0
  1372. selected_logprobs_idx = 0
  1373. for seq_group, sample_result in zip(sampling_metadata.seq_groups,
  1374. sample_results):
  1375. (prompt_logprobs, top_logprob_idx,
  1376. selected_logprobs_idx) = _get_prompt_logprob_if_needed(
  1377. seq_group, selected_logprobs, ranks, top_token_ids, top_logprobs,
  1378. selected_logprobs_idx, top_logprob_idx)
  1379. prompt_logprobs_per_seq_group.append(prompt_logprobs)
  1380. (sampled_logprobs, top_logprob_idx,
  1381. selected_logprobs_idx) = _get_sampled_logprob_if_needed(
  1382. seq_group, sample_result, selected_logprobs, ranks, top_token_ids,
  1383. top_logprobs, selected_logprobs_idx, top_logprob_idx)
  1384. sample_logprobs_per_seq_group.append(sampled_logprobs)
  1385. return prompt_logprobs_per_seq_group, sample_logprobs_per_seq_group
  1386. def _get_prompt_logprob_if_needed(
  1387. seq_group: SequenceGroupToSample,
  1388. selected_logprobs: torch.Tensor,
  1389. ranks: torch.Tensor,
  1390. top_token_ids: torch.Tensor,
  1391. top_logprobs: torch.Tensor,
  1392. selected_logprobs_idx: int,
  1393. top_logprob_idx: int,
  1394. ):
  1395. """Compute the prompt logprob from a sequence group if needed."""
  1396. sampling_params = seq_group.sampling_params
  1397. is_prompt = seq_group.is_prompt
  1398. # Find prompt logprobs
  1399. prompt_logprobs: Optional[PromptLogprobs] = None
  1400. if is_prompt and sampling_params.prompt_logprobs is not None:
  1401. prompt_logprobs = []
  1402. num_logprobs = sampling_params.prompt_logprobs
  1403. next_prompt_tokens = _get_next_prompt_tokens(seq_group)
  1404. # Pre-select indexes and create a list. It is faster than calling .item
  1405. # repetitively.
  1406. selected_logprob_items = selected_logprobs[
  1407. selected_logprobs_idx:selected_logprobs_idx +
  1408. len(next_prompt_tokens)].tolist()
  1409. rank_items = ranks[selected_logprobs_idx:selected_logprobs_idx +
  1410. len(next_prompt_tokens)].tolist()
  1411. for idx, token_id in enumerate(next_prompt_tokens):
  1412. # Calculate the prompt logprob of the real prompt tokens.
  1413. # {token_id: (logprob, rank_from_vocab)}
  1414. prompt_logprobs_dict: Dict[int, Tuple[float, int]] = {
  1415. token_id: (selected_logprob_items[idx], rank_items[idx])
  1416. }
  1417. # Add top K prompt logprobs along with its rank.
  1418. if num_logprobs > 0:
  1419. top_ids = top_token_ids[
  1420. top_logprob_idx, :num_logprobs].tolist()
  1421. top_probs = top_logprobs[
  1422. top_logprob_idx, :num_logprobs].tolist()
  1423. # Top K is already sorted by rank, so we can use 1 ~
  1424. # num_logprobs + 1 for rank.
  1425. top_ranks = range(1, num_logprobs + 1)
  1426. prompt_logprobs_dict.update({
  1427. top_id: (top_prob, rank)
  1428. for top_id, top_prob, rank in zip(top_ids, top_probs,
  1429. top_ranks)
  1430. })
  1431. prompt_logprobs.append({
  1432. token_id: Logprob(*logprob_and_rank)
  1433. for token_id, logprob_and_rank in prompt_logprobs_dict.items()
  1434. })
  1435. # + 1 to go to the next prompt token.
  1436. top_logprob_idx += 1
  1437. # + len(next_prompt_tokens) to go to the next prompt.
  1438. selected_logprobs_idx += len(next_prompt_tokens)
  1439. return prompt_logprobs, top_logprob_idx, selected_logprobs_idx
  1440. def _get_sampled_logprob_if_needed(
  1441. seq_group: SequenceGroupToSample,
  1442. sample_result: Tuple[List[int], List[int]],
  1443. selected_logprobs: torch.Tensor,
  1444. ranks: torch.Tensor,
  1445. top_token_ids: torch.Tensor,
  1446. top_logprobs: torch.Tensor,
  1447. selected_logprobs_idx: int,
  1448. top_logprob_idx: int,
  1449. ):
  1450. """Compute the sample logprob if needed."""
  1451. seq_ids = seq_group.seq_ids
  1452. num_logprobs = seq_group.sampling_params.logprobs
  1453. use_beam_search = seq_group.sampling_params.use_beam_search
  1454. sampled_logprobs: SampleLogprobs = []
  1455. next_token_ids, parent_seq_ids = sample_result
  1456. if seq_group.do_sample:
  1457. assert len(next_token_ids) > 0
  1458. if num_logprobs is None and not use_beam_search:
  1459. for next_token_id in next_token_ids:
  1460. # Use a dummy logprob
  1461. sampled_logprobs.append({next_token_id: Logprob(inf)})
  1462. else:
  1463. # Pre-select items from tensor. tolist() is faster than repetitive
  1464. # `.item()` calls.
  1465. selected_logprob_items = selected_logprobs[
  1466. selected_logprobs_idx:selected_logprobs_idx +
  1467. len(next_token_ids)].tolist()
  1468. rank_items = ranks[selected_logprobs_idx:selected_logprobs_idx +
  1469. len(next_token_ids)].tolist()
  1470. for idx, (next_token_id, parent_id) in enumerate(
  1471. zip(next_token_ids, parent_seq_ids)):
  1472. # Get the logprob of a sampled token.
  1473. sampled_logprobs_dict = {
  1474. next_token_id:
  1475. (selected_logprob_items[idx], rank_items[idx])
  1476. }
  1477. if num_logprobs is not None and num_logprobs > 0:
  1478. # Get top K logprobs.
  1479. top_ids = top_token_ids[top_logprob_idx +
  1480. parent_id, :num_logprobs].tolist()
  1481. top_probs = top_logprobs[
  1482. top_logprob_idx + parent_id, :num_logprobs].tolist()
  1483. # Top K is already sorted by rank, so we can use 1 ~
  1484. # num_logprobs + 1 for rank.
  1485. top_ranks = range(1, num_logprobs + 1)
  1486. sampled_logprobs_dict.update({
  1487. top_id: (top_prob, rank)
  1488. for top_id, top_prob, rank in zip(
  1489. top_ids, top_probs, top_ranks)
  1490. })
  1491. sampled_logprobs.append({
  1492. token_id: Logprob(*logprob_and_rank)
  1493. for token_id, logprob_and_rank in
  1494. sampled_logprobs_dict.items()
  1495. })
  1496. # NOTE: This part of code is not intuitive. `selected_logprobs` include
  1497. # logprobs for the current step, which has len(next_token_ids) tokens
  1498. # per sequence group. `logprobs` includes logprobs from the previous
  1499. # steps, which has len(seq_ids) tokens per sequence group.
  1500. # Iterate to the next sequence group in a batch.
  1501. selected_logprobs_idx += len(next_token_ids)
  1502. # Iterate to the next sequence group in a batch.
  1503. top_logprob_idx += len(seq_ids)
  1504. return sampled_logprobs, top_logprob_idx, selected_logprobs_idx
  1505. def _modify_greedy_probs_inplace(logprobs: torch.Tensor, probs: torch.Tensor,
  1506. sample_indices: torch.Tensor,
  1507. greedy_samples: torch.Tensor) -> None:
  1508. """Modify the probability distributions of the greedily-sampled tokens such
  1509. that each sampled token has a "probability" of 1.0. This is required by
  1510. speculative decoding, which depends on the sampling method being encoded
  1511. within the probability distribution for correctness.
  1512. # Why do we only need to do this for greedy sampling?
  1513. Aphrodite's sampler performs the following steps for greedy or multinomial
  1514. (random) sampling:
  1515. 1. Get logits from model.
  1516. 2. Modify logits according to per-sequence sampling parameters.
  1517. - Multiply by temperature, top-k and top-p masking, penalize tokens
  1518. according to their frequency, etc.
  1519. 3. Sample a token.
  1520. - Random sampling simply samples from the modified probability
  1521. distribution.
  1522. - Greedy sampling performs `argmax` to obtain the token with the
  1523. highest likelihood.
  1524. Ignoring greedy sampling for a moment, we find that the computed probability
  1525. distribution has the following property: we can sample from it independently
  1526. and find that the token sampled by the Sampler has a frequency corresponding
  1527. to how often we see it in our sampling. In other words, for tokens sampled
  1528. with Aphrodite's random SamplingType, the computed probability distribution
  1529. encodes the sampling methodology completely.
  1530. Greedy sampling does not normally have this property. Aphrodite modifies
  1531. logits according to sampling params, then performs `argmax`, then returns
  1532. the sampled token and the computed probability distribution. If we sample
  1533. from the distribution, we'll find the likelihood of the greedily-sampled
  1534. token is not always 1.0.
  1535. Since lossless speculative decoding requires that the sampling methodology
  1536. be encoded within the probability distribution, we are motivated to modify
  1537. the probability distribution such that the sampled token has probability 1
  1538. when speculative decoding is used.
  1539. NOTE: Alternatively, we could use an extremely low temperature to achieve
  1540. greedy sampling using multinomial computation and unite the codepaths. This
  1541. has implications on the overall design of the sampler, e.g. how to record
  1542. accurate logprobs for the user, so this improvement is deferred to later.
  1543. """
  1544. # NOTE: logprobs are not modified so they can be returned to the user.
  1545. probs[sample_indices, :] = 0
  1546. probs[sample_indices, greedy_samples] = 1.0
  1547. def _build_sampler_output(
  1548. sample_results: SampleResultType,
  1549. sampling_metadata: SamplingMetadata,
  1550. prompt_logprobs: Optional[List[Optional[PromptLogprobs]]],
  1551. sample_logprobs: Optional[List[SampleLogprobs]],
  1552. on_device_tensors: Optional[Tuple[torch.Tensor, torch.Tensor,
  1553. torch.Tensor]],
  1554. skip_sampler_cpu_output: bool = False,
  1555. ) -> SamplerOutput:
  1556. """Construct Python objects with the output of sampling.
  1557. Args:
  1558. on_device_tensors: Tuple containing on-device tensors with the
  1559. probabilities used in sampling and the sampled token ids. This
  1560. allows post-processing without copies to CPU/serialization, e.g. in
  1561. speculative decoding rejection sampling.
  1562. """
  1563. sampler_output: List[CompletionSequenceGroupOutput] = []
  1564. if not skip_sampler_cpu_output:
  1565. assert prompt_logprobs is not None
  1566. assert sample_logprobs is not None
  1567. for (seq_group, sample_result, group_prompt_logprobs,
  1568. group_sample_logprobs) in zip(sampling_metadata.seq_groups,
  1569. sample_results, prompt_logprobs,
  1570. sample_logprobs):
  1571. seq_ids = seq_group.seq_ids
  1572. next_token_ids, parent_ids = sample_result
  1573. seq_outputs: List[SequenceOutput] = []
  1574. for parent_id, next_token_id, logprobs in zip(
  1575. parent_ids, next_token_ids, group_sample_logprobs):
  1576. seq_outputs.append(
  1577. SequenceOutput(seq_ids[parent_id], next_token_id,
  1578. logprobs))
  1579. sampler_output.append(
  1580. CompletionSequenceGroupOutput(seq_outputs,
  1581. group_prompt_logprobs))
  1582. # If not specified, store None values in SamplerOutput.
  1583. if on_device_tensors is not None:
  1584. (sampled_token_probs, logprobs_tensor,
  1585. sampled_token_ids) = on_device_tensors
  1586. else:
  1587. sampled_token_probs, logprobs_tensor, sampled_token_ids = (None, None,
  1588. None)
  1589. return SamplerOutput(
  1590. outputs=sampler_output,
  1591. sampled_token_probs=sampled_token_probs,
  1592. sampled_token_ids=sampled_token_ids,
  1593. logprobs=logprobs_tensor,
  1594. )
  1595. def _get_next_prompt_tokens(seq_group: SequenceGroupToSample) -> List[str]:
  1596. """Get a list of next prompt tokens to compute logprob from a
  1597. given sequence group.
  1598. It is used to compute prompt logprob. Imagine you have logprob for each
  1599. query token. Query token needs to know the next prompt token id to compute
  1600. prompt logprob. This is a helper to obtain next prompt token ids.
  1601. This API has to be used only when the caller knows seq_group is in prefill
  1602. stage.
  1603. Returns:
  1604. A list of next prompt tokens to compute logprob.
  1605. """
  1606. assert seq_group.is_prompt, (
  1607. "Caller should ensure the sequence group is in a prefill stage.")
  1608. seq_ids = seq_group.seq_ids
  1609. query_len = seq_group.query_len
  1610. assert query_len is not None
  1611. # prompt has only 1 seq id.
  1612. assert len(seq_ids) == 1
  1613. seq_data = seq_group.seq_data[seq_ids[0]]
  1614. computed_len = seq_data.get_num_computed_tokens()
  1615. prompt_tokens = seq_data.prompt_token_ids
  1616. # +1 because we are looking for a next prompt token.
  1617. next_token_index_start = computed_len + 1
  1618. next_token_index_end = min(computed_len + query_len + 1,
  1619. len(prompt_tokens))
  1620. next_prompt_tokens = prompt_tokens[
  1621. next_token_index_start:next_token_index_end]
  1622. return next_prompt_tokens
  1623. def _get_ngrams(
  1624. ngram_size: int,
  1625. prev_input_ids: torch.Tensor
  1626. ) -> Dict[Tuple[int, ...], List[int]]:
  1627. """Get dictionary of ngrams and the tokens that followed them.
  1628. Args:
  1629. ngram_size: Size of ngrams to track
  1630. prev_input_ids: 1D tensor of previous token ids
  1631. Returns:
  1632. Dictionary mapping ngram tuples to list of tokens that followed them
  1633. """
  1634. generated_ngrams = {}
  1635. gen_tokens = prev_input_ids.tolist()
  1636. for i in range(len(gen_tokens) - ngram_size + 1):
  1637. ngram = tuple(gen_tokens[i:i + ngram_size - 1])
  1638. next_token = gen_tokens[i + ngram_size - 1]
  1639. if ngram in generated_ngrams:
  1640. generated_ngrams[ngram].append(next_token)
  1641. else:
  1642. generated_ngrams[ngram] = [next_token]
  1643. return generated_ngrams
  1644. def _get_generated_ngrams(
  1645. banned_ngrams: Dict[Tuple[int, ...], List[int]],
  1646. prev_input_ids: torch.Tensor,
  1647. ngram_size: int,
  1648. cur_len: int
  1649. ) -> List[int]:
  1650. """Get list of tokens that would create a repeated ngram if generated next.
  1651. Args:
  1652. banned_ngrams: Dictionary of previously seen ngrams and their next
  1653. tokens
  1654. prev_input_ids: Previous token ids
  1655. ngram_size: Size of ngrams to check
  1656. cur_len: Current position in sequence
  1657. Returns:
  1658. List of token ids that would create a repeat ngram
  1659. """
  1660. start_idx = cur_len + 1 - ngram_size
  1661. current_ngram = tuple(prev_input_ids[start_idx:cur_len].tolist())
  1662. return banned_ngrams.get(current_ngram, [])
  1663. def _calc_banned_ngram_tokens(
  1664. ngram_size: int,
  1665. prev_input_ids: torch.Tensor,
  1666. cur_len: int
  1667. ) -> List[int]:
  1668. """Calculate tokens that would create repeated ngrams if generated next.
  1669. Args:
  1670. ngram_size: Size of ngrams to prevent repeating
  1671. prev_input_ids: Previous token ids in sequence
  1672. cur_len: Current position in sequence
  1673. Returns:
  1674. List of token ids that should be banned to prevent ngram repetition
  1675. """
  1676. if cur_len + 1 < ngram_size:
  1677. return []
  1678. generated_ngrams = _get_ngrams(ngram_size, prev_input_ids)
  1679. banned_tokens = _get_generated_ngrams(
  1680. generated_ngrams,
  1681. prev_input_ids,
  1682. ngram_size,
  1683. cur_len
  1684. )
  1685. return banned_tokens
  1686. # def _apply_mirostat_v2(logits: torch.Tensor,
  1687. # sampling_tensors: SamplingTensors) -> torch.Tensor:
  1688. # # Reduce our view to just the affected logits
  1689. # logit_view = logits[sampling_tensors.miro_indices]
  1690. # # Calculate surprise value per token
  1691. # # Convert nats to bits for compatibility with ooba/kobold parameters.
  1692. # logit_surprise = torch.log_softmax(logit_view, dim=-1) / -math.log(2)
  1693. # # Mask out "too-surprising" tokens (surprisal > mu)
  1694. # mus = sampling_tensors.miro_mus
  1695. # miro_mask = logit_surprise > mus.unsqueeze(dim=-1)
  1696. # # Unmask most-likely logit to guarantee a selection.
  1697. # maxinds = torch.argmax(logit_view, dim=-1, keepdim=True)
  1698. # miro_mask.scatter_(dim=1, index=maxinds, value=False)
  1699. # # Apply logit mask (effectively a top-k filter).
  1700. # logit_view[miro_mask] = -float("inf")
  1701. # # Project logit changes made to the view onto the original.
  1702. # # I think this step might be redundant.
  1703. # logits[sampling_tensors.miro_indices] = logit_view
  1704. # return logits
  1705. # def _mirostat_store_args(logits: torch.Tensor, args: SamplingTensors,
  1706. # sample_results: List[Tuple[List[int], List[int]]],
  1707. # sampling_metadata: SamplingMetadata,
  1708. # output_metadata: OutputMetadata) -> None:
  1709. # """Based on whichever token was finally sampled, we calculate the
  1710. # final surprisal values to update the mus.
  1711. # Because a single sequence can have multiple samples, we must fork
  1712. # the mu accordingly."""
  1713. # assert sampling_metadata.seq_groups is not None
  1714. # seqid_to_tokens = {}
  1715. # seqid_to_indices = {}
  1716. # for (sids, _), (toks, parents) in zip(sampling_metadata.seq_groups,
  1717. # sample_results):
  1718. # for idx, (token, parent) in enumerate(zip(toks, parents)):
  1719. # seqid_to_tokens.setdefault(sids[parent], []).append(token)
  1720. # seqid_to_indices.setdefault(sids[parent], []).append(idx)
  1721. # seqids = args.miro_seqids
  1722. # picked_tokens = torch.tensor([seqid_to_tokens[x] for x in seqids],
  1723. # device=logits.device,
  1724. # dtype=torch.long)
  1725. # # Clumsily, we recalculate token surprisals.
  1726. # logits_view = logits[args.miro_indices]
  1727. # picked_surprise = torch.gather(torch.log_softmax(logits_view, dim=-1),
  1728. # dim=-1,
  1729. # index=picked_tokens) / -math.log(2)
  1730. # taus = args.miro_taus.unsqueeze(dim=-1) # AKA target surprisals
  1731. # etas = args.miro_etas.unsqueeze(dim=-1) # AKA accumulation rates
  1732. # mus = args.miro_mus.unsqueeze(dim=-1) # AKA surprisal accumulators
  1733. # nu_mus = mus - (picked_surprise - taus) * etas
  1734. # # Record updated mu values for use in the next iteration
  1735. # # Note how each mu is split into multiple based on the number of samples.
  1736. # for seqid, seq_mus in zip(seqids, nu_mus):
  1737. # for sample_idx, mu in zip(seqid_to_indices[seqid], seq_mus):
  1738. # output_metadata.add(seqid, sample_idx, "miro_mu", mu)