1
0

base.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import sys
  2. from abc import ABC, abstractmethod
  3. from collections import UserDict, defaultdict
  4. from typing import Any, Callable, Dict, List, Optional
  5. from typing import Sequence as GenericSequence
  6. from typing import Tuple, Type, TypedDict, TypeVar, Union, cast
  7. import numpy as np
  8. import torch
  9. import torch.types
  10. from loguru import logger
  11. from PIL import Image
  12. from torch import nn
  13. from typing_extensions import TypeAlias
  14. from aphrodite.common.config import ModelConfig
  15. from aphrodite.common.utils import JSONTree, json_map_leaves
  16. from aphrodite.inputs import InputContext
  17. NestedTensors = Union[GenericSequence[torch.Tensor], torch.Tensor]
  18. """
  19. Use a list instead of a tensor if the dimensions of each element do not match.
  20. Currently only supports up to singly nested list of tensors.
  21. """
  22. BatchedTensors: TypeAlias = JSONTree[torch.Tensor]
  23. """
  24. A nested JSON structure of tensors which have been batched via
  25. :meth:`MultiModalInputs.batch`.
  26. """
  27. BatchedTensorInputs: TypeAlias = Dict[str, JSONTree[torch.Tensor]]
  28. """
  29. A dictionary containing nested tensors which have been batched via
  30. :meth:`MultiModalInputs.batch`.
  31. """
  32. if sys.version_info < (3, 9):
  33. # UserDict cannot be subscripted
  34. class _MultiModalInputsBase(UserDict):
  35. pass
  36. else:
  37. class _MultiModalInputsBase(UserDict[str, NestedTensors]):
  38. pass
  39. class MultiModalInputs(_MultiModalInputsBase):
  40. """
  41. A dictionary that represents the keyword arguments to
  42. :meth:`~torch.nn.Module.forward`.
  43. """
  44. @staticmethod
  45. def _try_concat(
  46. tensors: List[NestedTensors],
  47. ) -> Union[GenericSequence[NestedTensors], NestedTensors]:
  48. """
  49. If each input tensor in the batch has the same shape, return a single
  50. batched tensor; otherwise, return a list of :class:`NestedTensors` with
  51. one element per item in the batch.
  52. """
  53. # may be list rather than tensors
  54. if isinstance(tensors[0], list):
  55. return [[t for t in tensor[0]]
  56. for tensor in cast(List[List[torch.Tensor]], tensors)]
  57. tensors_ = cast(List[torch.Tensor], tensors)
  58. unbatched_shape = tensors_[0].shape[1:]
  59. for tensor in tensors_:
  60. if tensor.shape[1:] != unbatched_shape:
  61. return [tensor.squeeze(0) for tensor in tensors_]
  62. return torch.cat(tensors_, dim=0)
  63. @staticmethod
  64. def batch(inputs_list: List["MultiModalInputs"]) -> BatchedTensorInputs:
  65. """
  66. Batch multiple inputs together into a dictionary.
  67. The resulting dictionary has the same keys as the inputs.
  68. If the corresponding value from each input is a tensor and they all
  69. share the same shape, the output value is a single batched tensor;
  70. otherwise, the output value is a list containing the original value
  71. from each input.
  72. """
  73. if len(inputs_list) == 0:
  74. return {}
  75. keys = inputs_list[0].keys()
  76. item_lists: Dict[str, List[NestedTensors]] = defaultdict(list)
  77. for inputs in inputs_list:
  78. if inputs.keys() != keys:
  79. msg = f"Inputs do not share the same keys ({keys})"
  80. raise ValueError(msg)
  81. for k, v in inputs.items():
  82. item_lists[k].append(v)
  83. return {
  84. k: MultiModalInputs._try_concat(item_list)
  85. for k, item_list in item_lists.items()
  86. } # type: ignore
  87. @staticmethod
  88. def as_kwargs(
  89. batched_inputs: BatchedTensorInputs,
  90. *,
  91. device: torch.types.Device,
  92. ) -> BatchedTensorInputs:
  93. return json_map_leaves(lambda x: x.to(device, non_blocking=True),
  94. batched_inputs)
  95. class MultiModalDataBuiltins(TypedDict, total=False):
  96. """Modality types that are pre-defined by Aphrodite."""
  97. image: Image.Image
  98. """The input image."""
  99. audio: Tuple[np.ndarray, Union[int, float]]
  100. """THe input audio and its sampling rate."""
  101. MultiModalDataDict = Union[MultiModalDataBuiltins, Dict[str, Any]]
  102. """
  103. A dictionary containing an item for each modality type to input.
  104. The data belonging to each modality is converted into keyword arguments
  105. to the model by the corresponding mapper. By default, the mapper of
  106. the corresponding plugin with the same modality key is applied.
  107. """
  108. MultiModalInputMapper = Callable[[InputContext, object], MultiModalInputs]
  109. """
  110. Return a dictionary to be passed as keyword arguments to
  111. :meth:`~torch.nn.Module.forward`. This is similar in concept to tokenizers
  112. and processors in HuggingFace Transformers.
  113. If the data is not supported, throw :exc:`TypeError`.
  114. """
  115. MultiModalTokensCalc = Union[int, Callable[[InputContext], int]]
  116. """
  117. Calculate the maximum number of multimodal tokens input to the language
  118. model. This does not include tokens that correspond to the input text.
  119. """
  120. N = TypeVar("N", bound=Type[nn.Module])
  121. class MultiModalPlugin(ABC):
  122. """
  123. Base class that defines data processing logic for a specific modality.
  124. In particular, we adopt a registry pattern to dispatch data processing
  125. according to the model being used (considering that different models may
  126. process the same data differently). This registry is in turn used by
  127. :class:`~MultiModalRegistry` which acts at a higher level
  128. (i.e., the modality of the data).
  129. """
  130. def __init__(self) -> None:
  131. self._input_mappers: Dict[Type[nn.Module], MultiModalInputMapper] = {}
  132. self._max_mm_tokens: Dict[Type[nn.Module], MultiModalTokensCalc] = {}
  133. @abstractmethod
  134. def get_data_key(self) -> str:
  135. """
  136. Get the data key corresponding to the modality.
  137. """
  138. raise NotImplementedError
  139. @abstractmethod
  140. def _default_input_mapper(self, ctx: InputContext,
  141. data: object) -> MultiModalInputs:
  142. """
  143. Return a dictionary to be passed as keyword arguments to
  144. :meth:`~torch.nn.Module.forward`. This is similar in concept to
  145. tokenizers and processors in HuggingFace Transformers.
  146. If the data is not supported, throw :exc:`TypeError`.
  147. """
  148. raise NotImplementedError
  149. def register_input_mapper(
  150. self,
  151. mapper: Optional[MultiModalInputMapper] = None,
  152. ):
  153. """
  154. Register an input mapper to a model class.
  155. When the model receives input data that matches the modality served by
  156. this plugin (see :meth:`get_data_type`), the provided function is
  157. invoked to transform the data into a dictionary of model inputs.
  158. If `None` is provided, then the default input mapper is used instead.
  159. See also:
  160. :ref:`input_processing_pipeline`
  161. :ref:`adding_a_new_multimodal_model`
  162. """
  163. def wrapper(model_cls: N) -> N:
  164. if model_cls in self._input_mappers:
  165. logger.warning(
  166. f"Model class {model_cls} already has an input mapper "
  167. f"registered to {self}. It is overwritten by the new one.")
  168. self._input_mappers[model_cls] = mapper \
  169. or self._default_input_mapper
  170. return model_cls
  171. return wrapper
  172. def map_input(self, model_config: ModelConfig,
  173. data: object) -> MultiModalInputs:
  174. """
  175. Apply an input mapper to a data passed
  176. to the model, transforming the data into a dictionary of model inputs.
  177. If the data is not something that the mapper expects, throws TypeError.
  178. The model is identified by ``model_config``.
  179. See also:
  180. :ref:`adding_a_new_multimodal_model`
  181. """
  182. # Avoid circular import
  183. from aphrodite.modeling.model_loader import get_model_architecture
  184. model_cls, _ = get_model_architecture(model_config)
  185. mapper = self._input_mappers.get(model_cls)
  186. if mapper is None:
  187. raise KeyError(f"No input mapper in {self} is registered for "
  188. f"model class {model_cls.__name__}.")
  189. return mapper(InputContext(model_config), data)
  190. @abstractmethod
  191. def _default_max_multimodal_tokens(self, ctx: InputContext) -> int:
  192. """
  193. Calculate the maximum number of multimodal tokens input to the language
  194. model. This does not include tokens that correspond to the input text.
  195. """
  196. raise NotImplementedError
  197. def _validate_max_multimodal_tokens(self, max_mm_tokens: int):
  198. if max_mm_tokens < 1:
  199. raise ValueError("You should set the number of tokens to a "
  200. f"positive integer. Found: {max_mm_tokens}")
  201. def register_max_multimodal_tokens(
  202. self,
  203. max_mm_tokens: Optional[MultiModalTokensCalc] = None,
  204. ):
  205. """
  206. Register the maximum number of multi-modal tokens input to the
  207. language model for a model class.
  208. If `None` is provided, then the default calculation is used instead.
  209. See also:
  210. :ref:`adding_a_new_multimodal_model`
  211. """
  212. def wrapper(model_cls: N) -> N:
  213. if model_cls in self._max_mm_tokens:
  214. logger.warning(
  215. f"Model class {model_cls} already calculates maximum "
  216. f"number of tokens in {self}. It is overwritten by the "
  217. "new one.")
  218. if isinstance(max_mm_tokens, int):
  219. self._validate_max_multimodal_tokens(max_mm_tokens)
  220. self._max_mm_tokens[model_cls] = max_mm_tokens \
  221. or self._default_max_multimodal_tokens
  222. return model_cls
  223. return wrapper
  224. def get_max_multimodal_tokens(self, model_config: ModelConfig) -> int:
  225. """
  226. Get the maximum number of multi-modal tokens
  227. for profiling the memory usage of a model.
  228. If this registry is not applicable to the model, `0` is returned.
  229. The model is identified by ``model_config``.
  230. See also:
  231. :ref:`adding_a_new_multimodal_model`
  232. """
  233. # Avoid circular import
  234. from aphrodite.modeling.model_loader import get_model_architecture
  235. model_cls, _ = get_model_architecture(model_config)
  236. if model_cls not in self._input_mappers:
  237. return 0
  238. max_mm_tokens = self._max_mm_tokens.get(model_cls)
  239. if max_mm_tokens is None:
  240. raise KeyError(f"No maximum number of multi-modal tokens is given "
  241. f"for model class {model_cls.__name__} in {self}.")
  242. if callable(max_mm_tokens):
  243. max_mm_tokens = max_mm_tokens(InputContext(model_config))
  244. self._validate_max_multimodal_tokens(max_mm_tokens)
  245. return max_mm_tokens