sampling_metadata.py 30 KB

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