sampling_metadata.py 29 KB

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