sampling_metadata.py 34 KB

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