modeling_mimi.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  1. # coding=utf-8
  2. # Copyright 2024 Kyutai, and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch Mimi model."""
  16. import math
  17. from dataclasses import dataclass
  18. from typing import List, Optional, Tuple, Union
  19. import torch
  20. import torch.utils.checkpoint
  21. from torch import nn
  22. from ...activations import ACT2FN
  23. from ...cache_utils import Cache, DynamicCache, SlidingWindowCache, StaticCache
  24. from ...modeling_attn_mask_utils import AttentionMaskConverter
  25. from ...modeling_outputs import BaseModelOutputWithPast
  26. from ...modeling_utils import PreTrainedModel
  27. from ...utils import (
  28. ModelOutput,
  29. add_start_docstrings,
  30. add_start_docstrings_to_model_forward,
  31. is_flash_attn_2_available,
  32. is_flash_attn_greater_or_equal_2_10,
  33. logging,
  34. replace_return_docstrings,
  35. )
  36. from .configuration_mimi import MimiConfig
  37. if is_flash_attn_2_available():
  38. from ...modeling_flash_attention_utils import _flash_attention_forward
  39. logger = logging.get_logger(__name__)
  40. # General docstring
  41. _CONFIG_FOR_DOC = "MimiConfig"
  42. @dataclass
  43. class MimiOutput(ModelOutput):
  44. """
  45. Args:
  46. audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
  47. Discret code embeddings computed using `model.encode`.
  48. audio_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*)
  49. Decoded audio values, obtained using the decoder part of Mimi.
  50. encoder_past_key_values (`Cache`, *optional*):
  51. Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the encoder transformer.
  52. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  53. The model will output the same cache format that is fed as input.
  54. If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
  55. have their past key value states given to this model).
  56. decoder_past_key_values (`Cache`, *optional*):
  57. Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the decoder transformer.
  58. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  59. The model will output the same cache format that is fed as input.
  60. If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
  61. have their past key value states given to this model).
  62. """
  63. audio_codes: torch.LongTensor = None
  64. audio_values: torch.FloatTensor = None
  65. encoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None
  66. decoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None
  67. @dataclass
  68. class MimiEncoderOutput(ModelOutput):
  69. """
  70. Args:
  71. audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
  72. Discret code embeddings computed using `model.encode`.
  73. encoder_past_key_values (`Cache`, *optional*):
  74. Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the encoder transformer.
  75. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  76. The model will output the same cache format that is fed as input.
  77. If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
  78. have their past key value states given to this model).
  79. """
  80. audio_codes: torch.LongTensor = None
  81. encoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None
  82. @dataclass
  83. class MimiDecoderOutput(ModelOutput):
  84. """
  85. Args:
  86. audio_values (`torch.FloatTensor` of shape `(batch_size, segment_length)`, *optional*):
  87. Decoded audio values, obtained using the decoder part of Mimi.
  88. decoder_past_key_values (`Cache`, *optional*):
  89. Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the decoder transformer.
  90. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  91. The model will output the same cache format that is fed as input.
  92. If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
  93. have their past key value states given to this model).
  94. """
  95. audio_values: torch.FloatTensor = None
  96. decoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None
  97. class MimiConv1d(nn.Module):
  98. """Conv1d with asymmetric or causal padding and normalization."""
  99. def __init__(
  100. self,
  101. config,
  102. in_channels: int,
  103. out_channels: int,
  104. kernel_size: int,
  105. stride: int = 1,
  106. dilation: int = 1,
  107. groups: int = 1,
  108. pad_mode=None,
  109. bias: bool = True,
  110. ):
  111. super().__init__()
  112. self.causal = config.use_causal_conv
  113. self.pad_mode = config.pad_mode if pad_mode is None else pad_mode
  114. # warn user on unusual setup between dilation and stride
  115. if stride > 1 and dilation > 1:
  116. logger.warning(
  117. "MimiConv1d has been initialized with stride > 1 and dilation > 1"
  118. f" (kernel_size={kernel_size} stride={stride}, dilation={dilation})."
  119. )
  120. self.conv = nn.Conv1d(
  121. in_channels, out_channels, kernel_size, stride, dilation=dilation, groups=groups, bias=bias
  122. )
  123. kernel_size = self.conv.kernel_size[0]
  124. stride = torch.tensor(self.conv.stride[0], dtype=torch.int64)
  125. dilation = self.conv.dilation[0]
  126. # Effective kernel size with dilations.
  127. kernel_size = torch.tensor((kernel_size - 1) * dilation + 1, dtype=torch.int64)
  128. self.register_buffer("stride", stride, persistent=False)
  129. self.register_buffer("kernel_size", kernel_size, persistent=False)
  130. self.register_buffer("padding_total", torch.tensor(kernel_size - stride, dtype=torch.int64), persistent=False)
  131. # Asymmetric padding required for odd strides
  132. self.padding_right = self.padding_total // 2
  133. self.padding_left = self.padding_total - self.padding_right
  134. def apply_weight_norm(self):
  135. weight_norm = nn.utils.weight_norm
  136. if hasattr(nn.utils.parametrizations, "weight_norm"):
  137. weight_norm = nn.utils.parametrizations.weight_norm
  138. weight_norm(self.conv)
  139. def remove_weight_norm(self):
  140. nn.utils.remove_weight_norm(self.conv)
  141. # Copied from transformers.models.encodec.modeling_encodec.EncodecConv1d._get_extra_padding_for_conv1d
  142. def _get_extra_padding_for_conv1d(
  143. self,
  144. hidden_states: torch.Tensor,
  145. ) -> torch.Tensor:
  146. """See `pad_for_conv1d`."""
  147. length = hidden_states.shape[-1]
  148. n_frames = (length - self.kernel_size + self.padding_total) / self.stride + 1
  149. n_frames = torch.ceil(n_frames).to(torch.int64) - 1
  150. ideal_length = n_frames * self.stride + self.kernel_size - self.padding_total
  151. return ideal_length - length
  152. @staticmethod
  153. # Copied from transformers.models.encodec.modeling_encodec.EncodecConv1d._pad1d
  154. def _pad1d(hidden_states: torch.Tensor, paddings: Tuple[int, int], mode: str = "zero", value: float = 0.0):
  155. """Tiny wrapper around torch.nn.functional.pad, just to allow for reflect padding on small input.
  156. If this is the case, we insert extra 0 padding to the right before the reflection happens.
  157. """
  158. length = hidden_states.shape[-1]
  159. padding_left, padding_right = paddings
  160. if not mode == "reflect":
  161. return nn.functional.pad(hidden_states, paddings, mode, value)
  162. max_pad = max(padding_left, padding_right)
  163. extra_pad = 0
  164. if length <= max_pad:
  165. extra_pad = max_pad - length + 1
  166. hidden_states = nn.functional.pad(hidden_states, (0, extra_pad))
  167. padded = nn.functional.pad(hidden_states, paddings, mode, value)
  168. end = padded.shape[-1] - extra_pad
  169. return padded[..., :end]
  170. def forward(self, hidden_states):
  171. extra_padding = self._get_extra_padding_for_conv1d(hidden_states)
  172. if self.causal:
  173. # Left padding for causal
  174. hidden_states = self._pad1d(hidden_states, (self.padding_total, extra_padding), mode=self.pad_mode)
  175. else:
  176. hidden_states = self._pad1d(
  177. hidden_states, (self.padding_left, self.padding_right + extra_padding), mode=self.pad_mode
  178. )
  179. hidden_states = self.conv(hidden_states)
  180. return hidden_states
  181. class MimiConvTranspose1d(nn.Module):
  182. """ConvTranspose1d with asymmetric or causal padding and normalization."""
  183. def __init__(
  184. self,
  185. config,
  186. in_channels: int,
  187. out_channels: int,
  188. kernel_size: int,
  189. stride: int = 1,
  190. groups: int = 1,
  191. bias=True,
  192. ):
  193. super().__init__()
  194. self.causal = config.use_causal_conv
  195. self.trim_right_ratio = config.trim_right_ratio
  196. self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride, groups=groups, bias=bias)
  197. if not (self.causal or self.trim_right_ratio == 1.0):
  198. raise ValueError("`trim_right_ratio` != 1.0 only makes sense for causal convolutions")
  199. kernel_size = self.conv.kernel_size[0]
  200. stride = self.conv.stride[0]
  201. padding_total = kernel_size - stride
  202. # We will only trim fixed padding. Extra padding from `pad_for_conv1d` would be
  203. # removed at the very end, when keeping only the right length for the output,
  204. # as removing it here would require also passing the length at the matching layer
  205. # in the encoder.
  206. if self.causal:
  207. # Trim the padding on the right according to the specified ratio
  208. # if trim_right_ratio = 1.0, trim everything from right
  209. self.padding_right = math.ceil(padding_total * self.trim_right_ratio)
  210. else:
  211. # Asymmetric padding required for odd strides
  212. self.padding_right = padding_total // 2
  213. self.padding_left = padding_total - self.padding_right
  214. def apply_weight_norm(self):
  215. weight_norm = nn.utils.weight_norm
  216. if hasattr(nn.utils.parametrizations, "weight_norm"):
  217. weight_norm = nn.utils.parametrizations.weight_norm
  218. weight_norm(self.conv)
  219. def remove_weight_norm(self):
  220. nn.utils.remove_weight_norm(self.conv)
  221. def forward(self, hidden_states):
  222. hidden_states = self.conv(hidden_states)
  223. # unpad
  224. end = hidden_states.shape[-1] - self.padding_right
  225. hidden_states = hidden_states[..., self.padding_left : end]
  226. return hidden_states
  227. # Copied from transformers.models.encodec.modeling_encodec.EncodecResnetBlock with Encodec->Mimi,EnCodec->Mimi
  228. class MimiResnetBlock(nn.Module):
  229. """
  230. Residual block from SEANet model as used by Mimi.
  231. """
  232. def __init__(self, config: MimiConfig, dim: int, dilations: List[int]):
  233. super().__init__()
  234. kernel_sizes = (config.residual_kernel_size, 1)
  235. if len(kernel_sizes) != len(dilations):
  236. raise ValueError("Number of kernel sizes should match number of dilations")
  237. hidden = dim // config.compress
  238. block = []
  239. for i, (kernel_size, dilation) in enumerate(zip(kernel_sizes, dilations)):
  240. in_chs = dim if i == 0 else hidden
  241. out_chs = dim if i == len(kernel_sizes) - 1 else hidden
  242. block += [nn.ELU()]
  243. block += [MimiConv1d(config, in_chs, out_chs, kernel_size, dilation=dilation)]
  244. self.block = nn.ModuleList(block)
  245. if config.use_conv_shortcut:
  246. self.shortcut = MimiConv1d(config, dim, dim, kernel_size=1)
  247. else:
  248. self.shortcut = nn.Identity()
  249. def forward(self, hidden_states):
  250. residual = hidden_states
  251. for layer in self.block:
  252. hidden_states = layer(hidden_states)
  253. return self.shortcut(residual) + hidden_states
  254. class MimiEncoder(nn.Module):
  255. """SEANet encoder as used by Mimi."""
  256. def __init__(self, config: MimiConfig):
  257. super().__init__()
  258. model = [MimiConv1d(config, config.audio_channels, config.num_filters, config.kernel_size)]
  259. scaling = 1
  260. # Downsample to raw audio scale
  261. for ratio in reversed(config.upsampling_ratios):
  262. current_scale = scaling * config.num_filters
  263. # Add residual layers
  264. for j in range(config.num_residual_layers):
  265. model += [MimiResnetBlock(config, current_scale, [config.dilation_growth_rate**j, 1])]
  266. # Add downsampling layers
  267. model += [nn.ELU()]
  268. model += [MimiConv1d(config, current_scale, current_scale * 2, kernel_size=ratio * 2, stride=ratio)]
  269. scaling *= 2
  270. model += [nn.ELU()]
  271. model += [MimiConv1d(config, scaling * config.num_filters, config.hidden_size, config.last_kernel_size)]
  272. self.layers = nn.ModuleList(model)
  273. # Copied from transformers.models.encodec.modeling_encodec.EncodecEncoder.forward
  274. def forward(self, hidden_states):
  275. for layer in self.layers:
  276. hidden_states = layer(hidden_states)
  277. return hidden_states
  278. class MimiLayerScale(nn.Module):
  279. """Layer scale from [Touvron et al 2021] (https://arxiv.org/pdf/2103.17239.pdf).
  280. This rescales diagonally the residual outputs close to 0, with a learnt scale.
  281. """
  282. def __init__(self, config):
  283. super().__init__()
  284. channels = config.hidden_size
  285. initial_scale = config.layer_scale_initial_scale
  286. self.scale = nn.Parameter(torch.full((channels,), initial_scale, requires_grad=True))
  287. def forward(self, x: torch.Tensor):
  288. return self.scale * x
  289. # Copied from transformers.models.mistral.modeling_mistral.MistralRotaryEmbedding with Mistral->Mimi
  290. class MimiRotaryEmbedding(nn.Module):
  291. def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
  292. super().__init__()
  293. self.dim = dim
  294. self.max_position_embeddings = max_position_embeddings
  295. self.base = base
  296. inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
  297. self.register_buffer("inv_freq", inv_freq, persistent=False)
  298. @torch.no_grad()
  299. # copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding.forward
  300. # TODO(joao): add me back asap :)
  301. def forward(self, x, position_ids):
  302. # x: [bs, num_attention_heads, seq_len, head_size]
  303. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
  304. position_ids_expanded = position_ids[:, None, :].float()
  305. # Force float32 since bfloat16 loses precision on long contexts
  306. # See https://github.com/huggingface/transformers/pull/29285
  307. device_type = x.device.type
  308. device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
  309. with torch.autocast(device_type=device_type, enabled=False):
  310. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  311. emb = torch.cat((freqs, freqs), dim=-1)
  312. cos = emb.cos()
  313. sin = emb.sin()
  314. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  315. # Copied from transformers.models.llama.modeling_llama.rotate_half
  316. def rotate_half(x):
  317. """Rotates half the hidden dims of the input."""
  318. x1 = x[..., : x.shape[-1] // 2]
  319. x2 = x[..., x.shape[-1] // 2 :]
  320. return torch.cat((-x2, x1), dim=-1)
  321. # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
  322. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  323. """Applies Rotary Position Embedding to the query and key tensors.
  324. Args:
  325. q (`torch.Tensor`): The query tensor.
  326. k (`torch.Tensor`): The key tensor.
  327. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  328. sin (`torch.Tensor`): The sine part of the rotary embedding.
  329. position_ids (`torch.Tensor`, *optional*):
  330. Deprecated and unused.
  331. unsqueeze_dim (`int`, *optional*, defaults to 1):
  332. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  333. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  334. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  335. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  336. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  337. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  338. Returns:
  339. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  340. """
  341. cos = cos.unsqueeze(unsqueeze_dim)
  342. sin = sin.unsqueeze(unsqueeze_dim)
  343. q_embed = (q * cos) + (rotate_half(q) * sin)
  344. k_embed = (k * cos) + (rotate_half(k) * sin)
  345. return q_embed, k_embed
  346. class MimiMLP(nn.Module):
  347. def __init__(self, config):
  348. super().__init__()
  349. self.config = config
  350. self.activation_fn = ACT2FN[config.hidden_act]
  351. self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
  352. self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
  353. # Copied from transformers.models.clip.modeling_clip.CLIPMLP.forward
  354. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  355. hidden_states = self.fc1(hidden_states)
  356. hidden_states = self.activation_fn(hidden_states)
  357. hidden_states = self.fc2(hidden_states)
  358. return hidden_states
  359. # Copied from transformers.models.llama.modeling_llama.repeat_kv
  360. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  361. """
  362. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  363. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  364. """
  365. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  366. if n_rep == 1:
  367. return hidden_states
  368. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  369. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  370. # Copied from transformers.models.gemma.modeling_gemma.GemmaAttention with Gemma->Mimi
  371. class MimiAttention(nn.Module):
  372. """Multi-headed attention from 'Attention Is All You Need' paper"""
  373. def __init__(self, config: MimiConfig, layer_idx: Optional[int] = None):
  374. super().__init__()
  375. self.config = config
  376. self.layer_idx = layer_idx
  377. if layer_idx is None:
  378. logger.warning_once(
  379. f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
  380. "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
  381. "when creating this class."
  382. )
  383. self.attention_dropout = config.attention_dropout
  384. self.hidden_size = config.hidden_size
  385. self.num_heads = config.num_attention_heads
  386. self.head_dim = config.head_dim
  387. self.num_key_value_heads = config.num_key_value_heads
  388. self.num_key_value_groups = self.num_heads // self.num_key_value_heads
  389. self.max_position_embeddings = config.max_position_embeddings
  390. self.rope_theta = config.rope_theta
  391. self.is_causal = True
  392. self.scaling = 1 / math.sqrt(config.head_dim)
  393. if self.hidden_size % self.num_heads != 0:
  394. raise ValueError(
  395. f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
  396. f" and `num_heads`: {self.num_heads})."
  397. )
  398. self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
  399. self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  400. self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
  401. self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
  402. self.rotary_emb = MimiRotaryEmbedding(
  403. self.head_dim,
  404. max_position_embeddings=self.max_position_embeddings,
  405. base=self.rope_theta,
  406. )
  407. self.sliding_window = config.sliding_window # Ignore copy
  408. def forward(
  409. self,
  410. hidden_states: torch.Tensor,
  411. attention_mask: Optional[torch.Tensor] = None,
  412. position_ids: Optional[torch.LongTensor] = None,
  413. past_key_value: Optional[Cache] = None,
  414. output_attentions: bool = False,
  415. use_cache: bool = False,
  416. cache_position: Optional[torch.LongTensor] = None,
  417. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  418. bsz, q_len, _ = hidden_states.size()
  419. query_states = self.q_proj(hidden_states)
  420. key_states = self.k_proj(hidden_states)
  421. value_states = self.v_proj(hidden_states)
  422. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  423. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  424. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  425. cos, sin = self.rotary_emb(value_states, position_ids)
  426. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  427. if past_key_value is not None:
  428. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  429. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  430. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  431. key_states = repeat_kv(key_states, self.num_key_value_groups)
  432. value_states = repeat_kv(value_states, self.num_key_value_groups)
  433. attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
  434. if attention_mask is not None: # no matter the length, we just slice it
  435. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  436. attn_weights = attn_weights + causal_mask
  437. # upcast attention to fp32
  438. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
  439. attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
  440. attn_output = torch.matmul(attn_weights, value_states)
  441. if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
  442. raise ValueError(
  443. f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
  444. f" {attn_output.size()}"
  445. )
  446. attn_output = attn_output.transpose(1, 2).contiguous()
  447. attn_output = attn_output.view(bsz, q_len, -1)
  448. attn_output = self.o_proj(attn_output)
  449. if not output_attentions:
  450. attn_weights = None
  451. return attn_output, attn_weights, past_key_value
  452. # Copied from transformers.models.gemma.modeling_gemma.GemmaFlashAttention2 with Gemma->Mimi
  453. class MimiFlashAttention2(MimiAttention):
  454. """
  455. Mimi flash attention module. This module inherits from `MimiAttention` as the weights of the module stays
  456. untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
  457. flash attention and deal with padding tokens in case the input contains any of them.
  458. """
  459. def __init__(self, *args, **kwargs):
  460. super().__init__(*args, **kwargs)
  461. # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
  462. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
  463. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
  464. self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
  465. def forward(
  466. self,
  467. hidden_states: torch.Tensor,
  468. attention_mask: Optional[torch.LongTensor] = None,
  469. position_ids: Optional[torch.LongTensor] = None,
  470. past_key_value: Optional[Cache] = None,
  471. output_attentions: bool = False,
  472. use_cache: bool = False,
  473. cache_position: Optional[torch.LongTensor] = None,
  474. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  475. if isinstance(past_key_value, StaticCache):
  476. raise ValueError(
  477. "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
  478. "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
  479. )
  480. output_attentions = False
  481. bsz, q_len, _ = hidden_states.size()
  482. query_states = self.q_proj(hidden_states)
  483. key_states = self.k_proj(hidden_states)
  484. value_states = self.v_proj(hidden_states)
  485. # Flash attention requires the input to have the shape
  486. # batch_size x seq_length x head_dim x hidden_dim
  487. # therefore we just need to keep the original shape
  488. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  489. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  490. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  491. cos, sin = self.rotary_emb(value_states, position_ids)
  492. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  493. if past_key_value is not None:
  494. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  495. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  496. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  497. # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
  498. # to be able to avoid many of these transpose/reshape/view.
  499. query_states = query_states.transpose(1, 2)
  500. key_states = key_states.transpose(1, 2)
  501. value_states = value_states.transpose(1, 2)
  502. dropout_rate = self.attention_dropout if self.training else 0.0
  503. # In PEFT, usually we cast the layer norms in float32 for training stability reasons
  504. # therefore the input hidden states gets silently casted in float32. Hence, we need
  505. # cast them back in the correct dtype just to be sure everything works as expected.
  506. # This might slowdown training & inference so it is recommended to not cast the LayerNorms
  507. # in fp32. (MimiRMSNorm handles it correctly)
  508. input_dtype = query_states.dtype
  509. if input_dtype == torch.float32:
  510. if torch.is_autocast_enabled():
  511. target_dtype = torch.get_autocast_gpu_dtype()
  512. # Handle the case where the model is quantized
  513. elif hasattr(self.config, "_pre_quantization_dtype"):
  514. target_dtype = self.config._pre_quantization_dtype
  515. else:
  516. target_dtype = self.q_proj.weight.dtype
  517. logger.warning_once(
  518. f"The input hidden states seems to be silently casted in float32, this might be related to"
  519. f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
  520. f" {target_dtype}."
  521. )
  522. query_states = query_states.to(target_dtype)
  523. key_states = key_states.to(target_dtype)
  524. value_states = value_states.to(target_dtype)
  525. attn_output = _flash_attention_forward(
  526. query_states,
  527. key_states,
  528. value_states,
  529. attention_mask,
  530. q_len,
  531. position_ids=position_ids,
  532. dropout=dropout_rate,
  533. sliding_window=getattr(self, "sliding_window", None),
  534. is_causal=self.is_causal,
  535. use_top_left_mask=self._flash_attn_uses_top_left_mask,
  536. )
  537. attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
  538. attn_output = self.o_proj(attn_output)
  539. if not output_attentions:
  540. attn_weights = None
  541. return attn_output, attn_weights, past_key_value
  542. # Copied from transformers.models.gemma.modeling_gemma.GemmaSdpaAttention with Gemma->Mimi
  543. class MimiSdpaAttention(MimiAttention):
  544. """
  545. Mimi attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
  546. `MimiAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
  547. SDPA API.
  548. """
  549. # Adapted from MimiAttention.forward
  550. def forward(
  551. self,
  552. hidden_states: torch.Tensor,
  553. attention_mask: Optional[torch.Tensor] = None,
  554. position_ids: Optional[torch.LongTensor] = None,
  555. past_key_value: Optional[Cache] = None,
  556. output_attentions: bool = False,
  557. use_cache: bool = False,
  558. cache_position: Optional[torch.LongTensor] = None,
  559. **kwargs,
  560. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  561. if output_attentions:
  562. # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
  563. logger.warning_once(
  564. "MimiModel is using MimiSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
  565. 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
  566. )
  567. return super().forward(
  568. hidden_states=hidden_states,
  569. attention_mask=attention_mask,
  570. position_ids=position_ids,
  571. past_key_value=past_key_value,
  572. output_attentions=output_attentions,
  573. use_cache=use_cache,
  574. cache_position=cache_position,
  575. )
  576. bsz, q_len, _ = hidden_states.size()
  577. query_states = self.q_proj(hidden_states)
  578. key_states = self.k_proj(hidden_states)
  579. value_states = self.v_proj(hidden_states)
  580. query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
  581. key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  582. value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
  583. cos, sin = self.rotary_emb(value_states, position_ids)
  584. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  585. if past_key_value is not None:
  586. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  587. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  588. key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
  589. key_states = repeat_kv(key_states, self.num_key_value_groups)
  590. value_states = repeat_kv(value_states, self.num_key_value_groups)
  591. causal_mask = attention_mask
  592. if attention_mask is not None:
  593. causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
  594. # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
  595. # Reference: https://github.com/pytorch/pytorch/issues/112577.
  596. if query_states.device.type == "cuda" and causal_mask is not None:
  597. query_states = query_states.contiguous()
  598. key_states = key_states.contiguous()
  599. value_states = value_states.contiguous()
  600. # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
  601. # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
  602. is_causal = True if causal_mask is None and q_len > 1 else False
  603. attn_output = torch.nn.functional.scaled_dot_product_attention(
  604. query_states,
  605. key_states,
  606. value_states,
  607. attn_mask=causal_mask,
  608. dropout_p=self.attention_dropout if self.training else 0.0,
  609. is_causal=is_causal,
  610. )
  611. attn_output = attn_output.transpose(1, 2).contiguous()
  612. attn_output = attn_output.view(bsz, q_len, -1)
  613. attn_output = self.o_proj(attn_output)
  614. return attn_output, None, past_key_value
  615. MIMI_ATTENTION_CLASSES = {
  616. "eager": MimiAttention,
  617. "flash_attention_2": MimiFlashAttention2,
  618. "sdpa": MimiSdpaAttention,
  619. }
  620. class MimiTransformerLayer(nn.Module):
  621. def __init__(self, config: MimiConfig, layer_idx: int):
  622. super().__init__()
  623. self.hidden_size = config.hidden_size
  624. self.self_attn = MIMI_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
  625. self.mlp = MimiMLP(config)
  626. self.input_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
  627. self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps)
  628. self.self_attn_layer_scale = MimiLayerScale(config)
  629. self.mlp_layer_scale = MimiLayerScale(config)
  630. def forward(
  631. self,
  632. hidden_states: torch.Tensor,
  633. attention_mask: Optional[torch.Tensor] = None,
  634. position_ids: Optional[torch.LongTensor] = None,
  635. past_key_value: Optional[Cache] = None,
  636. output_attentions: Optional[bool] = False,
  637. use_cache: Optional[bool] = False,
  638. cache_position: Optional[torch.LongTensor] = None,
  639. **kwargs,
  640. ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
  641. """
  642. Args:
  643. hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
  644. attention_mask (`torch.FloatTensor`, *optional*):
  645. attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
  646. query_sequence_length, key_sequence_length)` if default attention is used.
  647. output_attentions (`bool`, *optional*):
  648. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  649. returned tensors for more detail.
  650. use_cache (`bool`, *optional*):
  651. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
  652. (see `past_key_values`).
  653. past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
  654. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
  655. Indices depicting the position of the input sequence tokens in the sequence
  656. kwargs (`dict`, *optional*):
  657. Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
  658. into the model
  659. """
  660. residual = hidden_states
  661. hidden_states = self.input_layernorm(hidden_states)
  662. # Self Attention
  663. hidden_states, self_attn_weights, present_key_value = self.self_attn(
  664. hidden_states=hidden_states,
  665. attention_mask=attention_mask,
  666. position_ids=position_ids,
  667. past_key_value=past_key_value,
  668. output_attentions=output_attentions,
  669. use_cache=use_cache,
  670. cache_position=cache_position,
  671. **kwargs,
  672. )
  673. hidden_states = residual + self.self_attn_layer_scale(hidden_states)
  674. # Fully Connected
  675. residual = hidden_states
  676. hidden_states = self.post_attention_layernorm(hidden_states)
  677. hidden_states = self.mlp(hidden_states)
  678. hidden_states = residual + self.mlp_layer_scale(hidden_states)
  679. outputs = (hidden_states,)
  680. if output_attentions:
  681. outputs += (self_attn_weights,)
  682. if use_cache:
  683. outputs += (present_key_value,)
  684. return outputs
  685. class MimiTransformerModel(nn.Module):
  686. """
  687. Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MimiTransformerLayer`]
  688. Args:
  689. config: MimiConfig
  690. """
  691. def __init__(self, config: MimiConfig):
  692. super().__init__()
  693. self.layers = nn.ModuleList(
  694. [MimiTransformerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  695. )
  696. self._attn_implementation = config._attn_implementation
  697. self.gradient_checkpointing = False
  698. self.config = config
  699. def forward(
  700. self,
  701. hidden_states: torch.LongTensor = None,
  702. attention_mask: Optional[torch.Tensor] = None,
  703. position_ids: Optional[torch.LongTensor] = None,
  704. past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  705. use_cache: Optional[bool] = None,
  706. output_attentions: Optional[bool] = None,
  707. output_hidden_states: Optional[bool] = None,
  708. return_dict: Optional[bool] = None,
  709. cache_position: Optional[torch.LongTensor] = None,
  710. ) -> Union[Tuple, BaseModelOutputWithPast]:
  711. """
  712. Args:
  713. hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  714. Embedded representation that will be contextualized by the model
  715. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  716. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  717. - 1 for tokens that are **not masked**,
  718. - 0 for tokens that are **masked**.
  719. [What are attention masks?](../glossary#attention-mask)
  720. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  721. [`PreTrainedTokenizer.__call__`] for details.
  722. If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
  723. `past_key_values`).
  724. If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
  725. and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
  726. information on the default strategy.
  727. - 1 indicates the head is **not masked**,
  728. - 0 indicates the head is **masked**.
  729. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  730. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  731. config.n_positions - 1]`.
  732. [What are position IDs?](../glossary#position-ids)
  733. past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
  734. Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
  735. blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
  736. returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  737. Two formats are allowed:
  738. - a [`~cache_utils.Cache`] instance;
  739. - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
  740. shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
  741. cache format.
  742. The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
  743. legacy cache format will be returned.
  744. If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
  745. have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
  746. of shape `(batch_size, sequence_length)`.
  747. use_cache (`bool`, *optional*):
  748. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  749. `past_key_values`).
  750. output_attentions (`bool`, *optional*):
  751. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  752. tensors for more detail.
  753. output_hidden_states (`bool`, *optional*):
  754. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  755. more detail.
  756. return_dict (`bool`, *optional*):
  757. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  758. """
  759. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  760. output_hidden_states = (
  761. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  762. )
  763. use_cache = use_cache if use_cache is not None else self.config.use_cache
  764. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  765. if self.gradient_checkpointing and self.training and use_cache:
  766. logger.warning_once(
  767. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
  768. )
  769. use_cache = False
  770. if use_cache and not isinstance(past_key_values, Cache):
  771. if past_key_values is None:
  772. past_key_values = DynamicCache()
  773. else:
  774. past_key_values = DynamicCache.from_legacy_cache(past_key_values)
  775. logger.warning_once(
  776. "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
  777. "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
  778. "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
  779. )
  780. if cache_position is None:
  781. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  782. cache_position = torch.arange(
  783. past_seen_tokens, past_seen_tokens + hidden_states.shape[1], device=hidden_states.device
  784. )
  785. if position_ids is None:
  786. position_ids = cache_position.unsqueeze(0)
  787. causal_mask = None
  788. if attention_mask is not None:
  789. causal_mask = self._update_causal_mask(
  790. attention_mask, hidden_states, cache_position, past_key_values, output_attentions
  791. )
  792. # decoder layers
  793. all_hidden_states = () if output_hidden_states else None
  794. all_self_attns = () if output_attentions else None
  795. next_decoder_cache = None
  796. for decoder_layer in self.layers:
  797. if output_hidden_states:
  798. all_hidden_states += (hidden_states,)
  799. if self.gradient_checkpointing and self.training:
  800. layer_outputs = self._gradient_checkpointing_func(
  801. decoder_layer.__call__,
  802. hidden_states,
  803. causal_mask,
  804. position_ids,
  805. past_key_values,
  806. output_attentions,
  807. use_cache,
  808. cache_position,
  809. )
  810. else:
  811. layer_outputs = decoder_layer(
  812. hidden_states,
  813. attention_mask=causal_mask,
  814. position_ids=position_ids,
  815. past_key_value=past_key_values,
  816. output_attentions=output_attentions,
  817. use_cache=use_cache,
  818. cache_position=cache_position,
  819. )
  820. hidden_states = layer_outputs[0]
  821. if use_cache:
  822. next_decoder_cache = layer_outputs[2 if output_attentions else 1]
  823. if output_attentions:
  824. all_self_attns += (layer_outputs[1],)
  825. # add hidden states from the last decoder layer
  826. if output_hidden_states:
  827. all_hidden_states += (hidden_states,)
  828. next_cache = next_decoder_cache if use_cache else None
  829. if not return_dict:
  830. return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
  831. return BaseModelOutputWithPast(
  832. last_hidden_state=hidden_states,
  833. past_key_values=next_cache,
  834. hidden_states=all_hidden_states,
  835. attentions=all_self_attns,
  836. )
  837. # Copied from transformers.models.phi3.modeling_phi3.Phi3Model._update_causal_mask
  838. def _update_causal_mask(
  839. self,
  840. attention_mask: torch.Tensor,
  841. input_tensor: torch.Tensor,
  842. cache_position: torch.Tensor,
  843. past_key_values: Cache,
  844. output_attentions: bool,
  845. ):
  846. if self.config._attn_implementation == "flash_attention_2":
  847. if attention_mask is not None and 0.0 in attention_mask:
  848. return attention_mask
  849. return None
  850. # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
  851. # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
  852. # to infer the attention mask.
  853. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  854. using_static_cache = isinstance(past_key_values, StaticCache)
  855. using_sliding_window_cache = isinstance(past_key_values, SlidingWindowCache)
  856. # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
  857. if (
  858. self.config._attn_implementation == "sdpa"
  859. and not (using_static_cache or using_sliding_window_cache)
  860. and not output_attentions
  861. ):
  862. if AttentionMaskConverter._ignore_causal_mask_sdpa(
  863. attention_mask,
  864. inputs_embeds=input_tensor,
  865. past_key_values_length=past_seen_tokens,
  866. sliding_window=self.config.sliding_window,
  867. is_training=self.training,
  868. ):
  869. return None
  870. dtype, device = input_tensor.dtype, input_tensor.device
  871. min_dtype = torch.finfo(dtype).min
  872. sequence_length = input_tensor.shape[1]
  873. # SlidingWindowCache or StaticCache
  874. if using_sliding_window_cache or using_static_cache:
  875. target_length = past_key_values.get_max_cache_shape()
  876. # DynamicCache or no cache
  877. else:
  878. target_length = (
  879. attention_mask.shape[-1]
  880. if isinstance(attention_mask, torch.Tensor)
  881. else past_seen_tokens + sequence_length + 1
  882. )
  883. # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
  884. causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
  885. attention_mask,
  886. sequence_length=sequence_length,
  887. target_length=target_length,
  888. dtype=dtype,
  889. device=device,
  890. cache_position=cache_position,
  891. batch_size=input_tensor.shape[0],
  892. config=self.config,
  893. past_key_values=past_key_values,
  894. )
  895. if (
  896. self.config._attn_implementation == "sdpa"
  897. and attention_mask is not None
  898. and attention_mask.device.type == "cuda"
  899. and not output_attentions
  900. ):
  901. # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
  902. # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
  903. # Details: https://github.com/pytorch/pytorch/issues/110213
  904. causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
  905. return causal_mask
  906. @staticmethod
  907. # Copied from transformers.models.mistral.modeling_mistral.MistralModel._prepare_4d_causal_attention_mask_with_cache_position with Mistral->Mimi
  908. def _prepare_4d_causal_attention_mask_with_cache_position(
  909. attention_mask: torch.Tensor,
  910. sequence_length: int,
  911. target_length: int,
  912. dtype: torch.dtype,
  913. device: torch.device,
  914. cache_position: torch.Tensor,
  915. batch_size: int,
  916. config: MimiConfig,
  917. past_key_values: Cache,
  918. ):
  919. """
  920. Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
  921. `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
  922. Args:
  923. attention_mask (`torch.Tensor`):
  924. A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
  925. sequence_length (`int`):
  926. The sequence length being processed.
  927. target_length (`int`):
  928. The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
  929. dtype (`torch.dtype`):
  930. The dtype to use for the 4D attention mask.
  931. device (`torch.device`):
  932. The device to plcae the 4D attention mask on.
  933. cache_position (`torch.Tensor`):
  934. Indices depicting the position of the input sequence tokens in the sequence.
  935. batch_size (`torch.Tensor`):
  936. Batch size.
  937. config (`MimiConfig`):
  938. The model's configuration class
  939. past_key_values (`Cache`):
  940. The cache class that is being used currently to generate
  941. """
  942. if attention_mask is not None and attention_mask.dim() == 4:
  943. # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
  944. causal_mask = attention_mask
  945. else:
  946. min_dtype = torch.finfo(dtype).min
  947. causal_mask = torch.full(
  948. (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
  949. )
  950. diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
  951. if config.sliding_window is not None:
  952. # if we have sliding window, we should not attend to tokens beyond sliding window length, so we mask them out also
  953. # the check is needed to verify is current checkpoint was trained with sliding window or not
  954. if not isinstance(past_key_values, SlidingWindowCache) or sequence_length > target_length:
  955. sliding_attend_mask = torch.arange(target_length, device=device) <= (
  956. cache_position.reshape(-1, 1) - config.sliding_window
  957. )
  958. diagonal_attend_mask.bitwise_or_(sliding_attend_mask)
  959. causal_mask *= diagonal_attend_mask
  960. causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
  961. if attention_mask is not None:
  962. causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
  963. if attention_mask.shape[-1] > target_length:
  964. attention_mask = attention_mask[:, :target_length]
  965. mask_length = attention_mask.shape[-1]
  966. padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
  967. padding_mask = padding_mask == 0
  968. causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
  969. padding_mask, min_dtype
  970. )
  971. return causal_mask
  972. class MimiDecoder(nn.Module):
  973. """SEANet decoder as used by Mimi."""
  974. def __init__(self, config: MimiConfig):
  975. super().__init__()
  976. scaling = int(2 ** len(config.upsampling_ratios))
  977. model = [MimiConv1d(config, config.hidden_size, scaling * config.num_filters, config.kernel_size)]
  978. # Upsample to raw audio scale
  979. for ratio in config.upsampling_ratios:
  980. current_scale = scaling * config.num_filters
  981. # Add upsampling layers
  982. model += [nn.ELU()]
  983. model += [
  984. MimiConvTranspose1d(config, current_scale, current_scale // 2, kernel_size=ratio * 2, stride=ratio)
  985. ]
  986. # Add residual layers
  987. for j in range(config.num_residual_layers):
  988. model += [MimiResnetBlock(config, current_scale // 2, (config.dilation_growth_rate**j, 1))]
  989. scaling //= 2
  990. # Add final layers
  991. model += [nn.ELU()]
  992. model += [MimiConv1d(config, config.num_filters, config.audio_channels, config.last_kernel_size)]
  993. self.layers = nn.ModuleList(model)
  994. # Copied from transformers.models.encodec.modeling_encodec.EncodecDecoder.forward
  995. def forward(self, hidden_states):
  996. for layer in self.layers:
  997. hidden_states = layer(hidden_states)
  998. return hidden_states
  999. class MimiEuclideanCodebook(nn.Module):
  1000. """Codebook with Euclidean distance."""
  1001. def __init__(self, config: MimiConfig, epsilon: float = 1e-5):
  1002. super().__init__()
  1003. embed = torch.zeros(config.codebook_size, config.codebook_dim)
  1004. self.codebook_size = config.codebook_size
  1005. self.register_buffer("initialized", torch.Tensor([True]))
  1006. self.register_buffer("cluster_usage", torch.ones(config.codebook_size))
  1007. self.register_buffer("embed_sum", embed)
  1008. self._embed = None
  1009. self.epsilon = epsilon
  1010. @property
  1011. def embed(self) -> torch.Tensor:
  1012. if self._embed is None:
  1013. self._embed = self.embed_sum / self.cluster_usage.clamp(min=self.epsilon)[:, None]
  1014. return self._embed
  1015. def quantize(self, hidden_states):
  1016. # Projects each vector in `hidden_states` over the nearest centroid and return its index.
  1017. # `hidden_states` should be `[N, D]` with `N` the number of input vectors and `D` the dimension.
  1018. dists = torch.cdist(hidden_states[None], self.embed[None], p=2)[0]
  1019. embed_ind = dists.argmin(dim=-1)
  1020. return embed_ind
  1021. # Copied from transformers.models.encodec.modeling_encodec.EncodecEuclideanCodebook.encode
  1022. def encode(self, hidden_states):
  1023. shape = hidden_states.shape
  1024. # pre-process
  1025. hidden_states = hidden_states.reshape((-1, shape[-1]))
  1026. # quantize
  1027. embed_ind = self.quantize(hidden_states)
  1028. # post-process
  1029. embed_ind = embed_ind.view(*shape[:-1])
  1030. return embed_ind
  1031. # Copied from transformers.models.encodec.modeling_encodec.EncodecEuclideanCodebook.decode
  1032. def decode(self, embed_ind):
  1033. quantize = nn.functional.embedding(embed_ind, self.embed)
  1034. return quantize
  1035. # Copied from transformers.models.encodec.modeling_encodec.EncodecVectorQuantization with Encodec->Mimi
  1036. class MimiVectorQuantization(nn.Module):
  1037. """
  1038. Vector quantization implementation. Currently supports only euclidean distance.
  1039. """
  1040. def __init__(self, config: MimiConfig):
  1041. super().__init__()
  1042. self.codebook = MimiEuclideanCodebook(config)
  1043. def encode(self, hidden_states):
  1044. hidden_states = hidden_states.permute(0, 2, 1)
  1045. embed_in = self.codebook.encode(hidden_states)
  1046. return embed_in
  1047. def decode(self, embed_ind):
  1048. quantize = self.codebook.decode(embed_ind)
  1049. quantize = quantize.permute(0, 2, 1)
  1050. return quantize
  1051. class MimiResidualVectorQuantizer(nn.Module):
  1052. """Residual Vector Quantizer."""
  1053. def __init__(self, config: MimiConfig, num_quantizers: int = None):
  1054. super().__init__()
  1055. self.codebook_size = config.codebook_size
  1056. self.frame_rate = config.frame_rate
  1057. self.num_quantizers = num_quantizers if num_quantizers is not None else config.num_quantizers
  1058. self.layers = nn.ModuleList([MimiVectorQuantization(config) for _ in range(self.num_quantizers)])
  1059. self.input_proj = None
  1060. self.output_proj = None
  1061. if config.vector_quantization_hidden_dimension != config.hidden_size:
  1062. self.input_proj = torch.nn.Conv1d(
  1063. config.hidden_size, config.vector_quantization_hidden_dimension, 1, bias=False
  1064. )
  1065. self.output_proj = torch.nn.Conv1d(
  1066. config.vector_quantization_hidden_dimension, config.hidden_size, 1, bias=False
  1067. )
  1068. def encode(self, embeddings: torch.Tensor, num_quantizers: Optional[int] = None) -> torch.Tensor:
  1069. """
  1070. Encode a given input tensor with the specified frame rate at the given number of quantizers / codebooks. The RVQ encode method sets
  1071. the appropriate number of quantizers to use and returns indices for each quantizer.
  1072. """
  1073. if self.input_proj is not None:
  1074. embeddings = self.input_proj(embeddings)
  1075. num_quantizers = num_quantizers if num_quantizers is not None else self.num_quantizers
  1076. residual = embeddings
  1077. all_indices = []
  1078. for layer in self.layers[:num_quantizers]:
  1079. indices = layer.encode(residual)
  1080. quantized = layer.decode(indices)
  1081. residual = residual - quantized
  1082. all_indices.append(indices)
  1083. out_indices = torch.stack(all_indices)
  1084. return out_indices
  1085. def decode(self, codes: torch.Tensor) -> torch.Tensor:
  1086. """Decode the given codes of shape [B, K, T] to the quantized representation."""
  1087. quantized_out = torch.tensor(0.0, device=codes.device)
  1088. codes = codes.transpose(0, 1)
  1089. for i, indices in enumerate(codes):
  1090. layer = self.layers[i]
  1091. quantized = layer.decode(indices)
  1092. quantized_out = quantized_out + quantized
  1093. if self.output_proj is not None:
  1094. quantized_out = self.output_proj(quantized_out)
  1095. return quantized_out
  1096. class MimiSplitResidualVectorQuantizer(nn.Module):
  1097. """Split Residual Vector Quantizer."""
  1098. def __init__(self, config: MimiConfig):
  1099. super().__init__()
  1100. self.codebook_size = config.codebook_size
  1101. self.frame_rate = config.frame_rate
  1102. self.max_num_quantizers = config.num_quantizers
  1103. self.num_semantic_quantizers = config.num_semantic_quantizers
  1104. self.num_acoustic_quantizers = config.num_quantizers - config.num_semantic_quantizers
  1105. self.semantic_residual_vector_quantizer = MimiResidualVectorQuantizer(config, self.num_semantic_quantizers)
  1106. self.acoustic_residual_vector_quantizer = MimiResidualVectorQuantizer(config, self.num_acoustic_quantizers)
  1107. def encode(self, embeddings: torch.Tensor, num_quantizers: Optional[float] = None) -> torch.Tensor:
  1108. """
  1109. Encode a given input tensor with the specified frame rate at the given number of quantizers / codebooks. The RVQ encode method sets
  1110. the appropriate number of quantizers to use and returns indices for each quantizer.
  1111. """
  1112. num_quantizers = self.max_num_quantizers if num_quantizers is None else num_quantizers
  1113. if num_quantizers > self.max_num_quantizers:
  1114. raise ValueError(
  1115. f"The number of quantizers (i.e codebooks) asked should be lower than the total number of quantizers {self.max_num_quantizers}, but is currently {num_quantizers}."
  1116. )
  1117. if num_quantizers < self.num_semantic_quantizers:
  1118. raise ValueError(
  1119. f"The number of quantizers (i.e codebooks) asked should be higher than the number of semantic quantizers {self.num_semantic_quantizers}, but is currently {num_quantizers}."
  1120. )
  1121. # codes is [K, B, T], with T frames, K nb of codebooks.
  1122. codes = self.semantic_residual_vector_quantizer.encode(embeddings)
  1123. if num_quantizers > self.num_semantic_quantizers:
  1124. acoustic_codes = self.acoustic_residual_vector_quantizer.encode(
  1125. embeddings, num_quantizers=num_quantizers - self.num_semantic_quantizers
  1126. )
  1127. codes = torch.cat([codes, acoustic_codes], dim=0)
  1128. return codes
  1129. def decode(self, codes: torch.Tensor) -> torch.Tensor:
  1130. """Decode the given codes to the quantized representation."""
  1131. # The first num_semantic_quantizers codebooks are decoded using the semantic RVQ
  1132. quantized_out = self.semantic_residual_vector_quantizer.decode(codes[:, : self.num_semantic_quantizers])
  1133. # The rest of the codebooks are decoded using the acoustic RVQ
  1134. if codes.shape[1] > self.num_semantic_quantizers:
  1135. quantized_out += self.acoustic_residual_vector_quantizer.decode(codes[:, self.num_semantic_quantizers :])
  1136. return quantized_out
  1137. class MimiPreTrainedModel(PreTrainedModel):
  1138. """
  1139. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  1140. models.
  1141. """
  1142. config_class = MimiConfig
  1143. base_model_prefix = "mimi"
  1144. main_input_name = "input_values"
  1145. supports_gradient_checkpointing = True
  1146. _no_split_modules = ["MimiDecoderLayer"]
  1147. _skip_keys_device_placement = "past_key_values"
  1148. _supports_flash_attn_2 = True
  1149. _supports_sdpa = True
  1150. _supports_cache_class = True
  1151. _supports_static_cache = True
  1152. # Copied from transformers.models.encodec.modeling_encodec.EncodecPreTrainedModel._init_weights
  1153. def _init_weights(self, module):
  1154. """Initialize the weights"""
  1155. if isinstance(module, nn.Linear):
  1156. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  1157. if module.bias is not None:
  1158. module.bias.data.zero_()
  1159. elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
  1160. module.bias.data.zero_()
  1161. module.weight.data.fill_(1.0)
  1162. elif isinstance(module, nn.Conv1d):
  1163. nn.init.kaiming_normal_(module.weight)
  1164. if module.bias is not None:
  1165. k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))
  1166. nn.init.uniform_(module.bias, a=-k, b=k)
  1167. elif isinstance(module, nn.Embedding):
  1168. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  1169. if module.padding_idx is not None:
  1170. module.weight.data[module.padding_idx].zero_()
  1171. elif isinstance(module, nn.LSTM):
  1172. for name, param in module.named_parameters():
  1173. if "weight" in name:
  1174. nn.init.xavier_uniform_(param)
  1175. elif "bias" in name:
  1176. nn.init.constant_(param, 0.0)
  1177. MIMI_START_DOCSTRING = r"""
  1178. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  1179. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  1180. etc.)
  1181. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  1182. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  1183. and behavior.
  1184. Parameters:
  1185. config ([`MimiConfig`]):
  1186. Model configuration class with all the parameters of the model. Initializing with a config file does not
  1187. load the weights associated with the model, only the configuration. Check out the
  1188. [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  1189. """
  1190. MIMI_INPUTS_DOCSTRING = r"""
  1191. Args:
  1192. input_values (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`, *optional*):
  1193. Raw audio input converted to Float.
  1194. padding_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  1195. Indicates which inputs are to be ignored due to padding, where elements are either 1 for *not masked* or 0
  1196. for *masked*.
  1197. num_quantizers (`int`, *optional*):
  1198. Number of quantizers (i.e codebooks) to use. By default, all quantizers are used.
  1199. audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
  1200. Discret code embeddings computed using `model.encode`.
  1201. encoder_past_key_values (`Cache`, *optional*):
  1202. Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the encoder transformer.
  1203. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  1204. The model will output the same cache format that is fed as input.
  1205. If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
  1206. have their past key value states given to this model).
  1207. decoder_past_key_values (`Cache`, *optional*):
  1208. Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the decoder transformer.
  1209. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  1210. The model will output the same cache format that is fed as input.
  1211. If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
  1212. have their past key value states given to this model).
  1213. return_dict (`bool`, *optional*):
  1214. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1215. """
  1216. @add_start_docstrings(
  1217. "The Mimi neural audio codec model.",
  1218. MIMI_START_DOCSTRING,
  1219. )
  1220. class MimiModel(MimiPreTrainedModel):
  1221. def __init__(self, config: MimiConfig):
  1222. super().__init__(config)
  1223. self.config = config
  1224. self.encoder = MimiEncoder(config)
  1225. self.encoder_transformer = MimiTransformerModel(config)
  1226. self.downsample = None
  1227. self.upsample = None
  1228. if config.frame_rate != config.encodec_frame_rate:
  1229. self.downsample = MimiConv1d(
  1230. config,
  1231. config.hidden_size,
  1232. config.hidden_size,
  1233. kernel_size=2 * int(config.encodec_frame_rate / config.frame_rate),
  1234. stride=2,
  1235. bias=False,
  1236. pad_mode="replicate",
  1237. )
  1238. self.upsample = MimiConvTranspose1d(
  1239. config,
  1240. config.hidden_size,
  1241. config.hidden_size,
  1242. kernel_size=2 * int(config.encodec_frame_rate / config.frame_rate),
  1243. stride=2,
  1244. bias=False,
  1245. groups=config.upsample_groups,
  1246. )
  1247. self.decoder_transformer = MimiTransformerModel(config)
  1248. self.decoder = MimiDecoder(config)
  1249. self.quantizer = MimiSplitResidualVectorQuantizer(config)
  1250. self.bits_per_codebook = int(math.log2(self.config.codebook_size))
  1251. if 2**self.bits_per_codebook != self.config.codebook_size:
  1252. raise ValueError("The codebook_size must be a power of 2.")
  1253. # Initialize weights and apply final processing
  1254. self.post_init()
  1255. def get_encoder(self):
  1256. return self.encoder
  1257. def get_decoder(self):
  1258. return self.decoder
  1259. def _encode_frame(
  1260. self,
  1261. input_values: torch.Tensor,
  1262. num_quantizers: int,
  1263. padding_mask: int,
  1264. past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  1265. return_dict: Optional[bool] = None,
  1266. ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
  1267. """
  1268. Encodes the given input using the underlying VQVAE. The padding mask is required to compute the correct scale.
  1269. """
  1270. embeddings = self.encoder(input_values)
  1271. encoder_outputs = self.encoder_transformer(
  1272. embeddings.transpose(1, 2), past_key_values=past_key_values, return_dict=return_dict
  1273. )
  1274. if return_dict:
  1275. past_key_values = encoder_outputs.get("past_key_values")
  1276. elif len(encoder_outputs) > 1:
  1277. past_key_values = encoder_outputs[1]
  1278. embeddings = encoder_outputs[0].transpose(1, 2)
  1279. embeddings = self.downsample(embeddings)
  1280. codes = self.quantizer.encode(embeddings, num_quantizers)
  1281. codes = codes.transpose(0, 1)
  1282. return codes, past_key_values
  1283. def encode(
  1284. self,
  1285. input_values: torch.Tensor,
  1286. padding_mask: torch.Tensor = None,
  1287. num_quantizers: Optional[float] = None,
  1288. encoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  1289. return_dict: Optional[bool] = None,
  1290. ) -> Union[Tuple[torch.Tensor, Optional[torch.Tensor]], MimiEncoderOutput]:
  1291. """
  1292. Encodes the input audio waveform into discrete codes.
  1293. Args:
  1294. input_values (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
  1295. Float values of the input audio waveform.
  1296. padding_mask (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
  1297. Indicates which inputs are to be ignored due to padding, where elements are either 1 for *not masked* or 0
  1298. for *masked*.
  1299. num_quantizers (`int`, *optional*):
  1300. Number of quantizers (i.e codebooks) to use. By default, all quantizers are used.
  1301. encoder_past_key_values (`Cache`, *optional*):
  1302. Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the encoder transformer.
  1303. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  1304. The model will output the same cache format that is fed as input.
  1305. If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
  1306. have their past key value states given to this model).
  1307. return_dict (`bool`, *optional*):
  1308. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1309. Returns:
  1310. `codebook` of shape `[batch_size, num_codebooks, frames]`, the discrete encoded codes for the input audio waveform.
  1311. """
  1312. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1313. num_quantizers = self.config.num_quantizers if num_quantizers is None else num_quantizers
  1314. if num_quantizers > self.config.num_quantizers:
  1315. raise ValueError(
  1316. f"The number of quantizers (i.e codebooks) asked should be lower than the total number of quantizers {self.config.num_quantizers}, but is currently {num_quantizers}."
  1317. )
  1318. _, channels, input_length = input_values.shape
  1319. if channels < 1 or channels > 2:
  1320. raise ValueError(f"Number of audio channels must be 1 or 2, but got {channels}")
  1321. if padding_mask is None:
  1322. padding_mask = torch.ones_like(input_values).bool()
  1323. encoded_frames, encoder_past_key_values = self._encode_frame(
  1324. input_values,
  1325. num_quantizers,
  1326. padding_mask.bool(),
  1327. past_key_values=encoder_past_key_values,
  1328. return_dict=return_dict,
  1329. )
  1330. if not return_dict:
  1331. return (
  1332. encoded_frames,
  1333. encoder_past_key_values,
  1334. )
  1335. return MimiEncoderOutput(encoded_frames, encoder_past_key_values)
  1336. def _decode_frame(
  1337. self,
  1338. codes: torch.Tensor,
  1339. past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  1340. return_dict: Optional[bool] = None,
  1341. ) -> torch.Tensor:
  1342. embeddings = self.quantizer.decode(codes)
  1343. embeddings = self.upsample(embeddings)
  1344. decoder_outputs = self.decoder_transformer(
  1345. embeddings.transpose(1, 2), past_key_values=past_key_values, return_dict=return_dict
  1346. )
  1347. if return_dict:
  1348. past_key_values = decoder_outputs.get("past_key_values")
  1349. elif len(decoder_outputs) > 1:
  1350. past_key_values = decoder_outputs[1]
  1351. embeddings = decoder_outputs[0].transpose(1, 2)
  1352. outputs = self.decoder(embeddings)
  1353. return outputs, past_key_values
  1354. def decode(
  1355. self,
  1356. audio_codes: torch.Tensor,
  1357. padding_mask: Optional[torch.Tensor] = None,
  1358. decoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  1359. return_dict: Optional[bool] = None,
  1360. ) -> Union[Tuple[torch.Tensor, torch.Tensor], MimiDecoderOutput]:
  1361. """
  1362. Decodes the given frames into an output audio waveform.
  1363. Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be
  1364. trimmed.
  1365. Args:
  1366. audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
  1367. Discret code embeddings computed using `model.encode`.
  1368. padding_mask (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
  1369. Indicates which inputs are to be ignored due to padding, where elements are either 1 for *not masked* or 0
  1370. for *masked*.
  1371. decoder_past_key_values (`Cache`, *optional*):
  1372. Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the decoder transformer.
  1373. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
  1374. The model will output the same cache format that is fed as input.
  1375. If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
  1376. have their past key value states given to this model).
  1377. return_dict (`bool`, *optional*):
  1378. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1379. """
  1380. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1381. audio_values, decoder_past_key_values = self._decode_frame(
  1382. audio_codes, past_key_values=decoder_past_key_values, return_dict=return_dict
  1383. )
  1384. # truncate based on padding mask
  1385. if padding_mask is not None and padding_mask.shape[-1] < audio_values.shape[-1]:
  1386. audio_values = audio_values[..., : padding_mask.shape[-1]]
  1387. if not return_dict:
  1388. return (
  1389. audio_values,
  1390. decoder_past_key_values,
  1391. )
  1392. return MimiDecoderOutput(audio_values, decoder_past_key_values)
  1393. @add_start_docstrings_to_model_forward(MIMI_INPUTS_DOCSTRING)
  1394. @replace_return_docstrings(output_type=MimiOutput, config_class=_CONFIG_FOR_DOC)
  1395. def forward(
  1396. self,
  1397. input_values: torch.Tensor,
  1398. padding_mask: Optional[torch.Tensor] = None,
  1399. num_quantizers: Optional[int] = None,
  1400. audio_codes: Optional[torch.Tensor] = None,
  1401. encoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  1402. decoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
  1403. return_dict: Optional[bool] = None,
  1404. ) -> Union[Tuple[torch.Tensor, torch.Tensor], MimiOutput]:
  1405. r"""
  1406. Returns:
  1407. Examples:
  1408. ```python
  1409. >>> from datasets import load_dataset
  1410. >>> from transformers import AutoFeatureExtractor, MimiModel
  1411. >>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example")
  1412. >>> audio_sample = dataset["train"]["audio"][0]["array"]
  1413. >>> model_id = "kyutai/mimi"
  1414. >>> model = MimiModel.from_pretrained(model_id)
  1415. >>> feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)
  1416. >>> inputs = feature_extractor(raw_audio=audio_sample, return_tensors="pt")
  1417. >>> outputs = model(**inputs)
  1418. >>> audio_codes = outputs.audio_codes
  1419. >>> audio_values = outputs.audio_values
  1420. ```"""
  1421. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1422. if padding_mask is None:
  1423. padding_mask = torch.ones_like(input_values).bool()
  1424. if audio_codes is None:
  1425. encoder_outputs = self.encode(
  1426. input_values, padding_mask, num_quantizers, encoder_past_key_values, return_dict=return_dict
  1427. )
  1428. audio_codes = encoder_outputs[0]
  1429. if return_dict:
  1430. encoder_past_key_values = encoder_outputs.get("past_key_values")
  1431. elif len(encoder_outputs) > 1:
  1432. encoder_past_key_values = encoder_outputs[1]
  1433. decoder_outputs = self.decode(audio_codes, padding_mask, decoder_past_key_values, return_dict=return_dict)
  1434. audio_values = decoder_outputs[0]
  1435. if return_dict:
  1436. decoder_past_key_values = decoder_outputs.get("past_key_values")
  1437. elif len(decoder_outputs) > 1:
  1438. decoder_past_key_values = decoder_outputs[1]
  1439. if not return_dict:
  1440. return (audio_codes, audio_values, encoder_past_key_values, decoder_past_key_values)
  1441. return MimiOutput(
  1442. audio_codes=audio_codes,
  1443. audio_values=audio_values,
  1444. encoder_past_key_values=encoder_past_key_values,
  1445. decoder_past_key_values=decoder_past_key_values,
  1446. )