utils.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. from array import array
  2. from itertools import count
  3. from typing import Callable, Dict, List, Optional
  4. from typing import Sequence as GenericSequence
  5. from typing import TypeVar, Union
  6. from unittest.mock import MagicMock
  7. import torch
  8. from aphrodite.common.sampling_params import SamplingParams
  9. from aphrodite.common.sequence import (CompletionSequenceGroupOutput, Logprob,
  10. SequenceData, SequenceGroupMetadata,
  11. SequenceOutput)
  12. from aphrodite.common.utils import (get_distributed_init_method, get_ip,
  13. get_open_port)
  14. from aphrodite.constants import APHRODITE_TOKEN_ID_ARRAY_TYPE
  15. from aphrodite.engine.args_tools import EngineArgs
  16. from aphrodite.modeling.layers.sampler import SamplerOutput
  17. from aphrodite.modeling.utils import set_random_seed
  18. from aphrodite.worker.cache_engine import CacheEngine
  19. from aphrodite.worker.model_runner import ModelRunner
  20. from aphrodite.worker.worker import Worker
  21. T = TypeVar("T", bound=Worker)
  22. def round_up_to_next_block(seq_len: int, block_size: int) -> int:
  23. return (seq_len + block_size - 1) // block_size
  24. def mock_worker(cls=None,
  25. vocab_size: int = 30_000,
  26. max_model_len: int = 2048,
  27. rank: int = 0,
  28. use_spec: bool = True) -> MagicMock:
  29. if cls is None:
  30. cls = Worker
  31. spec = cls if use_spec else None
  32. worker = MagicMock(spec=spec)
  33. worker.vocab_size = vocab_size
  34. worker.max_model_len = max_model_len
  35. worker.rank = rank
  36. worker.device = 'cuda:0'
  37. return worker
  38. def patch_execute_model_with_seeds(worker: Worker, rand_seeds: List[int]):
  39. seed_iter = iter(rand_seeds)
  40. original_execute_model = worker.execute_model
  41. def new_execute_model(*args, **kwargs):
  42. result = original_execute_model(*args, **kwargs)
  43. set_random_seed(next(seed_iter))
  44. return result
  45. return new_execute_model
  46. def zero_kv_cache(cache_engine: List[CacheEngine]):
  47. assert cache_engine[0].gpu_cache
  48. for key_blocks, value_blocks in cache_engine[0].gpu_cache:
  49. key_blocks.zero_()
  50. value_blocks.zero_()
  51. def create_worker(cls: Callable[..., T],
  52. model_name: str,
  53. block_size: int,
  54. num_gpu_blocks: int,
  55. seed: int,
  56. is_driver_worker: bool = True,
  57. enforce_eager: bool = True,
  58. model_runner_cls: Optional[ModelRunner] = None) -> T:
  59. engine_args = EngineArgs(
  60. model=model_name,
  61. seed=seed,
  62. block_size=block_size,
  63. enforce_eager=enforce_eager,
  64. )
  65. engine_config = engine_args.create_engine_config()
  66. distributed_init_method = get_distributed_init_method(
  67. get_ip(), get_open_port())
  68. worker = cls(
  69. model_config=engine_config.model_config,
  70. parallel_config=engine_config.parallel_config,
  71. scheduler_config=engine_config.scheduler_config,
  72. device_config=engine_config.device_config,
  73. cache_config=engine_config.cache_config,
  74. load_config=engine_config.load_config,
  75. local_rank=0,
  76. rank=0,
  77. distributed_init_method=distributed_init_method,
  78. is_driver_worker=is_driver_worker,
  79. model_runner_cls=model_runner_cls,
  80. )
  81. worker.init_device()
  82. worker.load_model()
  83. engine_config.cache_config.num_gpu_blocks = num_gpu_blocks
  84. engine_config.cache_config.num_cpu_blocks = 0
  85. worker.initialize_cache(
  86. num_gpu_blocks=engine_config.cache_config.num_gpu_blocks,
  87. num_cpu_blocks=engine_config.cache_config.num_cpu_blocks)
  88. return worker
  89. def create_seq_group_metadata_from_prompts(
  90. prompts: List[List[int]],
  91. num_gpu_blocks: int,
  92. block_size: int,
  93. final_prompt_lens: List[int],
  94. continuations: Optional[List[List[int]]] = None,
  95. seq_ids: Optional[List[int]] = None,
  96. ) -> List[SequenceGroupMetadata]:
  97. if continuations is None:
  98. continuations = [[] for _ in prompts]
  99. if seq_ids is None:
  100. seq_ids = list(i for i, _ in enumerate(prompts))
  101. free_gpu_blocks = list(range(num_gpu_blocks))
  102. block_allocations = {
  103. i: [
  104. free_gpu_blocks.pop()
  105. for _ in range(round_up_to_next_block(final_len, block_size))
  106. ]
  107. for i, final_len in enumerate(final_prompt_lens)
  108. }
  109. return [
  110. SequenceGroupMetadata(
  111. request_id=str(i),
  112. is_prompt=len(cont_token_ids) == 0,
  113. seq_data={
  114. i:
  115. SequenceData(
  116. array(APHRODITE_TOKEN_ID_ARRAY_TYPE, prompt_token_ids[:]),
  117. _output_token_ids=array(APHRODITE_TOKEN_ID_ARRAY_TYPE,
  118. cont_token_ids[:]),
  119. ),
  120. },
  121. sampling_params=SamplingParams(temperature=0.0, ),
  122. block_tables={i: block_allocations[i][:]},
  123. ) for i, (prompt_token_ids,
  124. cont_token_ids) in enumerate(zip(prompts, continuations))
  125. ]
  126. def assert_logprobs_dict_allclose(
  127. actual_logprobs: List[Dict[int, Logprob]],
  128. expected_logprobs: List[Dict[int, Logprob]]) -> None:
  129. for single_step_actual_logprobs, single_step_expected_logprobs in zip(
  130. actual_logprobs, expected_logprobs):
  131. assert set(single_step_actual_logprobs.keys()) == set(
  132. single_step_expected_logprobs.keys())
  133. for token_id in single_step_actual_logprobs:
  134. actual = torch.tensor(
  135. single_step_actual_logprobs[token_id].logprob)
  136. expected = torch.tensor(
  137. single_step_expected_logprobs[token_id].logprob)
  138. torch.testing.assert_close(actual, expected)
  139. def create_sampler_output_list(
  140. token_ids: torch.Tensor,
  141. probs: GenericSequence[Optional[torch.Tensor]],
  142. logprobs: GenericSequence[Optional[torch.Tensor]],
  143. seq_ids: Optional[List[int]] = None) -> List[SamplerOutput]:
  144. num_steps, batch_size = token_ids.shape
  145. token_ids_by_step = token_ids.tolist()
  146. if seq_ids is None:
  147. seq_ids = list(range(batch_size))
  148. return [
  149. SamplerOutput(outputs=[
  150. CompletionSequenceGroupOutput(
  151. samples=[
  152. SequenceOutput(
  153. output_token=token_id,
  154. parent_seq_id=seq_ids[seq_index],
  155. logprobs={token_id: Logprob(0)},
  156. )
  157. ],
  158. prompt_logprobs=None,
  159. ) for seq_index, token_id in enumerate(token_ids_by_step[step])
  160. ],
  161. sampled_token_probs=probs[step],
  162. logprobs=logprobs[step],
  163. sampled_token_ids=token_ids[step])
  164. for step in range(num_steps)
  165. ]
  166. def create_batch(batch_size,
  167. k,
  168. prompt_len: Union[int, List[int]] = 10,
  169. prev_output_token_len: int = 10,
  170. seq_ids: Optional[List[int]] = None,
  171. num_gpu_blocks: Optional[int] = None,
  172. block_size: Optional[int] = None):
  173. if block_size is None:
  174. block_size = 8
  175. if num_gpu_blocks is None:
  176. num_gpu_blocks = 2048 // block_size
  177. iterator = count()
  178. if isinstance(prompt_len, int):
  179. prompt_lens = [prompt_len for _ in range(batch_size)]
  180. else:
  181. prompt_lens = prompt_len
  182. prompts = [[next(iterator) for _ in range(p_len)] for p_len in prompt_lens]
  183. prev_output_tokens = [[
  184. next(iterator) for _ in range(prev_output_token_len)
  185. ] for _ in range(batch_size)]
  186. final_prompt_lens = [
  187. len(prompt) + len(prev_output_token) + k + 1
  188. for prompt, prev_output_token in zip(prompts, prev_output_tokens)
  189. ]
  190. seq_group_metadata_list = create_seq_group_metadata_from_prompts(
  191. prompts, num_gpu_blocks, block_size, final_prompt_lens,
  192. prev_output_tokens, seq_ids)
  193. return seq_group_metadata_list, prompts, prev_output_tokens