neuron_model_runner.py 11 KB

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