sampling_metadata.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  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. sampling_params = seq_group_metadata.sampling_params
  225. is_prompt = seq_group_metadata.is_prompt
  226. generator: Optional[torch.Generator] = None
  227. # If the current seq group is in decode stage, it is None.
  228. seq_len: Optional[int] = None
  229. query_len: Optional[int] = None
  230. prompt_logprob_indices: List[int] = \
  231. sample_obj.prompt_logprob_indices if cache is not None else []
  232. sample_indices: List[int] = \
  233. sample_obj.sample_indices if cache is not None else []
  234. do_sample = seq_group_metadata.do_sample
  235. if seq_group_metadata.is_prompt:
  236. if sampling_params.seed is not None:
  237. generator = torch.Generator(device=device).manual_seed(
  238. sampling_params.seed)
  239. if generators is not None:
  240. generators[seq_group_metadata.request_id] = generator
  241. num_prompts += 1
  242. num_prefill_sample = len(seq_ids)
  243. assert num_prefill_sample == 1
  244. assert query_lens is not None and seq_lens is not None
  245. query_len, seq_len = query_lens[i], seq_lens[i]
  246. # If we need sampling, exclude num_prefill_sample tokens from
  247. # prompt logprob.
  248. prompt_logprob_len = (query_len - num_prefill_sample
  249. if do_sample else query_len)
  250. sample_len = num_prefill_sample if do_sample else 0
  251. else:
  252. # Decode
  253. prompt_logprob_len = 0
  254. sample_len = len(seq_ids) if do_sample else 0
  255. if sampling_params.seed is not None and generators is not None:
  256. generator = generators.get(seq_group_metadata.request_id)
  257. # Update indices to select from the model output.
  258. """
  259. This blocks computes selected_token_indices which is used in the
  260. following way.
  261. hidden_states = model(...)
  262. logits = hidden_states[selected_token_indices]
  263. """
  264. if sampling_params.prompt_logprobs is not None:
  265. selected_token_indices.extend(
  266. range(model_output_idx, model_output_idx + prompt_logprob_len))
  267. model_output_idx += prompt_logprob_len
  268. if do_sample:
  269. selected_token_indices.extend(
  270. range(model_output_idx, model_output_idx + sample_len))
  271. model_output_idx += sample_len
  272. # We now find indices for logprob computation and sampling.
  273. """
  274. This block computes categorized_sample_indices which is used in the
  275. following way.
  276. hidden_states = model(...)
  277. logits = hidden_states[selected_token_indices]
  278. def sample(logits):
  279. # Use categorized_sample_indices for sampling.
  280. # prompt_logprob_indices to find prompt logprob indices.
  281. # sample_indices to find sample indices.
  282. """
  283. if sampling_params.prompt_logprobs is not None:
  284. prompt_logprob_indices.extend(
  285. range(logit_idx, logit_idx + prompt_logprob_len))
  286. logit_idx += prompt_logprob_len
  287. if do_sample:
  288. sample_indices.extend(range(logit_idx, logit_idx + sample_len))
  289. categorized_sample_indices[sampling_params.sampling_type].extend(
  290. list(
  291. zip(range(logit_idx, logit_idx + sample_len),
  292. range(sample_idx, sample_idx + sample_len))))
  293. logit_idx += sample_len
  294. sample_idx += sample_len
  295. if cache is not None:
  296. sample_obj.sampling_params = sampling_params
  297. sample_obj.seq_data = seq_group_metadata.seq_data
  298. sample_obj.seq_len = seq_len
  299. sample_obj.query_len = query_len
  300. sample_obj.generator = generator
  301. sample_obj.is_prompt = is_prompt
  302. else:
  303. sample_obj = SequenceGroupToSample(
  304. seq_ids=list(seq_ids),
  305. sampling_params=sampling_params,
  306. seq_data=seq_group_metadata.seq_data,
  307. seq_len=seq_len,
  308. query_len=query_len,
  309. generator=generator,
  310. is_prompt=is_prompt,
  311. prompt_logprob_indices=list(prompt_logprob_indices),
  312. sample_indices=list(sample_indices))
  313. seq_groups.append(sample_obj)
  314. if cache is not None:
  315. cache.reset()
  316. return (seq_groups, selected_token_indices, categorized_sample_indices,
  317. num_prompts)
  318. @dataclass
  319. class SamplingTensors:
  320. """Tensors for sampling."""
  321. temperatures: torch.Tensor
  322. dynatemp_mins: torch.Tensor
  323. dynatemp_maxs: torch.Tensor
  324. dynatemp_exps: torch.Tensor
  325. temperature_lasts: torch.Tensor
  326. top_ps: torch.Tensor
  327. top_ks: torch.Tensor
  328. top_as: torch.Tensor
  329. min_ps: torch.Tensor
  330. presence_penalties: torch.Tensor
  331. frequency_penalties: torch.Tensor
  332. repetition_penalties: torch.Tensor
  333. tfss: torch.Tensor
  334. eta_cutoffs: torch.Tensor
  335. epsilon_cutoffs: torch.Tensor
  336. typical_ps: torch.Tensor
  337. smoothing_factors: torch.Tensor
  338. smoothing_curves: torch.Tensor
  339. xtc_thresholds: torch.Tensor
  340. xtc_probabilities: torch.Tensor
  341. sampling_seeds: torch.Tensor
  342. sample_indices: torch.Tensor
  343. extra_seeds: Optional[torch.Tensor]
  344. prompt_tokens: torch.Tensor
  345. output_tokens: torch.Tensor
  346. @classmethod
  347. def from_sampling_metadata(
  348. cls,
  349. sampling_metadata: "SamplingMetadata",
  350. vocab_size: int,
  351. device: torch.device,
  352. dtype: torch.dtype,
  353. *,
  354. extra_seeds_to_generate: int = 0,
  355. extra_entropy: Optional[Tuple[int, ...]] = None
  356. ) -> Tuple["SamplingTensors", bool, bool, bool, bool, bool, bool, bool,
  357. bool, bool, bool, bool, bool]:
  358. """
  359. extra_seeds_to_generate: extra seeds to generate using the
  360. user-defined seed for each sequence.
  361. extra_entropy: extra entropy to use when generating seeds.
  362. """
  363. prompt_tokens: List[array] = []
  364. output_tokens: List[array] = []
  365. top_ks: List[int] = []
  366. temperatures: List[float] = []
  367. dynatemp_mins: List[float] = []
  368. dynatemp_maxs: List[float] = []
  369. dynatemp_exps: List[float] = []
  370. temperature_lasts: List[bool] = []
  371. top_ps: List[float] = []
  372. top_as: List[float] = []
  373. min_ps: List[float] = []
  374. presence_penalties: List[float] = []
  375. frequency_penalties: List[float] = []
  376. repetition_penalties: List[float] = []
  377. tfss: List[float] = []
  378. eta_cutoffs: List[float] = []
  379. epsilon_cutoffs: List[float] = []
  380. typical_ps: List[float] = []
  381. smoothing_factors: List[float] = []
  382. smoothing_curves: List[float] = []
  383. xtc_thresholds: List[float] = []
  384. xtc_probabilities: List[float] = []
  385. sampling_seeds: List[List[int]] = []
  386. sample_indices: List[int] = []
  387. do_penalties = False
  388. do_temperatures = 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_xtc = False
  398. do_temp_last = False
  399. if _USE_TRITON_SAMPLER:
  400. prompt_best_of: List[int] = []
  401. # We need one base seed per Triton slice.
  402. seeds_to_generate = (extra_seeds_to_generate +
  403. get_num_triton_sampler_splits(vocab_size))
  404. assert sampling_metadata.seq_groups is not None
  405. for seq_group in sampling_metadata.seq_groups:
  406. seq_ids = seq_group.seq_ids
  407. params = seq_group.sampling_params
  408. # k should not be greater than the vocab size.
  409. top_k = min(params.top_k, vocab_size)
  410. top_k = vocab_size if top_k == -1 else top_k
  411. temperature = params.temperature
  412. if temperature < _SAMPLING_EPS:
  413. # NOTE: Zero temperature means deterministic sampling
  414. # (i.e., greedy sampling or beam search).
  415. # Set the temperature to 1 to avoid division by zero.
  416. temperature = 1.0
  417. do_temperatures |= (temperature != 1.0 or
  418. params.dynatemp_min > _SAMPLING_EPS or
  419. params.dynatemp_max > _SAMPLING_EPS)
  420. do_top_p_top_k |= (params.top_p < 1.0 - _SAMPLING_EPS or
  421. top_k != vocab_size)
  422. do_top_as |= params.top_a > 0.0
  423. do_min_p |= params.min_p > _SAMPLING_EPS
  424. do_penalties |= (abs(params.presence_penalty) >= _SAMPLING_EPS or
  425. abs(params.frequency_penalty) >= _SAMPLING_EPS or
  426. params.repetition_penalty > 1.0)
  427. do_tfss |= params.tfs < 1.0 - _SAMPLING_EPS
  428. do_eta_cutoffs |= params.eta_cutoff > _SAMPLING_EPS
  429. do_epsilon_cutoffs |= params.epsilon_cutoff > _SAMPLING_EPS
  430. do_typical_ps |= params.typical_p < 1.0 - _SAMPLING_EPS
  431. do_quadratic |= (params.smoothing_factor > _SAMPLING_EPS or
  432. params.smoothing_curve > 1.0)
  433. do_xtc |= params.xtc_probability > _SAMPLING_EPS
  434. do_temp_last |= params.temperature_last
  435. is_prompt = seq_group.is_prompt
  436. wants_prompt_logprobs = params.prompt_logprobs is not None
  437. n_seqs = 0
  438. if seq_group.is_prompt and wants_prompt_logprobs:
  439. assert seq_group.query_len is not None
  440. n_seqs += len(seq_group.prompt_logprob_indices)
  441. if seq_group.do_sample:
  442. assert len(seq_group.sample_indices) == len(seq_ids)
  443. n_seqs += len(seq_ids)
  444. temperatures += [temperature] * n_seqs
  445. dynatemp_mins += [params.dynatemp_min] * n_seqs
  446. dynatemp_maxs += [params.dynatemp_max] * n_seqs
  447. dynatemp_exps += [params.dynatemp_exponent] * n_seqs
  448. temperature_lasts += [params.temperature_last] * n_seqs
  449. top_ps += [params.top_p] * n_seqs
  450. top_ks += [top_k] * n_seqs
  451. top_as += [params.top_a] * n_seqs
  452. min_ps += [params.min_p] * n_seqs
  453. presence_penalties += [params.presence_penalty] * n_seqs
  454. frequency_penalties += [params.frequency_penalty] * n_seqs
  455. repetition_penalties += [params.repetition_penalty] * n_seqs
  456. tfss += [params.tfs] * n_seqs
  457. eta_cutoffs += [params.eta_cutoff] * n_seqs
  458. epsilon_cutoffs += [params.epsilon_cutoff] * n_seqs
  459. typical_ps += [params.typical_p] * n_seqs
  460. smoothing_factors += [params.smoothing_factor] * n_seqs
  461. smoothing_curves += [params.smoothing_curve] * n_seqs
  462. xtc_thresholds += [params.xtc_threshold] * n_seqs
  463. xtc_probabilities += [params.xtc_probability] * n_seqs
  464. if _USE_TRITON_SAMPLER:
  465. if is_prompt:
  466. prompt_best_of.append(params.best_of)
  467. query_len = seq_group.query_len
  468. assert query_len is not None
  469. seed = params.seed
  470. is_greedy = params.sampling_type == SamplingType.GREEDY
  471. for seq_id in seq_ids:
  472. seq_data = seq_group.seq_data[seq_id]
  473. extra_entropy = extra_entropy or ()
  474. seq_seeds = cls._get_sequence_seeds(
  475. seed,
  476. seq_data.get_len(),
  477. *extra_entropy,
  478. seq_id,
  479. seeds_to_generate=seeds_to_generate,
  480. is_greedy=is_greedy)
  481. sampling_seeds.append(seq_seeds)
  482. sample_indices.extend(seq_group.sample_indices)
  483. if do_penalties:
  484. for seq_group in sampling_metadata.seq_groups:
  485. seq_ids = seq_group.seq_ids
  486. if (seq_group.is_prompt
  487. and params.prompt_logprobs is not None):
  488. prefill_len = len(seq_group.prompt_logprob_indices)
  489. prompt_tokens.extend(
  490. array('l') for _ in range(prefill_len))
  491. output_tokens.extend(
  492. array('l') for _ in range(prefill_len))
  493. if seq_group.do_sample:
  494. for seq_id in seq_ids:
  495. seq_data = seq_group.seq_data[seq_id]
  496. prompt_tokens.append(seq_data.prompt_token_ids_array)
  497. output_tokens.append(seq_data.output_token_ids_array)
  498. sampling_tensors = SamplingTensors.from_lists(
  499. temperatures, dynatemp_mins, dynatemp_maxs, dynatemp_exps,
  500. temperature_lasts, top_ps, top_ks, top_as, min_ps,
  501. presence_penalties, frequency_penalties, repetition_penalties,
  502. tfss, eta_cutoffs, epsilon_cutoffs, typical_ps, smoothing_factors,
  503. smoothing_curves, xtc_thresholds, xtc_probabilities, sampling_seeds,
  504. sample_indices, prompt_tokens, output_tokens, vocab_size,
  505. extra_seeds_to_generate, device, dtype)
  506. return (sampling_tensors, do_penalties, do_temperatures,
  507. do_top_p_top_k, do_top_as, do_min_p, do_tfss, do_eta_cutoffs,
  508. do_epsilon_cutoffs, do_typical_ps, do_quadratic, do_xtc,
  509. do_temp_last)
  510. @classmethod
  511. def from_lists(cls, temperatures: List[float], dynatemp_mins: List[float],
  512. dynatemp_maxs: List[float], dynatemp_exps: List[float],
  513. temperature_lasts: List[bool], top_ps: List[float],
  514. top_ks: List[int], top_as: List[float],
  515. min_ps: List[float], presence_penalties: List[float],
  516. frequency_penalties: List[float],
  517. repetition_penalties: List[float], tfss: List[float],
  518. eta_cutoffs: List[float], epsilon_cutoffs: List[float],
  519. typical_ps: List[float], smoothing_factors: List[float],
  520. smoothing_curves: List[float], xtc_thresholds: List[float],
  521. xtc_probabilities: List[float],
  522. sampling_seeds: List[List[int]],
  523. sample_indices: List[int], prompt_tokens: List[array],
  524. output_tokens: List[array], vocab_size: int,
  525. extra_seeds_to_generate: int, device: torch.device,
  526. dtype: torch.dtype) -> "SamplingTensors":
  527. # Note that the performance will be very bad without
  528. # pinned memory.
  529. pin_memory = is_pin_memory_available()
  530. do_penalties = prompt_tokens or output_tokens
  531. if do_penalties:
  532. prompt_t = make_tensor_with_pad(
  533. prompt_tokens,
  534. vocab_size,
  535. device="cpu",
  536. dtype=torch.int64,
  537. pin_memory=pin_memory,
  538. )
  539. output_t = make_tensor_with_pad(
  540. output_tokens,
  541. vocab_size,
  542. device="cpu",
  543. dtype=torch.int64,
  544. pin_memory=pin_memory,
  545. )
  546. else:
  547. empty_tensor = torch.empty(0, device=device, dtype=torch.long)
  548. prompt_t = empty_tensor
  549. output_t = empty_tensor
  550. temperatures_t = torch.tensor(
  551. temperatures,
  552. device="cpu",
  553. dtype=dtype,
  554. pin_memory=pin_memory,
  555. )
  556. dynatemp_mins_t = torch.tensor(
  557. dynatemp_mins,
  558. device="cpu",
  559. dtype=dtype,
  560. pin_memory=pin_memory,
  561. )
  562. dynatemp_maxs_t = torch.tensor(
  563. dynatemp_maxs,
  564. device="cpu",
  565. dtype=dtype,
  566. pin_memory=pin_memory,
  567. )
  568. dynatemp_exps_t = torch.tensor(
  569. dynatemp_exps,
  570. device="cpu",
  571. dtype=dtype,
  572. pin_memory=pin_memory,
  573. )
  574. temp_lasts_t = torch.tensor(
  575. temperature_lasts,
  576. device="cpu",
  577. dtype=torch.bool,
  578. pin_memory=pin_memory,
  579. )
  580. top_ps_t = torch.tensor(
  581. top_ps,
  582. device="cpu",
  583. dtype=dtype,
  584. pin_memory=pin_memory,
  585. )
  586. top_as_t = torch.tensor(top_as,
  587. device="cpu",
  588. dtype=dtype,
  589. pin_memory=pin_memory)
  590. min_ps_t = torch.tensor(
  591. min_ps,
  592. device="cpu",
  593. dtype=dtype,
  594. pin_memory=pin_memory,
  595. )
  596. presence_penalties_t = torch.tensor(
  597. presence_penalties,
  598. device="cpu",
  599. dtype=dtype,
  600. pin_memory=pin_memory,
  601. )
  602. frequency_penalties_t = torch.tensor(
  603. frequency_penalties,
  604. device="cpu",
  605. dtype=dtype,
  606. pin_memory=pin_memory,
  607. )
  608. repetition_penalties_t = torch.tensor(
  609. repetition_penalties,
  610. device="cpu",
  611. dtype=dtype,
  612. pin_memory=pin_memory,
  613. )
  614. top_ks_t = torch.tensor(
  615. top_ks,
  616. device="cpu",
  617. dtype=torch.int,
  618. pin_memory=pin_memory,
  619. )
  620. tfss_t = torch.tensor(tfss,
  621. device="cpu",
  622. dtype=dtype,
  623. pin_memory=pin_memory)
  624. eta_cutoffs_t = torch.tensor(eta_cutoffs,
  625. device="cpu",
  626. dtype=dtype,
  627. pin_memory=pin_memory)
  628. epsilon_cutoffs_t = torch.tensor(epsilon_cutoffs,
  629. device="cpu",
  630. dtype=dtype,
  631. pin_memory=pin_memory)
  632. typical_ps_t = torch.tensor(typical_ps,
  633. device="cpu",
  634. dtype=dtype,
  635. pin_memory=pin_memory)
  636. smoothing_factors_t = torch.tensor(smoothing_factors,
  637. device="cpu",
  638. dtype=dtype,
  639. pin_memory=pin_memory)
  640. smoothing_curves_t = torch.tensor(smoothing_curves,
  641. device="cpu",
  642. dtype=dtype,
  643. pin_memory=pin_memory)
  644. xtc_thresholds_t = torch.tensor(xtc_thresholds,
  645. device="cpu",
  646. dtype=dtype,
  647. pin_memory=pin_memory)
  648. xtc_probabilities_t = torch.tensor(xtc_probabilities,
  649. device="cpu",
  650. dtype=dtype,
  651. pin_memory=pin_memory)
  652. sample_indices_t = torch.tensor(
  653. sample_indices,
  654. device="cpu",
  655. dtype=torch.long,
  656. pin_memory=pin_memory,
  657. )
  658. # need to transpose and make contiguous to
  659. # copy the tensor correctly.
  660. # [batch_size, n_seeds] -> [n_seeds, batch_size]
  661. sampling_seeds_t = torch.tensor(
  662. sampling_seeds,
  663. device="cpu",
  664. dtype=torch.long,
  665. pin_memory=pin_memory,
  666. ).t().contiguous()
  667. # Because the memory is pinned, we can do non-blocking
  668. # transfer to device.
  669. # How many seeds the sample operation itself will need.
  670. num_base_seeds = sampling_seeds_t.shape[0] - extra_seeds_to_generate
  671. sampling_seeds_gpu = sampling_seeds_t.to(device=device,
  672. non_blocking=True)
  673. extra_seeds_gpu = sampling_seeds_gpu[num_base_seeds:]
  674. if not extra_seeds_gpu.numel():
  675. extra_seeds_gpu = None
  676. sampling_seeds_gpu = sampling_seeds_gpu[:num_base_seeds]
  677. return cls(
  678. temperatures=temperatures_t.to(device=device, non_blocking=True),
  679. dynatemp_mins=dynatemp_mins_t.to(device=device, non_blocking=True),
  680. dynatemp_maxs=dynatemp_maxs_t.to(device=device, non_blocking=True),
  681. dynatemp_exps=dynatemp_exps_t.to(device=device, non_blocking=True),
  682. temperature_lasts=temp_lasts_t.to(device=device, non_blocking=True),
  683. top_ps=top_ps_t.to(device=device, non_blocking=True),
  684. top_ks=top_ks_t.to(device=device, non_blocking=True),
  685. top_as=top_as_t.to(device=device, non_blocking=True),
  686. min_ps=min_ps_t.to(device=device, non_blocking=True),
  687. presence_penalties=presence_penalties_t.to(device=device,
  688. non_blocking=True),
  689. frequency_penalties=frequency_penalties_t.to(device=device,
  690. non_blocking=True),
  691. repetition_penalties=repetition_penalties_t.to(device=device,
  692. non_blocking=True),
  693. tfss=tfss_t.to(device=device, non_blocking=True),
  694. eta_cutoffs=eta_cutoffs_t.to(device=device, non_blocking=True),
  695. epsilon_cutoffs=epsilon_cutoffs_t.to(device=device,
  696. non_blocking=True),
  697. smoothing_factors=smoothing_factors_t.to(device=device,
  698. non_blocking=True),
  699. smoothing_curves=smoothing_curves_t.to(device=device,
  700. non_blocking=True),
  701. xtc_thresholds=xtc_thresholds_t.to(device=device,
  702. non_blocking=True),
  703. xtc_probabilities=xtc_probabilities_t.to(device=device,
  704. non_blocking=True),
  705. typical_ps=typical_ps_t.to(device=device, non_blocking=True),
  706. prompt_tokens=prompt_t.to(device=device, non_blocking=True),
  707. output_tokens=output_t.to(device=device, non_blocking=True),
  708. sampling_seeds=sampling_seeds_gpu,
  709. sample_indices=sample_indices_t.to(device=device,
  710. non_blocking=True),
  711. extra_seeds=extra_seeds_gpu,
  712. )
  713. @staticmethod
  714. def _get_sequence_seeds(
  715. seed: int|None,
  716. *extra_entropy: int,
  717. seeds_to_generate: int,
  718. is_greedy: bool,
  719. ):
  720. """Get `seeds_to_generate` child seeds from `seed` and extra entropy."""
  721. if not is_greedy:
  722. if seed is None:
  723. randint_fn = random.randint
  724. else:
  725. generator = random.Random(str((seed, ) + extra_entropy))
  726. randint_fn = generator.randint
  727. lo, hi = torch.iinfo(torch.long).min, torch.iinfo(torch.long).max
  728. # If the user/random sets seed = 0 but request should
  729. # have sampling, we need to change it to something
  730. # else. We use a constant in that case.
  731. # This way we don't need to create and load a bool
  732. # matrix in the sampling kernel, which reduces CPU
  733. # overhead and latency.
  734. seq_seeds = [
  735. randint_fn(lo, hi) or _SEED_0_REPLACEMENT
  736. for _ in range(seeds_to_generate)
  737. ]
  738. else:
  739. # For the kernel, seed == 0 means greedy decoding.
  740. seq_seeds = [0] * seeds_to_generate
  741. return seq_seeds