1
0

base.py 11 KB

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