ultravox.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. # Adapted from https://github.com/fixie-ai/ultravox/blob/ecd58c4041030bae2ad15aa6bcf04ab43199ea02/ultravox/model/ultravox_model.py
  2. """PyTorch Ultravox model."""
  3. import itertools
  4. import math
  5. from array import array
  6. from functools import lru_cache
  7. from typing import (Iterable, List, Literal, Mapping, Optional, Tuple,
  8. TypedDict, Union, cast)
  9. import librosa
  10. import numpy as np
  11. import torch
  12. import torch.utils.checkpoint
  13. from torch import nn
  14. from torch.nn import functional as F
  15. from transformers.models.whisper import WhisperFeatureExtractor
  16. from transformers.models.whisper.modeling_whisper import WhisperEncoder
  17. from aphrodite.attention import AttentionMetadata
  18. from aphrodite.common.config import CacheConfig, MultiModalConfig
  19. from aphrodite.common.sequence import (APHRODITE_TOKEN_ID_ARRAY_TYPE,
  20. SamplerOutput, SequenceData)
  21. from aphrodite.inputs import INPUT_REGISTRY
  22. from aphrodite.inputs.data import LLMInputs
  23. from aphrodite.inputs.registry import InputContext
  24. from aphrodite.modeling.layers.activation import SiluAndMul, get_act_fn
  25. from aphrodite.modeling.layers.layernorm import RMSNorm
  26. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  27. from aphrodite.modeling.models.interfaces import SupportsMultiModal
  28. from aphrodite.modeling.models.utils import (filter_weights,
  29. init_aphrodite_registered_model,
  30. merge_multimodal_embeddings)
  31. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  32. from aphrodite.multimodal import MULTIMODAL_REGISTRY
  33. from aphrodite.multimodal.base import MultiModalInputs
  34. from aphrodite.multimodal.utils import (cached_get_tokenizer,
  35. repeat_and_pad_placeholder_tokens)
  36. from aphrodite.quantization.base_config import QuantizationConfig
  37. from aphrodite.transformers_utils.configs.ultravox import UltravoxConfig
  38. _AUDIO_PLACEHOLDER_TOKEN = 128002
  39. _AUDIO_TOKENS_PER_SECOND = 6.25
  40. class UltravoxAudioFeatureInputs(TypedDict):
  41. type: Literal["audio_features"]
  42. data: Union[torch.Tensor, List[torch.Tensor]]
  43. """Shape: `(batch_size, 80, M)"""
  44. class UltravoxAudioEmbeddingInputs(TypedDict):
  45. type: Literal["audio_embeds"]
  46. data: torch.Tensor
  47. UltravoxAudioInputs = Union[UltravoxAudioFeatureInputs,
  48. UltravoxAudioEmbeddingInputs]
  49. @lru_cache
  50. def cached_feature_extractor(model_id: str) -> WhisperFeatureExtractor:
  51. return WhisperFeatureExtractor.from_pretrained(model_id)
  52. def whisper_feature_extractor(ctx: InputContext) -> WhisperFeatureExtractor:
  53. return cached_feature_extractor(
  54. ctx.get_hf_config(UltravoxConfig).audio_model_id)
  55. def get_ultravox_max_audio_tokens(ctx: InputContext):
  56. feature_extractor = whisper_feature_extractor(ctx)
  57. return math.ceil(feature_extractor.chunk_length * _AUDIO_TOKENS_PER_SECOND)
  58. def dummy_data_for_ultravox(
  59. ctx: InputContext,
  60. seq_len: int,
  61. mm_counts: Mapping[str, int],
  62. ):
  63. feature_extractor = whisper_feature_extractor(ctx)
  64. audio_count = mm_counts["audio"]
  65. audio_token_ids = array(APHRODITE_TOKEN_ID_ARRAY_TYPE, [
  66. _AUDIO_PLACEHOLDER_TOKEN
  67. ]) * get_ultravox_max_audio_tokens(ctx) * audio_count
  68. other_token_ids = array(APHRODITE_TOKEN_ID_ARRAY_TYPE,
  69. [0]) * (seq_len - len(audio_token_ids))
  70. audio_and_sr = (np.array([0.0] * feature_extractor.chunk_length), 1)
  71. mm_dict = {
  72. "audio":
  73. audio_and_sr if audio_count == 1 else [audio_and_sr] * audio_count
  74. }
  75. return (SequenceData(audio_token_ids + other_token_ids), mm_dict)
  76. def input_mapper_for_ultravox(ctx: InputContext, data: object):
  77. if isinstance(data, tuple):
  78. (audio, sr) = cast(Tuple[np.ndarray, Union[float, int]], data)
  79. feature_extractor = whisper_feature_extractor(ctx)
  80. if sr != feature_extractor.sampling_rate:
  81. audio = librosa.resample(audio,
  82. orig_sr=sr,
  83. target_sr=feature_extractor.sampling_rate)
  84. sr = feature_extractor.sampling_rate
  85. minimum_audio_length = feature_extractor.n_fft // 2 + 1
  86. if len(audio) < minimum_audio_length:
  87. # Not enough audio; pad it.
  88. audio = np.pad(audio, (0, minimum_audio_length - len(audio)))
  89. return MultiModalInputs({
  90. "audio_features":
  91. feature_extractor(audio,
  92. sampling_rate=sr,
  93. padding="longest",
  94. return_tensors="pt")["input_features"]
  95. })
  96. raise NotImplementedError(f"Unsupported data type: {type(data)}")
  97. def input_processor_for_ultravox(ctx: InputContext, llm_inputs: LLMInputs):
  98. multi_modal_data = llm_inputs.get("multi_modal_data")
  99. if multi_modal_data is None or "audio" not in multi_modal_data:
  100. return llm_inputs
  101. feature_extractor = whisper_feature_extractor(ctx)
  102. audio_data, sample_rate = multi_modal_data["audio"]
  103. audio_length = audio_data.shape[0]
  104. if sample_rate != feature_extractor.sampling_rate:
  105. # Account for resampling.
  106. adjustment = feature_extractor.sampling_rate / sample_rate
  107. audio_length = math.ceil(adjustment * audio_length)
  108. feature_extractor_output_length = math.ceil(
  109. (audio_length -
  110. (feature_extractor.hop_length - 1)) / feature_extractor.hop_length)
  111. uv_config = ctx.get_hf_config(UltravoxConfig)
  112. audio_num_tokens = min(
  113. max(
  114. 1,
  115. math.ceil(feature_extractor_output_length /
  116. (uv_config.stack_factor * 2))),
  117. get_ultravox_max_audio_tokens(ctx))
  118. tokenizer = cached_get_tokenizer(ctx.model_config.tokenizer)
  119. new_prompt, new_token_ids = repeat_and_pad_placeholder_tokens(
  120. tokenizer,
  121. llm_inputs.get("prompt"),
  122. llm_inputs["prompt_token_ids"],
  123. placeholder_token_id=_AUDIO_PLACEHOLDER_TOKEN,
  124. repeat_count=audio_num_tokens,
  125. )
  126. # NOTE: Create a defensive copy of the original inputs
  127. return LLMInputs(prompt_token_ids=new_token_ids,
  128. prompt=new_prompt,
  129. multi_modal_data=multi_modal_data)
  130. class StackAudioFrames(nn.Module):
  131. """
  132. Stack the audio embedding frames to reduce the sequence length by a factor
  133. of `stack_factor`.
  134. """
  135. def __init__(self, stack_factor: int = 8):
  136. super().__init__()
  137. self.stack_factor = stack_factor
  138. def forward(self, audio_embeds: torch.Tensor) -> torch.Tensor:
  139. B, T, C = audio_embeds.shape
  140. T_pad = (T + self.stack_factor -
  141. 1) // self.stack_factor * self.stack_factor
  142. audio_embeds = F.pad(audio_embeds, (0, 0, 0, T_pad - T))
  143. B, T, C = audio_embeds.shape
  144. audio_embeds = audio_embeds.view(B, T // self.stack_factor,
  145. C * self.stack_factor)
  146. return audio_embeds
  147. class FlippedSiluAndMul(SiluAndMul):
  148. """Ultravox is trained with SwiGLU with flipped halves."""
  149. def forward(self, x: torch.Tensor):
  150. a, b = x.chunk(2, dim=-1)
  151. flipped = torch.cat((b, a), dim=-1)
  152. return super().forward(flipped)
  153. class UltravoxProjector(nn.Module):
  154. def __init__(self, config: UltravoxConfig):
  155. super().__init__()
  156. self.hidden_dim = config.hidden_size
  157. self._pad_and_stack = StackAudioFrames(config.stack_factor)
  158. dim = config.audio_config.hidden_size * config.stack_factor
  159. self.ln_pre = RMSNorm(dim)
  160. self.linear_1 = nn.Linear(dim, self.hidden_dim, bias=False)
  161. dim = self.hidden_dim
  162. if config.projector_act == "swiglu":
  163. self.act = FlippedSiluAndMul()
  164. dim = dim // 2
  165. else:
  166. self.act = get_act_fn(config.projector_act)
  167. self.linear_2 = nn.Linear(dim,
  168. config.text_config.hidden_size,
  169. bias=False)
  170. self.ln_post = RMSNorm(config.text_config.hidden_size)
  171. def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
  172. audio_features = self._pad_and_stack(audio_features)
  173. audio_features = self.ln_pre(audio_features)
  174. hidden_states = self.linear_1(audio_features)
  175. hidden_states = self.act(hidden_states)
  176. hidden_states = self.linear_2(hidden_states)
  177. hidden_states = self.ln_post(hidden_states)
  178. return hidden_states
  179. class ModifiedWhisperEncoder(WhisperEncoder):
  180. """
  181. Encoder portion of OpenAI's Whisper model.
  182. This implementation is a slightly modified version of HF Transformers'
  183. Whisper Encoder, with only a few fixes:
  184. 1. base_model_prefix updated to allow for doing `.from_pretrained`
  185. directly on the encoder
  186. 2. allow less than 30 second of audio padding to be passed in:
  187. - relaxed ValueError check for `input_features` length to be less
  188. than or equal to `expected_seq_length` instead of strictly equal
  189. - embed_pos is now sliced to match the length of `inputs_embeds`
  190. Original: https://github.com/huggingface/transformers/blob/main/src/transformers/models/whisper/modeling_whisper.py
  191. See commentary: https://github.com/huggingface/transformers/issues/25744
  192. """
  193. base_model_prefix = "model.encoder"
  194. def forward(
  195. self,
  196. input_features,
  197. ):
  198. expected_seq_length = (self.config.max_source_positions *
  199. self.conv1.stride[0] * self.conv2.stride[0])
  200. if input_features.shape[-1] > expected_seq_length:
  201. raise ValueError(
  202. f"Whisper expects the mel input features to be of length "
  203. f"{expected_seq_length} or less, but found "
  204. f"{input_features.shape[-1]}. Make sure to pad the input mel "
  205. f"features to {expected_seq_length}.")
  206. inputs_embeds = nn.functional.gelu(self.conv1(input_features))
  207. inputs_embeds = nn.functional.gelu(self.conv2(inputs_embeds))
  208. inputs_embeds = inputs_embeds.permute(0, 2, 1)
  209. embed_pos = self.embed_positions.weight[:inputs_embeds.size(-2)]
  210. hidden_states = inputs_embeds + embed_pos
  211. hidden_states = nn.functional.dropout(hidden_states,
  212. p=self.dropout,
  213. training=self.training)
  214. for encoder_layer in self.layers:
  215. layer_outputs = encoder_layer(
  216. hidden_states,
  217. None,
  218. layer_head_mask=None,
  219. )
  220. hidden_states = layer_outputs[0]
  221. hidden_states = self.layer_norm(hidden_states)
  222. return hidden_states
  223. @MULTIMODAL_REGISTRY.register_input_mapper("audio", input_mapper_for_ultravox)
  224. @MULTIMODAL_REGISTRY.register_max_multimodal_tokens(
  225. "audio", get_ultravox_max_audio_tokens)
  226. @INPUT_REGISTRY.register_dummy_data(dummy_data_for_ultravox)
  227. @INPUT_REGISTRY.register_input_processor(input_processor_for_ultravox)
  228. class UltravoxModel(nn.Module, SupportsMultiModal):
  229. def __init__(self,
  230. config: UltravoxConfig,
  231. multimodal_config: MultiModalConfig,
  232. cache_config: Optional[CacheConfig] = None,
  233. quant_config: Optional["QuantizationConfig"] = None):
  234. super().__init__()
  235. self.config = config
  236. self.multi_modal_config = multimodal_config
  237. assert self.multi_modal_config
  238. if config.audio_model_id is not None:
  239. self.audio_tower = ModifiedWhisperEncoder.from_pretrained(
  240. config.audio_model_id)
  241. else:
  242. self.audio_tower = ModifiedWhisperEncoder(config.audio_config)
  243. self.multi_modal_projector = UltravoxProjector(config)
  244. self.language_model = init_aphrodite_registered_model(
  245. config.text_config, cache_config, quant_config)
  246. def _audio_features_to_embeddings(
  247. self, input_features: torch.Tensor) -> torch.Tensor:
  248. audio_input = input_features.to(self.audio_tower.dtype)
  249. audio_features = self.audio_tower(audio_input)
  250. audio_features = audio_features.to(self.audio_tower.dtype)
  251. audio_embeddings = self.multi_modal_projector(audio_features)
  252. return audio_embeddings
  253. def _parse_and_validate_audio_input(
  254. self, **kwargs: object) -> Optional[UltravoxAudioInputs]:
  255. audio_features = kwargs.pop("audio_features", None)
  256. audio_embeds = kwargs.pop("audio_embeds", None)
  257. if audio_features is None and audio_embeds is None:
  258. return None
  259. if audio_features is not None:
  260. if not isinstance(audio_features, (torch.Tensor, list)):
  261. raise ValueError("Incorrect type of audio features. "
  262. f"Got type: {type(audio_features)}")
  263. return UltravoxAudioFeatureInputs(type="audio_features",
  264. data=audio_features)
  265. if audio_embeds is not None:
  266. if not isinstance(audio_embeds, torch.Tensor):
  267. raise ValueError("Incorrect type of audio embeds. "
  268. f"Got type: {type(audio_embeds)}")
  269. return UltravoxAudioEmbeddingInputs(type="audio_embeds",
  270. data=audio_embeds)
  271. raise AssertionError("This line should be unreachable.")
  272. def _process_audio_input(
  273. self, audio_input: UltravoxAudioInputs
  274. ) -> Union[torch.Tensor, List[torch.Tensor]]:
  275. if audio_input["type"] == "audio_embeds":
  276. return audio_input["data"]
  277. audio_features = audio_input["data"]
  278. if isinstance(audio_features, list):
  279. # TODO: Batch these through the encoder/projector instead of
  280. # serializing them.
  281. return [
  282. self._audio_features_to_embeddings(
  283. features.unsqueeze(0)).squeeze(0)
  284. for features in audio_features
  285. ]
  286. else:
  287. return self._audio_features_to_embeddings(audio_features)
  288. def forward(self, input_ids: torch.Tensor, positions: torch.Tensor,
  289. kv_caches: List[torch.Tensor],
  290. attn_metadata: AttentionMetadata,
  291. intermediate_tensors: Optional[torch.Tensor],
  292. **kwargs) -> SamplerOutput:
  293. """Run forward pass for Ultravox
  294. One key thing to understand is the `input_ids` already accounts for the
  295. positions of the to-be-inserted audio embeddings. The to-be-inserted
  296. audio has a size that is essentially 6.25 tokens per second of audio.
  297. This way, the `positions` and `attn_metadata` are consistent
  298. with the `input_ids`.
  299. Args:
  300. input_features: A batch of audio inputs, [1, 80, M].
  301. """
  302. audio_input = self._parse_and_validate_audio_input(**kwargs)
  303. if audio_input is not None:
  304. audio_embeddings = self._process_audio_input(audio_input)
  305. inputs_embeds = self.language_model.model.get_input_embeddings(
  306. input_ids)
  307. inputs_embeds = merge_multimodal_embeddings(
  308. input_ids, inputs_embeds, audio_embeddings,
  309. _AUDIO_PLACEHOLDER_TOKEN)
  310. input_ids = None
  311. else:
  312. inputs_embeds = None
  313. hidden_states = self.language_model.model(
  314. input_ids=input_ids,
  315. positions=positions,
  316. kv_caches=kv_caches,
  317. attn_metadata=attn_metadata,
  318. intermediate_tensors=intermediate_tensors,
  319. inputs_embeds=inputs_embeds)
  320. return hidden_states
  321. def compute_logits(self, hidden_states: torch.Tensor,
  322. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  323. return self.language_model.compute_logits(hidden_states,
  324. sampling_metadata)
  325. def sample(
  326. self,
  327. logits: torch.Tensor,
  328. sampling_metadata: SamplingMetadata,
  329. ) -> Optional[SamplerOutput]:
  330. return self.language_model.sample(logits, sampling_metadata)
  331. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  332. # prepare weight iterators for components
  333. projector_weights, llm_weights = itertools.tee(weights, 2)
  334. # load projector weights
  335. projector_weights = filter_weights(projector_weights,
  336. "multi_modal_projector")
  337. projector_params_dict = dict(
  338. self.multi_modal_projector.named_parameters())
  339. for name, loaded_weight in projector_weights:
  340. param = projector_params_dict[name]
  341. weight_loader = getattr(param, "weight_loader",
  342. default_weight_loader)
  343. weight_loader(param, loaded_weight)
  344. # load llm backbone
  345. llm_weights = filter_weights(llm_weights, "language_model")
  346. self.language_model.load_weights(llm_weights)