utils.py 7.6 KB

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