sampler.py 85 KB

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