modeling_emu3.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/emu3/modular_emu3.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_emu3.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2024 HuggingFace Inc. team. All rights reserved.
  9. #
  10. #
  11. # Licensed under the Apache License, Version 2.0 (the "License");
  12. # you may not use this file except in compliance with the License.
  13. # You may obtain a copy of the License at
  14. #
  15. # http://www.apache.org/licenses/LICENSE-2.0
  16. #
  17. # Unless required by applicable law or agreed to in writing, software
  18. # distributed under the License is distributed on an "AS IS" BASIS,
  19. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. # See the License for the specific language governing permissions and
  21. # limitations under the License.
  22. import math
  23. from functools import cached_property
  24. from typing import Callable, Optional, Union
  25. import torch
  26. import torch.nn as nn
  27. import torch.nn.functional as F
  28. from ...activations import ACT2FN
  29. from ...cache_utils import Cache, DynamicCache
  30. from ...generation import GenerationMixin
  31. from ...integrations import use_kernel_forward_from_hub
  32. from ...masking_utils import create_causal_mask
  33. from ...modeling_layers import GradientCheckpointingLayer
  34. from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
  35. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  36. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  37. from ...processing_utils import Unpack
  38. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
  39. from ...utils.deprecation import deprecate_kwarg
  40. from ...utils.generic import check_model_inputs
  41. from .configuration_emu3 import Emu3Config, Emu3TextConfig, Emu3VQVAEConfig
  42. def rotate_half(x):
  43. """Rotates half the hidden dims of the input."""
  44. x1 = x[..., : x.shape[-1] // 2]
  45. x2 = x[..., x.shape[-1] // 2 :]
  46. return torch.cat((-x2, x1), dim=-1)
  47. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  48. """Applies Rotary Position Embedding to the query and key tensors.
  49. Args:
  50. q (`torch.Tensor`): The query tensor.
  51. k (`torch.Tensor`): The key tensor.
  52. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  53. sin (`torch.Tensor`): The sine part of the rotary embedding.
  54. position_ids (`torch.Tensor`, *optional*):
  55. Deprecated and unused.
  56. unsqueeze_dim (`int`, *optional*, defaults to 1):
  57. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  58. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  59. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  60. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  61. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  62. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  63. Returns:
  64. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  65. """
  66. cos = cos.unsqueeze(unsqueeze_dim)
  67. sin = sin.unsqueeze(unsqueeze_dim)
  68. q_embed = (q * cos) + (rotate_half(q) * sin)
  69. k_embed = (k * cos) + (rotate_half(k) * sin)
  70. return q_embed, k_embed
  71. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  72. """
  73. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  74. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  75. """
  76. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  77. if n_rep == 1:
  78. return hidden_states
  79. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  80. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  81. def eager_attention_forward(
  82. module: nn.Module,
  83. query: torch.Tensor,
  84. key: torch.Tensor,
  85. value: torch.Tensor,
  86. attention_mask: Optional[torch.Tensor],
  87. scaling: float,
  88. dropout: float = 0.0,
  89. **kwargs: Unpack[TransformersKwargs],
  90. ):
  91. key_states = repeat_kv(key, module.num_key_value_groups)
  92. value_states = repeat_kv(value, module.num_key_value_groups)
  93. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  94. if attention_mask is not None:
  95. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  96. attn_weights = attn_weights + causal_mask
  97. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  98. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  99. attn_output = torch.matmul(attn_weights, value_states)
  100. attn_output = attn_output.transpose(1, 2).contiguous()
  101. return attn_output, attn_weights
  102. class Emu3Attention(nn.Module):
  103. """Multi-headed attention from 'Attention Is All You Need' paper"""
  104. def __init__(self, config: Emu3Config, layer_idx: int):
  105. super().__init__()
  106. self.config = config
  107. self.layer_idx = layer_idx
  108. self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
  109. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  110. self.scaling = self.head_dim**-0.5
  111. self.attention_dropout = config.attention_dropout
  112. self.is_causal = True
  113. self.q_proj = nn.Linear(
  114. config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
  115. )
  116. self.k_proj = nn.Linear(
  117. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  118. )
  119. self.v_proj = nn.Linear(
  120. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  121. )
  122. self.o_proj = nn.Linear(
  123. config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
  124. )
  125. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  126. def forward(
  127. self,
  128. hidden_states: torch.Tensor,
  129. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  130. attention_mask: Optional[torch.Tensor],
  131. past_key_values: Optional[Cache] = None,
  132. cache_position: Optional[torch.LongTensor] = None,
  133. **kwargs: Unpack[TransformersKwargs],
  134. ) -> tuple[torch.Tensor, torch.Tensor]:
  135. input_shape = hidden_states.shape[:-1]
  136. hidden_shape = (*input_shape, -1, self.head_dim)
  137. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  138. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  139. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  140. cos, sin = position_embeddings
  141. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  142. if past_key_values is not None:
  143. # sin and cos are specific to RoPE models; cache_position needed for the static cache
  144. cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
  145. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  146. attention_interface: Callable = eager_attention_forward
  147. if self.config._attn_implementation != "eager":
  148. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  149. attn_output, attn_weights = attention_interface(
  150. self,
  151. query_states,
  152. key_states,
  153. value_states,
  154. attention_mask,
  155. dropout=0.0 if not self.training else self.attention_dropout,
  156. scaling=self.scaling,
  157. **kwargs,
  158. )
  159. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  160. attn_output = self.o_proj(attn_output)
  161. return attn_output, attn_weights
  162. @use_kernel_forward_from_hub("RMSNorm")
  163. class Emu3RMSNorm(nn.Module):
  164. def __init__(self, hidden_size, eps=1e-6):
  165. """
  166. Emu3RMSNorm is equivalent to T5LayerNorm
  167. """
  168. super().__init__()
  169. self.weight = nn.Parameter(torch.ones(hidden_size))
  170. self.variance_epsilon = eps
  171. def forward(self, hidden_states):
  172. input_dtype = hidden_states.dtype
  173. hidden_states = hidden_states.to(torch.float32)
  174. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  175. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  176. return self.weight * hidden_states.to(input_dtype)
  177. def extra_repr(self):
  178. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  179. class Emu3MLP(nn.Module):
  180. def __init__(self, config):
  181. super().__init__()
  182. self.config = config
  183. self.hidden_size = config.hidden_size
  184. self.intermediate_size = config.intermediate_size
  185. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  186. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  187. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
  188. self.act_fn = ACT2FN[config.hidden_act]
  189. def forward(self, x):
  190. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  191. return down_proj
  192. class Emu3DecoderLayer(GradientCheckpointingLayer):
  193. def __init__(self, config: Emu3Config, layer_idx: int):
  194. super().__init__()
  195. self.hidden_size = config.hidden_size
  196. self.self_attn = Emu3Attention(config=config, layer_idx=layer_idx)
  197. self.mlp = Emu3MLP(config)
  198. self.input_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  199. self.post_attention_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  200. self.dropout = nn.Dropout(config.attention_dropout)
  201. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  202. def forward(
  203. self,
  204. hidden_states: torch.Tensor,
  205. attention_mask: Optional[torch.Tensor] = None,
  206. position_ids: Optional[torch.LongTensor] = None,
  207. past_key_values: Optional[Cache] = None,
  208. use_cache: Optional[bool] = False,
  209. cache_position: Optional[torch.LongTensor] = None,
  210. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
  211. **kwargs: Unpack[TransformersKwargs],
  212. ) -> torch.Tensor:
  213. residual = hidden_states
  214. hidden_states = self.input_layernorm(hidden_states)
  215. hidden_states, _ = self.self_attn(
  216. hidden_states=hidden_states,
  217. attention_mask=attention_mask,
  218. position_ids=position_ids,
  219. past_key_values=past_key_values,
  220. use_cache=use_cache,
  221. cache_position=cache_position,
  222. position_embeddings=position_embeddings,
  223. **kwargs,
  224. )
  225. hidden_states = residual + self.dropout(hidden_states)
  226. residual = hidden_states
  227. hidden_states = self.post_attention_layernorm(hidden_states)
  228. hidden_states = self.mlp(hidden_states)
  229. hidden_states = residual + self.dropout(hidden_states)
  230. return hidden_states
  231. class Emu3VQVAEVectorQuantizer(nn.Module):
  232. """
  233. A module for vector quantization using learned embedding vectors.
  234. This module implements the quantization process similar to te one described in
  235. the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous
  236. input vectors into discrete codebook vectors, which are learned during training.
  237. Current implementation improves over previous ones by avoiding costly matrix multiplications
  238. and allowing for post-hoc remapping of indices.
  239. """
  240. def __init__(self, config: Emu3VQVAEConfig):
  241. super().__init__()
  242. self.embedding = nn.Embedding(config.codebook_size, config.embed_dim)
  243. self.embedding.weight.data.uniform_(-1.0 / config.codebook_size, 1.0 / config.codebook_size)
  244. def forward(self, hidden_state: torch.Tensor):
  245. batch_size, temporal, channels, height, width = hidden_state.shape
  246. hidden_state = hidden_state.permute(0, 1, 3, 4, 2).contiguous()
  247. hidden_state_flattened = hidden_state.view(-1, channels)
  248. # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
  249. hidden_state_sum = torch.sum(hidden_state_flattened**2, dim=1, keepdim=True)
  250. embedding_sum = torch.sum(self.embedding.weight**2, dim=1)
  251. # "bd,dn->bn",
  252. distances = 2 * torch.matmul(hidden_state_flattened, self.embedding.weight.transpose(0, 1))
  253. distances = hidden_state_sum + embedding_sum - distances
  254. min_encoding_indices = torch.argmin(distances, dim=1)
  255. min_encoding_indices = min_encoding_indices.view(batch_size, temporal, height, width)
  256. return min_encoding_indices
  257. class Emu3VQVAEEncoderConvDownsample(nn.Module):
  258. def __init__(self, in_channels):
  259. super().__init__()
  260. self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
  261. def forward(self, hidden_states):
  262. # no asymmetric padding in torch conv, must do it ourselves
  263. hidden_states = F.pad(hidden_states, pad=(0, 1, 0, 1), mode="constant", value=0)
  264. hidden_states = self.conv(hidden_states)
  265. return hidden_states
  266. class Emu3VQVAEEncoderConvUpsample(nn.Module):
  267. def __init__(self, in_channels):
  268. super().__init__()
  269. self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
  270. def forward(self, hidden_states):
  271. hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
  272. hidden_states = self.conv(hidden_states)
  273. return hidden_states
  274. class Emu3VQVAEConv3d(nn.Module):
  275. def __init__(
  276. self,
  277. in_channel: int,
  278. out_channel: int,
  279. kernel_size: tuple[int],
  280. stride: tuple[int],
  281. ):
  282. super().__init__()
  283. padding_sizes = [one_kernel - one_stride for one_kernel, one_stride in zip(kernel_size[1:], stride[1:])]
  284. self.padding = ()
  285. for pad_size in padding_sizes[::-1]:
  286. self.padding += (pad_size // 2 + pad_size % 2, pad_size // 2)
  287. self.padding += (2, 0)
  288. self.conv = nn.Conv3d(
  289. in_channel,
  290. out_channel,
  291. kernel_size,
  292. stride=stride,
  293. )
  294. def forward(self, hidden_states: torch.Tensor):
  295. hidden_states = F.pad(hidden_states, self.padding)
  296. hidden_states = self.conv(hidden_states)
  297. return hidden_states
  298. class Emu3VQVAESpatialNorm(nn.Module):
  299. def __init__(
  300. self,
  301. in_channels: int,
  302. out_channels: int,
  303. ):
  304. super().__init__()
  305. self.norm_layer = nn.GroupNorm(
  306. num_channels=out_channels,
  307. num_groups=32,
  308. eps=1e-6,
  309. affine=True,
  310. )
  311. self.conv_y = nn.Conv2d(
  312. in_channels,
  313. out_channels,
  314. kernel_size=1,
  315. stride=1,
  316. padding=0,
  317. )
  318. self.conv_b = nn.Conv2d(
  319. in_channels,
  320. out_channels,
  321. kernel_size=1,
  322. stride=1,
  323. padding=0,
  324. )
  325. def forward(self, hidden_states: torch.Tensor, quant_states: torch.Tensor):
  326. quant_states = F.interpolate(quant_states, size=hidden_states.shape[-2:], mode="nearest")
  327. hidden_states = self.norm_layer(hidden_states)
  328. hidden_states = hidden_states * self.conv_y(quant_states) + self.conv_b(quant_states)
  329. return hidden_states
  330. class Emu3VQVAETemporalUpsample(nn.Module):
  331. def __init__(
  332. self,
  333. in_channel: int,
  334. out_channel: int,
  335. ):
  336. super().__init__()
  337. self.conv = Emu3VQVAEConv3d(
  338. in_channel,
  339. out_channel,
  340. kernel_size=(3, 3, 3),
  341. stride=(1, 1, 1),
  342. )
  343. def forward(self, hidden_states: torch.Tensor):
  344. batch_size, channels, temporal, height, width = hidden_states.shape
  345. hidden_states = hidden_states.permute(0, 1, 3, 4, 2).contiguous().view(batch_size, -1, temporal)
  346. hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
  347. hidden_states = hidden_states.view(batch_size, channels, height, width, -1).permute(0, 1, 4, 2, 3).contiguous()
  348. hidden_states = self.conv(hidden_states)
  349. return hidden_states
  350. class Emu3VQVAETemporalDownsample(nn.Module):
  351. def __init__(
  352. self,
  353. in_channel: int,
  354. out_channel: int,
  355. ):
  356. super().__init__()
  357. self.conv = Emu3VQVAEConv3d(
  358. in_channel,
  359. out_channel,
  360. kernel_size=(4, 3, 3),
  361. stride=(2, 1, 1),
  362. )
  363. def forward(self, hidden_states: torch.Tensor):
  364. hidden_states = self.conv(hidden_states)
  365. return hidden_states
  366. class Emu3VQVAETemporalResnetBlock(nn.Module):
  367. def __init__(
  368. self,
  369. in_channels,
  370. out_channels=None,
  371. ):
  372. super().__init__()
  373. self.in_channels = in_channels
  374. self.out_channels = in_channels if out_channels is None else out_channels
  375. self.norm1 = nn.BatchNorm3d(in_channels)
  376. self.conv1 = Emu3VQVAEConv3d(
  377. in_channels,
  378. out_channels,
  379. kernel_size=(3, 3, 3),
  380. stride=(1, 1, 1),
  381. )
  382. self.norm2 = nn.BatchNorm3d(out_channels)
  383. self.conv2 = Emu3VQVAEConv3d(
  384. out_channels,
  385. out_channels,
  386. kernel_size=(3, 3, 3),
  387. stride=(1, 1, 1),
  388. )
  389. if self.in_channels != self.out_channels:
  390. self.nin_shortcut = nn.Conv3d(
  391. in_channels,
  392. out_channels,
  393. kernel_size=1,
  394. stride=1,
  395. padding=0,
  396. )
  397. def forward(self, hidden_states):
  398. residual = hidden_states
  399. hidden_states = self.norm1(hidden_states)
  400. hidden_states *= torch.sigmoid(hidden_states)
  401. hidden_states = self.conv1(hidden_states)
  402. hidden_states = self.norm2(hidden_states)
  403. hidden_states *= torch.sigmoid(hidden_states)
  404. hidden_states = self.conv2(hidden_states)
  405. if self.in_channels != self.out_channels:
  406. residual = self.nin_shortcut(residual)
  407. return residual + hidden_states
  408. class Emu3VQVAEResnetBlock(nn.Module):
  409. def __init__(
  410. self,
  411. in_channels: int,
  412. out_channels: Optional[int] = None,
  413. quant_channels: Optional[int] = None,
  414. ):
  415. super().__init__()
  416. self.in_channels = in_channels
  417. out_channels = in_channels if out_channels is None else out_channels
  418. self.out_channels = out_channels
  419. self.quant_channels = quant_channels
  420. if quant_channels is None:
  421. self.norm1 = nn.GroupNorm(num_channels=in_channels, num_groups=32, eps=1e-6, affine=True)
  422. self.norm2 = nn.GroupNorm(num_channels=out_channels, num_groups=32, eps=1e-6, affine=True)
  423. else:
  424. self.norm1 = Emu3VQVAESpatialNorm(quant_channels, in_channels)
  425. self.norm2 = Emu3VQVAESpatialNorm(quant_channels, out_channels)
  426. self.conv1 = nn.Conv2d(
  427. in_channels,
  428. out_channels,
  429. kernel_size=3,
  430. stride=1,
  431. padding=1,
  432. )
  433. self.conv2 = nn.Conv2d(
  434. out_channels,
  435. out_channels,
  436. kernel_size=3,
  437. stride=1,
  438. padding=1,
  439. )
  440. if self.in_channels != self.out_channels:
  441. self.nin_shortcut = nn.Conv2d(
  442. in_channels,
  443. out_channels,
  444. kernel_size=1,
  445. stride=1,
  446. padding=0,
  447. )
  448. def forward(self, hidden_states: torch.Tensor, quant_channels: Optional[torch.Tensor] = None):
  449. norm_args = () if self.quant_channels is None else (quant_channels,)
  450. residual = hidden_states
  451. hidden_states = self.norm1(hidden_states, *norm_args)
  452. hidden_states *= torch.sigmoid(hidden_states)
  453. hidden_states = self.conv1(hidden_states)
  454. hidden_states = self.norm2(hidden_states, *norm_args)
  455. hidden_states *= torch.sigmoid(hidden_states)
  456. hidden_states = self.conv2(hidden_states)
  457. if self.in_channels != self.out_channels:
  458. residual = self.nin_shortcut(residual)
  459. return residual + hidden_states
  460. class Emu3VQVAEAttentionBlock(nn.Module):
  461. """Multi-headed attention from 'Attention Is All You Need' paper"""
  462. def __init__(self, config: Emu3VQVAEConfig):
  463. super().__init__()
  464. self.config = config
  465. self.embed_dim = config.hidden_size
  466. self.num_heads = config.num_attention_heads
  467. self.head_dim = self.embed_dim // self.num_heads
  468. if self.head_dim * self.num_heads != self.embed_dim:
  469. raise ValueError(
  470. f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
  471. f" {self.num_heads})."
  472. )
  473. self.scale = self.head_dim**-0.5
  474. self.dropout = config.attention_dropout
  475. self.is_causal = False
  476. self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
  477. self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
  478. self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
  479. self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
  480. # for compatibility with the attention interface
  481. self.num_key_value_groups = 1
  482. def forward(
  483. self,
  484. hidden_states: torch.Tensor,
  485. attention_mask: Optional[torch.Tensor] = None,
  486. **kwargs,
  487. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  488. """Input shape: Batch x Time x Channel"""
  489. batch_size, seq_length, embed_dim = hidden_states.shape
  490. queries = self.q_proj(hidden_states)
  491. keys = self.k_proj(hidden_states)
  492. values = self.v_proj(hidden_states)
  493. queries = queries.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
  494. keys = keys.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
  495. values = values.view(batch_size, seq_length, self.num_heads, self.head_dim).transpose(1, 2)
  496. attention_interface: Callable = eager_attention_forward
  497. if self.config._attn_implementation != "eager":
  498. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  499. attn_output, attn_weights = attention_interface(
  500. self,
  501. queries,
  502. keys,
  503. values,
  504. attention_mask,
  505. is_causal=self.is_causal,
  506. scaling=self.scale,
  507. dropout=0.0 if not self.training else self.dropout,
  508. )
  509. attn_output = attn_output.reshape(batch_size, seq_length, embed_dim).contiguous()
  510. attn_output = self.out_proj(attn_output)
  511. return attn_output, attn_weights
  512. class Emu3VQVAEGroupNorm(nn.GroupNorm):
  513. """
  514. Same as the torch GroupNorm with the only difference that this ones accepts
  515. an optional kwarg `quant_states` which is not used. This class makes it easier to
  516. use SpatialNorm or GroupNorm without conditionals
  517. """
  518. def __init__(self, **kwargs):
  519. super().__init__(**kwargs)
  520. def forward(self, input, quant_states=None):
  521. return F.group_norm(input, self.num_groups, self.weight, self.bias, self.eps)
  522. class Emu3VQVAEMiddleBlock(nn.Module):
  523. def __init__(self, config, in_channels, quant_channels=None):
  524. super().__init__()
  525. self.block_1 = Emu3VQVAEResnetBlock(
  526. in_channels=in_channels,
  527. out_channels=in_channels,
  528. quant_channels=quant_channels,
  529. )
  530. self.attn_1 = Emu3VQVAEAttentionBlock(config)
  531. if quant_channels is None:
  532. self.attn_norm = Emu3VQVAEGroupNorm(num_channels=in_channels, num_groups=32, eps=1e-6, affine=True)
  533. else:
  534. self.attn_norm = Emu3VQVAESpatialNorm(quant_channels, in_channels)
  535. self.block_2 = Emu3VQVAEResnetBlock(
  536. in_channels=in_channels,
  537. out_channels=in_channels,
  538. quant_channels=quant_channels,
  539. )
  540. def forward(self, hidden_states: torch.FloatTensor, quant_states: Optional[torch.FloatTensor] = None):
  541. hidden_states = self.block_1(hidden_states, quant_states)
  542. residual = hidden_states
  543. hidden_states = self.attn_norm(hidden_states, quant_states)
  544. batch_size, channels, height, width = hidden_states.shape
  545. hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2)
  546. hidden_states = self.attn_1(hidden_states)[0]
  547. hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
  548. hidden_states = residual + hidden_states
  549. hidden_states = self.block_2(hidden_states, quant_states)
  550. return hidden_states
  551. class Emu3VQVAEDownBlock(nn.Module):
  552. def __init__(self, config):
  553. super().__init__()
  554. self.num_resolutions = len(config.channel_multiplier)
  555. self.num_res_blocks = config.num_res_blocks
  556. base_channels = config.base_channels
  557. channel_multiplier = config.channel_multiplier
  558. in_channel_multiplier = (1,) + tuple(channel_multiplier)
  559. self.in_channel_multiplier = in_channel_multiplier
  560. self.down = nn.ModuleList()
  561. for i_level in range(self.num_resolutions):
  562. block = nn.ModuleList()
  563. attn = nn.ModuleList()
  564. attn_norms = nn.ModuleList()
  565. block_in = base_channels * in_channel_multiplier[i_level]
  566. block_out = base_channels * channel_multiplier[i_level]
  567. for i_block in range(self.num_res_blocks):
  568. block.append(
  569. Emu3VQVAEResnetBlock(
  570. in_channels=block_in,
  571. out_channels=block_out,
  572. )
  573. )
  574. block_in = block_out
  575. if config.attn_resolutions is not None and i_level in config.attn_resolutions:
  576. attn.append(Emu3VQVAEAttentionBlock(config))
  577. attn_norms.append(nn.GroupNorm(num_channels=block_in, num_groups=32, eps=1e-6, affine=True))
  578. down = nn.Module()
  579. down.block = block
  580. down.attn = attn
  581. down.attn_norms = attn_norms
  582. if i_level != self.num_resolutions - 1:
  583. down.downsample = Emu3VQVAEEncoderConvDownsample(block_in)
  584. self.down.append(down)
  585. def forward(self, hidden_states: torch.FloatTensor):
  586. for i_level, blocks in enumerate(self.down):
  587. for i_block in range(self.num_res_blocks):
  588. hidden_states = blocks.block[i_block](hidden_states)
  589. if len(blocks.attn) > 0:
  590. residual = hidden_states
  591. hidden_states = blocks.attn_norms[i_block](hidden_states)
  592. batch_size, channels, height, width = hidden_states.shape
  593. hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2)
  594. hidden_states = blocks.attn[i_block](hidden_states)[0]
  595. hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
  596. hidden_states = residual + hidden_states
  597. if i_level != self.num_resolutions - 1:
  598. hidden_states = blocks.downsample(hidden_states)
  599. return hidden_states
  600. class Emu3VQVAEUpBlock(nn.Module):
  601. def __init__(self, config):
  602. super().__init__()
  603. self.num_resolutions = len(config.channel_multiplier)
  604. self.num_res_blocks = config.num_res_blocks
  605. quant_channels = config.embed_dim
  606. block_in = config.base_channels * config.channel_multiplier[-1]
  607. self.up = nn.ModuleList()
  608. for i_level in reversed(range(self.num_resolutions)):
  609. block = nn.ModuleList()
  610. attn = nn.ModuleList()
  611. attn_norms = nn.ModuleList()
  612. block_out = config.base_channels * config.channel_multiplier[i_level]
  613. for i_block in range(self.num_res_blocks + 1):
  614. block.append(
  615. Emu3VQVAEResnetBlock(
  616. in_channels=block_in,
  617. out_channels=block_out,
  618. quant_channels=quant_channels,
  619. )
  620. )
  621. block_in = block_out
  622. if i_level in config.attn_resolutions:
  623. attn.append(Emu3VQVAEAttentionBlock(config))
  624. attn_norms.append(Emu3VQVAESpatialNorm(quant_channels, block_in))
  625. up = nn.Module()
  626. up.block = block
  627. up.attn = attn
  628. up.attn_norms = attn_norms
  629. if i_level != 0:
  630. up.upsample = Emu3VQVAEEncoderConvUpsample(block_in)
  631. self.up.insert(0, up)
  632. def forward(self, hidden_states: torch.FloatTensor, quant_states: torch.FloatTensor):
  633. for i_level, blocks in enumerate(self.up[::-1]):
  634. for i_block in range(self.num_res_blocks + 1):
  635. hidden_states = blocks.block[i_block](hidden_states, quant_states)
  636. if len(blocks.attn) > 0:
  637. residual = hidden_states
  638. hidden_states = blocks.attn_norms[i_block](hidden_states, quant_states)
  639. batch_size, channels, height, width = hidden_states.shape
  640. hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2)
  641. hidden_states = blocks.attn[i_block](hidden_states)[0]
  642. hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2)
  643. hidden_states = residual + hidden_states
  644. if i_level != len(self.up) - 1:
  645. hidden_states = blocks.upsample(hidden_states)
  646. return hidden_states
  647. class Emu3VQVAEEncoder(nn.Module):
  648. def __init__(self, config):
  649. super().__init__()
  650. base_channels = config.base_channels
  651. in_channels = config.in_channels
  652. double_latent = config.double_latent
  653. latent_channels = config.latent_channels
  654. channel_multiplier = config.channel_multiplier
  655. out_channels = 2 * latent_channels if double_latent else latent_channels
  656. block_in = base_channels * channel_multiplier[-1]
  657. self.conv_in = torch.nn.Conv2d(in_channels, base_channels, kernel_size=3, stride=1, padding=1)
  658. self.down_block = Emu3VQVAEDownBlock(config)
  659. self.middle_block = Emu3VQVAEMiddleBlock(config, block_in)
  660. self.norm_out = torch.nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)
  661. self.conv_out = torch.nn.Conv2d(
  662. block_in,
  663. out_channels,
  664. kernel_size=3,
  665. stride=1,
  666. padding=1,
  667. )
  668. temporal_down_blocks = int(math.log2(config.temporal_downsample_factor))
  669. self.time_conv = nn.ModuleList()
  670. self.time_res_stack = nn.ModuleList()
  671. for i in range(temporal_down_blocks):
  672. conv = Emu3VQVAETemporalDownsample(out_channels, out_channels)
  673. self.time_conv.append(conv)
  674. for _ in range(config.num_res_blocks):
  675. time_res_conv = Emu3VQVAETemporalResnetBlock(
  676. in_channels=out_channels,
  677. out_channels=out_channels,
  678. )
  679. self.time_res_stack.append(time_res_conv)
  680. def forward(self, pixel_values: torch.LongTensor):
  681. temporal_dim = pixel_values.shape[1]
  682. pixel_values = pixel_values.reshape(-1, *pixel_values.shape[2:])
  683. # downsampling & middle
  684. hidden_states = self.conv_in(pixel_values)
  685. hidden_states = self.down_block(hidden_states)
  686. hidden_states = self.middle_block(hidden_states)
  687. # end
  688. hidden_states = self.norm_out(hidden_states)
  689. hidden_states *= torch.sigmoid(hidden_states)
  690. hidden_states = self.conv_out(hidden_states)
  691. hidden_states = hidden_states.reshape(-1, temporal_dim, *hidden_states.shape[1:])
  692. hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
  693. # temporal convs
  694. for conv in self.time_conv:
  695. hidden_states = conv(hidden_states)
  696. hidden_states *= torch.sigmoid(hidden_states)
  697. for layer in self.time_res_stack:
  698. hidden_states = layer(hidden_states)
  699. hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
  700. return hidden_states
  701. class Emu3VQVAEDecoder(nn.Module):
  702. def __init__(self, config: Emu3VQVAEConfig):
  703. super().__init__()
  704. quant_channels = config.embed_dim
  705. block_in = config.base_channels * config.channel_multiplier[-1]
  706. self.time_res_stack = nn.ModuleList()
  707. for _ in range(config.num_res_blocks):
  708. time_res_conv = Emu3VQVAETemporalResnetBlock(
  709. in_channels=config.latent_channels, out_channels=config.latent_channels
  710. )
  711. self.time_res_stack.append(time_res_conv)
  712. temp_upsample_block_num = int(math.log2(config.temporal_downsample_factor))
  713. self.time_conv = nn.ModuleList()
  714. for i in range(temp_upsample_block_num):
  715. conv = Emu3VQVAETemporalUpsample(config.latent_channels, config.latent_channels)
  716. self.time_conv.append(conv)
  717. self.conv_in = nn.Conv2d(
  718. config.latent_channels,
  719. block_in,
  720. kernel_size=3,
  721. stride=1,
  722. padding=1,
  723. )
  724. self.middle_block = Emu3VQVAEMiddleBlock(config, block_in, quant_channels=quant_channels)
  725. self.up_block = Emu3VQVAEUpBlock(config)
  726. block_in = config.base_channels * config.channel_multiplier[0]
  727. self.norm_out = Emu3VQVAESpatialNorm(quant_channels, block_in)
  728. self.conv_out = nn.Conv2d(
  729. block_in,
  730. config.out_channels,
  731. kernel_size=3,
  732. stride=1,
  733. padding=1,
  734. )
  735. def forward(self, hidden_states: torch.Tensor, quant_states: torch.Tensor):
  736. hidden_quant_states = torch.cat((hidden_states, quant_states), dim=0)
  737. hidden_quant_states = hidden_quant_states.permute(0, 2, 1, 3, 4)
  738. # temporal convs
  739. for layer in self.time_res_stack:
  740. hidden_quant_states = layer(hidden_quant_states)
  741. for layer in self.time_conv:
  742. hidden_quant_states = layer(hidden_quant_states)
  743. hidden_quant_states *= torch.sigmoid(hidden_quant_states)
  744. hidden_quant_states = hidden_quant_states.permute(0, 2, 1, 3, 4)
  745. hidden_states, quant_states = torch.chunk(hidden_quant_states, 2, dim=0)
  746. hidden_states = hidden_states.reshape(-1, *hidden_states.shape[2:])
  747. quant_states = quant_states.reshape(-1, *quant_states.shape[2:])
  748. hidden_states = self.conv_in(hidden_states)
  749. # middle & upsampling
  750. hidden_states = self.middle_block(hidden_states, quant_states)
  751. hidden_states = self.up_block(hidden_states, quant_states)
  752. hidden_states = self.norm_out(hidden_states, quant_states)
  753. hidden_states *= torch.sigmoid(hidden_states)
  754. hidden_states = self.conv_out(hidden_states)
  755. return hidden_states
  756. @auto_docstring(
  757. custom_intro="""
  758. The VQ-VAE model used in Emu3 for encoding/decoding images into discrete tokens.
  759. This model follows the "Make-a-scene: Scene-based text-to-image generation with human priors" paper from
  760. [ Oran Gafni, Adam Polyak, Oron Ashual, Shelly Sheynin, Devi Parikh, and Yaniv
  761. Taigman](https://huggingface.co/papers/2203.13131).
  762. """
  763. )
  764. class Emu3VQVAE(PreTrainedModel):
  765. config: Emu3VQVAEConfig
  766. base_model_prefix = "emuvideovq"
  767. main_input_name = "pixel_values"
  768. _supports_sdpa = True
  769. _supports_flash_attn = True
  770. _supports_flex_attn = True
  771. _supports_attention_backend = True
  772. _no_split_modules = [
  773. "Emu3VQVAETemporalResnetBlock",
  774. "Emu3VQVAEAttentionBlock",
  775. "Emu3VQVAEResnetBlock",
  776. "Emu3VQVAEVectorQuantizer",
  777. ]
  778. def _init_weights(self, module):
  779. if isinstance(module, (nn.Conv2d, nn.Conv3d)):
  780. nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
  781. if module.bias is not None:
  782. fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight)
  783. bound = 1 / math.sqrt(fan_in)
  784. nn.init.uniform_(module.bias, -bound, bound)
  785. elif isinstance(module, nn.Linear):
  786. nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5))
  787. if module.bias is not None:
  788. fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight)
  789. bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
  790. nn.init.uniform_(module.bias, -bound, bound)
  791. elif isinstance(module, (nn.BatchNorm2d, nn.BatchNorm3d, nn.GroupNorm)):
  792. nn.init.constant_(module.weight, 1.0)
  793. nn.init.constant_(module.bias, 0.0)
  794. elif isinstance(module, nn.Embedding):
  795. module.weight.data.normal_()
  796. if module.padding_idx is not None:
  797. module.weight.data[module.padding_idx].zero_()
  798. def __init__(self, config: Emu3VQVAEConfig):
  799. super().__init__(config)
  800. self.config = config
  801. self.encoder = Emu3VQVAEEncoder(config)
  802. self.decoder = Emu3VQVAEDecoder(config)
  803. self.quantize = Emu3VQVAEVectorQuantizer(config)
  804. self.vision_spatial_factor = 2 ** (len(config.channel_multiplier) - 1)
  805. self.quant_conv = Emu3VQVAEConv3d(
  806. config.latent_channels, config.embed_dim, kernel_size=(3, 1, 1), stride=(1, 1, 1)
  807. )
  808. self.post_quant_conv = Emu3VQVAEConv3d(
  809. config.embed_dim, config.latent_channels, kernel_size=(3, 1, 1), stride=(1, 1, 1)
  810. )
  811. self.spatial_scale_factor = 2 ** (len(config.channel_multiplier) - 1)
  812. self.eval() # Emu3's VQ model is frozen
  813. self.post_init()
  814. def encode(self, pixel_values: torch.Tensor, image_sizes: torch.Tensor):
  815. is_image = pixel_values.ndim == 4
  816. if is_image:
  817. temporal = self.config.temporal_downsample_factor
  818. batch_size, channels, height, width = pixel_values.shape
  819. pixel_values = pixel_values.unsqueeze(1).repeat(1, temporal, 1, 1, 1)
  820. else:
  821. batch_size, temporal, channels, height, width = pixel_values.shape
  822. hidden_states = self.encoder(pixel_values)
  823. # b t c h w -> b c t h w
  824. hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
  825. hidden_states = self.quant_conv(hidden_states)
  826. # b c t h w -> b t c h w
  827. hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
  828. codes = self.quantize(hidden_states)
  829. image_tokens = codes.squeeze(1) if is_image else codes
  830. image_tokens = [
  831. single_image[: int(size[0] / self.vision_spatial_factor), : int(size[1] / self.vision_spatial_factor)]
  832. for single_image, size in zip(image_tokens, image_sizes)
  833. ]
  834. return image_tokens
  835. def decode(self, hidden_states: torch.Tensor):
  836. is_image = hidden_states.ndim == 3
  837. if is_image:
  838. hidden_states = hidden_states.unsqueeze(1)
  839. batch_size, temporal, height, width = hidden_states.shape
  840. quant = self.quantize.embedding(hidden_states.flatten())
  841. channels = quant.shape[-1]
  842. quant = quant.view(batch_size, temporal, height, width, channels).permute(0, 4, 1, 2, 3).contiguous()
  843. post_quant = self.post_quant_conv(quant)
  844. quant = quant.permute(0, 2, 1, 3, 4)
  845. post_quant = post_quant.permute(0, 2, 1, 3, 4)
  846. video = self.decoder(post_quant, quant)
  847. video = video.reshape(
  848. batch_size,
  849. temporal * self.config.temporal_downsample_factor,
  850. self.config.out_channels,
  851. height * self.spatial_scale_factor,
  852. width * self.spatial_scale_factor,
  853. )
  854. return video[:, 0] if is_image else video
  855. class Emu3ImageVocabularyMapping:
  856. """
  857. A class for mapping discrete image tokens from VQGAN to BPE tokens.
  858. """
  859. def __init__(self, vocab_map):
  860. self.vocab_map = vocab_map
  861. self.eol_token_id = vocab_map.get("<|extra_200|>")
  862. self.image_token_id = vocab_map.get("<image>")
  863. @cached_property
  864. def image_tokens(self):
  865. return sorted([val for name, val in self.vocab_map.items() if name.startswith("<|visual token")])
  866. @cached_property
  867. def image_tokens_str(self):
  868. return sorted([name for name, val in self.vocab_map.items() if name.startswith("<|visual token")])
  869. @cached_property
  870. def img2bpe(self):
  871. return {int(token[-8:-2]): self.vocab_map[token] for token in self.image_tokens_str}
  872. @cached_property
  873. def bpe2img(self):
  874. return {v: k for k, v in self.img2bpe.items()}
  875. @cached_property
  876. def bpe2img_mapping_tensor(self):
  877. mapping = torch.zeros(max(self.bpe2img.keys()) + 1, dtype=torch.int)
  878. for k, v in self.bpe2img.items():
  879. mapping[k] = v
  880. return mapping
  881. @cached_property
  882. def img2bpe_mapping_tensor(self):
  883. mapping = torch.zeros(max(self.img2bpe.keys()) + 1, dtype=torch.int)
  884. for k, v in self.img2bpe.items():
  885. mapping[k] = v
  886. return mapping
  887. def convert_img2bpe(self, img_batch: list[torch.Tensor]) -> torch.Tensor:
  888. device = img_batch.device
  889. eol_row = torch.ones((img_batch.shape[0], 1), dtype=torch.int) * self.eol_token_id
  890. img_tokens = self.img2bpe_mapping_tensor[img_batch.to("cpu")]
  891. img_tokens = torch.cat([img_tokens, eol_row], dim=-1)
  892. return img_tokens.to(device)
  893. def convert_bpe2img(self, img_batch: torch.Tensor) -> torch.Tensor:
  894. device = img_batch.device
  895. img_batch = img_batch[..., :-1] # remove last row of EOL tokens
  896. img_tokens = self.bpe2img_mapping_tensor[img_batch.to("cpu")]
  897. return img_tokens.to(device)
  898. @auto_docstring
  899. class Emu3PreTrainedModel(PreTrainedModel):
  900. config: Emu3Config
  901. base_model_prefix = "model"
  902. supports_gradient_checkpointing = True
  903. _no_split_modules = [
  904. "Emu3DecoderLayer",
  905. ]
  906. _skip_keys_device_placement = ["past_key_values", "causal_mask"]
  907. _supports_flash_attn = True
  908. _supports_sdpa = True
  909. _can_compile_fullgraph = True
  910. _supports_param_buffer_assignment = False
  911. _supports_flex_attn = True
  912. _supports_attention_backend = True
  913. class Emu3RotaryEmbedding(nn.Module):
  914. inv_freq: torch.Tensor # fix linting for `register_buffer`
  915. def __init__(self, config: Emu3Config, device=None):
  916. super().__init__()
  917. # BC: "rope_type" was originally "type"
  918. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  919. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  920. else:
  921. self.rope_type = "default"
  922. self.max_seq_len_cached = config.max_position_embeddings
  923. self.original_max_seq_len = config.max_position_embeddings
  924. self.config = config
  925. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  926. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  927. self.register_buffer("inv_freq", inv_freq, persistent=False)
  928. self.original_inv_freq = self.inv_freq
  929. @torch.no_grad()
  930. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  931. def forward(self, x, position_ids):
  932. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  933. position_ids_expanded = position_ids[:, None, :].float()
  934. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  935. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  936. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  937. emb = torch.cat((freqs, freqs), dim=-1)
  938. cos = emb.cos() * self.attention_scaling
  939. sin = emb.sin() * self.attention_scaling
  940. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  941. @auto_docstring
  942. class Emu3TextModel(Emu3PreTrainedModel):
  943. _can_record_outputs = {
  944. "hidden_states": Emu3DecoderLayer,
  945. "attentions": Emu3Attention,
  946. }
  947. def __init__(self, config: Emu3Config):
  948. super().__init__(config)
  949. self.padding_idx = config.pad_token_id
  950. self.vocab_size = config.vocab_size
  951. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  952. self.layers = nn.ModuleList(
  953. [Emu3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  954. )
  955. self.norm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  956. self.rotary_emb = Emu3RotaryEmbedding(config=config)
  957. self.gradient_checkpointing = False
  958. # Initialize weights and apply final processing
  959. self.post_init()
  960. @check_model_inputs()
  961. @auto_docstring
  962. def forward(
  963. self,
  964. input_ids: Optional[torch.LongTensor] = None,
  965. attention_mask: Optional[torch.Tensor] = None,
  966. position_ids: Optional[torch.LongTensor] = None,
  967. past_key_values: Optional[Cache] = None,
  968. inputs_embeds: Optional[torch.FloatTensor] = None,
  969. cache_position: Optional[torch.LongTensor] = None,
  970. use_cache: Optional[bool] = None,
  971. **kwargs: Unpack[TransformersKwargs],
  972. ) -> BaseModelOutputWithPast:
  973. if (input_ids is None) ^ (inputs_embeds is not None):
  974. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  975. if inputs_embeds is None:
  976. inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
  977. if use_cache and past_key_values is None:
  978. past_key_values = DynamicCache(config=self.config)
  979. if cache_position is None:
  980. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  981. cache_position: torch.Tensor = torch.arange(
  982. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  983. )
  984. if position_ids is None:
  985. position_ids = cache_position.unsqueeze(0)
  986. causal_mask = create_causal_mask(
  987. config=self.config,
  988. input_embeds=inputs_embeds,
  989. attention_mask=attention_mask,
  990. cache_position=cache_position,
  991. past_key_values=past_key_values,
  992. position_ids=position_ids,
  993. )
  994. hidden_states = inputs_embeds
  995. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  996. for decoder_layer in self.layers[: self.config.num_hidden_layers]:
  997. hidden_states = decoder_layer(
  998. hidden_states,
  999. attention_mask=causal_mask,
  1000. position_ids=position_ids,
  1001. past_key_values=past_key_values,
  1002. cache_position=cache_position,
  1003. position_embeddings=position_embeddings,
  1004. **kwargs,
  1005. )
  1006. hidden_states = self.norm(hidden_states)
  1007. return BaseModelOutputWithPast(
  1008. last_hidden_state=hidden_states,
  1009. past_key_values=past_key_values,
  1010. )
  1011. @auto_docstring
  1012. class Emu3ForCausalLM(Emu3PreTrainedModel, GenerationMixin):
  1013. _tied_weights_keys = ["lm_head.weight"]
  1014. _tp_plan = {"lm_head": "colwise_rep"}
  1015. _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
  1016. config: Emu3TextConfig
  1017. def __init__(self, config):
  1018. super().__init__(config)
  1019. self.model = Emu3TextModel(config)
  1020. self.vocab_size = config.vocab_size
  1021. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  1022. # Initialize weights and apply final processing
  1023. self.post_init()
  1024. @can_return_tuple
  1025. @auto_docstring
  1026. def forward(
  1027. self,
  1028. input_ids: Optional[torch.LongTensor] = None,
  1029. attention_mask: Optional[torch.Tensor] = None,
  1030. position_ids: Optional[torch.LongTensor] = None,
  1031. past_key_values: Optional[Cache] = None,
  1032. inputs_embeds: Optional[torch.FloatTensor] = None,
  1033. labels: Optional[torch.LongTensor] = None,
  1034. use_cache: Optional[bool] = None,
  1035. cache_position: Optional[torch.LongTensor] = None,
  1036. logits_to_keep: Union[int, torch.Tensor] = 0,
  1037. **kwargs: Unpack[TransformersKwargs],
  1038. ) -> CausalLMOutputWithPast:
  1039. r"""
  1040. Example:
  1041. ```python
  1042. >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
  1043. >>> import torch
  1044. >>> import requests
  1045. >>> from PIL import Image
  1046. >>> model = Emu3ForCausalLM.from_pretrained("BAAI/Emu3-Chat-hf", dtype=torch.bfloat16)
  1047. >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")
  1048. >>> inputs = processor(text=["Can you write me a poem about winter."], return_tensors="pt").to(model.device)
  1049. >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
  1050. >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
  1051. ```"""
  1052. outputs: BaseModelOutputWithPast = self.model(
  1053. input_ids=input_ids,
  1054. attention_mask=attention_mask,
  1055. position_ids=position_ids,
  1056. past_key_values=past_key_values,
  1057. inputs_embeds=inputs_embeds,
  1058. use_cache=use_cache,
  1059. cache_position=cache_position,
  1060. **kwargs,
  1061. )
  1062. hidden_states = outputs.last_hidden_state
  1063. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1064. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1065. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1066. loss = None
  1067. if labels is not None:
  1068. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
  1069. return CausalLMOutputWithPast(
  1070. loss=loss,
  1071. logits=logits,
  1072. past_key_values=outputs.past_key_values,
  1073. hidden_states=outputs.hidden_states,
  1074. attentions=outputs.attentions,
  1075. )
  1076. class Emu3Model(Emu3PreTrainedModel):
  1077. _checkpoint_conversion_mapping = {"text_model.model": "text_model"}
  1078. def __init__(self, config):
  1079. super().__init__(config)
  1080. self.text_model = Emu3TextModel._from_config(config.text_config)
  1081. self.vqmodel = Emu3VQVAE(config.vq_config)
  1082. self.vocabulary_mapping = Emu3ImageVocabularyMapping(config.vocabulary_map)
  1083. # Initialize weights and apply final processing
  1084. self.post_init()
  1085. def get_input_embeddings(self):
  1086. return self.text_model.get_input_embeddings()
  1087. def set_input_embeddings(self, value):
  1088. self.text_model.set_input_embeddings(value)
  1089. def set_decoder(self, decoder):
  1090. self.text_model = decoder
  1091. def get_decoder(self):
  1092. return self.text_model
  1093. def get_image_tokens(self, pixel_values: torch.FloatTensor, image_sizes: torch.LongTensor):
  1094. """
  1095. Tokenizes images into discrete tokens with VQGAN module. Converts
  1096. obtained image tokens into BPE tokens and wraps with "boi" and "eoi"
  1097. special tokens.
  1098. Args:
  1099. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
  1100. The tensors corresponding to the input images.
  1101. image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
  1102. The sizes of the images in the batch, being (height, width) for each image.
  1103. """
  1104. image_tokens_list = self.vqmodel.encode(pixel_values, image_sizes)
  1105. bpe_tokens_list = [self.vocabulary_mapping.convert_img2bpe(tokens).flatten() for tokens in image_tokens_list]
  1106. bpe_tokens = torch.cat(bpe_tokens_list)
  1107. return bpe_tokens
  1108. def get_image_features(self, pixel_values: torch.FloatTensor, image_sizes: torch.LongTensor):
  1109. """
  1110. Tokenizes images into discrete tokens with VQGAN module and embeds
  1111. them with text embeddings layer
  1112. Args:
  1113. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
  1114. The tensors corresponding to the input images.
  1115. """
  1116. image_tokens = self.get_image_tokens(pixel_values, image_sizes)
  1117. split_sizes = [
  1118. (height // self.vqmodel.vision_spatial_factor) * (width // self.vqmodel.vision_spatial_factor + 1)
  1119. for height, width in image_sizes
  1120. ]
  1121. image_features = self.get_input_embeddings()(image_tokens)
  1122. image_features = torch.split(image_features, split_sizes)
  1123. return image_features
  1124. @torch.no_grad
  1125. def decode_image_tokens(self, image_tokens: torch.LongTensor, height: int, width: int):
  1126. """
  1127. Decodes generated image tokens from language model to continuous pixel values
  1128. with VQGAN module via upsampling.
  1129. Args:
  1130. image_tokens (`torch.LongTensor` of shape `(batch_size, num_of_tokens)`):
  1131. The tensors corresponding to the input images.
  1132. height (`int`):
  1133. Height of the generated image before upsampling.
  1134. width (`int`):
  1135. Width of the generated image before upsampling.
  1136. """
  1137. sequences = image_tokens[:, :-3].view(-1, height, width + 1)
  1138. image_tokens = self.vocabulary_mapping.convert_bpe2img(sequences)
  1139. image = self.vqmodel.decode(image_tokens)
  1140. return image
  1141. def get_placeholder_mask(
  1142. self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
  1143. ):
  1144. """
  1145. Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
  1146. equal to the length of multimodal features. If the lengths are different, an error is raised.
  1147. """
  1148. if input_ids is None:
  1149. special_image_mask = inputs_embeds == self.get_input_embeddings()(
  1150. torch.tensor(self.vocabulary_mapping.image_token_id, dtype=torch.long, device=inputs_embeds.device)
  1151. )
  1152. special_image_mask = special_image_mask.all(-1)
  1153. else:
  1154. special_image_mask = input_ids == self.vocabulary_mapping.image_token_id
  1155. n_image_tokens = special_image_mask.sum()
  1156. special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
  1157. n_image_features = image_features.shape[0] * image_features.shape[1]
  1158. if inputs_embeds[special_image_mask].numel() != image_features.numel():
  1159. raise ValueError(
  1160. f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}"
  1161. )
  1162. return special_image_mask
  1163. @can_return_tuple
  1164. @auto_docstring
  1165. def forward(
  1166. self,
  1167. input_ids: Optional[torch.LongTensor] = None,
  1168. pixel_values: Optional[torch.FloatTensor] = None,
  1169. image_sizes: Optional[torch.Tensor] = None,
  1170. attention_mask: Optional[torch.Tensor] = None,
  1171. position_ids: Optional[torch.LongTensor] = None,
  1172. past_key_values: Optional[Cache] = None,
  1173. inputs_embeds: Optional[torch.FloatTensor] = None,
  1174. use_cache: Optional[bool] = None,
  1175. cache_position: Optional[torch.LongTensor] = None,
  1176. **kwargs: Unpack[TransformersKwargs],
  1177. ) -> Union[tuple, CausalLMOutputWithPast]:
  1178. r"""
  1179. image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
  1180. The sizes of the images in the batch, being (height, width) for each image. Image sizes can be obtained using
  1181. [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
  1182. [`Emu3ImageProcessor`] for processing images).
  1183. """
  1184. if (input_ids is None) ^ (inputs_embeds is not None):
  1185. raise ValueError(
  1186. "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
  1187. )
  1188. if inputs_embeds is None:
  1189. inputs_embeds = self.get_input_embeddings()(input_ids)
  1190. if pixel_values is not None:
  1191. image_embeds = self.get_image_features(pixel_values, image_sizes)
  1192. image_embeds = torch.cat(image_embeds, dim=0)
  1193. special_image_mask = self.get_placeholder_mask(
  1194. input_ids, inputs_embeds=inputs_embeds, image_features=image_embeds
  1195. )
  1196. inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_embeds)
  1197. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  1198. outputs = self.text_model(
  1199. attention_mask=attention_mask,
  1200. position_ids=position_ids,
  1201. past_key_values=past_key_values,
  1202. inputs_embeds=inputs_embeds,
  1203. use_cache=use_cache,
  1204. cache_position=cache_position,
  1205. **kwargs,
  1206. )
  1207. return outputs
  1208. class Emu3ForConditionalGeneration(Emu3PreTrainedModel, GenerationMixin):
  1209. base_model_prefix = ""
  1210. _tied_weights_keys = ["lm_head.weight"]
  1211. _checkpoint_conversion_mapping = {
  1212. "^text_model.model": "model.text_model",
  1213. "^vqmodel": "model.vqmodel",
  1214. "^text_model.lm_head": "lm_head",
  1215. }
  1216. def __init__(self, config):
  1217. super().__init__(config)
  1218. self.model = Emu3Model(config)
  1219. self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
  1220. self.post_init()
  1221. def get_input_embeddings(self):
  1222. return self.model.get_input_embeddings()
  1223. def set_input_embeddings(self, value):
  1224. self.model.set_input_embeddings(value)
  1225. def get_output_embeddings(self) -> nn.Module:
  1226. return self.lm_head
  1227. def set_decoder(self, decoder):
  1228. self.model.set_decoder(decoder)
  1229. def get_decoder(self):
  1230. return self.model.get_decoder()
  1231. # Make modules available through conditional class for BC
  1232. @property
  1233. def text_model(self):
  1234. return self.model.text_model
  1235. @property
  1236. def vqmodel(self):
  1237. return self.model.vqmodel
  1238. @property
  1239. def vocabulary_mapping(self):
  1240. return self.model.vocabulary_mapping
  1241. def decode_image_tokens(self, **kwargs):
  1242. return self.model.decode_image_tokens(**kwargs)
  1243. @can_return_tuple
  1244. @auto_docstring
  1245. def forward(
  1246. self,
  1247. input_ids: Optional[torch.LongTensor] = None,
  1248. pixel_values: Optional[torch.FloatTensor] = None,
  1249. image_sizes: Optional[torch.Tensor] = None,
  1250. attention_mask: Optional[torch.Tensor] = None,
  1251. position_ids: Optional[torch.LongTensor] = None,
  1252. past_key_values: Optional[Cache] = None,
  1253. inputs_embeds: Optional[torch.FloatTensor] = None,
  1254. use_cache: Optional[bool] = None,
  1255. cache_position: Optional[torch.LongTensor] = None,
  1256. labels: Optional[torch.LongTensor] = None,
  1257. logits_to_keep: Union[int, torch.Tensor] = 0,
  1258. **kwargs: Unpack[TransformersKwargs],
  1259. ) -> Union[tuple, CausalLMOutputWithPast]:
  1260. r"""
  1261. image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
  1262. The sizes of the images in the batch, being (height, width) for each image. Image sizes can be obtained using
  1263. [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
  1264. [`Emu3ImageProcessor`] for processing images).
  1265. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1266. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  1267. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  1268. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  1269. Example:
  1270. ```python
  1271. >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
  1272. >>> import torch
  1273. >>> import requests
  1274. >>> from PIL import Image
  1275. >>> model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", dtype=torch.bfloat16)
  1276. >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")
  1277. >>> conversation = [
  1278. ... {
  1279. ... "role": "system",
  1280. ... "content": [
  1281. ... {"type": "text", "text": "You are a helpful assistant."},
  1282. ... ],
  1283. ... },
  1284. ... {
  1285. ... "role": "user",
  1286. ... "content": [
  1287. ... {"type": "image"},
  1288. ... {"type": "text", "text": "Please describe the image."},
  1289. ... ],
  1290. ... },
  1291. ... ]
  1292. >>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
  1293. >>> image = Image.open(requests.get("https://www.ilankelman.org/stopsigns/australia.jpg", stream=True).raw)
  1294. >>> inputs = processor(images=[image], text=[prompt], return_tensors="pt").to(model.device, torch.bfloat16)
  1295. >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
  1296. >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
  1297. ```"""
  1298. outputs = self.model(
  1299. input_ids=input_ids,
  1300. attention_mask=attention_mask,
  1301. position_ids=position_ids,
  1302. past_key_values=past_key_values,
  1303. inputs_embeds=inputs_embeds,
  1304. use_cache=use_cache,
  1305. cache_position=cache_position,
  1306. **kwargs,
  1307. )
  1308. hidden_states = outputs[0]
  1309. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1310. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1311. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1312. loss = None
  1313. if labels is not None:
  1314. loss = self.loss_function(
  1315. logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
  1316. )
  1317. return CausalLMOutputWithPast(
  1318. loss=loss,
  1319. logits=logits,
  1320. past_key_values=outputs.past_key_values,
  1321. hidden_states=outputs.hidden_states,
  1322. attentions=outputs.attentions,
  1323. )
  1324. def prepare_inputs_for_generation(
  1325. self,
  1326. input_ids,
  1327. past_key_values=None,
  1328. attention_mask=None,
  1329. inputs_embeds=None,
  1330. cache_position=None,
  1331. position_ids=None,
  1332. use_cache=True,
  1333. pixel_values=None,
  1334. **kwargs,
  1335. ):
  1336. # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
  1337. model_inputs = super().prepare_inputs_for_generation(
  1338. input_ids,
  1339. past_key_values=past_key_values,
  1340. attention_mask=attention_mask,
  1341. inputs_embeds=inputs_embeds,
  1342. cache_position=cache_position,
  1343. position_ids=position_ids,
  1344. pixel_values=pixel_values,
  1345. use_cache=use_cache,
  1346. **kwargs,
  1347. )
  1348. if cache_position[0] != 0:
  1349. model_inputs["pixel_values"] = None
  1350. return model_inputs
  1351. __all__ = [
  1352. "Emu3ForConditionalGeneration",
  1353. "Emu3ForCausalLM",
  1354. "Emu3TextModel",
  1355. "Emu3PreTrainedModel",
  1356. "Emu3VQVAE",
  1357. "Emu3Model",
  1358. ]