sampler.py 89 KB

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