sampler.py 81 KB

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