sampling_metadata.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. import random
  2. from array import array
  3. from dataclasses import dataclass
  4. from typing import Dict, List, Optional, Tuple
  5. import torch
  6. from aphrodite.common.sampling_params import SamplingParams, SamplingType
  7. from aphrodite.common.sequence import SequenceData, SequenceGroupMetadata
  8. from aphrodite.common.utils import (PyObjectCache, async_tensor_h2d,
  9. is_pin_memory_available,
  10. make_tensor_with_pad, maybe_expand_dim)
  11. from aphrodite.constants import APHRODITE_TOKEN_ID_ARRAY_TYPE
  12. from aphrodite.triton_utils.sample import get_num_triton_sampler_splits
  13. _SAMPLING_EPS = 1e-5
  14. _SEED_0_REPLACEMENT = 3403598558
  15. # Some triton sampler related code is guarded before it is ready.
  16. _USE_TRITON_SAMPLER = False
  17. @dataclass
  18. class SequenceGroupToSample:
  19. # |---------- N-1 iteration --------|
  20. # |---------------- N iteration ---------------------|
  21. # |- tokenA -|......................|-- newTokens ---|
  22. # |---------- context_len ----------|
  23. # |-------------------- seq_len ----------------------|
  24. # |-- query_len ---|
  25. # Sequence ids for the sequence group in a previous step.
  26. seq_ids: List[int]
  27. sampling_params: SamplingParams
  28. # seq_id -> sequence data.
  29. seq_data: Dict[int, SequenceData]
  30. # The length of the sequence (all tokens seen in the past + new token to
  31. # compute attention) of the sequence group. None if it is in a decode
  32. # stage.
  33. seq_len: Optional[int]
  34. # The length of new query tokens to compute in the current step. None if it
  35. # is in a decode stage. The length of query_len <= seq_len if chunked
  36. # prefill is enabled.
  37. query_len: Optional[int]
  38. # A random number generator for sampling.
  39. generator: Optional[torch.Generator]
  40. # True if the sequence group is in prefill stage. False if it is in a
  41. # decode stage.
  42. is_prompt: bool
  43. # Query token indices from logits. to compute prompt logprob. Empty if
  44. # prompt logprob is not required.
  45. prompt_logprob_indices: List[int]
  46. # Sample token indices from logits. Empty if sampling is not required.
  47. sample_indices: List[int]
  48. @property
  49. def do_sample(self):
  50. return len(self.sample_indices) > 0
  51. def __post_init__(self):
  52. if len(self.prompt_logprob_indices) > 0:
  53. assert self.sampling_params.prompt_logprobs is not None
  54. if self.is_prompt:
  55. assert self.seq_len is not None
  56. assert self.query_len is not None
  57. def gen_seq_group_to_sample_builder(num_seqs: int):
  58. return lambda: SequenceGroupToSample(
  59. seq_ids=[0] * num_seqs,
  60. sampling_params=None,
  61. seq_data=None, # type: ignore
  62. seq_len=0,
  63. query_len=0,
  64. generator=None,
  65. is_prompt=True,
  66. prompt_logprob_indices=[],
  67. sample_indices=[])
  68. class SamplingMetadataCache:
  69. """Used to cache SamplingMetadata objects between scheduler iterations
  70. """
  71. def __init__(self):
  72. self._seq_group_to_sample_cache: Dict[int, PyObjectCache] = {}
  73. def get_cached_seq_group_to_sample(self, num_seqs):
  74. if num_seqs not in self._seq_group_to_sample_cache:
  75. self._seq_group_to_sample_cache[num_seqs] = PyObjectCache(
  76. gen_seq_group_to_sample_builder(num_seqs))
  77. obj = self._seq_group_to_sample_cache[num_seqs].get_object()
  78. return obj
  79. def reset(self):
  80. for cache in self._seq_group_to_sample_cache.values():
  81. cache.reset()
  82. class SamplingMetadata:
  83. """Metadata for input sequences. Used in sampler.
  84. The usage is as follow;
  85. ```
  86. hidden_states = execute_model(...)
  87. logits = hidden_states[sampling_metadata.selected_token_indices]
  88. sample(logits)
  89. def sample(logits):
  90. # Use categorized_sample_indices for sampling....
  91. ```
  92. Args:
  93. seq_groups: List of batched sequence groups.
  94. selected_token_indices: (num_query_tokens_to_logprob). Indices to find
  95. logits from the initial model output hidden states.
  96. categorized_sample_indices: SamplingType -> token indices to sample.
  97. Each token indices is 2D tensor of (num_indices, num_indices) where
  98. the first item means the sample index within the returned logit
  99. (before pruning padding), and the second item means the sample
  100. index after pruning using selected_token_indices.
  101. For example, if the returned logit is [1, 2, 3], and we select
  102. [1, 2] for sampling, the pruned logit will be [2, 3]. In this case,
  103. The first tuple is [1, 2] (sampled index within original logit),
  104. and the second tuple is [0, 1] (sampled index within pruned logit).
  105. num_prompts: Number of prompt sequence groups in seq_groups.
  106. skip_sampler_cpu_output: Indicates if we want to skip the GPU=>CPU
  107. serialization of token outputs.
  108. reuse_sampling_tensors: Indicates if we want to reuse sampling
  109. tensors that are part of the sampler forward pass. Currently,
  110. it is mainly used for multi-step decode.
  111. """
  112. def __init__(
  113. self,
  114. seq_groups: List[SequenceGroupToSample],
  115. selected_token_indices: torch.Tensor,
  116. categorized_sample_indices: Dict[SamplingType, torch.Tensor],
  117. num_prompts: int,
  118. skip_sampler_cpu_output: bool = False,
  119. reuse_sampling_tensors: bool = False,
  120. ) -> None:
  121. self.seq_groups = seq_groups
  122. self.selected_token_indices = selected_token_indices
  123. self.categorized_sample_indices = categorized_sample_indices
  124. self.num_prompts = num_prompts
  125. self.skip_sampler_cpu_output = skip_sampler_cpu_output
  126. self.reuse_sampling_tensors = reuse_sampling_tensors
  127. @staticmethod
  128. def prepare(
  129. seq_group_metadata_list: List[SequenceGroupMetadata],
  130. seq_lens: List[int],
  131. query_lens: Optional[List[int]],
  132. device: str,
  133. pin_memory: bool,
  134. generators: Optional[Dict[str, torch.Generator]] = None,
  135. cache: Optional[SamplingMetadataCache] = None
  136. ) -> "SamplingMetadata":
  137. (
  138. seq_groups,
  139. selected_token_indices,
  140. categorized_sample_indices,
  141. num_prompts,
  142. ) = _prepare_seq_groups(seq_group_metadata_list, seq_lens, query_lens,
  143. device, generators, cache)
  144. selected_token_indices = async_tensor_h2d(selected_token_indices,
  145. dtype=torch.long,
  146. target_device=device,
  147. pin_memory=pin_memory)
  148. categorized_sample_indices = {
  149. t: maybe_expand_dim(
  150. async_tensor_h2d(seq_ids,
  151. dtype=torch.int,
  152. target_device=device,
  153. pin_memory=pin_memory), 2, 2)
  154. for t, seq_ids in categorized_sample_indices.items()
  155. }
  156. sampling_metadata = SamplingMetadata(
  157. seq_groups=seq_groups,
  158. selected_token_indices=selected_token_indices,
  159. categorized_sample_indices=categorized_sample_indices,
  160. num_prompts=num_prompts,
  161. )
  162. return sampling_metadata
  163. def __repr__(self) -> str:
  164. return (
  165. "SamplingMetadata("
  166. f"seq_groups={self.seq_groups}, "
  167. f"selected_token_indices={self.selected_token_indices}, "
  168. f"categorized_sample_indices={self.categorized_sample_indices}), ")
  169. def _prepare_seq_groups(
  170. seq_group_metadata_list: List[SequenceGroupMetadata],
  171. seq_lens: List[int],
  172. query_lens: Optional[List[int]],
  173. device: str,
  174. generators: Optional[Dict[str, torch.Generator]] = None,
  175. cache: Optional[SamplingMetadataCache] = None,
  176. ) -> Tuple[List[SequenceGroupToSample], List[int], Dict[
  177. SamplingType, List[Tuple[int, int]]], int]:
  178. """Prepare sequence groups and indices for sampling.
  179. Args:
  180. seq_group_metadata_list: A list of sequence group to batch.
  181. seq_lens: A list of sequence lens per sequence group.
  182. Index of prompt len should match with seq_group_metadata_list.
  183. query_lens: A list of query lengths. Prompt lens include the length
  184. of entire prompt tokens, and it could be shorter.
  185. device: A device to use for random number generators,
  186. `SequenceGroupToSample.generator`.
  187. generators: A store of per-request random number generators used
  188. for seeded requests.
  189. Returns:
  190. seq_groups: A list of sequence group to sample.
  191. selected_token_indices: See the definition from `SamplingMetadata`.
  192. categorized_sample_indices: See the definition from `SamplingMetadata`.
  193. num_prompts: Total number of prompts from `seq_group_metadata_list`.
  194. """
  195. # Batched sequence groups for the current model forward stsep.
  196. seq_groups: List[SequenceGroupToSample] = []
  197. # A list of token indices to sample/compute logprob. It is used to
  198. # prune the outcome logits from the model for the performance.
  199. selected_token_indices: List[int] = []
  200. # Used for selected_token_indices.
  201. model_output_idx = 0
  202. # Sampling type -> (
  203. # indices to sample/prompt logprob within pruned output logits,
  204. # indices to sample within pruned logits)
  205. categorized_sample_indices: Dict[SamplingType, List[Tuple[int, int]]] = {
  206. t: []
  207. for t in SamplingType
  208. }
  209. # Index of logits to compute logprob. Logits include both prompt logprob
  210. # and sample logprob indices.
  211. logit_idx = 0
  212. # Index to sample from a sample tensor. It is used by triton sample kernel.
  213. # See `_sample_with_triton_kernel` for more details.
  214. sample_idx = 0
  215. # Total number of prompts from given sequence groups.
  216. num_prompts = 0
  217. for i, seq_group_metadata in enumerate(seq_group_metadata_list):
  218. seq_ids = seq_group_metadata.seq_data.keys()
  219. if cache is not None:
  220. sample_obj = cache.get_cached_seq_group_to_sample(len(seq_ids))
  221. for j, seq_id in enumerate(seq_ids):
  222. sample_obj.seq_ids[j] = seq_id
  223. sample_obj.prompt_logprob_indices.clear()
  224. sample_obj.sample_indices.clear()
  225. sampling_params = seq_group_metadata.sampling_params
  226. is_prompt = seq_group_metadata.is_prompt
  227. generator: Optional[torch.Generator] = None
  228. # If the current seq group is in decode stage, it is None.
  229. seq_len: Optional[int] = None
  230. query_len: Optional[int] = None
  231. prompt_logprob_indices: List[int] = \
  232. sample_obj.prompt_logprob_indices if cache is not None else []
  233. sample_indices: List[int] = \
  234. sample_obj.sample_indices if cache is not None else []
  235. do_sample = seq_group_metadata.do_sample
  236. if seq_group_metadata.is_prompt:
  237. if sampling_params.seed is not None:
  238. generator = torch.Generator(device=device).manual_seed(
  239. sampling_params.seed)
  240. if generators is not None:
  241. generators[seq_group_metadata.request_id] = generator
  242. num_prompts += 1
  243. num_prefill_sample = len(seq_ids)
  244. assert num_prefill_sample == 1
  245. assert query_lens is not None and seq_lens is not None
  246. query_len, seq_len = query_lens[i], seq_lens[i]
  247. # If we need sampling, exclude num_prefill_sample tokens from
  248. # prompt logprob.
  249. prompt_logprob_len = (query_len - num_prefill_sample
  250. if do_sample else query_len)
  251. sample_len = num_prefill_sample if do_sample else 0
  252. else:
  253. # Decode
  254. prompt_logprob_len = 0
  255. sample_len = len(seq_ids) if do_sample else 0
  256. if sampling_params.seed is not None and generators is not None:
  257. generator = generators.get(seq_group_metadata.request_id)
  258. # Update indices to select from the model output.
  259. """
  260. This blocks computes selected_token_indices which is used in the
  261. following way.
  262. hidden_states = model(...)
  263. logits = hidden_states[selected_token_indices]
  264. """
  265. if sampling_params.prompt_logprobs is not None:
  266. selected_token_indices.extend(
  267. range(model_output_idx, model_output_idx + prompt_logprob_len))
  268. model_output_idx += prompt_logprob_len
  269. if do_sample:
  270. selected_token_indices.extend(
  271. range(model_output_idx, model_output_idx + sample_len))
  272. model_output_idx += sample_len
  273. # We now find indices for logprob computation and sampling.
  274. """
  275. This block computes categorized_sample_indices which is used in the
  276. following way.
  277. hidden_states = model(...)
  278. logits = hidden_states[selected_token_indices]
  279. def sample(logits):
  280. # Use categorized_sample_indices for sampling.
  281. # prompt_logprob_indices to find prompt logprob indices.
  282. # sample_indices to find sample indices.
  283. """
  284. if sampling_params.prompt_logprobs is not None:
  285. prompt_logprob_indices.extend(
  286. range(logit_idx, logit_idx + prompt_logprob_len))
  287. logit_idx += prompt_logprob_len
  288. if do_sample:
  289. sample_indices.extend(range(logit_idx, logit_idx + sample_len))
  290. categorized_sample_indices[sampling_params.sampling_type].extend(
  291. list(
  292. zip(range(logit_idx, logit_idx + sample_len),
  293. range(sample_idx, sample_idx + sample_len))))
  294. logit_idx += sample_len
  295. sample_idx += sample_len
  296. if cache is not None:
  297. sample_obj.sampling_params = sampling_params
  298. sample_obj.seq_data = seq_group_metadata.seq_data
  299. sample_obj.seq_len = seq_len
  300. sample_obj.query_len = query_len
  301. sample_obj.generator = generator
  302. sample_obj.is_prompt = is_prompt
  303. else:
  304. sample_obj = SequenceGroupToSample(
  305. seq_ids=list(seq_ids),
  306. sampling_params=sampling_params,
  307. seq_data=seq_group_metadata.seq_data,
  308. seq_len=seq_len,
  309. query_len=query_len,
  310. generator=generator,
  311. is_prompt=is_prompt,
  312. prompt_logprob_indices=list(prompt_logprob_indices),
  313. sample_indices=list(sample_indices))
  314. seq_groups.append(sample_obj)
  315. if cache is not None:
  316. cache.reset()
  317. return (seq_groups, selected_token_indices, categorized_sample_indices,
  318. num_prompts)
  319. @dataclass
  320. class SamplingTensors:
  321. """Tensors for sampling."""
  322. temperatures: torch.Tensor
  323. dynatemp_mins: torch.Tensor
  324. dynatemp_maxs: torch.Tensor
  325. dynatemp_exps: torch.Tensor
  326. temperature_lasts: torch.Tensor
  327. top_ps: torch.Tensor
  328. top_ks: torch.Tensor
  329. top_as: torch.Tensor
  330. min_ps: torch.Tensor
  331. presence_penalties: torch.Tensor
  332. frequency_penalties: torch.Tensor
  333. repetition_penalties: torch.Tensor
  334. no_repeat_ngram_sizes: torch.Tensor
  335. tfss: torch.Tensor
  336. eta_cutoffs: torch.Tensor
  337. epsilon_cutoffs: torch.Tensor
  338. typical_ps: torch.Tensor
  339. smoothing_factors: torch.Tensor
  340. smoothing_curves: torch.Tensor
  341. xtc_thresholds: torch.Tensor
  342. xtc_probabilities: torch.Tensor
  343. nsigmas: torch.Tensor
  344. dry_multipliers: torch.Tensor
  345. dry_bases: torch.Tensor
  346. dry_allowed_lengths: torch.Tensor
  347. dry_sequence_breaker_ids: torch.Tensor
  348. dry_ranges: torch.Tensor
  349. skews: torch.Tensor
  350. sampling_seeds: torch.Tensor
  351. sample_indices: torch.Tensor
  352. extra_seeds: Optional[torch.Tensor]
  353. prompt_tokens: torch.Tensor
  354. output_tokens: torch.Tensor
  355. @classmethod
  356. def from_sampling_metadata(
  357. cls,
  358. sampling_metadata: "SamplingMetadata",
  359. vocab_size: int,
  360. device: torch.device,
  361. dtype: torch.dtype,
  362. *,
  363. extra_seeds_to_generate: int = 0,
  364. extra_entropy: Optional[Tuple[int, ...]] = None
  365. ) -> Tuple["SamplingTensors", bool, bool, bool, bool, bool, bool, bool,
  366. bool, bool, bool, bool, bool, bool, bool, bool, bool]:
  367. """
  368. extra_seeds_to_generate: extra seeds to generate using the
  369. user-defined seed for each sequence.
  370. extra_entropy: extra entropy to use when generating seeds.
  371. """
  372. prompt_tokens: List[array] = []
  373. output_tokens: List[array] = []
  374. top_ks: List[int] = []
  375. temperatures: List[float] = []
  376. dynatemp_mins: List[float] = []
  377. dynatemp_maxs: List[float] = []
  378. dynatemp_exps: List[float] = []
  379. temperature_lasts: List[bool] = []
  380. top_ps: List[float] = []
  381. top_as: List[float] = []
  382. min_ps: List[float] = []
  383. presence_penalties: List[float] = []
  384. frequency_penalties: List[float] = []
  385. repetition_penalties: List[float] = []
  386. no_repeat_ngram_sizes: List[int] = []
  387. tfss: List[float] = []
  388. eta_cutoffs: List[float] = []
  389. epsilon_cutoffs: List[float] = []
  390. typical_ps: List[float] = []
  391. smoothing_factors: List[float] = []
  392. smoothing_curves: List[float] = []
  393. xtc_thresholds: List[float] = []
  394. xtc_probabilities: List[float] = []
  395. nsigmas: List[float] = []
  396. sampling_seeds: List[List[int]] = []
  397. sample_indices: List[int] = []
  398. dry_multipliers: List[float] = []
  399. dry_bases: List[float] = []
  400. dry_allowed_lengths: List[int] = []
  401. dry_sequence_breaker_ids: List[List[int]] = []
  402. dry_ranges: List[int] = []
  403. skews: List[float] = []
  404. do_penalties = False
  405. do_no_repeat_ngrams = False
  406. do_temperatures = False
  407. do_top_p_top_k = False
  408. do_top_as = False
  409. do_min_p = False
  410. do_tfss = False
  411. do_eta_cutoffs = False
  412. do_epsilon_cutoffs = False
  413. do_typical_ps = False
  414. do_quadratic = False
  415. do_xtc = False
  416. do_nsigmas = False
  417. do_dry = False
  418. do_skews = False
  419. do_temp_last = False
  420. if _USE_TRITON_SAMPLER:
  421. prompt_best_of: List[int] = []
  422. # We need one base seed per Triton slice.
  423. seeds_to_generate = (extra_seeds_to_generate +
  424. get_num_triton_sampler_splits(vocab_size))
  425. assert sampling_metadata.seq_groups is not None
  426. for seq_group in sampling_metadata.seq_groups:
  427. seq_ids = seq_group.seq_ids
  428. params = seq_group.sampling_params
  429. # k should not be greater than the vocab size.
  430. top_k = min(params.top_k, vocab_size)
  431. top_k = vocab_size if top_k == -1 else top_k
  432. temperature = params.temperature
  433. if temperature < _SAMPLING_EPS:
  434. # NOTE: Zero temperature means deterministic sampling
  435. # (i.e., greedy sampling or beam search).
  436. # Set the temperature to 1 to avoid division by zero.
  437. temperature = 1.0
  438. do_temperatures |= (temperature != 1.0 or
  439. params.dynatemp_min > _SAMPLING_EPS or
  440. params.dynatemp_max > _SAMPLING_EPS)
  441. do_top_p_top_k |= (params.top_p < 1.0 - _SAMPLING_EPS or
  442. top_k != vocab_size)
  443. do_top_as |= params.top_a > 0.0
  444. do_min_p |= params.min_p > _SAMPLING_EPS
  445. do_penalties |= (abs(params.presence_penalty) >= _SAMPLING_EPS or
  446. abs(params.frequency_penalty) >= _SAMPLING_EPS or
  447. params.repetition_penalty > 1.0)
  448. do_no_repeat_ngrams |= params.no_repeat_ngram_size > 0
  449. do_tfss |= params.tfs < 1.0 - _SAMPLING_EPS
  450. do_eta_cutoffs |= params.eta_cutoff > _SAMPLING_EPS
  451. do_epsilon_cutoffs |= params.epsilon_cutoff > _SAMPLING_EPS
  452. do_typical_ps |= params.typical_p < 1.0 - _SAMPLING_EPS
  453. do_quadratic |= (params.smoothing_factor > _SAMPLING_EPS or
  454. params.smoothing_curve > 1.0)
  455. do_xtc |= params.xtc_probability > _SAMPLING_EPS
  456. do_nsigmas |= params.nsigma > _SAMPLING_EPS
  457. do_dry |= params.dry_multiplier > _SAMPLING_EPS
  458. do_skews |= abs(params.skew) > _SAMPLING_EPS
  459. do_temp_last |= params.temperature_last
  460. is_prompt = seq_group.is_prompt
  461. wants_prompt_logprobs = params.prompt_logprobs is not None
  462. n_seqs = 0
  463. if seq_group.is_prompt and wants_prompt_logprobs:
  464. assert seq_group.query_len is not None
  465. n_seqs += len(seq_group.prompt_logprob_indices)
  466. if seq_group.do_sample:
  467. assert len(seq_group.sample_indices) == len(seq_ids)
  468. n_seqs += len(seq_ids)
  469. temperatures += [temperature] * n_seqs
  470. dynatemp_mins += [params.dynatemp_min] * n_seqs
  471. dynatemp_maxs += [params.dynatemp_max] * n_seqs
  472. dynatemp_exps += [params.dynatemp_exponent] * n_seqs
  473. temperature_lasts += [params.temperature_last] * n_seqs
  474. top_ps += [params.top_p] * n_seqs
  475. top_ks += [top_k] * n_seqs
  476. top_as += [params.top_a] * n_seqs
  477. min_ps += [params.min_p] * n_seqs
  478. presence_penalties += [params.presence_penalty] * n_seqs
  479. frequency_penalties += [params.frequency_penalty] * n_seqs
  480. repetition_penalties += [params.repetition_penalty] * n_seqs
  481. no_repeat_ngram_sizes += [params.no_repeat_ngram_size] * n_seqs
  482. tfss += [params.tfs] * n_seqs
  483. eta_cutoffs += [params.eta_cutoff] * n_seqs
  484. epsilon_cutoffs += [params.epsilon_cutoff] * n_seqs
  485. typical_ps += [params.typical_p] * n_seqs
  486. smoothing_factors += [params.smoothing_factor] * n_seqs
  487. smoothing_curves += [params.smoothing_curve] * n_seqs
  488. xtc_thresholds += [params.xtc_threshold] * n_seqs
  489. xtc_probabilities += [params.xtc_probability] * n_seqs
  490. nsigmas += [params.nsigma] * n_seqs
  491. dry_multipliers += [params.dry_multiplier] * n_seqs
  492. dry_bases += [params.dry_base] * n_seqs
  493. dry_allowed_lengths += [params.dry_allowed_length] * n_seqs
  494. dry_sequence_breaker_ids += (
  495. [params.dry_sequence_breaker_ids] * n_seqs)
  496. dry_ranges += [params.dry_range] * n_seqs
  497. skews += [params.skew] * n_seqs
  498. if _USE_TRITON_SAMPLER:
  499. if is_prompt:
  500. prompt_best_of.append(params.best_of)
  501. query_len = seq_group.query_len
  502. assert query_len is not None
  503. seed = params.seed
  504. is_greedy = params.sampling_type == SamplingType.GREEDY
  505. for seq_id in seq_ids:
  506. seq_data = seq_group.seq_data[seq_id]
  507. extra_entropy = extra_entropy or ()
  508. seq_seeds = cls._get_sequence_seeds(
  509. seed,
  510. seq_data.get_len(),
  511. *extra_entropy,
  512. seq_id,
  513. seeds_to_generate=seeds_to_generate,
  514. is_greedy=is_greedy)
  515. sampling_seeds.append(seq_seeds)
  516. sample_indices.extend(seq_group.sample_indices)
  517. if do_penalties or do_dry or do_no_repeat_ngrams:
  518. for seq_group in sampling_metadata.seq_groups:
  519. seq_ids = seq_group.seq_ids
  520. if (seq_group.is_prompt
  521. and params.prompt_logprobs is not None):
  522. prefill_len = len(seq_group.prompt_logprob_indices)
  523. prompt_tokens.extend(
  524. array(APHRODITE_TOKEN_ID_ARRAY_TYPE)
  525. for _ in range(prefill_len))
  526. output_tokens.extend(
  527. array(APHRODITE_TOKEN_ID_ARRAY_TYPE)
  528. for _ in range(prefill_len))
  529. if seq_group.do_sample:
  530. for seq_id in seq_ids:
  531. seq_data = seq_group.seq_data[seq_id]
  532. prompt_tokens.append(seq_data.prompt_token_ids_array)
  533. output_tokens.append(seq_data.output_token_ids_array)
  534. sampling_tensors = SamplingTensors.from_lists(
  535. temperatures, dynatemp_mins, dynatemp_maxs, dynatemp_exps,
  536. temperature_lasts, top_ps, top_ks, top_as, min_ps,
  537. presence_penalties, frequency_penalties, repetition_penalties,
  538. no_repeat_ngram_sizes, tfss, eta_cutoffs, epsilon_cutoffs,
  539. typical_ps, smoothing_factors, smoothing_curves, xtc_thresholds,
  540. xtc_probabilities, nsigmas, dry_multipliers, dry_bases,
  541. dry_allowed_lengths, dry_sequence_breaker_ids, dry_ranges, skews,
  542. sampling_seeds, sample_indices, prompt_tokens, output_tokens,
  543. vocab_size, extra_seeds_to_generate, device, dtype)
  544. return (sampling_tensors, do_penalties, do_no_repeat_ngrams,
  545. do_temperatures, do_top_p_top_k, do_top_as, do_min_p,
  546. do_tfss, do_eta_cutoffs, do_epsilon_cutoffs, do_typical_ps,
  547. do_quadratic, do_xtc, do_nsigmas, do_dry, do_skews,
  548. do_temp_last)
  549. @classmethod
  550. def from_lists(cls, temperatures: List[float], dynatemp_mins: List[float],
  551. dynatemp_maxs: List[float], dynatemp_exps: List[float],
  552. temperature_lasts: List[bool], top_ps: List[float],
  553. top_ks: List[int], top_as: List[float],
  554. min_ps: List[float], presence_penalties: List[float],
  555. frequency_penalties: List[float],
  556. repetition_penalties: List[float],
  557. no_repeat_ngram_sizes: List[int], tfss: List[float],
  558. eta_cutoffs: List[float], epsilon_cutoffs: List[float],
  559. typical_ps: List[float], smoothing_factors: List[float],
  560. smoothing_curves: List[float], xtc_thresholds: List[float],
  561. xtc_probabilities: List[float], nsigmas: List[float],
  562. dry_multipliers: List[float], dry_bases: List[float],
  563. dry_allowed_lengths: List[int],
  564. dry_sequence_breaker_ids: List[List[int]],
  565. dry_ranges: List[int], skews: List[float],
  566. sampling_seeds: List[List[int]],
  567. sample_indices: List[int], prompt_tokens: List[array],
  568. output_tokens: List[array], vocab_size: int,
  569. extra_seeds_to_generate: int, device: torch.device,
  570. dtype: torch.dtype) -> "SamplingTensors":
  571. # Note that the performance will be very bad without
  572. # pinned memory.
  573. pin_memory = is_pin_memory_available()
  574. do_penalties = prompt_tokens or output_tokens
  575. if do_penalties:
  576. prompt_t = make_tensor_with_pad(
  577. prompt_tokens,
  578. vocab_size,
  579. device="cpu",
  580. dtype=torch.int64,
  581. pin_memory=pin_memory,
  582. )
  583. output_t = make_tensor_with_pad(
  584. output_tokens,
  585. vocab_size,
  586. device="cpu",
  587. dtype=torch.int64,
  588. pin_memory=pin_memory,
  589. )
  590. else:
  591. empty_tensor = torch.empty(0, device=device, dtype=torch.long)
  592. prompt_t = empty_tensor
  593. output_t = empty_tensor
  594. temperatures_t = torch.tensor(
  595. temperatures,
  596. device="cpu",
  597. dtype=dtype,
  598. pin_memory=pin_memory,
  599. )
  600. dynatemp_mins_t = torch.tensor(
  601. dynatemp_mins,
  602. device="cpu",
  603. dtype=dtype,
  604. pin_memory=pin_memory,
  605. )
  606. dynatemp_maxs_t = torch.tensor(
  607. dynatemp_maxs,
  608. device="cpu",
  609. dtype=dtype,
  610. pin_memory=pin_memory,
  611. )
  612. dynatemp_exps_t = torch.tensor(
  613. dynatemp_exps,
  614. device="cpu",
  615. dtype=dtype,
  616. pin_memory=pin_memory,
  617. )
  618. temp_lasts_t = torch.tensor(
  619. temperature_lasts,
  620. device="cpu",
  621. dtype=torch.bool,
  622. pin_memory=pin_memory,
  623. )
  624. top_ps_t = torch.tensor(
  625. top_ps,
  626. device="cpu",
  627. dtype=dtype,
  628. pin_memory=pin_memory,
  629. )
  630. top_as_t = torch.tensor(top_as,
  631. device="cpu",
  632. dtype=dtype,
  633. pin_memory=pin_memory)
  634. min_ps_t = torch.tensor(
  635. min_ps,
  636. device="cpu",
  637. dtype=dtype,
  638. pin_memory=pin_memory,
  639. )
  640. presence_penalties_t = torch.tensor(
  641. presence_penalties,
  642. device="cpu",
  643. dtype=dtype,
  644. pin_memory=pin_memory,
  645. )
  646. frequency_penalties_t = torch.tensor(
  647. frequency_penalties,
  648. device="cpu",
  649. dtype=dtype,
  650. pin_memory=pin_memory,
  651. )
  652. repetition_penalties_t = torch.tensor(
  653. repetition_penalties,
  654. device="cpu",
  655. dtype=dtype,
  656. pin_memory=pin_memory,
  657. )
  658. no_repeat_ngram_sizes_t = torch.tensor(
  659. no_repeat_ngram_sizes,
  660. device="cpu",
  661. dtype=torch.int,
  662. pin_memory=pin_memory,
  663. )
  664. top_ks_t = torch.tensor(
  665. top_ks,
  666. device="cpu",
  667. dtype=torch.int,
  668. pin_memory=pin_memory,
  669. )
  670. tfss_t = torch.tensor(tfss,
  671. device="cpu",
  672. dtype=dtype,
  673. pin_memory=pin_memory)
  674. eta_cutoffs_t = torch.tensor(eta_cutoffs,
  675. device="cpu",
  676. dtype=dtype,
  677. pin_memory=pin_memory)
  678. epsilon_cutoffs_t = torch.tensor(epsilon_cutoffs,
  679. device="cpu",
  680. dtype=dtype,
  681. pin_memory=pin_memory)
  682. typical_ps_t = torch.tensor(typical_ps,
  683. device="cpu",
  684. dtype=dtype,
  685. pin_memory=pin_memory)
  686. smoothing_factors_t = torch.tensor(smoothing_factors,
  687. device="cpu",
  688. dtype=dtype,
  689. pin_memory=pin_memory)
  690. smoothing_curves_t = torch.tensor(smoothing_curves,
  691. device="cpu",
  692. dtype=dtype,
  693. pin_memory=pin_memory)
  694. xtc_thresholds_t = torch.tensor(xtc_thresholds,
  695. device="cpu",
  696. dtype=dtype,
  697. pin_memory=pin_memory)
  698. xtc_probabilities_t = torch.tensor(xtc_probabilities,
  699. device="cpu",
  700. dtype=dtype,
  701. pin_memory=pin_memory)
  702. nsigmas_t = torch.tensor(nsigmas,
  703. device="cpu",
  704. dtype=dtype,
  705. pin_memory=pin_memory)
  706. dry_multipliers_t = torch.tensor(
  707. dry_multipliers,
  708. device="cpu",
  709. dtype=dtype,
  710. pin_memory=pin_memory,
  711. )
  712. dry_bases_t = torch.tensor(
  713. dry_bases,
  714. device="cpu",
  715. dtype=dtype,
  716. pin_memory=pin_memory,
  717. )
  718. dry_allowed_lengths_t = torch.tensor(
  719. dry_allowed_lengths,
  720. device="cpu",
  721. dtype=torch.int,
  722. pin_memory=pin_memory,
  723. )
  724. dry_sequence_breakers_t = torch.tensor(
  725. [seq + [0] * (max(len(s) for s in
  726. dry_sequence_breaker_ids) - len(seq))
  727. for seq in dry_sequence_breaker_ids],
  728. device="cpu",
  729. dtype=torch.long,
  730. pin_memory=pin_memory,
  731. )
  732. dry_ranges_t = torch.tensor(
  733. dry_ranges,
  734. device="cpu",
  735. dtype=torch.int,
  736. pin_memory=pin_memory,
  737. )
  738. skews_t = torch.tensor(
  739. skews,
  740. device="cpu",
  741. dtype=dtype,
  742. pin_memory=pin_memory,
  743. )
  744. sample_indices_t = torch.tensor(
  745. sample_indices,
  746. device="cpu",
  747. dtype=torch.long,
  748. pin_memory=pin_memory,
  749. )
  750. # need to transpose and make contiguous to
  751. # copy the tensor correctly.
  752. # [batch_size, n_seeds] -> [n_seeds, batch_size]
  753. sampling_seeds_t = torch.tensor(
  754. sampling_seeds,
  755. device="cpu",
  756. dtype=torch.long,
  757. pin_memory=pin_memory,
  758. ).t().contiguous()
  759. # Because the memory is pinned, we can do non-blocking
  760. # transfer to device.
  761. # How many seeds the sample operation itself will need.
  762. num_base_seeds = sampling_seeds_t.shape[0] - extra_seeds_to_generate
  763. sampling_seeds_gpu = sampling_seeds_t.to(device=device,
  764. non_blocking=True)
  765. extra_seeds_gpu = sampling_seeds_gpu[num_base_seeds:]
  766. if not extra_seeds_gpu.numel():
  767. extra_seeds_gpu = None
  768. sampling_seeds_gpu = sampling_seeds_gpu[:num_base_seeds]
  769. return cls(
  770. temperatures=temperatures_t.to(device=device, non_blocking=True),
  771. dynatemp_mins=dynatemp_mins_t.to(device=device, non_blocking=True),
  772. dynatemp_maxs=dynatemp_maxs_t.to(device=device, non_blocking=True),
  773. dynatemp_exps=dynatemp_exps_t.to(device=device, non_blocking=True),
  774. temperature_lasts=temp_lasts_t.to(device=device, non_blocking=True),
  775. top_ps=top_ps_t.to(device=device, non_blocking=True),
  776. top_ks=top_ks_t.to(device=device, non_blocking=True),
  777. top_as=top_as_t.to(device=device, non_blocking=True),
  778. min_ps=min_ps_t.to(device=device, non_blocking=True),
  779. presence_penalties=presence_penalties_t.to(device=device,
  780. non_blocking=True),
  781. frequency_penalties=frequency_penalties_t.to(device=device,
  782. non_blocking=True),
  783. repetition_penalties=repetition_penalties_t.to(device=device,
  784. non_blocking=True),
  785. no_repeat_ngram_sizes=no_repeat_ngram_sizes_t.to(device=device,
  786. non_blocking=True),
  787. tfss=tfss_t.to(device=device, non_blocking=True),
  788. eta_cutoffs=eta_cutoffs_t.to(device=device, non_blocking=True),
  789. epsilon_cutoffs=epsilon_cutoffs_t.to(device=device,
  790. non_blocking=True),
  791. smoothing_factors=smoothing_factors_t.to(device=device,
  792. non_blocking=True),
  793. smoothing_curves=smoothing_curves_t.to(device=device,
  794. non_blocking=True),
  795. xtc_thresholds=xtc_thresholds_t.to(device=device,
  796. non_blocking=True),
  797. xtc_probabilities=xtc_probabilities_t.to(device=device,
  798. non_blocking=True),
  799. nsigmas=nsigmas_t.to(device=device, non_blocking=True),
  800. dry_multipliers=dry_multipliers_t.to(device=device,
  801. non_blocking=True),
  802. dry_bases=dry_bases_t.to(device=device, non_blocking=True),
  803. dry_allowed_lengths=dry_allowed_lengths_t.to(device=device,
  804. non_blocking=True),
  805. dry_sequence_breaker_ids=dry_sequence_breakers_t.to(device=device,
  806. non_blocking=True),
  807. dry_ranges=dry_ranges_t.to(device=device, non_blocking=True),
  808. skews=skews_t.to(device=device, non_blocking=True),
  809. typical_ps=typical_ps_t.to(device=device, non_blocking=True),
  810. prompt_tokens=prompt_t.to(device=device, non_blocking=True),
  811. output_tokens=output_t.to(device=device, non_blocking=True),
  812. sampling_seeds=sampling_seeds_gpu,
  813. sample_indices=sample_indices_t.to(device=device,
  814. non_blocking=True),
  815. extra_seeds=extra_seeds_gpu,
  816. )
  817. @staticmethod
  818. def _get_sequence_seeds(
  819. seed: int|None,
  820. *extra_entropy: int,
  821. seeds_to_generate: int,
  822. is_greedy: bool,
  823. ):
  824. """Get `seeds_to_generate` child seeds from `seed` and extra entropy."""
  825. if not is_greedy:
  826. if seed is None:
  827. randint_fn = random.randint
  828. else:
  829. generator = random.Random(str((seed, ) + extra_entropy))
  830. randint_fn = generator.randint
  831. lo, hi = torch.iinfo(torch.long).min, torch.iinfo(torch.long).max
  832. # If the user/random sets seed = 0 but request should
  833. # have sampling, we need to change it to something
  834. # else. We use a constant in that case.
  835. # This way we don't need to create and load a bool
  836. # matrix in the sampling kernel, which reduces CPU
  837. # overhead and latency.
  838. seq_seeds = [
  839. randint_fn(lo, hi) or _SEED_0_REPLACEMENT
  840. for _ in range(seeds_to_generate)
  841. ]
  842. else:
  843. # For the kernel, seed == 0 means greedy decoding.
  844. seq_seeds = [0] * seeds_to_generate
  845. return seq_seeds