neuron_model_runner.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. from dataclasses import dataclass
  2. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
  3. import torch
  4. from loguru import logger
  5. from torch import nn
  6. from aphrodite.common.config import (DeviceConfig, ModelConfig, ParallelConfig,
  7. SchedulerConfig)
  8. from aphrodite.common.sequence import (IntermediateTensors,
  9. SequenceGroupMetadata)
  10. from aphrodite.common.utils import (is_pin_memory_available,
  11. make_tensor_with_pad)
  12. from aphrodite.modeling.layers.sampler import SamplerOutput
  13. from aphrodite.modeling.model_loader.neuron import get_neuron_model
  14. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  15. from aphrodite.multimodal import (MULTIMODAL_REGISTRY, BatchedTensorInputs,
  16. MultiModalInputs)
  17. from aphrodite.task_handler.model_runner_base import (ModelRunnerBase,
  18. ModelRunnerInputBase)
  19. if TYPE_CHECKING:
  20. from aphrodite.attention.backends.abstract import AttentionBackend
  21. @dataclass(frozen=True)
  22. class ModelInputForNeuron(ModelRunnerInputBase):
  23. """
  24. Used by the NeuronModelRunner.
  25. """
  26. input_tokens: Optional[torch.Tensor] = None
  27. input_positions: Optional[torch.Tensor] = None
  28. input_block_ids: Optional[torch.Tensor] = None
  29. sampling_metadata: Optional["SamplingMetadata"] = None
  30. multi_modal_kwargs: Optional[BatchedTensorInputs] = None
  31. def as_broadcastable_tensor_dict(
  32. self) -> Dict[str, Union[int, torch.Tensor]]:
  33. raise NotImplementedError("ModelInputForNeuron cannot be broadcast.")
  34. @classmethod
  35. def from_broadcasted_tensor_dict(
  36. cls,
  37. tensor_dict: Dict[str, Any],
  38. attn_backend: Optional["AttentionBackend"] = None,
  39. ) -> "ModelInputForNeuron":
  40. assert attn_backend is None
  41. return cls.from_broadcasted_tensor_dict(tensor_dict)
  42. class NeuronModelRunner(ModelRunnerBase[ModelInputForNeuron]):
  43. def __init__(
  44. self,
  45. model_config: ModelConfig,
  46. parallel_config: ParallelConfig,
  47. scheduler_config: SchedulerConfig,
  48. device_config: DeviceConfig,
  49. **kwargs,
  50. ):
  51. self.model_config = model_config
  52. self.parallel_config = parallel_config
  53. self.scheduler_config = scheduler_config
  54. if model_config is not None and model_config.get_sliding_window():
  55. logger.warning("Sliding window is not supported on Neuron. "
  56. "The model will run without sliding window.")
  57. self.device_config = (device_config
  58. if device_config is not None else DeviceConfig())
  59. self.device = self.device_config.device
  60. self.pin_memory = is_pin_memory_available()
  61. # Multi-modal data support
  62. self.multi_modal_input_mapper = MULTIMODAL_REGISTRY \
  63. .create_input_mapper(self.model_config)
  64. # Lazy initialization.
  65. self.model: nn.Module # initialize after load_model.
  66. def load_model(self) -> None:
  67. self.model = get_neuron_model(self.model_config,
  68. parallel_config=self.parallel_config,
  69. scheduler_config=self.scheduler_config)
  70. def _prepare_prompt(
  71. self,
  72. seq_group_metadata_list: List[SequenceGroupMetadata],
  73. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, List[int],
  74. BatchedTensorInputs]:
  75. assert len(seq_group_metadata_list) > 0
  76. input_tokens: List[List[int]] = []
  77. input_positions: List[List[int]] = []
  78. input_block_ids: List[int] = []
  79. seq_lens: List[int] = []
  80. multi_modal_inputs_list: List[MultiModalInputs] = []
  81. for seq_group_metadata in seq_group_metadata_list:
  82. assert seq_group_metadata.is_prompt
  83. seq_ids = list(seq_group_metadata.seq_data.keys())
  84. assert len(seq_ids) == 1
  85. seq_id = seq_ids[0]
  86. seq_data = seq_group_metadata.seq_data[seq_id]
  87. prompt_tokens = seq_data.get_token_ids()
  88. seq_len = len(prompt_tokens)
  89. seq_lens.append(seq_len)
  90. input_tokens.append(prompt_tokens)
  91. input_positions.append(list(range(seq_len)))
  92. assert seq_group_metadata.block_tables is not None
  93. block_table = seq_group_metadata.block_tables[seq_id]
  94. assert len(block_table) == 1
  95. input_block_ids.append(block_table[0])
  96. mm_data = seq_group_metadata.multi_modal_data
  97. if mm_data:
  98. # Process multi-modal data
  99. mm_kwargs = self.multi_modal_input_mapper(mm_data)
  100. multi_modal_inputs_list.append(mm_kwargs)
  101. max_seq_len = max(seq_lens)
  102. assert max_seq_len > 0
  103. input_tokens = make_tensor_with_pad(input_tokens,
  104. max_seq_len,
  105. pad=0,
  106. dtype=torch.long,
  107. device=self.device)
  108. input_positions = make_tensor_with_pad(input_positions,
  109. max_seq_len,
  110. pad=0,
  111. dtype=torch.long,
  112. device=self.device)
  113. input_block_ids = torch.tensor(input_block_ids,
  114. dtype=torch.long,
  115. device=self.device)
  116. multi_modal_kwargs = MultiModalInputs.batch(multi_modal_inputs_list)
  117. return (input_tokens, input_positions, input_block_ids, seq_lens,
  118. multi_modal_kwargs)
  119. def _prepare_decode(
  120. self,
  121. seq_group_metadata_list: List[SequenceGroupMetadata],
  122. ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  123. assert len(seq_group_metadata_list) > 0
  124. input_tokens: List[List[int]] = []
  125. input_positions: List[List[int]] = []
  126. input_block_ids: List[int] = []
  127. context_lens: List[int] = []
  128. for seq_group_metadata in seq_group_metadata_list:
  129. assert not seq_group_metadata.is_prompt
  130. seq_ids = list(seq_group_metadata.seq_data.keys())
  131. for seq_id in seq_ids:
  132. seq_data = seq_group_metadata.seq_data[seq_id]
  133. generation_token = seq_data.get_last_token_id()
  134. input_tokens.append([generation_token])
  135. seq_len = seq_data.get_len()
  136. position = seq_len - 1
  137. input_positions.append([position])
  138. context_lens.append(seq_len)
  139. assert seq_group_metadata.block_tables is not None
  140. block_table = seq_group_metadata.block_tables[seq_id]
  141. assert len(block_table) == 1
  142. input_block_ids.append(block_table[0])
  143. input_tokens = make_tensor_with_pad(input_tokens,
  144. max_len=1,
  145. pad=0,
  146. dtype=torch.long,
  147. device=self.device)
  148. input_positions = make_tensor_with_pad(input_positions,
  149. max_len=1,
  150. pad=0,
  151. dtype=torch.long,
  152. device=self.device)
  153. context_lens = torch.tensor(context_lens,
  154. dtype=torch.int,
  155. device=self.device)
  156. input_block_ids = torch.tensor(input_block_ids,
  157. dtype=torch.long,
  158. device=self.device)
  159. return input_tokens, input_positions, input_block_ids
  160. def make_model_input_from_broadcasted_tensor_dict(
  161. self, tensor_dict: Dict[str, Any]) -> ModelInputForNeuron:
  162. return ModelInputForNeuron.from_broadcasted_tensor_dict(tensor_dict)
  163. def prepare_model_input(
  164. self,
  165. seq_group_metadata_list: List[SequenceGroupMetadata],
  166. virtual_engine: int = 0,
  167. finished_requests_ids: Optional[List[str]] = None
  168. ) -> ModelInputForNeuron:
  169. multi_modal_kwargs = None
  170. # NOTE: We assume that all sequences in the group are all prompts or
  171. # all decodes.
  172. is_prompt = seq_group_metadata_list[0].is_prompt
  173. # Prepare input tensors.
  174. if is_prompt:
  175. (input_tokens, input_positions, input_block_ids, seq_lens,
  176. multi_modal_kwargs
  177. ) = self._prepare_prompt(seq_group_metadata_list)
  178. else:
  179. (input_tokens, input_positions,
  180. input_block_ids) = self._prepare_decode(seq_group_metadata_list)
  181. seq_lens = []
  182. sampling_metadata = SamplingMetadata.prepare(
  183. seq_group_metadata_list,
  184. seq_lens,
  185. # query_lens is not needed if chunked prefill is not
  186. # supported. Since neuron worker doesn't support chunked prefill
  187. # just use seq_lens instead.
  188. seq_lens,
  189. self.device,
  190. self.pin_memory,
  191. generators=self.get_generators(finished_requests_ids))
  192. return ModelInputForNeuron(input_tokens=input_tokens,
  193. input_positions=input_positions,
  194. input_block_ids=input_block_ids,
  195. sampling_metadata=sampling_metadata,
  196. multi_modal_kwargs=multi_modal_kwargs)
  197. @torch.inference_mode()
  198. def execute_model(
  199. self,
  200. model_input: ModelInputForNeuron,
  201. kv_caches: Optional[List[torch.Tensor]] = None,
  202. intermediate_tensors: Optional[IntermediateTensors] = None,
  203. num_steps: int = 1,
  204. ) -> Optional[List[SamplerOutput]]:
  205. if num_steps > 1:
  206. raise ValueError(
  207. "NeuronModelRunner does not support multi-step execution.")
  208. hidden_states = self.model(
  209. input_ids=model_input.input_tokens,
  210. positions=model_input.input_positions,
  211. input_block_ids=model_input.input_block_ids,
  212. **MultiModalInputs.as_kwargs(model_input.multi_modal_kwargs or {},
  213. device=self.device),
  214. )
  215. # Compute the logits.
  216. logits = self.model.compute_logits(hidden_states,
  217. model_input.sampling_metadata)
  218. # Sample the next token.
  219. output = self.model.sample(
  220. logits=logits,
  221. sampling_metadata=model_input.sampling_metadata,
  222. )
  223. return [output]
  224. @property
  225. def vocab_size(self) -> int:
  226. return self.model_config.get_vocab_size()