base.py 10 KB

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