modeling_mimi.py 78 KB

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