base.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import sys
  2. from abc import ABC, abstractmethod
  3. from collections import UserDict, defaultdict
  4. from typing import Callable, Dict, List, Mapping, Optional
  5. from typing import Sequence as GenericSequence
  6. from typing import Tuple, Type, TypedDict, TypeVar, Union, cast, final
  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. _T = TypeVar("_T")
  96. MultiModalData: TypeAlias = Union[_T, List[_T]]
  97. """
  98. Either a single data instance, or a list of data instances.
  99. The number of data instances allowed per modality is restricted by
  100. `--limit-mm-per-prompt`.
  101. """
  102. @final
  103. class MultiModalDataBuiltins(TypedDict, total=False):
  104. """Modality types that are predefined by vLLM."""
  105. image: MultiModalData[Image.Image]
  106. """The input image(s)."""
  107. audio: MultiModalData[Tuple[np.ndarray, Union[int, float]]]
  108. """The input audio item(s) and corresponding sampling rate(s)."""
  109. MultiModalDataDict = Union[MultiModalDataBuiltins,
  110. Mapping[str, MultiModalData[object]]]
  111. """
  112. A dictionary containing an item for each modality type to input.
  113. The data belonging to each modality is converted into keyword arguments
  114. to the model by the corresponding mapper. By default, the mapper of
  115. the corresponding plugin with the same modality key is applied.
  116. """
  117. MultiModalInputMapper = Callable[[InputContext, MultiModalData[object]],
  118. MultiModalInputs]
  119. """
  120. Return a dictionary to be passed as keyword arguments to
  121. :meth:`~torch.nn.Module.forward`. This is similar in concept to tokenizers
  122. and processors in HuggingFace Transformers.
  123. If the data is not supported, throw :exc:`TypeError`.
  124. """
  125. MultiModalTokensCalc = Union[int, Callable[[InputContext], int]]
  126. """
  127. Calculate the maximum number of multimodal tokens input to the language
  128. model. This does not include tokens that correspond to the input text.
  129. """
  130. N = TypeVar("N", bound=Type[nn.Module])
  131. class MultiModalPlugin(ABC):
  132. """
  133. Base class that defines data processing logic for a specific modality.
  134. In particular, we adopt a registry pattern to dispatch data processing
  135. according to the model being used (considering that different models may
  136. process the same data differently). This registry is in turn used by
  137. :class:`~MultiModalRegistry` which acts at a higher level
  138. (i.e., the modality of the data).
  139. """
  140. def __init__(self) -> None:
  141. self._input_mappers: Dict[Type[nn.Module], MultiModalInputMapper] = {}
  142. self._max_mm_tokens: Dict[Type[nn.Module], MultiModalTokensCalc] = {}
  143. @abstractmethod
  144. def get_data_key(self) -> str:
  145. """
  146. Get the data key corresponding to the modality.
  147. """
  148. raise NotImplementedError
  149. @abstractmethod
  150. def _default_input_mapper(
  151. self,
  152. ctx: InputContext,
  153. data: MultiModalData[object],
  154. ) -> MultiModalInputs:
  155. """
  156. Return a dictionary to be passed as keyword arguments to
  157. :meth:`~torch.nn.Module.forward`. This is similar in concept to
  158. tokenizers and processors in HuggingFace Transformers.
  159. If the data is not supported, throw :exc:`TypeError`.
  160. """
  161. raise NotImplementedError
  162. def register_input_mapper(
  163. self,
  164. mapper: Optional[MultiModalInputMapper] = None,
  165. ):
  166. """
  167. Register an input mapper to a model class.
  168. When the model receives input data that matches the modality served by
  169. this plugin (see :meth:`get_data_type`), the provided function is
  170. invoked to transform the data into a dictionary of model inputs.
  171. If `None` is provided, then the default input mapper is used instead.
  172. See also:
  173. :ref:`input_processing_pipeline`
  174. :ref:`adding_a_new_multimodal_model`
  175. """
  176. def wrapper(model_cls: N) -> N:
  177. if model_cls in self._input_mappers:
  178. logger.warning(
  179. f"Model class {model_cls} already has an input mapper "
  180. f"registered to {self}. It is overwritten by the new one.")
  181. self._input_mappers[model_cls] = mapper \
  182. or self._default_input_mapper
  183. return model_cls
  184. return wrapper
  185. def map_input(self, model_config: ModelConfig,
  186. data: MultiModalData[object]) -> MultiModalInputs:
  187. """
  188. Apply an input mapper to a data passed
  189. to the model, transforming the data into a dictionary of model inputs.
  190. If the data is not something that the mapper expects, throws TypeError.
  191. The model is identified by ``model_config``.
  192. See also:
  193. :ref:`adding_a_new_multimodal_model`
  194. """
  195. # Avoid circular import
  196. from aphrodite.modeling.model_loader import get_model_architecture
  197. model_cls, _ = get_model_architecture(model_config)
  198. mapper = self._input_mappers.get(model_cls)
  199. if mapper is None:
  200. raise KeyError(f"No input mapper in {self} is registered for "
  201. f"model class {model_cls.__name__}.")
  202. return mapper(InputContext(model_config), data)
  203. @abstractmethod
  204. def _default_max_multimodal_tokens(self, ctx: InputContext) -> int:
  205. """
  206. Calculate the maximum number of tokens, corresponding to a single
  207. instance of multimodal data, that are passed to the language model.
  208. """
  209. raise NotImplementedError
  210. def _validate_max_multimodal_tokens(self, max_mm_tokens: int):
  211. if max_mm_tokens < 1:
  212. raise ValueError("You should set the number of tokens to a "
  213. f"positive integer. Found: {max_mm_tokens}")
  214. def register_max_multimodal_tokens(
  215. self,
  216. max_mm_tokens: Optional[MultiModalTokensCalc] = None,
  217. ):
  218. """
  219. Register the maximum number of tokens, corresponding to a single
  220. instance of multimodal data, that are passed to the language model
  221. for a model class.
  222. If `None` is provided, then the default calculation is used instead.
  223. See also:
  224. :ref:`adding_a_new_multimodal_model`
  225. """
  226. def wrapper(model_cls: N) -> N:
  227. if model_cls in self._max_mm_tokens:
  228. logger.warning(
  229. f"Model class {model_cls} already calculates maximum "
  230. f"number of tokens in {self}. It is overwritten by the "
  231. "new one.")
  232. if isinstance(max_mm_tokens, int):
  233. self._validate_max_multimodal_tokens(max_mm_tokens)
  234. self._max_mm_tokens[model_cls] = max_mm_tokens \
  235. or self._default_max_multimodal_tokens
  236. return model_cls
  237. return wrapper
  238. def get_max_multimodal_tokens(self, model_config: ModelConfig) -> int:
  239. """
  240. Get the maximum number of multi-modal tokens
  241. for profiling the memory usage of a model.
  242. If this registry is not applicable to the model, `0` is returned.
  243. The model is identified by ``model_config``.
  244. See also:
  245. :ref:`adding_a_new_multimodal_model`
  246. """
  247. # Avoid circular import
  248. from aphrodite.modeling.model_loader import get_model_architecture
  249. model_cls, _ = get_model_architecture(model_config)
  250. if model_cls not in self._input_mappers:
  251. return 0
  252. max_mm_tokens = self._max_mm_tokens.get(model_cls)
  253. if max_mm_tokens is None:
  254. raise KeyError(f"No maximum number of multi-modal tokens is given "
  255. f"for model class {model_cls.__name__} in {self}.")
  256. if callable(max_mm_tokens):
  257. max_mm_tokens = max_mm_tokens(InputContext(model_config))
  258. self._validate_max_multimodal_tokens(max_mm_tokens)
  259. return max_mm_tokens