test_model_runner.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. from array import array
  2. from typing import List
  3. import pytest
  4. import torch
  5. from aphrodite.common.sequence import (SamplingParams, SequenceData,
  6. SequenceGroupMetadata)
  7. from aphrodite.common.utils import get_open_port
  8. from aphrodite.constants import APHRODITE_TOKEN_ID_ARRAY_TYPE
  9. from aphrodite.distributed.parallel_state import (
  10. ensure_model_parallel_initialized, init_distributed_environment)
  11. from aphrodite.engine.args_tools import EngineArgs
  12. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  13. from aphrodite.worker.model_runner import ModelRunner, _get_graph_batch_size
  14. def _create_model_runner(model: str, *args, **kwargs) -> ModelRunner:
  15. engine_args = EngineArgs(model, *args, **kwargs)
  16. engine_config = engine_args.create_engine_config()
  17. model_runner = ModelRunner(
  18. model_config=engine_config.model_config,
  19. parallel_config=engine_config.parallel_config,
  20. scheduler_config=engine_config.scheduler_config,
  21. device_config=engine_config.device_config,
  22. cache_config=engine_config.cache_config,
  23. load_config=engine_config.load_config,
  24. lora_config=engine_config.lora_config,
  25. prompt_adapter_config=engine_config.prompt_adapter_config,
  26. is_driver_worker=True,
  27. )
  28. return model_runner
  29. @pytest.mark.parametrize("batch_size", list(range(1, 257)))
  30. def test_prepare_prompt(batch_size):
  31. model_runner = _create_model_runner(
  32. "facebook/opt-125m",
  33. max_num_batched_tokens=100000,
  34. max_num_seqs=100000,
  35. enable_chunked_prefill=False,
  36. )
  37. seq_lens: List[int] = []
  38. seq_group_metadata_list: List[SequenceGroupMetadata] = []
  39. block_tables = {0: [1]}
  40. for i in range(batch_size):
  41. # make sure all tokens fit into one block
  42. seq_len = i % (model_runner.block_size - 1) + 1
  43. seq_lens.append(seq_len)
  44. seq_data = SequenceData(array(APHRODITE_TOKEN_ID_ARRAY_TYPE,
  45. range(seq_len)))
  46. seq_group_metadata = SequenceGroupMetadata(
  47. request_id=f"test_{i}",
  48. is_prompt=True,
  49. seq_data={0: seq_data},
  50. sampling_params=SamplingParams(temperature=0),
  51. block_tables=block_tables,
  52. )
  53. assert seq_group_metadata.token_chunk_size == seq_data.get_len()
  54. seq_group_metadata_list.append(seq_group_metadata)
  55. expected_selected_token_indices = []
  56. selected_token_start_idx = 0
  57. for seq_len in seq_lens:
  58. expected_selected_token_indices.append(selected_token_start_idx +
  59. seq_len - 1)
  60. selected_token_start_idx += seq_len
  61. model_input = model_runner._prepare_model_input_tensors(
  62. seq_group_metadata_list)
  63. input_tokens = model_input.input_tokens
  64. input_positions = model_input.input_positions
  65. attn_metadata = model_input.attn_metadata
  66. return_seq_lens = model_input.seq_lens
  67. slot_mapping = attn_metadata.slot_mapping
  68. assert return_seq_lens == seq_lens
  69. assert len(slot_mapping) == len(input_tokens)
  70. # Verify input metadata is correct for prompts.
  71. device = model_runner.device
  72. assert attn_metadata.num_prefills > 0
  73. assert attn_metadata.num_decode_tokens == 0
  74. torch.testing.assert_close(
  75. attn_metadata.seq_lens_tensor,
  76. torch.tensor(seq_lens, device=device, dtype=torch.int))
  77. assert attn_metadata.seq_lens == seq_lens
  78. assert attn_metadata.max_prefill_seq_len == max(seq_lens)
  79. assert attn_metadata.max_decode_seq_len == 0
  80. # Test subquery start locs.
  81. start_idx = 0
  82. start_loc = [start_idx]
  83. for seq_len in seq_lens:
  84. start_idx += seq_len
  85. start_loc.append(start_idx)
  86. torch.testing.assert_close(
  87. attn_metadata.query_start_loc,
  88. torch.tensor(start_loc, dtype=torch.int32, device=device))
  89. # Test seq start locs. Note that for normal prefill it is
  90. # equivalent to query_start_loc.
  91. start_idx = 0
  92. seq_start_loc = [start_idx]
  93. for seq_len in seq_lens:
  94. start_idx += seq_len
  95. seq_start_loc.append(start_idx)
  96. torch.testing.assert_close(
  97. attn_metadata.seq_start_loc,
  98. torch.tensor(start_loc, dtype=torch.int32, device=device))
  99. torch.testing.assert_close(
  100. attn_metadata.context_lens_tensor,
  101. torch.zeros(attn_metadata.context_lens_tensor.shape[0],
  102. dtype=torch.int,
  103. device=device))
  104. expected = torch.tensor([[] for _ in range(len(seq_group_metadata_list))],
  105. dtype=torch.int32,
  106. device=model_runner.device)
  107. torch.testing.assert_close(attn_metadata.block_tables, expected)
  108. # Cuda graph should not be used for prerill.
  109. assert attn_metadata.use_cuda_graph is False
  110. assert len(input_tokens) == sum(seq_lens)
  111. assert len(input_positions) == sum(seq_lens)
  112. torch.testing.assert_close(input_tokens, input_positions)
  113. sampling_metadata = SamplingMetadata.prepare(
  114. seq_group_metadata_list,
  115. seq_lens,
  116. query_lens=seq_lens,
  117. device=model_runner.device,
  118. pin_memory=model_runner.pin_memory)
  119. assert len(input_tokens) == sum(seq_lens)
  120. assert len(input_positions) == sum(seq_lens)
  121. actual = sampling_metadata.selected_token_indices
  122. expected = torch.tensor(expected_selected_token_indices,
  123. device=actual.device,
  124. dtype=actual.dtype)
  125. torch.testing.assert_close(actual, expected)
  126. torch.allclose(input_tokens, input_positions)
  127. actual = sampling_metadata.selected_token_indices
  128. expected = torch.tensor(expected_selected_token_indices,
  129. device=actual.device,
  130. dtype=actual.dtype)
  131. torch.testing.assert_close(actual, expected)
  132. @pytest.mark.parametrize("batch_size", list(range(1, 257)))
  133. def test_prepare_decode_cuda_graph(batch_size):
  134. model_runner = _create_model_runner(
  135. "facebook/opt-125m",
  136. seed=0,
  137. dtype="float16",
  138. enforce_eager=False,
  139. max_num_batched_tokens=100000,
  140. max_num_seqs=100000,
  141. enable_chunked_prefill=False,
  142. )
  143. context_lens: List[int] = []
  144. seq_group_metadata_list: List[SequenceGroupMetadata] = []
  145. # Assume each seq group finishes prefill.
  146. for i in range(batch_size):
  147. # make sure all tokens fit into one block
  148. context_len = i % (model_runner.block_size - 1) + 1
  149. context_lens.append(context_len)
  150. seq_data = SequenceData(
  151. array(APHRODITE_TOKEN_ID_ARRAY_TYPE, range(context_len)))
  152. seq_data.update_num_computed_tokens(context_len)
  153. # Append one token ID since prefill is finished.
  154. seq_data.append_token_id(1, 0)
  155. seq_group_metadata = SequenceGroupMetadata(
  156. request_id=f"test_{i}",
  157. is_prompt=False,
  158. seq_data={0: seq_data},
  159. sampling_params=SamplingParams(temperature=0),
  160. block_tables={0: [1]},
  161. )
  162. assert seq_group_metadata.token_chunk_size == 1
  163. seq_group_metadata_list.append(seq_group_metadata)
  164. model_input = model_runner._prepare_model_input_tensors(
  165. seq_group_metadata_list)
  166. input_tokens, input_positions, attn_metadata, slot_mapping = (
  167. model_input.input_tokens, model_input.input_positions,
  168. model_input.attn_metadata, model_input.attn_metadata.slot_mapping)
  169. assert len(slot_mapping) == len(input_tokens)
  170. expected_bs = _get_graph_batch_size(len(seq_group_metadata_list))
  171. # Verify input metadata is correct for prompts.
  172. device = model_runner.device
  173. assert attn_metadata.num_prefills == 0
  174. assert attn_metadata.num_prefill_tokens == 0
  175. seq_lens = [context_len + 1 for context_len in context_lens]
  176. # seq_lens are padded to expected_bs
  177. for _ in range(expected_bs - len(seq_lens)):
  178. seq_lens.append(1)
  179. assert attn_metadata.seq_lens == seq_lens
  180. assert attn_metadata.num_decode_tokens == len(seq_lens)
  181. start_idx = 0
  182. start_loc = [start_idx]
  183. for _ in context_lens:
  184. # decode has only 1 token for query.
  185. start_idx += 1
  186. start_loc.append(start_idx)
  187. torch.testing.assert_close(
  188. attn_metadata.query_start_loc,
  189. torch.tensor(start_loc, dtype=torch.int32, device=device))
  190. start_idx = 0
  191. seq_start_loc = [start_idx]
  192. for seq_len in seq_lens:
  193. start_idx += seq_len
  194. seq_start_loc.append(start_idx)
  195. torch.testing.assert_close(
  196. attn_metadata.seq_start_loc,
  197. torch.tensor(seq_start_loc, dtype=torch.int32, device=device))
  198. torch.testing.assert_close(
  199. attn_metadata.context_lens_tensor,
  200. torch.tensor(context_lens, dtype=torch.int, device=device))
  201. assert attn_metadata.max_decode_seq_len == max(seq_lens)
  202. torch.testing.assert_close(
  203. attn_metadata.seq_lens_tensor[:len(seq_lens)],
  204. torch.tensor(seq_lens, dtype=torch.int, device=device))
  205. # block table's first index corresponds to each batch, meaning in
  206. # decoding it is each token.
  207. assert attn_metadata.block_tables.shape[0] == len(input_tokens)
  208. # Block table's second dim correspondsd to each token's block number.
  209. # It is padded up to
  210. assert attn_metadata.block_tables.shape[1] == (
  211. model_runner.get_max_block_per_batch())
  212. assert attn_metadata.use_cuda_graph is True
  213. assert len(input_tokens) == expected_bs
  214. assert len(input_positions) == expected_bs
  215. torch.allclose(input_tokens, input_positions)
  216. # Verify Sampling
  217. expected_selected_token_indices = []
  218. selected_token_start_idx = 0
  219. for _ in context_lens:
  220. expected_selected_token_indices.append(selected_token_start_idx)
  221. selected_token_start_idx += 1
  222. sampling_metadata = SamplingMetadata.prepare(
  223. seq_group_metadata_list,
  224. seq_lens,
  225. # query lens is all 1 for decode.
  226. query_lens=[1 for _ in range(len(context_lens))],
  227. device=model_runner.device,
  228. pin_memory=model_runner.pin_memory)
  229. actual = sampling_metadata.selected_token_indices
  230. expected = torch.tensor(expected_selected_token_indices,
  231. device=actual.device,
  232. dtype=actual.dtype)
  233. torch.testing.assert_close(actual, expected)
  234. def test_empty_seq_group():
  235. """Verify prepare prompt and decode returns empty output."""
  236. model_runner = _create_model_runner(
  237. "facebook/opt-125m",
  238. seed=0,
  239. dtype="float16",
  240. enforce_eager=False,
  241. )
  242. seq_group_metadata_list: List[SequenceGroupMetadata] = []
  243. model_input = model_runner._prepare_model_input_tensors(
  244. seq_group_metadata_list)
  245. input_tokens, input_positions, attn_metadata = (
  246. model_input.input_tokens,
  247. model_input.input_positions,
  248. model_input.attn_metadata,
  249. )
  250. assert input_tokens is None
  251. assert input_positions is None
  252. assert attn_metadata is None
  253. model_input = model_runner._prepare_model_input_tensors(
  254. seq_group_metadata_list)
  255. (input_tokens, input_positions, attn_metadata, return_seq_lens) = (
  256. model_input.input_tokens,
  257. model_input.input_positions,
  258. model_input.attn_metadata,
  259. model_input.seq_lens,
  260. )
  261. assert input_tokens is None
  262. assert input_positions is None
  263. assert attn_metadata is None
  264. assert return_seq_lens is None
  265. @pytest.fixture
  266. def distributed_init():
  267. init_distributed_environment(
  268. world_size=1,
  269. rank=0,
  270. distributed_init_method=f"tcp://127.0.0.1:{get_open_port()}",
  271. local_rank=0)
  272. ensure_model_parallel_initialized(1, 1)
  273. @pytest.mark.parametrize("batch_size", list(range(2, 128)))
  274. @pytest.mark.parametrize("enforce_eager", [True, False])
  275. def test_hybrid_batches(batch_size, enforce_eager, distributed_init):
  276. model_runner = _create_model_runner(
  277. "facebook/opt-125m",
  278. seed=0,
  279. dtype="float16",
  280. enforce_eager=enforce_eager,
  281. max_num_batched_tokens=100000,
  282. max_num_seqs=100000,
  283. enable_chunked_prefill=True,
  284. )
  285. # Add prefill requests.
  286. seq_lens: List[int] = []
  287. seq_group_metadata_list: List[SequenceGroupMetadata] = []
  288. prefill_metadata_list: List[SequenceGroupMetadata] = []
  289. decode_metadata_list: List[SequenceGroupMetadata] = []
  290. block_tables = {0: [1]}
  291. prefill_batch_size = batch_size // 2
  292. decode_batch_size = batch_size - prefill_batch_size
  293. for i in range(prefill_batch_size):
  294. # make sure all tokens fit into one block
  295. seq_len = i % (model_runner.block_size - 1) + 1
  296. seq_lens.append(seq_len)
  297. seq_data = SequenceData(array(APHRODITE_TOKEN_ID_ARRAY_TYPE,
  298. range(seq_len)))
  299. seq_group_metadata = SequenceGroupMetadata(
  300. request_id=f"test_{i}",
  301. is_prompt=True,
  302. seq_data={0: seq_data},
  303. sampling_params=SamplingParams(temperature=0),
  304. block_tables=block_tables,
  305. )
  306. assert seq_group_metadata.token_chunk_size == seq_data.get_len()
  307. seq_group_metadata_list.append(seq_group_metadata)
  308. prefill_metadata_list.append(seq_group_metadata)
  309. # Add decode requests
  310. for i in range(prefill_batch_size, batch_size):
  311. # make sure all tokens fit into one block
  312. context_len = i % (model_runner.block_size - 1) + 1
  313. prompt_toks = array(APHRODITE_TOKEN_ID_ARRAY_TYPE, range(context_len))
  314. seq_data = SequenceData(prompt_toks)
  315. seq_data.append_token_id(1, 0)
  316. seq_data.update_num_computed_tokens(context_len)
  317. seq_group_metadata = SequenceGroupMetadata(
  318. request_id=f"test_{i}",
  319. is_prompt=False,
  320. seq_data={0: seq_data},
  321. sampling_params=SamplingParams(temperature=0),
  322. block_tables={0: [1]},
  323. )
  324. assert seq_group_metadata.token_chunk_size == 1
  325. seq_group_metadata_list.append(seq_group_metadata)
  326. decode_metadata_list.append(seq_group_metadata)
  327. model_input = model_runner.prepare_model_input(seq_group_metadata_list)
  328. (input_tokens, input_positions, attn_metadata) = (
  329. model_input.input_tokens,
  330. model_input.input_positions,
  331. model_input.attn_metadata,
  332. )
  333. prefill_meta_actual = attn_metadata.prefill_metadata
  334. decode_meta_actual = attn_metadata.decode_metadata
  335. assert len(attn_metadata.slot_mapping) == len(input_tokens)
  336. assert len(input_positions) == len(input_tokens)
  337. assert attn_metadata.num_prefills == prefill_batch_size
  338. assert attn_metadata.num_decode_tokens == decode_batch_size
  339. assert attn_metadata.num_prefill_tokens == sum(seq_lens)
  340. # Verify attn metadata is consistent. We don't need to test individual
  341. # values here because they are tested above.
  342. attn_metadata = model_runner._prepare_model_input_tensors(
  343. seq_group_metadata_list).attn_metadata
  344. for attr_expected, attr_actual in zip(vars(attn_metadata.prefill_metadata),
  345. vars(prefill_meta_actual)):
  346. assert attr_expected[1] == attr_actual[1]
  347. for attr_expected, attr_actual in zip(vars(attn_metadata.decode_metadata),
  348. vars(decode_meta_actual)):
  349. assert attr_expected[1] == attr_actual[1]