registry.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import functools
  2. from collections import UserDict
  3. from dataclasses import dataclass
  4. from typing import (TYPE_CHECKING, Callable, Dict, Mapping, Optional, Protocol,
  5. Tuple, Type)
  6. from loguru import logger
  7. from torch import nn
  8. from transformers import PretrainedConfig
  9. from typing_extensions import TypeVar
  10. from .data import LLMInputs
  11. if TYPE_CHECKING:
  12. from aphrodite.common.config import ModelConfig
  13. from aphrodite.common.sequence import SequenceData
  14. from aphrodite.multimodal import MultiModalDataDict, MultiModalRegistry
  15. C = TypeVar("C", bound=PretrainedConfig)
  16. @dataclass(frozen=True)
  17. class InputContext:
  18. """
  19. Contains information about the model which may be used to
  20. modify the inputs.
  21. """
  22. model_config: "ModelConfig"
  23. """The configuration of the model."""
  24. def get_hf_config(self, hf_config_type: Type[C]) -> C:
  25. """
  26. Get the HuggingFace configuration
  27. (:class:`transformers.PretrainedConfig`) of the model,
  28. additionally checking its type.
  29. Raises:
  30. ValueError: If the model is not of the specified type.
  31. """
  32. hf_config = self.model_config.hf_config
  33. if not isinstance(hf_config, hf_config_type):
  34. raise TypeError("Invalid type of HuggingFace config. "
  35. f"Expected type: {hf_config_type}, but "
  36. f"found type: {type(hf_config)}")
  37. return hf_config
  38. N = TypeVar("N", bound=Type[nn.Module])
  39. class DummyDataFactory(Protocol):
  40. def __call__(
  41. self,
  42. ctx: InputContext,
  43. seq_len: int,
  44. mm_counts: Mapping[str, int],
  45. ) -> Tuple["SequenceData", Optional["MultiModalDataDict"]]:
  46. """
  47. Create dummy data to be inputted into the model.
  48. Note:
  49. :data:`InputProcessor` is not applied to the dummy data.
  50. """
  51. ...
  52. class _MultiModalCounts(UserDict):
  53. """
  54. Wraps `mm_counts` for a more informative error message
  55. when attempting to access a plugin that does not exist.
  56. """
  57. def __getitem__(self, key: str) -> int:
  58. try:
  59. return super().__getitem__(key)
  60. except KeyError as exc:
  61. msg = (f"There is no multi-modal plugin with the key: {key}. "
  62. f"Available keys: {set(self.keys())}")
  63. raise KeyError(msg) from exc
  64. InputProcessor = Callable[[InputContext, LLMInputs], LLMInputs]
  65. """Preprocess the inputs to the model."""
  66. class InputRegistry:
  67. """
  68. A registry to dispatch data processing
  69. according to the target model.
  70. """
  71. def __init__(self) -> None:
  72. self._dummy_factories_by_model_type: Dict[Type[nn.Module],
  73. DummyDataFactory] = {}
  74. self._input_processors_by_model_type: Dict[Type[nn.Module],
  75. InputProcessor] = {}
  76. def _default_dummy_data_factory(
  77. self,
  78. ctx: InputContext,
  79. seq_len: int,
  80. mm_counts: Mapping[str, int],
  81. ) -> Tuple["SequenceData", Optional["MultiModalDataDict"]]:
  82. """
  83. The default dummy data factory represents the longest possible text
  84. that can be inputted to the model.
  85. Note:
  86. :data:`InputProcessor` is not applied to the dummy data.
  87. """
  88. # Avoid circular import
  89. from aphrodite.common.sequence import SequenceData
  90. dummy_seq_data = SequenceData([0] * seq_len)
  91. dummy_multi_modal_data = None
  92. return dummy_seq_data, dummy_multi_modal_data
  93. def register_dummy_data(self, factory: DummyDataFactory):
  94. """
  95. Register a dummy data factory to a model class.
  96. During memory profiling, the provided function is invoked to create
  97. dummy data to be inputted into the model. The resulting memory usage
  98. should be an upper bound of what the model would use at inference time.
  99. """
  100. def wrapper(model_cls: N) -> N:
  101. if model_cls in self._dummy_factories_by_model_type:
  102. logger.warning(
  103. f"Model class {model_cls} already has dummy data "
  104. f"registered to {self}. It is overwritten by the new one.")
  105. self._dummy_factories_by_model_type[model_cls] = factory
  106. return model_cls
  107. return wrapper
  108. def dummy_data_for_profiling(
  109. self,
  110. model_config: "ModelConfig",
  111. seq_len: int,
  112. mm_registry: "MultiModalRegistry",
  113. ) -> Tuple["SequenceData", Optional["MultiModalDataDict"]]:
  114. """
  115. Create dummy data for profiling the memory usage of a model.
  116. The model is identified by ``model_config``.
  117. See also:
  118. :ref:`enabling_multimodal_inputs`
  119. Note:
  120. This should be called after
  121. :meth:`~MultiModalRegistry.init_mm_limits_per_prompt`.
  122. """
  123. # Avoid circular import
  124. from aphrodite.modeling.model_loader import get_model_architecture
  125. model_cls, _ = get_model_architecture(model_config)
  126. dummy_factory = self._dummy_factories_by_model_type \
  127. .get(model_cls, self._default_dummy_data_factory)
  128. mm_counts = mm_registry.get_mm_limits_per_prompt(model_config)
  129. seq_data, mm_data = dummy_factory(
  130. InputContext(model_config),
  131. seq_len,
  132. _MultiModalCounts(mm_counts),
  133. )
  134. # Having more tokens is over-conservative but otherwise fine
  135. num_tokens = seq_data.prompt_token_ids
  136. assert len(num_tokens) >= seq_len, (
  137. f"Expected at least {seq_len} dummy tokens for profiling, "
  138. f"but found {len(num_tokens)} tokens instead.")
  139. if mm_data is not None:
  140. for k, v in mm_data.items():
  141. num_items = len(v) if isinstance(v, list) else 1
  142. num_expected = mm_counts[k]
  143. assert num_items >= num_expected, (
  144. f"Expected at least {num_expected} dummy '{k}' instances "
  145. f"for profiling, but found {num_items} instances instead.")
  146. return seq_data, mm_data
  147. def _default_input_processor(self, ctx: InputContext,
  148. inputs: LLMInputs) -> LLMInputs:
  149. """The default input processor is a no-op."""
  150. return inputs
  151. def register_input_processor(self, processor: InputProcessor):
  152. """
  153. Register an input processor to a model class.
  154. The provided function is invoked on each input to the model. This
  155. happens before
  156. :meth:`~aphrodite.multimodal.MultiModalRegistry.map_input`.
  157. See also:
  158. :ref:`input_processing_pipeline`
  159. """
  160. def wrapper(model_cls: N) -> N:
  161. if model_cls in self._input_processors_by_model_type:
  162. logger.warning(
  163. f"Model class {model_cls} already has input processor "
  164. f"registered to {self}. It is overwritten by the new one.")
  165. self._input_processors_by_model_type[model_cls] = processor
  166. return model_cls
  167. return wrapper
  168. def process_input(self, model_config: "ModelConfig",
  169. inputs: LLMInputs) -> LLMInputs:
  170. """
  171. Apply an input processor to an instance of model inputs.
  172. The model is identified by ``model_config``.
  173. See also:
  174. :ref:`input_processing_pipeline`
  175. """
  176. # Avoid circular import
  177. from aphrodite.modeling.model_loader import get_model_architecture
  178. model_cls, _ = get_model_architecture(model_config)
  179. processor = self._input_processors_by_model_type \
  180. .get(model_cls, self._default_input_processor)
  181. return processor(InputContext(model_config), inputs)
  182. def create_input_processor(self, model_config: "ModelConfig"):
  183. """
  184. Create an input processor (see :meth:`process_input`) for a
  185. specific model.
  186. """
  187. return functools.partial(self.process_input, model_config)