modeling_emu3.py 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  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. # Copyright 2024 HuggingFace Inc. team. All rights reserved.
  8. #
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License");
  11. # you may not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS,
  18. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. import math
  22. from collections.abc import Callable
  23. from dataclasses import dataclass
  24. from functools import cached_property
  25. from typing import Optional
  26. import torch
  27. import torch.nn as nn
  28. import torch.nn.functional as F
  29. from ... import initialization as init
  30. from ...activations import ACT2FN
  31. from ...cache_utils import Cache, DynamicCache
  32. from ...generation import GenerationMixin
  33. from ...integrations import use_kernel_forward_from_hub, use_kernel_func_from_hub, use_kernelized_func
  34. from ...masking_utils import create_causal_mask
  35. from ...modeling_layers import GradientCheckpointingLayer
  36. from ...modeling_outputs import BaseModelOutputWithPast, BaseModelOutputWithPooling, CausalLMOutputWithPast
  37. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  38. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  39. from ...processing_utils import Unpack
  40. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple, torch_compilable_check
  41. from ...utils.generic import maybe_autocast, merge_with_config_defaults
  42. from ...utils.output_capturing import capture_outputs
  43. from .configuration_emu3 import Emu3Config, Emu3TextConfig, Emu3VQVAEConfig
  44. @dataclass
  45. @auto_docstring
  46. class Emu3VQVAEModelOutput(BaseModelOutputWithPooling):
  47. r"""
  48. image_tokens (`torch.LongTensor` of shape `(batch_size, config.vocab_size`):
  49. Indices of the image tokens predicted by the VQ-VAE model.
  50. """
  51. image_tokens: torch.LongTensor | None = None
  52. def rotate_half(x):
  53. """Rotates half the hidden dims of the input."""
  54. x1 = x[..., : x.shape[-1] // 2]
  55. x2 = x[..., x.shape[-1] // 2 :]
  56. return torch.cat((-x2, x1), dim=-1)
  57. @use_kernel_func_from_hub("rotary_pos_emb")
  58. def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
  59. """Applies Rotary Position Embedding to the query and key tensors.
  60. Args:
  61. q (`torch.Tensor`): The query tensor.
  62. k (`torch.Tensor`): The key tensor.
  63. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  64. sin (`torch.Tensor`): The sine part of the rotary embedding.
  65. unsqueeze_dim (`int`, *optional*, defaults to 1):
  66. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  67. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  68. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  69. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  70. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  71. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  72. Returns:
  73. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  74. """
  75. cos = cos.unsqueeze(unsqueeze_dim)
  76. sin = sin.unsqueeze(unsqueeze_dim)
  77. q_embed = (q * cos) + (rotate_half(q) * sin)
  78. k_embed = (k * cos) + (rotate_half(k) * sin)
  79. return q_embed, k_embed
  80. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  81. """
  82. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  83. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  84. """
  85. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  86. if n_rep == 1:
  87. return hidden_states
  88. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  89. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  90. def eager_attention_forward(
  91. module: nn.Module,
  92. query: torch.Tensor,
  93. key: torch.Tensor,
  94. value: torch.Tensor,
  95. attention_mask: torch.Tensor | None,
  96. scaling: float,
  97. dropout: float = 0.0,
  98. **kwargs: Unpack[TransformersKwargs],
  99. ):
  100. key_states = repeat_kv(key, module.num_key_value_groups)
  101. value_states = repeat_kv(value, module.num_key_value_groups)
  102. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  103. if attention_mask is not None:
  104. attn_weights = attn_weights + attention_mask
  105. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  106. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  107. attn_output = torch.matmul(attn_weights, value_states)
  108. attn_output = attn_output.transpose(1, 2).contiguous()
  109. return attn_output, attn_weights
  110. @use_kernelized_func(apply_rotary_pos_emb)
  111. class Emu3Attention(nn.Module):
  112. """Multi-headed attention from 'Attention Is All You Need' paper"""
  113. def __init__(self, config: Emu3Config, layer_idx: int):
  114. super().__init__()
  115. self.config = config
  116. self.layer_idx = layer_idx
  117. self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
  118. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  119. self.scaling = self.head_dim**-0.5
  120. self.attention_dropout = config.attention_dropout
  121. self.is_causal = True
  122. self.q_proj = nn.Linear(
  123. config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
  124. )
  125. self.k_proj = nn.Linear(
  126. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  127. )
  128. self.v_proj = nn.Linear(
  129. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  130. )
  131. self.o_proj = nn.Linear(
  132. config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
  133. )
  134. def forward(
  135. self,
  136. hidden_states: torch.Tensor,
  137. position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
  138. attention_mask: torch.Tensor | None = None,
  139. past_key_values: Cache | None = None,
  140. **kwargs: Unpack[TransformersKwargs],
  141. ) -> tuple[torch.Tensor, torch.Tensor]:
  142. input_shape = hidden_states.shape[:-1]
  143. hidden_shape = (*input_shape, -1, self.head_dim)
  144. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  145. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  146. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  147. cos, sin = position_embeddings
  148. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  149. if past_key_values is not None:
  150. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
  151. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  152. self.config._attn_implementation, eager_attention_forward
  153. )
  154. attn_output, attn_weights = attention_interface(
  155. self,
  156. query_states,
  157. key_states,
  158. value_states,
  159. attention_mask,
  160. dropout=0.0 if not self.training else self.attention_dropout,
  161. scaling=self.scaling,
  162. **kwargs,
  163. )
  164. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  165. attn_output = self.o_proj(attn_output)
  166. return attn_output, attn_weights
  167. @use_kernel_forward_from_hub("RMSNorm")
  168. class Emu3RMSNorm(nn.Module):
  169. def __init__(self, hidden_size, eps: float = 1e-6) -> None:
  170. """
  171. Emu3RMSNorm is equivalent to T5LayerNorm
  172. """
  173. super().__init__()
  174. self.weight = nn.Parameter(torch.ones(hidden_size))
  175. self.variance_epsilon = eps
  176. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  177. input_dtype = hidden_states.dtype
  178. hidden_states = hidden_states.to(torch.float32)
  179. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  180. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  181. return self.weight * hidden_states.to(input_dtype)
  182. def extra_repr(self):
  183. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  184. class Emu3MLP(nn.Module):
  185. def __init__(self, config):
  186. super().__init__()
  187. self.config = config
  188. self.hidden_size = config.hidden_size
  189. self.intermediate_size = config.intermediate_size
  190. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  191. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  192. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
  193. self.act_fn = ACT2FN[config.hidden_act]
  194. def forward(self, x):
  195. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  196. return down_proj
  197. class Emu3DecoderLayer(GradientCheckpointingLayer):
  198. def __init__(self, config: Emu3Config, layer_idx: int):
  199. super().__init__()
  200. self.hidden_size = config.hidden_size
  201. self.self_attn = Emu3Attention(config=config, layer_idx=layer_idx)
  202. self.mlp = Emu3MLP(config)
  203. self.input_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  204. self.post_attention_layernorm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  205. self.dropout = nn.Dropout(config.attention_dropout)
  206. def forward(
  207. self,
  208. hidden_states: torch.Tensor,
  209. attention_mask: torch.Tensor | None = None,
  210. position_ids: torch.LongTensor | None = None,
  211. past_key_values: Cache | None = None,
  212. use_cache: bool | None = False,
  213. position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
  214. **kwargs: Unpack[TransformersKwargs],
  215. ) -> torch.Tensor:
  216. residual = hidden_states
  217. hidden_states = self.input_layernorm(hidden_states)
  218. hidden_states, _ = self.self_attn(
  219. hidden_states=hidden_states,
  220. attention_mask=attention_mask,
  221. position_ids=position_ids,
  222. past_key_values=past_key_values,
  223. use_cache=use_cache,
  224. position_embeddings=position_embeddings,
  225. **kwargs,
  226. )
  227. hidden_states = residual + self.dropout(hidden_states)
  228. residual = hidden_states
  229. hidden_states = self.post_attention_layernorm(hidden_states)
  230. hidden_states = self.mlp(hidden_states)
  231. hidden_states = residual + self.dropout(hidden_states)
  232. return hidden_states
  233. class Emu3VQVAEVectorQuantizer(nn.Module):
  234. """
  235. A module for vector quantization using learned embedding vectors.
  236. This module implements the quantization process similar to te one described in
  237. the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous
  238. input vectors into discrete codebook vectors, which are learned during training.
  239. Current implementation improves over previous ones by avoiding costly matrix multiplications
  240. and allowing for post-hoc remapping of indices.
  241. """
  242. def __init__(self, config: Emu3VQVAEConfig):
  243. super().__init__()
  244. self.embedding = nn.Embedding(config.codebook_size, config.embed_dim)
  245. self.embedding.weight.data.uniform_(-1.0 / config.codebook_size, 1.0 / config.codebook_size)
  246. def forward(self, hidden_state: torch.Tensor):
  247. batch_size, temporal, channels, height, width = hidden_state.shape
  248. hidden_state = hidden_state.permute(0, 1, 3, 4, 2).contiguous()
  249. hidden_state_flattened = hidden_state.view(-1, channels)
  250. # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
  251. hidden_state_sum = torch.sum(hidden_state_flattened**2, dim=1, keepdim=True)
  252. embedding_sum = torch.sum(self.embedding.weight**2, dim=1)
  253. # "bd,dn->bn",
  254. distances = 2 * torch.matmul(hidden_state_flattened, self.embedding.weight.transpose(0, 1))
  255. distances = hidden_state_sum + embedding_sum - distances
  256. min_encoding_indices = torch.argmin(distances, dim=1)
  257. min_encoding_indices = min_encoding_indices.view(batch_size, temporal, height, width)
  258. return min_encoding_indices
  259. class Emu3VQVAEEncoderConvDownsample(nn.Module):
  260. def __init__(self, in_channels):
  261. super().__init__()
  262. self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)
  263. def forward(self, hidden_states):
  264. # no asymmetric padding in torch conv, must do it ourselves
  265. hidden_states = F.pad(hidden_states, pad=(0, 1, 0, 1), mode="constant", value=0)
  266. hidden_states = self.conv(hidden_states)
  267. return hidden_states
  268. class Emu3VQVAEEncoderConvUpsample(nn.Module):
  269. def __init__(self, in_channels):
  270. super().__init__()
  271. self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)
  272. def forward(self, hidden_states):
  273. hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
  274. hidden_states = self.conv(hidden_states)
  275. return hidden_states
  276. class Emu3VQVAEConv3d(nn.Module):
  277. def __init__(
  278. self,
  279. in_channel: int,
  280. out_channel: int,
  281. kernel_size: tuple[int],
  282. stride: tuple[int],
  283. ):
  284. super().__init__()
  285. padding_sizes = [one_kernel - one_stride for one_kernel, one_stride in zip(kernel_size[1:], stride[1:])]
  286. self.padding = ()
  287. for pad_size in padding_sizes[::-1]:
  288. self.padding += (pad_size // 2 + pad_size % 2, pad_size // 2)
  289. self.padding += (2, 0)
  290. self.conv = nn.Conv3d(
  291. in_channel,
  292. out_channel,
  293. kernel_size,
  294. stride=stride,
  295. )
  296. def forward(self, hidden_states: torch.Tensor):
  297. hidden_states = F.pad(hidden_states, self.padding)
  298. hidden_states = self.conv(hidden_states)
  299. return hidden_states
  300. class Emu3VQVAESpatialNorm(nn.Module):
  301. def __init__(
  302. self,
  303. in_channels: int,
  304. out_channels: int,
  305. ):
  306. super().__init__()
  307. self.norm_layer = nn.GroupNorm(
  308. num_channels=out_channels,
  309. num_groups=32,
  310. eps=1e-6,
  311. affine=True,
  312. )
  313. self.conv_y = nn.Conv2d(
  314. in_channels,
  315. out_channels,
  316. kernel_size=1,
  317. stride=1,
  318. padding=0,
  319. )
  320. self.conv_b = nn.Conv2d(
  321. in_channels,
  322. out_channels,
  323. kernel_size=1,
  324. stride=1,
  325. padding=0,
  326. )
  327. def forward(self, hidden_states: torch.Tensor, quant_states: torch.Tensor):
  328. quant_states = F.interpolate(quant_states, size=hidden_states.shape[-2:], mode="nearest")
  329. hidden_states = self.norm_layer(hidden_states)
  330. hidden_states = hidden_states * self.conv_y(quant_states) + self.conv_b(quant_states)
  331. return hidden_states
  332. class Emu3VQVAETemporalUpsample(nn.Module):
  333. def __init__(
  334. self,
  335. in_channel: int,
  336. out_channel: int,
  337. ):
  338. super().__init__()
  339. self.conv = Emu3VQVAEConv3d(
  340. in_channel,
  341. out_channel,
  342. kernel_size=(3, 3, 3),
  343. stride=(1, 1, 1),
  344. )
  345. def forward(self, hidden_states: torch.Tensor):
  346. batch_size, channels, temporal, height, width = hidden_states.shape
  347. hidden_states = hidden_states.permute(0, 1, 3, 4, 2).contiguous().view(batch_size, -1, temporal)
  348. hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
  349. hidden_states = hidden_states.view(batch_size, channels, height, width, -1).permute(0, 1, 4, 2, 3).contiguous()
  350. hidden_states = self.conv(hidden_states)
  351. return hidden_states
  352. class Emu3VQVAETemporalDownsample(nn.Module):
  353. def __init__(
  354. self,
  355. in_channel: int,
  356. out_channel: int,
  357. ):
  358. super().__init__()
  359. self.conv = Emu3VQVAEConv3d(
  360. in_channel,
  361. out_channel,
  362. kernel_size=(4, 3, 3),
  363. stride=(2, 1, 1),
  364. )
  365. def forward(self, hidden_states: torch.Tensor):
  366. hidden_states = self.conv(hidden_states)
  367. return hidden_states
  368. class Emu3VQVAETemporalResnetBlock(nn.Module):
  369. def __init__(
  370. self,
  371. in_channels,
  372. out_channels=None,
  373. ):
  374. super().__init__()
  375. self.in_channels = in_channels
  376. self.out_channels = in_channels if out_channels is None else out_channels
  377. self.norm1 = nn.BatchNorm3d(in_channels)
  378. self.conv1 = Emu3VQVAEConv3d(
  379. in_channels,
  380. out_channels,
  381. kernel_size=(3, 3, 3),
  382. stride=(1, 1, 1),
  383. )
  384. self.norm2 = nn.BatchNorm3d(out_channels)
  385. self.conv2 = Emu3VQVAEConv3d(
  386. out_channels,
  387. out_channels,
  388. kernel_size=(3, 3, 3),
  389. stride=(1, 1, 1),
  390. )
  391. if self.in_channels != self.out_channels:
  392. self.nin_shortcut = nn.Conv3d(
  393. in_channels,
  394. out_channels,
  395. kernel_size=1,
  396. stride=1,
  397. padding=0,
  398. )
  399. def forward(self, hidden_states):
  400. residual = hidden_states
  401. hidden_states = self.norm1(hidden_states)
  402. hidden_states *= torch.sigmoid(hidden_states)
  403. hidden_states = self.conv1(hidden_states)
  404. hidden_states = self.norm2(hidden_states)
  405. hidden_states *= torch.sigmoid(hidden_states)
  406. hidden_states = self.conv2(hidden_states)
  407. if self.in_channels != self.out_channels:
  408. residual = self.nin_shortcut(residual)
  409. return residual + hidden_states
  410. class Emu3VQVAEResnetBlock(nn.Module):
  411. def __init__(
  412. self,
  413. in_channels: int,
  414. out_channels: int | None = None,
  415. quant_channels: int | None = None,
  416. ):
  417. super().__init__()
  418. self.in_channels = in_channels
  419. out_channels = in_channels if out_channels is None else out_channels
  420. self.out_channels = out_channels
  421. self.quant_channels = quant_channels
  422. if quant_channels is None:
  423. self.norm1 = nn.GroupNorm(num_channels=in_channels, num_groups=32, eps=1e-6, affine=True)
  424. self.norm2 = nn.GroupNorm(num_channels=out_channels, num_groups=32, eps=1e-6, affine=True)
  425. else:
  426. self.norm1 = Emu3VQVAESpatialNorm(quant_channels, in_channels)
  427. self.norm2 = Emu3VQVAESpatialNorm(quant_channels, out_channels)
  428. self.conv1 = nn.Conv2d(
  429. in_channels,
  430. out_channels,
  431. kernel_size=3,
  432. stride=1,
  433. padding=1,
  434. )
  435. self.conv2 = nn.Conv2d(
  436. out_channels,
  437. out_channels,
  438. kernel_size=3,
  439. stride=1,
  440. padding=1,
  441. )
  442. if self.in_channels != self.out_channels:
  443. self.nin_shortcut = nn.Conv2d(
  444. in_channels,
  445. out_channels,
  446. kernel_size=1,
  447. stride=1,
  448. padding=0,
  449. )
  450. def forward(self, hidden_states: torch.Tensor, quant_channels: torch.Tensor | None = None):
  451. norm_args = () if self.quant_channels is None else (quant_channels,)
  452. residual = hidden_states
  453. hidden_states = self.norm1(hidden_states, *norm_args)
  454. hidden_states *= torch.sigmoid(hidden_states)
  455. hidden_states = self.conv1(hidden_states)
  456. hidden_states = self.norm2(hidden_states, *norm_args)
  457. hidden_states *= torch.sigmoid(hidden_states)
  458. hidden_states = self.conv2(hidden_states)
  459. if self.in_channels != self.out_channels:
  460. residual = self.nin_shortcut(residual)
  461. return residual + hidden_states
  462. class Emu3VQVAEAttentionBlock(nn.Module):
  463. """Multi-headed attention from 'Attention Is All You Need' paper"""
  464. def __init__(self, config: Emu3VQVAEConfig):
  465. super().__init__()
  466. self.config = config
  467. self.embed_dim = config.hidden_size
  468. self.num_heads = config.num_attention_heads
  469. self.head_dim = self.embed_dim // self.num_heads
  470. if self.head_dim * self.num_heads != self.embed_dim:
  471. raise ValueError(
  472. f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
  473. f" {self.num_heads})."
  474. )
  475. self.scale = self.head_dim**-0.5
  476. self.dropout = config.attention_dropout
  477. self.is_causal = False
  478. self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
  479. self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
  480. self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
  481. self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
  482. # for compatibility with the attention interface
  483. self.num_key_value_groups = 1
  484. def forward(
  485. self,
  486. hidden_states: torch.Tensor,
  487. attention_mask: torch.Tensor | None = None,
  488. **kwargs,
  489. ) -> tuple[torch.Tensor, torch.Tensor | None]:
  490. """Input shape: Batch x Time x Channel"""
  491. input_shape = hidden_states.shape[:-1]
  492. hidden_shape = (*input_shape, -1, self.head_dim)
  493. queries = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  494. keys = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  495. values = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  496. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  497. self.config._attn_implementation, eager_attention_forward
  498. )
  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(*input_shape, -1).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: torch.FloatTensor | None = 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. input_modalities = ("image",)
  769. _supports_sdpa = True
  770. _supports_flash_attn = True
  771. _supports_flex_attn = True
  772. _supports_attention_backend = True
  773. _no_split_modules = [
  774. "Emu3VQVAETemporalResnetBlock",
  775. "Emu3VQVAEAttentionBlock",
  776. "Emu3VQVAEResnetBlock",
  777. "Emu3VQVAEVectorQuantizer",
  778. ]
  779. _can_record_outputs = {
  780. "hidden_states": [Emu3VQVAEResnetBlock, Emu3VQVAETemporalResnetBlock],
  781. "attentions": Emu3VQVAEAttentionBlock,
  782. }
  783. @torch.no_grad()
  784. def _init_weights(self, module):
  785. if isinstance(module, (nn.Conv2d, nn.Conv3d)):
  786. init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu")
  787. if module.bias is not None:
  788. fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(module.weight)
  789. bound = 1 / math.sqrt(fan_in)
  790. init.uniform_(module.bias, -bound, bound)
  791. elif isinstance(module, nn.Linear):
  792. init.kaiming_uniform_(module.weight, a=math.sqrt(5))
  793. if module.bias is not None:
  794. fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(module.weight)
  795. bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
  796. init.uniform_(module.bias, -bound, bound)
  797. elif isinstance(module, (nn.BatchNorm2d, nn.BatchNorm3d, nn.GroupNorm)):
  798. init.constant_(module.weight, 1.0)
  799. init.constant_(module.bias, 0.0)
  800. if getattr(module, "running_mean", None) is not None:
  801. init.zeros_(module.running_mean)
  802. init.ones_(module.running_var)
  803. init.zeros_(module.num_batches_tracked)
  804. elif isinstance(module, nn.Embedding):
  805. init.normal_(module.weight)
  806. # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
  807. if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
  808. init.zeros_(module.weight[module.padding_idx])
  809. def __init__(self, config: Emu3VQVAEConfig):
  810. super().__init__(config)
  811. self.config = config
  812. self.encoder = Emu3VQVAEEncoder(config)
  813. self.decoder = Emu3VQVAEDecoder(config)
  814. self.quantize = Emu3VQVAEVectorQuantizer(config)
  815. self.vision_spatial_factor = 2 ** (len(config.channel_multiplier) - 1)
  816. self.quant_conv = Emu3VQVAEConv3d(
  817. config.latent_channels, config.embed_dim, kernel_size=(3, 1, 1), stride=(1, 1, 1)
  818. )
  819. self.post_quant_conv = Emu3VQVAEConv3d(
  820. config.embed_dim, config.latent_channels, kernel_size=(3, 1, 1), stride=(1, 1, 1)
  821. )
  822. self.spatial_scale_factor = 2 ** (len(config.channel_multiplier) - 1)
  823. self.eval() # Emu3's VQ model is frozen
  824. self.post_init()
  825. @merge_with_config_defaults
  826. @capture_outputs
  827. def encode(
  828. self, pixel_values: torch.Tensor, image_sizes: torch.Tensor, **kwargs: Unpack[TransformersKwargs]
  829. ) -> Emu3VQVAEModelOutput:
  830. is_image = pixel_values.ndim == 4
  831. if is_image:
  832. temporal = self.config.temporal_downsample_factor
  833. batch_size, channels, height, width = pixel_values.shape
  834. pixel_values = pixel_values.unsqueeze(1).repeat(1, temporal, 1, 1, 1)
  835. else:
  836. batch_size, temporal, channels, height, width = pixel_values.shape
  837. hidden_states = self.encoder(pixel_values)
  838. # b t c h w -> b c t h w
  839. conv_hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
  840. conv_hidden_states = self.quant_conv(conv_hidden_states)
  841. # b c t h w -> b t c h w
  842. conv_hidden_states = conv_hidden_states.permute(0, 2, 1, 3, 4)
  843. codes = self.quantize(conv_hidden_states)
  844. image_tokens = codes.squeeze(1) if is_image else codes
  845. image_tokens = [
  846. single_image[: int(size[0] / self.vision_spatial_factor), : int(size[1] / self.vision_spatial_factor)]
  847. for single_image, size in zip(image_tokens, image_sizes)
  848. ]
  849. return Emu3VQVAEModelOutput(
  850. last_hidden_state=hidden_states,
  851. image_tokens=image_tokens,
  852. )
  853. def decode(self, hidden_states: torch.Tensor):
  854. is_image = hidden_states.ndim == 3
  855. if is_image:
  856. hidden_states = hidden_states.unsqueeze(1)
  857. batch_size, temporal, height, width = hidden_states.shape
  858. quant = self.quantize.embedding(hidden_states.flatten())
  859. channels = quant.shape[-1]
  860. quant = quant.view(batch_size, temporal, height, width, channels).permute(0, 4, 1, 2, 3).contiguous()
  861. post_quant = self.post_quant_conv(quant)
  862. quant = quant.permute(0, 2, 1, 3, 4)
  863. post_quant = post_quant.permute(0, 2, 1, 3, 4)
  864. video = self.decoder(post_quant, quant)
  865. video = video.reshape(
  866. batch_size,
  867. temporal * self.config.temporal_downsample_factor,
  868. self.config.out_channels,
  869. height * self.spatial_scale_factor,
  870. width * self.spatial_scale_factor,
  871. )
  872. return video[:, 0] if is_image else video
  873. class Emu3ImageVocabularyMapping:
  874. """
  875. A class for mapping discrete image tokens from VQGAN to BPE tokens.
  876. """
  877. def __init__(self, vocab_map):
  878. self.vocab_map = vocab_map
  879. self.eol_token_id = vocab_map.get("<|extra_200|>")
  880. self.image_token_id = vocab_map.get("<image>")
  881. @cached_property
  882. def image_tokens(self):
  883. return sorted([val for name, val in self.vocab_map.items() if name.startswith("<|visual token")])
  884. @cached_property
  885. def image_tokens_str(self):
  886. return sorted([name for name, val in self.vocab_map.items() if name.startswith("<|visual token")])
  887. @cached_property
  888. def img2bpe(self):
  889. return {int(token[-8:-2]): self.vocab_map[token] for token in self.image_tokens_str}
  890. @cached_property
  891. def bpe2img(self):
  892. return {v: k for k, v in self.img2bpe.items()}
  893. @cached_property
  894. def bpe2img_mapping_tensor(self):
  895. mapping = torch.zeros(max(self.bpe2img.keys()) + 1, dtype=torch.int)
  896. for k, v in self.bpe2img.items():
  897. mapping[k] = v
  898. return mapping
  899. @cached_property
  900. def img2bpe_mapping_tensor(self):
  901. mapping = torch.zeros(max(self.img2bpe.keys()) + 1, dtype=torch.int)
  902. for k, v in self.img2bpe.items():
  903. mapping[k] = v
  904. return mapping
  905. def convert_img2bpe(self, img_batch: list[torch.Tensor]) -> torch.Tensor:
  906. device = img_batch.device
  907. eol_row = torch.ones((img_batch.shape[0], 1), dtype=torch.int) * self.eol_token_id
  908. img_tokens = self.img2bpe_mapping_tensor[img_batch.to("cpu")]
  909. img_tokens = torch.cat([img_tokens, eol_row], dim=-1)
  910. return img_tokens.to(device)
  911. def convert_bpe2img(self, img_batch: torch.Tensor) -> torch.Tensor:
  912. device = img_batch.device
  913. img_batch = img_batch[..., :-1] # remove last row of EOL tokens
  914. img_tokens = self.bpe2img_mapping_tensor[img_batch.to("cpu")]
  915. return img_tokens.to(device)
  916. @auto_docstring
  917. class Emu3PreTrainedModel(PreTrainedModel):
  918. config: Emu3Config
  919. base_model_prefix = "model"
  920. input_modalities = ("image", "text")
  921. supports_gradient_checkpointing = True
  922. _no_split_modules = [
  923. "Emu3DecoderLayer",
  924. ]
  925. _skip_keys_device_placement = ["past_key_values", "causal_mask"]
  926. _supports_flash_attn = True
  927. _supports_sdpa = True
  928. _can_compile_fullgraph = True
  929. _supports_flex_attn = True
  930. _supports_attention_backend = True
  931. _can_record_outputs = {
  932. "hidden_states": Emu3DecoderLayer,
  933. "attentions": Emu3Attention,
  934. }
  935. class Emu3RotaryEmbedding(nn.Module):
  936. inv_freq: torch.Tensor # fix linting for `register_buffer`
  937. def __init__(self, config: Emu3Config, device=None):
  938. super().__init__()
  939. self.max_seq_len_cached = config.max_position_embeddings
  940. self.original_max_seq_len = config.max_position_embeddings
  941. self.config = config
  942. self.rope_type = self.config.rope_parameters["rope_type"]
  943. rope_init_fn: Callable = self.compute_default_rope_parameters
  944. if self.rope_type != "default":
  945. rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  946. inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
  947. self.register_buffer("inv_freq", inv_freq, persistent=False)
  948. self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
  949. @staticmethod
  950. def compute_default_rope_parameters(
  951. config: Emu3Config | None = None,
  952. device: Optional["torch.device"] = None,
  953. seq_len: int | None = None,
  954. ) -> tuple["torch.Tensor", float]:
  955. """
  956. Computes the inverse frequencies according to the original RoPE implementation
  957. Args:
  958. config ([`~transformers.PreTrainedConfig`]):
  959. The model configuration.
  960. device (`torch.device`):
  961. The device to use for initialization of the inverse frequencies.
  962. seq_len (`int`, *optional*):
  963. The current sequence length. Unused for this type of RoPE.
  964. Returns:
  965. Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
  966. post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
  967. """
  968. base = config.rope_parameters["rope_theta"]
  969. dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
  970. attention_factor = 1.0 # Unused in this type of RoPE
  971. # Compute the inverse frequencies
  972. inv_freq = 1.0 / (
  973. base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
  974. )
  975. return inv_freq, attention_factor
  976. @torch.no_grad()
  977. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  978. def forward(self, x, position_ids):
  979. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  980. position_ids_expanded = position_ids[:, None, :].float()
  981. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  982. with maybe_autocast(device_type=device_type, enabled=False): # Force float32
  983. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  984. emb = torch.cat((freqs, freqs), dim=-1)
  985. cos = emb.cos() * self.attention_scaling
  986. sin = emb.sin() * self.attention_scaling
  987. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  988. @auto_docstring
  989. class Emu3TextModel(Emu3PreTrainedModel):
  990. config: Emu3TextConfig
  991. def __init__(self, config: Emu3TextConfig):
  992. super().__init__(config)
  993. self.padding_idx = config.pad_token_id
  994. self.vocab_size = config.vocab_size
  995. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  996. self.layers = nn.ModuleList(
  997. [Emu3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  998. )
  999. self.norm = Emu3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  1000. self.rotary_emb = Emu3RotaryEmbedding(config=config)
  1001. self.gradient_checkpointing = False
  1002. # Initialize weights and apply final processing
  1003. self.post_init()
  1004. @merge_with_config_defaults
  1005. @capture_outputs
  1006. @auto_docstring
  1007. def forward(
  1008. self,
  1009. input_ids: torch.LongTensor | None = None,
  1010. attention_mask: torch.Tensor | None = None,
  1011. position_ids: torch.LongTensor | None = None,
  1012. past_key_values: Cache | None = None,
  1013. inputs_embeds: torch.FloatTensor | None = None,
  1014. use_cache: bool | None = None,
  1015. **kwargs: Unpack[TransformersKwargs],
  1016. ) -> BaseModelOutputWithPast:
  1017. if (input_ids is None) ^ (inputs_embeds is not None):
  1018. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  1019. if inputs_embeds is None:
  1020. inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
  1021. if use_cache and past_key_values is None:
  1022. past_key_values = DynamicCache(config=self.config)
  1023. if position_ids is None:
  1024. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  1025. position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
  1026. position_ids = position_ids.unsqueeze(0)
  1027. causal_mask = create_causal_mask(
  1028. config=self.config,
  1029. inputs_embeds=inputs_embeds,
  1030. attention_mask=attention_mask,
  1031. past_key_values=past_key_values,
  1032. position_ids=position_ids,
  1033. )
  1034. hidden_states = inputs_embeds
  1035. position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
  1036. for decoder_layer in self.layers[: self.config.num_hidden_layers]:
  1037. hidden_states = decoder_layer(
  1038. hidden_states,
  1039. attention_mask=causal_mask,
  1040. position_embeddings=position_embeddings,
  1041. position_ids=position_ids,
  1042. past_key_values=past_key_values,
  1043. use_cache=use_cache,
  1044. **kwargs,
  1045. )
  1046. hidden_states = self.norm(hidden_states)
  1047. return BaseModelOutputWithPast(
  1048. last_hidden_state=hidden_states,
  1049. past_key_values=past_key_values,
  1050. )
  1051. @auto_docstring
  1052. class Emu3ForCausalLM(Emu3PreTrainedModel, GenerationMixin):
  1053. _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
  1054. _tp_plan = {"lm_head": "colwise_gather_output"}
  1055. _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
  1056. config: Emu3TextConfig
  1057. def __init__(self, config):
  1058. super().__init__(config)
  1059. self.model = Emu3TextModel(config)
  1060. self.vocab_size = config.vocab_size
  1061. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  1062. # Initialize weights and apply final processing
  1063. self.post_init()
  1064. @can_return_tuple
  1065. @auto_docstring
  1066. def forward(
  1067. self,
  1068. input_ids: torch.LongTensor | None = None,
  1069. attention_mask: torch.Tensor | None = None,
  1070. position_ids: torch.LongTensor | None = None,
  1071. past_key_values: Cache | None = None,
  1072. inputs_embeds: torch.FloatTensor | None = None,
  1073. labels: torch.LongTensor | None = None,
  1074. use_cache: bool | None = None,
  1075. logits_to_keep: int | torch.Tensor = 0,
  1076. **kwargs: Unpack[TransformersKwargs],
  1077. ) -> CausalLMOutputWithPast:
  1078. r"""
  1079. Example:
  1080. ```python
  1081. >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
  1082. >>> import torch
  1083. >>> import httpx
  1084. >>> from io import BytesIO
  1085. >>> from PIL import Image
  1086. >>> model = Emu3ForCausalLM.from_pretrained("BAAI/Emu3-Chat-hf", dtype=torch.bfloat16)
  1087. >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")
  1088. >>> inputs = processor(text=["Can you write me a poem about winter."], return_tensors="pt").to(model.device)
  1089. >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
  1090. >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
  1091. ```"""
  1092. outputs: BaseModelOutputWithPast = self.model(
  1093. input_ids=input_ids,
  1094. attention_mask=attention_mask,
  1095. position_ids=position_ids,
  1096. past_key_values=past_key_values,
  1097. inputs_embeds=inputs_embeds,
  1098. use_cache=use_cache,
  1099. **kwargs,
  1100. )
  1101. hidden_states = outputs.last_hidden_state
  1102. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1103. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1104. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1105. loss = None
  1106. if labels is not None:
  1107. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
  1108. return CausalLMOutputWithPast(
  1109. loss=loss,
  1110. logits=logits,
  1111. past_key_values=outputs.past_key_values,
  1112. hidden_states=outputs.hidden_states,
  1113. attentions=outputs.attentions,
  1114. )
  1115. class Emu3Model(Emu3PreTrainedModel):
  1116. def __init__(self, config):
  1117. super().__init__(config)
  1118. self.text_model = Emu3TextModel._from_config(config.text_config)
  1119. self.vqmodel = Emu3VQVAE(config.vq_config)
  1120. self.vocabulary_mapping = Emu3ImageVocabularyMapping(config.vocabulary_map)
  1121. # Initialize weights and apply final processing
  1122. self.post_init()
  1123. def get_input_embeddings(self):
  1124. return self.text_model.get_input_embeddings()
  1125. def set_input_embeddings(self, value):
  1126. self.text_model.set_input_embeddings(value)
  1127. def get_image_tokens(self, pixel_values: torch.FloatTensor, image_sizes: torch.LongTensor) -> torch.LongTensor:
  1128. """
  1129. Tokenizes images into discrete tokens with VQGAN module. Converts
  1130. obtained image tokens into BPE tokens and wraps with "boi" and "eoi"
  1131. special tokens.
  1132. Args:
  1133. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`):
  1134. The tensors corresponding to the input images.
  1135. image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
  1136. The sizes of the images in the batch, being (height, width) for each image.
  1137. """
  1138. vqmodel_outputs: Emu3VQVAEModelOutput = self.vqmodel.encode(pixel_values, image_sizes, return_dict=True)
  1139. bpe_tokens_list = [
  1140. self.vocabulary_mapping.convert_img2bpe(tokens).flatten() for tokens in vqmodel_outputs.image_tokens
  1141. ]
  1142. bpe_tokens = torch.cat(bpe_tokens_list)
  1143. return bpe_tokens
  1144. @can_return_tuple
  1145. @auto_docstring(
  1146. custom_intro="Tokenizes images into discrete tokens with VQGAN module and embeds them with text embeddings layer"
  1147. )
  1148. def get_image_features(
  1149. self, pixel_values: torch.FloatTensor, image_sizes: torch.LongTensor, **kwargs: Unpack[TransformersKwargs]
  1150. ) -> tuple | Emu3VQVAEModelOutput:
  1151. r"""
  1152. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)):
  1153. The tensors corresponding to the input images.
  1154. """
  1155. vqmodel_outputs: Emu3VQVAEModelOutput = self.vqmodel.encode(
  1156. pixel_values, image_sizes, return_dict=True, **kwargs
  1157. )
  1158. split_sizes = [
  1159. (height // self.vqmodel.vision_spatial_factor) * (width // self.vqmodel.vision_spatial_factor + 1)
  1160. for height, width in image_sizes
  1161. ]
  1162. bpe_tokens_list = [
  1163. self.vocabulary_mapping.convert_img2bpe(tokens).flatten() for tokens in vqmodel_outputs.image_tokens
  1164. ]
  1165. bpe_tokens = torch.cat(bpe_tokens_list)
  1166. image_embeddings = self.get_input_embeddings()(bpe_tokens)
  1167. image_features = torch.split(image_embeddings, split_sizes)
  1168. vqmodel_outputs.pooler_output = image_features
  1169. return vqmodel_outputs
  1170. @torch.no_grad()
  1171. def decode_image_tokens(self, image_tokens: torch.LongTensor, height: int, width: int):
  1172. """
  1173. Decodes generated image tokens from language model to continuous pixel values
  1174. with VQGAN module via upsampling.
  1175. Args:
  1176. image_tokens (`torch.LongTensor` of shape `(batch_size, num_of_tokens)`):
  1177. The tensors corresponding to the input images.
  1178. height (`int`):
  1179. Height of the generated image before upsampling.
  1180. width (`int`):
  1181. Width of the generated image before upsampling.
  1182. """
  1183. sequences = image_tokens[:, :-3].view(-1, height, width + 1)
  1184. image_tokens = self.vocabulary_mapping.convert_bpe2img(sequences)
  1185. image = self.vqmodel.decode(image_tokens)
  1186. return image
  1187. def get_placeholder_mask(
  1188. self, input_ids: torch.LongTensor, inputs_embeds: torch.FloatTensor, image_features: torch.FloatTensor
  1189. ):
  1190. """
  1191. Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
  1192. equal to the length of multimodal features. If the lengths are different, an error is raised.
  1193. """
  1194. if input_ids is None:
  1195. special_image_mask = inputs_embeds == self.get_input_embeddings()(
  1196. torch.tensor(self.vocabulary_mapping.image_token_id, dtype=torch.long, device=inputs_embeds.device)
  1197. )
  1198. special_image_mask = special_image_mask.all(-1)
  1199. else:
  1200. special_image_mask = input_ids == self.vocabulary_mapping.image_token_id
  1201. n_image_tokens = special_image_mask.sum()
  1202. n_image_features = image_features.shape[0] * image_features.shape[1]
  1203. special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
  1204. torch_compilable_check(
  1205. inputs_embeds[special_image_mask].numel() == image_features.numel(),
  1206. f"Image features and image tokens do not match, tokens: {n_image_tokens}, features: {n_image_features}",
  1207. )
  1208. return special_image_mask
  1209. @can_return_tuple
  1210. @auto_docstring
  1211. def forward(
  1212. self,
  1213. input_ids: torch.LongTensor | None = None,
  1214. pixel_values: torch.FloatTensor | None = None,
  1215. image_sizes: torch.Tensor | None = None,
  1216. attention_mask: torch.Tensor | None = None,
  1217. position_ids: torch.LongTensor | None = None,
  1218. past_key_values: Cache | None = None,
  1219. inputs_embeds: torch.FloatTensor | None = None,
  1220. use_cache: bool | None = None,
  1221. **kwargs: Unpack[TransformersKwargs],
  1222. ) -> tuple | CausalLMOutputWithPast:
  1223. r"""
  1224. image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
  1225. The sizes of the images in the batch, being (height, width) for each image. Image sizes can be obtained using
  1226. [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
  1227. [`Emu3ImageProcessor`] for processing images).
  1228. """
  1229. if (input_ids is None) ^ (inputs_embeds is not None):
  1230. raise ValueError(
  1231. "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
  1232. )
  1233. if inputs_embeds is None:
  1234. inputs_embeds = self.get_input_embeddings()(input_ids)
  1235. if pixel_values is not None:
  1236. image_features = self.get_image_features(pixel_values, image_sizes).pooler_output
  1237. image_features = torch.cat(image_features, dim=0)
  1238. special_image_mask = self.get_placeholder_mask(
  1239. input_ids, inputs_embeds=inputs_embeds, image_features=image_features
  1240. )
  1241. inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
  1242. # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
  1243. outputs = self.text_model(
  1244. attention_mask=attention_mask,
  1245. position_ids=position_ids,
  1246. past_key_values=past_key_values,
  1247. inputs_embeds=inputs_embeds,
  1248. use_cache=use_cache,
  1249. **kwargs,
  1250. )
  1251. return outputs
  1252. class Emu3ForConditionalGeneration(Emu3PreTrainedModel, GenerationMixin):
  1253. output_modalities = ("image", "text")
  1254. _tied_weights_keys = {"lm_head.weight": "model.text_model.embed_tokens.weight"}
  1255. def __init__(self, config):
  1256. super().__init__(config)
  1257. self.model = Emu3Model(config)
  1258. self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
  1259. self.post_init()
  1260. def get_input_embeddings(self):
  1261. return self.model.get_input_embeddings()
  1262. def set_input_embeddings(self, value):
  1263. self.model.set_input_embeddings(value)
  1264. def get_output_embeddings(self) -> nn.Module:
  1265. return self.lm_head
  1266. def decode_image_tokens(self, **kwargs):
  1267. return self.model.decode_image_tokens(**kwargs)
  1268. @can_return_tuple
  1269. @auto_docstring
  1270. def forward(
  1271. self,
  1272. input_ids: torch.LongTensor | None = None,
  1273. pixel_values: torch.FloatTensor | None = None,
  1274. image_sizes: torch.Tensor | None = None,
  1275. attention_mask: torch.Tensor | None = None,
  1276. position_ids: torch.LongTensor | None = None,
  1277. past_key_values: Cache | None = None,
  1278. inputs_embeds: torch.FloatTensor | None = None,
  1279. use_cache: bool | None = None,
  1280. labels: torch.LongTensor | None = None,
  1281. logits_to_keep: int | torch.Tensor = 0,
  1282. **kwargs: Unpack[TransformersKwargs],
  1283. ) -> tuple | CausalLMOutputWithPast:
  1284. r"""
  1285. image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`):
  1286. The sizes of the images in the batch, being (height, width) for each image. Image sizes can be obtained using
  1287. [`AutoImageProcessor`]. See [`Emu3ImageProcessor.__call__`] for details ([]`Emu3Processor`] uses
  1288. [`Emu3ImageProcessor`] for processing images).
  1289. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1290. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  1291. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  1292. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  1293. Example:
  1294. ```python
  1295. >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration
  1296. >>> import torch
  1297. >>> import httpx
  1298. >>> from io import BytesIO
  1299. >>> from PIL import Image
  1300. >>> model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", dtype=torch.bfloat16)
  1301. >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf")
  1302. >>> conversation = [
  1303. ... {
  1304. ... "role": "system",
  1305. ... "content": [
  1306. ... {"type": "text", "text": "You are a helpful assistant."},
  1307. ... ],
  1308. ... },
  1309. ... {
  1310. ... "role": "user",
  1311. ... "content": [
  1312. ... {"type": "image"},
  1313. ... {"type": "text", "text": "Please describe the image."},
  1314. ... ],
  1315. ... },
  1316. ... ]
  1317. >>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
  1318. >>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
  1319. >>> with httpx.stream("GET", url) as response:
  1320. ... image = Image.open(BytesIO(response.read()))
  1321. >>> inputs = processor(images=[image], text=[prompt], return_tensors="pt").to(model.device, torch.bfloat16)
  1322. >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False)
  1323. >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
  1324. ```"""
  1325. outputs = self.model(
  1326. input_ids=input_ids,
  1327. attention_mask=attention_mask,
  1328. position_ids=position_ids,
  1329. past_key_values=past_key_values,
  1330. inputs_embeds=inputs_embeds,
  1331. use_cache=use_cache,
  1332. **kwargs,
  1333. )
  1334. hidden_states = outputs[0]
  1335. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  1336. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1337. logits = self.lm_head(hidden_states[:, slice_indices, :])
  1338. loss = None
  1339. if labels is not None:
  1340. loss = self.loss_function(
  1341. logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
  1342. )
  1343. return CausalLMOutputWithPast(
  1344. loss=loss,
  1345. logits=logits,
  1346. past_key_values=outputs.past_key_values,
  1347. hidden_states=outputs.hidden_states,
  1348. attentions=outputs.attentions,
  1349. )
  1350. def prepare_inputs_for_generation(
  1351. self,
  1352. input_ids,
  1353. past_key_values=None,
  1354. attention_mask=None,
  1355. inputs_embeds=None,
  1356. position_ids=None,
  1357. use_cache=True,
  1358. pixel_values=None,
  1359. is_first_iteration=False,
  1360. **kwargs,
  1361. ):
  1362. # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
  1363. model_inputs = super().prepare_inputs_for_generation(
  1364. input_ids,
  1365. past_key_values=past_key_values,
  1366. attention_mask=attention_mask,
  1367. inputs_embeds=inputs_embeds,
  1368. position_ids=position_ids,
  1369. pixel_values=pixel_values,
  1370. use_cache=use_cache,
  1371. is_first_iteration=is_first_iteration,
  1372. **kwargs,
  1373. )
  1374. if not is_first_iteration and use_cache:
  1375. model_inputs["pixel_values"] = None
  1376. return model_inputs
  1377. __all__ = [
  1378. "Emu3ForConditionalGeneration",
  1379. "Emu3ForCausalLM",
  1380. "Emu3TextModel",
  1381. "Emu3PreTrainedModel",
  1382. "Emu3VQVAE",
  1383. "Emu3Model",
  1384. ]