sampling_metadata.py 36 KB

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