text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
class Emu3TextKwargs(TextKwargs, total=False): return_for_image_generation: bool
3,462
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
class Emu3ImagesKwargs(ImagesKwargs, total=False): ratio: str image_area: int
3,463
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
class Emu3ProcessorKwargs(ProcessingKwargs, total=False): text_kwargs: Emu3TextKwargs images_kwargs: Emu3ImagesKwargs _defaults = { "text_kwargs": { "return_for_image_generation": False, }, "images_kwargs": { "ratio": "1:1", "image_area": 518400, }, }
3,464
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
class Emu3Processor(ProcessorMixin): r""" Constructs a Emu3 processor which wraps a Emu3 image processor and a GPT2 tokenizer into a single processor. [`Emu3Processor`] offers all the functionalities of [`Emu3ImageProcessor`] and [`GPT2TokenizerFast`]. See the [`~Emu3Processor.__call__`] and [`~Emu3Processor.decode`] for more information. Args: image_processor ([`Emu3ImageProcessor`]): The image processor is a required input. tokenizer ([`Emu3TokenizerFast`]): The tokenizer is a required input. chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages in a chat into a tokenizable string. """ attributes = ["image_processor", "tokenizer"] tokenizer_class = ("GPT2Tokenizer", "GPT2TokenizerFast") image_processor_class = "Emu3ImageProcessor"
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
def __init__( self, image_processor, tokenizer, chat_template=None, **kwargs, ): self.image_token = tokenizer.image_token # image_token as placeholder to be replaced by vq-vae tokens self.image_start_token = tokenizer.boi_token # "<|image start|>" fixed tokens for start and end of image self.image_end_token = tokenizer.eoi_token # "<|image end|>" self.fake_token_around_image = tokenizer.image_wrapper_token # "<|image token|>" every image starts with it self.eof_token = tokenizer.eof_token # "<|extra_201|>" self.bos_token = tokenizer.bos_token self.downsample_ratio = 8 super().__init__(image_processor, tokenizer, chat_template=chat_template)
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
def __call__( self, images: Optional[ImageInput] = None, text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None, audio=None, videos=None, **kwargs: Unpack[Emu3ProcessorKwargs], ) -> BatchFeature: """ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to Emu3TokenizerFast's [`~Emu3TokenizerFast.__call__`] if `text` is not `None` to encode the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the doctsring of the above two methods for more information.
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
Args: images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`): The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch tensor. Both channels-first and channels-last formats are supported. text (`str`, `List[str]`, `List[List[str]]`): The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set `is_split_into_words=True` (to lift the ambiguity with a batch of sequences). return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Acceptable values are:
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
- `'tf'`: Return TensorFlow `tf.constant` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects. - `'np'`: Return NumPy `np.ndarray` objects. - `'jax'`: Return JAX `jnp.ndarray` objects. Returns: [`BatchFeature`]: A [`BatchFeature`] with the following fields: - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not `None`). - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`. """ # check if images and text inputs are reversed for BC
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
if isinstance(text, str): text = [text] elif not isinstance(text, list) and not isinstance(text[0], str): raise TypeError("Invalid input text. Please provide a string, or a list of strings") output_kwargs = self._merge_kwargs( Emu3ProcessorKwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs, ) return_for_image_generation = output_kwargs["text_kwargs"].pop("return_for_image_generation", False) ratio = output_kwargs["images_kwargs"].pop("ratio", None) image_area = output_kwargs["images_kwargs"].pop("image_area", None) if return_for_image_generation and images is not None: raise ValueError("You should not provide `images` when `return_for_image_generation=True`") if not return_for_image_generation and text is None and images is None: raise ValueError("You must provide either text or images when `return_for_image_generation=False`")
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
image_features = {} image_start_tokens = f"{self.image_start_token}" image_end_tokens = f"{self.eof_token}{self.image_end_token}" # generate text from image + text input, so we add placeholders for image tokens if not return_for_image_generation and images is not None: image_features = self.image_processor(images, **output_kwargs["images_kwargs"]) image_sizes = iter(image_features.image_sizes) prompt_strings = [] for sample in text: while self.image_token in sample: image_size = next(image_sizes) height, width = image_size height = height // self.downsample_ratio width = width // self.downsample_ratio image_seq_length = height * (width + 1) # +1 for extra row when converting to BPE in modeling code
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
image_placeholder = f"{image_start_tokens}{height}*{width}{self.fake_token_around_image}{'<placeholder>' * image_seq_length}{image_end_tokens}" sample = sample.replace(self.image_token, image_placeholder, 1) sample = f"{self.bos_token}{sample}" # add BOS because PT tokenizer doesn't add it prompt_strings.append(sample) text = [sample.replace("<placeholder>", self.image_token) for sample in prompt_strings] # generate image from text input, so we add begin-of-image tokens from where image generation starts elif return_for_image_generation: height, width = self.calculate_generate_size(ratio, image_area, self.downsample_ratio) image_prompt = f"{image_start_tokens}{height}*{width}{self.fake_token_around_image}" text = [f"{self.bos_token}{sample}{image_prompt}" for sample in text] image_features["image_sizes"] = [[height, width]] * len(text)
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
# else just generate from text-only input, and we do no special treatment for text data = self.tokenizer(text, **output_kwargs["text_kwargs"]) data.update(**image_features) return BatchFeature(data=data, tensor_type=output_kwargs["common_kwargs"]["return_tensors"]) def calculate_generate_size(self, ratio, image_area, spatial_factor): width, height = map(int, ratio.split(":")) current_area = width * height target_ratio = (image_area / current_area) ** 0.5 token_height = int(round(height * target_ratio / spatial_factor)) token_width = int(round(width * target_ratio / spatial_factor)) return token_height, token_width def postprocess(self, images: ImageInput, **kwargs): return self.image_processor.postprocess(images, **kwargs)
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to Emu3TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs) def decode(self, *args, **kwargs): """ This method forwards all its arguments to Emu3TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs) @property def model_input_names(self): tokenizer_input_names = self.tokenizer.model_input_names image_processor_input_names = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
3,465
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/processing_emu3.py
class Emu3VQVAEConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Emu3VQVAE`]. It is used to instantiate an VQ-VAE model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a configuration to the VQ model presented in Emu3 paper.
3,466
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: codebook_size (`int`, *optional*, defaults to 32768): Codebook size of the VQ model. embed_dim (`int`, *optional*, defaults to 4): Dimension of the quantized vector in codebook. latent_channels (`int`, *optional*, defaults to 4): Dimension of the output channel of encoder and the input channel of decoder double_latent (`bool`, *optional*, defaults to `False`): Whether double the output dim of the encoder. in_channels (`int`, *optional*, defaults to 3): Input channel of encoder. out_channels (`int`, *optional*, defaults to 3): Output channel of decoder. temporal_downsample_factor (`int`, *optional*, defaults to 4): Temporal downsample factor.
3,466
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
base_channels (`int`, *optional*, defaults to 256): Basic channel number of the intermediate blocks. channel_multiplier (`List[int]`, *optional*, defaults to `[1, 2, 2, 4]`): Channel scaling factor of the intermediate blocks. num_res_blocks (`int`, *optional*, defaults to 2): Residual block number in each stage. attn_resolutions (`List[int]`, *optional*, defaults to `[3]`): Stage indices to apply attention. hidden_size (`int`, *optional*, defaults to 1024): Dimension of the hidden representations in the attention layer. num_attention_heads (`int`, *optional*, defaults to 1): Number of attention heads for each attention layer. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities.
3,466
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
```python >>> from transformers import Emu3VQVAE, Emu3VQVAEConfig >>> # Initializing a video VQ model of Emu3 configuration >>> configuration = Emu3VQVAEConfig() >>> # Initializing a model from the Emu3 VQ model style configuration >>> model = Emu3VQVAE(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "emu3_vqgan" base_config_key = "vq_config"
3,466
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
def __init__( self, codebook_size: int = 32768, embed_dim: int = 4, latent_channels: int = 4, double_latent: bool = False, in_channels: int = 3, out_channels: int = 3, temporal_downsample_factor: int = 4, base_channels: int = 256, channel_multiplier: List[int] = [1, 2, 2, 4], num_res_blocks: int = 2, attn_resolutions: List[int] = [3], hidden_size: int = 1024, num_attention_heads: int = 1, attention_dropout: float = 0.0, **kwargs, ): super().__init__(**kwargs)
3,466
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
self.codebook_size = codebook_size self.embed_dim = embed_dim self.latent_channels = latent_channels self.double_latent = double_latent self.in_channels = in_channels self.out_channels = out_channels self.temporal_downsample_factor = temporal_downsample_factor self.base_channels = base_channels self.channel_multiplier = channel_multiplier self.num_res_blocks = num_res_blocks self.attn_resolutions = attn_resolutions self.hidden_size = hidden_size self.num_attention_heads = num_attention_heads self.attention_dropout = attention_dropout
3,466
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
class Emu3TextConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Emu3TextModel`]. It is used to instantiate a emu3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [Emu3-community/Emu3-Chat-hf](https://huggingface.co/Emu3-community/Emu3-Chat-hf). Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
Args: vocab_size (`int`, *optional*, defaults to 184622): Vocabulary size of the Emu3 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Emu3Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 14336): Dimension of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer decoder. num_key_value_heads (`int`, *optional*, defaults to 8): This is the number of key_value heads that should be used to implement Grouped Query Attention. If
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `num_attention_heads`. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 9216): The maximum sequence length that this model might ever be used with. Emu supports up to 9216 tokens, rms_norm_eps (`float`, *optional*, defaults to 1e-05):
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. pad_token_id (`int`, *optional*, defaults to 151643): Padding token id. bos_token_id (`int`, *optional*, defaults to 151849): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 151850): End of stream token id. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie weight embeddings rope_theta (`float`, *optional*, defaults to 1000000.0): The base period of the RoPE embeddings. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value accordingly. Expected contents: `rope_type` (`str`): The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope', 'llama3'], with 'default' being the original RoPE implementation. `factor` (`float`, *optional*): Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In most scaling types, a `factor` of x will enable the model to handle sequences of length x * original maximum pre-trained length. `original_max_position_embeddings` (`int`, *optional*): Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during pretraining.
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
`attention_factor` (`float`, *optional*): Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention computation. If unspecified, it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value. `beta_fast` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear ramp function. If unspecified, it defaults to 32. `beta_slow` (`float`, *optional*): Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear ramp function. If unspecified, it defaults to 1. `short_factor` (`List[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to short contexts (<
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
`original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `long_factor` (`List[float]`, *optional*): Only used with 'longrope'. The scaling factor to be applied to long contexts (< `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden size divided by the number of attention heads divided by 2 `low_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE `high_freq_factor` (`float`, *optional*): Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE mlp_bias (`bool`, *optional*, defaults to `False`):
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers. attention_bias (`bool`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. attention_dropout (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
```python >>> from transformers import Emu3Model, Emu3Config >>> # Initializing a Emu3-community/Emu3-Chat-hf style configuration >>> configuration = Emu3Config() >>> # Initializing a model from the Emu3-community/Emu3-Chat-hf style configuration >>> model = Emu3Model(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "emu3_text_model" base_config_key = "text_config" keys_to_ignore_at_inference = ["past_key_values"]
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
def __init__( self, vocab_size: int = 184622, hidden_size: int = 4096, intermediate_size: int = 14336, num_hidden_layers: int = 32, num_attention_heads: int = 32, num_key_value_heads: Optional[int] = 8, hidden_act: str = "silu", max_position_embeddings: int = 9216, rms_norm_eps: float = 1e-5, use_cache: bool = True, pad_token_id: int = 151643, bos_token_id: int = 151849, eos_token_id: int = 151850, tie_word_embeddings: bool = False, rope_theta: float = 1000000.0, rope_scaling: Optional = None, mlp_bias=False, attention_bias=False, attention_dropout: float = 0.1, initializer_range: float = 0.02, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.mlp_bias = mlp_bias self.attention_bias = attention_bias self.initializer_range = initializer_range rope_config_validation(self)
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
self.attention_dropout = attention_dropout super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
3,467
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
class Emu3Config(PretrainedConfig): """ This is the configuration class to store the configuration of a [`Emu3Model`]. It is used to instantiate a emu3 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the [Emu3-community/Emu3-Chat-hf](https://huggingface.co/Emu3-community/Emu3-Chat-hf). Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
3,468
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
Args: vq_config (`Union[Dict, Emu3VQVAEConfig]`, *optional*): Emu3VQVAEConfig instance containing the configuration for the VQ-VAE model. text_config (`Union[Dict, Emu3TextConfig]``, *optional*): Emu3TextConfig instance containing the configuration for the language model. vocabulary_map (`dict`, *optional*): A dictionary containing the vocabulary map from the tokenizer. Used to obtain tokens from the image inputs. """ model_type = "emu3" keys_to_ignore_at_inference = ["past_key_values"] sub_configs = {"text_config": Emu3TextConfig, "vq_config": Emu3VQVAEConfig}
3,468
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
def __init__( self, vq_config: Union[Dict, Emu3VQVAEConfig] = None, text_config: Union[Dict, Emu3TextConfig] = None, vocabulary_map: Dict[int, int] = None, **kwargs, ): if vq_config is None: vq_config = Emu3VQVAEConfig() elif isinstance(vq_config, dict): vq_config = Emu3VQVAEConfig(**vq_config) if text_config is None: text_config = Emu3TextConfig() elif isinstance(text_config, dict): text_config = Emu3TextConfig(**text_config) self.vq_config = vq_config self.text_config = text_config self.vocabulary_map = vocabulary_map super().__init__(**kwargs)
3,468
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/configuration_emu3.py
class Emu3DecoderLayer(LlamaDecoderLayer): def __init__(self, config: Emu3Config, layer_idx: int): super().__init__(config, layer_idx) self.dropout = nn.Dropout(config.attention_dropout)
3,469
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, **kwargs, ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, query_sequence_length, key_sequence_length)` if default attention is used.
3,469
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence kwargs (`dict`, *optional*): Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code into the model """ residual = hidden_states
3,469
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
hidden_states = self.input_layernorm(hidden_states) # Self Attention hidden_states, self_attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) hidden_states = residual + self.dropout(hidden_states) # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + self.dropout(hidden_states) outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,) return outputs
3,469
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEVectorQuantizer(nn.Module): """ A module for vector quantization using learned embedding vectors. This module implements the quantization process similar to te one described in the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous input vectors into discrete codebook vectors, which are learned during training. Current implementation improves over previous ones by avoiding costly matrix multiplications and allowing for post-hoc remapping of indices. """ def __init__(self, config: Emu3VQVAEConfig): super().__init__() self.embedding = nn.Embedding(config.codebook_size, config.embed_dim) self.embedding.weight.data.uniform_(-1.0 / config.codebook_size, 1.0 / config.codebook_size)
3,470
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
def forward(self, hidden_state: torch.Tensor): batch_size, temporal, channels, height, width = hidden_state.shape hidden_state = hidden_state.permute(0, 1, 3, 4, 2).contiguous() hidden_state_flattened = hidden_state.view(-1, channels) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z hidden_state_sum = torch.sum(hidden_state_flattened**2, dim=1, keepdim=True) embedding_sum = torch.sum(self.embedding.weight**2, dim=1) # "bd,dn->bn", distances = 2 * torch.matmul(hidden_state_flattened, self.embedding.weight.transpose(0, 1)) distances = hidden_state_sum + embedding_sum - distances min_encoding_indices = torch.argmin(distances, dim=1) min_encoding_indices = min_encoding_indices.view(batch_size, temporal, height, width) return min_encoding_indices
3,470
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEEncoderConvDownsample(ChameleonVQVAEEncoderConvDownsample): pass
3,471
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEEncoderConvUpsample(nn.Module): def __init__(self, in_channels): super().__init__() self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1) def forward(self, hidden_states): hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest") hidden_states = self.conv(hidden_states) return hidden_states
3,472
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEConv3d(nn.Module): def __init__( self, in_channel: int, out_channel: int, kernel_size: Tuple[int], stride: Tuple[int], ): super().__init__() padding_sizes = [one_kernel - one_stride for one_kernel, one_stride in zip(kernel_size[1:], stride[1:])] self.padding = () for pad_size in padding_sizes[::-1]: self.padding += (pad_size // 2 + pad_size % 2, pad_size // 2) self.padding += (2, 0) self.conv = nn.Conv3d( in_channel, out_channel, kernel_size, stride=stride, ) def forward(self, hidden_states: torch.Tensor): hidden_states = F.pad(hidden_states, self.padding) hidden_states = self.conv(hidden_states) return hidden_states
3,473
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAESpatialNorm(nn.Module): def __init__( self, in_channels: int, out_channels: int, ): super().__init__() self.norm_layer = nn.GroupNorm( num_channels=out_channels, num_groups=32, eps=1e-6, affine=True, ) self.conv_y = nn.Conv2d( in_channels, out_channels, kernel_size=1, stride=1, padding=0, ) self.conv_b = nn.Conv2d( in_channels, out_channels, kernel_size=1, stride=1, padding=0, ) def forward(self, hidden_states: torch.Tensor, quant_states: torch.Tensor): quant_states = F.interpolate(quant_states, size=hidden_states.shape[-2:], mode="nearest") hidden_states = self.norm_layer(hidden_states) hidden_states = hidden_states * self.conv_y(quant_states) + self.conv_b(quant_states) return hidden_states
3,474
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAETemporalUpsample(nn.Module): def __init__( self, in_channel: int, out_channel: int, ): super().__init__() self.conv = Emu3VQVAEConv3d( in_channel, out_channel, kernel_size=(3, 3, 3), stride=(1, 1, 1), ) def forward(self, hidden_states: torch.Tensor): batch_size, channels, temporal, height, width = hidden_states.shape hidden_states = hidden_states.permute(0, 1, 3, 4, 2).contiguous().view(batch_size, -1, temporal) hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest") hidden_states = hidden_states.view(batch_size, channels, height, width, -1).permute(0, 1, 4, 2, 3).contiguous() hidden_states = self.conv(hidden_states) return hidden_states
3,475
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAETemporalDownsample(nn.Module): def __init__( self, in_channel: int, out_channel: int, ): super().__init__() self.conv = Emu3VQVAEConv3d( in_channel, out_channel, kernel_size=(4, 3, 3), stride=(2, 1, 1), ) def forward(self, hidden_states: torch.Tensor): hidden_states = self.conv(hidden_states) return hidden_states
3,476
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAETemporalResnetBlock(nn.Module): def __init__( self, in_channels, out_channels=None, ): super().__init__() self.in_channels = in_channels self.out_channels = in_channels if out_channels is None else out_channels self.norm1 = nn.BatchNorm3d(in_channels) self.conv1 = Emu3VQVAEConv3d( in_channels, out_channels, kernel_size=(3, 3, 3), stride=(1, 1, 1), ) self.norm2 = nn.BatchNorm3d(out_channels) self.conv2 = Emu3VQVAEConv3d( out_channels, out_channels, kernel_size=(3, 3, 3), stride=(1, 1, 1), ) if self.in_channels != self.out_channels: self.nin_shortcut = nn.Conv3d( in_channels, out_channels, kernel_size=1, stride=1, padding=0, )
3,477
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
def forward(self, hidden_states): residual = hidden_states hidden_states = self.norm1(hidden_states) hidden_states *= torch.sigmoid(hidden_states) hidden_states = self.conv1(hidden_states) hidden_states = self.norm2(hidden_states) hidden_states *= torch.sigmoid(hidden_states) hidden_states = self.conv2(hidden_states) if self.in_channels != self.out_channels: residual = self.nin_shortcut(residual) return residual + hidden_states
3,477
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEResnetBlock(nn.Module): def __init__( self, in_channels: int, out_channels: Optional[int] = None, quant_channels: Optional[int] = None, ): super().__init__() self.in_channels = in_channels out_channels = in_channels if out_channels is None else out_channels self.out_channels = out_channels self.quant_channels = quant_channels if quant_channels is None: self.norm1 = nn.GroupNorm(num_channels=in_channels, num_groups=32, eps=1e-6, affine=True) self.norm2 = nn.GroupNorm(num_channels=out_channels, num_groups=32, eps=1e-6, affine=True) else: self.norm1 = Emu3VQVAESpatialNorm(quant_channels, in_channels) self.norm2 = Emu3VQVAESpatialNorm(quant_channels, out_channels) self.conv1 = nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=1, padding=1, )
3,478
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
self.conv2 = nn.Conv2d( out_channels, out_channels, kernel_size=3, stride=1, padding=1, ) if self.in_channels != self.out_channels: self.nin_shortcut = nn.Conv2d( in_channels, out_channels, kernel_size=1, stride=1, padding=0, ) def forward(self, hidden_states: torch.Tensor, quant_channels: Optional[torch.Tensor] = None): norm_args = () if self.quant_channels is None else (quant_channels,) residual = hidden_states hidden_states = self.norm1(hidden_states, *norm_args) hidden_states *= torch.sigmoid(hidden_states) hidden_states = self.conv1(hidden_states) hidden_states = self.norm2(hidden_states, *norm_args) hidden_states *= torch.sigmoid(hidden_states) hidden_states = self.conv2(hidden_states)
3,478
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
if self.in_channels != self.out_channels: residual = self.nin_shortcut(residual) return residual + hidden_states
3,478
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEAttentionBlock(SiglipAttention): pass
3,479
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEGroupNorm(nn.GroupNorm): """ Same as the torch GroupNorm with the only difference that this ones accepts an optional kwarg `quant_states` which is not used. This class makes it easier to use SpatialNorm or GroupNorm without conditionals """ def __init__(self, **kwargs): super().__init__(**kwargs) def forward(self, input, quant_states=None): return F.group_norm(input, self.num_groups, self.weight, self.bias, self.eps)
3,480
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEMiddleBlock(nn.Module): def __init__(self, config, in_channels, quant_channels=None): super().__init__() self.block_1 = Emu3VQVAEResnetBlock( in_channels=in_channels, out_channels=in_channels, quant_channels=quant_channels, ) self.attn_1 = Emu3VQVAEAttentionBlock(config) if quant_channels is None: self.attn_norm = Emu3VQVAEGroupNorm(num_channels=in_channels, num_groups=32, eps=1e-6, affine=True) else: self.attn_norm = Emu3VQVAESpatialNorm(quant_channels, in_channels) self.block_2 = Emu3VQVAEResnetBlock( in_channels=in_channels, out_channels=in_channels, quant_channels=quant_channels, )
3,481
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
def forward(self, hidden_states: torch.FloatTensor, quant_states: torch.FloatTensor = None): hidden_states = self.block_1(hidden_states, quant_states) residual = hidden_states hidden_states = self.attn_norm(hidden_states, quant_states) batch_size, channels, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2) hidden_states = self.attn_1(hidden_states)[0] hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2) hidden_states = residual + hidden_states hidden_states = self.block_2(hidden_states, quant_states) return hidden_states
3,481
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEDownBlock(nn.Module): def __init__(self, config): super().__init__() self.num_resolutions = len(config.channel_multiplier) self.num_res_blocks = config.num_res_blocks base_channels = config.base_channels channel_multiplier = config.channel_multiplier
3,482
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
in_channel_multiplier = (1,) + tuple(channel_multiplier) self.in_channel_multiplier = in_channel_multiplier self.down = nn.ModuleList() for i_level in range(self.num_resolutions): block = nn.ModuleList() attn = nn.ModuleList() attn_norms = nn.ModuleList() block_in = base_channels * in_channel_multiplier[i_level] block_out = base_channels * channel_multiplier[i_level] for i_block in range(self.num_res_blocks): block.append( Emu3VQVAEResnetBlock( in_channels=block_in, out_channels=block_out, ) ) block_in = block_out if config.attn_resolutions is not None and i_level in config.attn_resolutions: attn.append(Emu3VQVAEAttentionBlock(config))
3,482
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
attn_norms.append(nn.GroupNorm(num_channels=block_in, num_groups=32, eps=1e-6, affine=True))
3,482
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
down = nn.Module() down.block = block down.attn = attn down.attn_norms = attn_norms if i_level != self.num_resolutions - 1: down.downsample = Emu3VQVAEEncoderConvDownsample(block_in) self.down.append(down) def forward(self, hidden_states: torch.FloatTensor): for i_level, blocks in enumerate(self.down): for i_block in range(self.num_res_blocks): hidden_states = blocks.block[i_block](hidden_states) if len(blocks.attn) > 0: residual = hidden_states hidden_states = blocks.attn_norms[i_block](hidden_states) batch_size, channels, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2) hidden_states = blocks.attn[i_block](hidden_states)[0]
3,482
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2) hidden_states = residual + hidden_states if i_level != self.num_resolutions - 1: hidden_states = blocks.downsample(hidden_states) return hidden_states
3,482
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEUpBlock(nn.Module): def __init__(self, config): super().__init__() self.num_resolutions = len(config.channel_multiplier) self.num_res_blocks = config.num_res_blocks quant_channels = config.embed_dim block_in = config.base_channels * config.channel_multiplier[-1]
3,483
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
self.up = nn.ModuleList() for i_level in reversed(range(self.num_resolutions)): block = nn.ModuleList() attn = nn.ModuleList() attn_norms = nn.ModuleList() block_out = config.base_channels * config.channel_multiplier[i_level] for i_block in range(self.num_res_blocks + 1): block.append( Emu3VQVAEResnetBlock( in_channels=block_in, out_channels=block_out, quant_channels=quant_channels, ) ) block_in = block_out if i_level in config.attn_resolutions: attn.append(Emu3VQVAEAttentionBlock(config)) attn_norms.append(Emu3VQVAESpatialNorm(quant_channels, block_in))
3,483
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
up = nn.Module() up.block = block up.attn = attn up.attn_norms = attn_norms if i_level != 0: up.upsample = Emu3VQVAEEncoderConvUpsample(block_in) self.up.insert(0, up) def forward(self, hidden_states: torch.FloatTensor, quant_states: torch.FloatTensor): for i_level, blocks in enumerate(self.up[::-1]): for i_block in range(self.num_res_blocks + 1): hidden_states = blocks.block[i_block](hidden_states, quant_states) if len(blocks.attn) > 0: residual = hidden_states hidden_states = blocks.attn_norms[i_block](hidden_states, quant_states) batch_size, channels, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channels, height * width).transpose(1, 2) hidden_states = blocks.attn[i_block](hidden_states)[0]
3,483
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
hidden_states = hidden_states.reshape(batch_size, height, width, channels).permute(0, 3, 1, 2) hidden_states = residual + hidden_states if i_level != len(self.up) - 1: hidden_states = blocks.upsample(hidden_states) return hidden_states
3,483
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEEncoder(nn.Module): def __init__(self, config): super().__init__() base_channels = config.base_channels in_channels = config.in_channels double_latent = config.double_latent latent_channels = config.latent_channels channel_multiplier = config.channel_multiplier out_channels = 2 * latent_channels if double_latent else latent_channels block_in = base_channels * channel_multiplier[-1] self.conv_in = torch.nn.Conv2d(in_channels, base_channels, kernel_size=3, stride=1, padding=1) self.down_block = Emu3VQVAEDownBlock(config) self.middle_block = Emu3VQVAEMiddleBlock(config, block_in) self.norm_out = torch.nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True) self.conv_out = torch.nn.Conv2d( block_in, out_channels, kernel_size=3, stride=1, padding=1, )
3,484
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
temporal_down_blocks = int(math.log2(config.temporal_downsample_factor)) self.time_conv = nn.ModuleList() self.time_res_stack = nn.ModuleList() for i in range(temporal_down_blocks): conv = Emu3VQVAETemporalDownsample(out_channels, out_channels) self.time_conv.append(conv) for _ in range(config.num_res_blocks): time_res_conv = Emu3VQVAETemporalResnetBlock( in_channels=out_channels, out_channels=out_channels, ) self.time_res_stack.append(time_res_conv) def forward(self, pixel_values: torch.LongTensor): temporal_dim = pixel_values.shape[1] pixel_values = pixel_values.reshape(-1, *pixel_values.shape[2:]) # downsampling & middle hidden_states = self.conv_in(pixel_values) hidden_states = self.down_block(hidden_states) hidden_states = self.middle_block(hidden_states)
3,484
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
# end hidden_states = self.norm_out(hidden_states) hidden_states *= torch.sigmoid(hidden_states) hidden_states = self.conv_out(hidden_states) hidden_states = hidden_states.reshape(-1, temporal_dim, *hidden_states.shape[1:]) hidden_states = hidden_states.permute(0, 2, 1, 3, 4) # temporal convs for conv in self.time_conv: hidden_states = conv(hidden_states) hidden_states *= torch.sigmoid(hidden_states) for layer in self.time_res_stack: hidden_states = layer(hidden_states) hidden_states = hidden_states.permute(0, 2, 1, 3, 4) return hidden_states
3,484
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAEDecoder(nn.Module): def __init__(self, config: Emu3VQVAEConfig): super().__init__() quant_channels = config.embed_dim block_in = config.base_channels * config.channel_multiplier[-1] self.time_res_stack = nn.ModuleList() for _ in range(config.num_res_blocks): time_res_conv = Emu3VQVAETemporalResnetBlock( in_channels=config.latent_channels, out_channels=config.latent_channels ) self.time_res_stack.append(time_res_conv) temp_upsample_block_num = int(math.log2(config.temporal_downsample_factor)) self.time_conv = nn.ModuleList() for i in range(temp_upsample_block_num): conv = Emu3VQVAETemporalUpsample(config.latent_channels, config.latent_channels) self.time_conv.append(conv) self.conv_in = nn.Conv2d( config.latent_channels, block_in, kernel_size=3, stride=1, padding=1, )
3,485
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
self.middle_block = Emu3VQVAEMiddleBlock(config, block_in, quant_channels=quant_channels) self.up_block = Emu3VQVAEUpBlock(config) block_in = config.base_channels * config.channel_multiplier[0] self.norm_out = Emu3VQVAESpatialNorm(quant_channels, block_in) self.conv_out = nn.Conv2d( block_in, config.out_channels, kernel_size=3, stride=1, padding=1, ) def forward(self, hidden_states: torch.Tensor, quant_states: torch.Tensor): hidden_quant_states = torch.cat((hidden_states, quant_states), dim=0) hidden_quant_states = hidden_quant_states.permute(0, 2, 1, 3, 4) # temporal convs for layer in self.time_res_stack: hidden_quant_states = layer(hidden_quant_states) for layer in self.time_conv: hidden_quant_states = layer(hidden_quant_states) hidden_quant_states *= torch.sigmoid(hidden_quant_states)
3,485
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
hidden_quant_states = hidden_quant_states.permute(0, 2, 1, 3, 4) hidden_states, quant_states = torch.chunk(hidden_quant_states, 2, dim=0) hidden_states = hidden_states.reshape(-1, *hidden_states.shape[2:]) quant_states = quant_states.reshape(-1, *quant_states.shape[2:]) hidden_states = self.conv_in(hidden_states) # middle & upsampling hidden_states = self.middle_block(hidden_states, quant_states) hidden_states = self.up_block(hidden_states, quant_states) hidden_states = self.norm_out(hidden_states, quant_states) hidden_states *= torch.sigmoid(hidden_states) hidden_states = self.conv_out(hidden_states) return hidden_states
3,485
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3VQVAE(PreTrainedModel): config_class = Emu3VQVAEConfig base_model_prefix = "emuvideovq" main_input_name = "pixel_values" _no_split_modules = [ "Emu3VQVAETemporalResnetBlock", "Emu3VQVAEAttentionBlock", "Emu3VQVAEResnetBlock", "Emu3VQVAEVectorQuantizer", ]
3,486
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
def _init_weights(self, module): if isinstance(module, (nn.Conv2d, nn.Conv3d)): nn.init.kaiming_normal_(module.weight, mode="fan_out", nonlinearity="relu") elif isinstance(module, nn.Linear): nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5)) if module.bias is not None: fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight) bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0 nn.init.uniform_(module.bias, -bound, bound) elif isinstance(module, (nn.BatchNorm2d, nn.BatchNorm3d, nn.GroupNorm)): nn.init.constant_(module.weight, 1) nn.init.constant_(module.bias, 0) def __init__(self, config: Emu3VQVAEConfig): super().__init__(config) self.config = config
3,486
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
self.encoder = Emu3VQVAEEncoder(config) self.decoder = Emu3VQVAEDecoder(config) self.quantize = Emu3VQVAEVectorQuantizer(config) self.vision_spatial_factor = 2 ** (len(config.channel_multiplier) - 1) self.quant_conv = Emu3VQVAEConv3d( config.latent_channels, config.embed_dim, kernel_size=(3, 1, 1), stride=(1, 1, 1) ) self.post_quant_conv = Emu3VQVAEConv3d( config.embed_dim, config.latent_channels, kernel_size=(3, 1, 1), stride=(1, 1, 1) ) self.spatial_scale_factor = 2 ** (len(config.channel_multiplier) - 1) self.eval() # Emu3's VQ model is frozen self.post_init()
3,486
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
def encode(self, pixel_values: torch.Tensor, image_sizes: torch.Tensor): is_image = pixel_values.ndim == 4 if is_image: temporal = self.config.temporal_downsample_factor batch_size, channels, height, width = pixel_values.shape pixel_values = pixel_values.unsqueeze(1).repeat(1, temporal, 1, 1, 1) else: batch_size, temporal, channels, height, width = pixel_values.shape hidden_states = self.encoder(pixel_values) # b t c h w -> b c t h w hidden_states = hidden_states.permute(0, 2, 1, 3, 4) hidden_states = self.quant_conv(hidden_states) # b c t h w -> b t c h w hidden_states = hidden_states.permute(0, 2, 1, 3, 4) codes = self.quantize(hidden_states) image_tokens = codes.squeeze(1) if is_image else codes
3,486
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
image_tokens = [ single_image[: int(size[0] / self.vision_spatial_factor), : int(size[1] / self.vision_spatial_factor)] for single_image, size in zip(image_tokens, image_sizes) ] return image_tokens def decode(self, hidden_states: torch.Tensor): is_image = hidden_states.ndim == 3 if is_image: hidden_states = hidden_states.unsqueeze(1) batch_size, temporal, height, width = hidden_states.shape quant = self.quantize.embedding(hidden_states.flatten()) channels = quant.shape[-1] quant = quant.view(batch_size, temporal, height, width, channels).permute(0, 4, 1, 2, 3).contiguous() post_quant = self.post_quant_conv(quant) quant = quant.permute(0, 2, 1, 3, 4) post_quant = post_quant.permute(0, 2, 1, 3, 4)
3,486
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
video = self.decoder(post_quant, quant) video = video.reshape( batch_size, temporal * self.config.temporal_downsample_factor, self.config.out_channels, height * self.spatial_scale_factor, width * self.spatial_scale_factor, ) return video[:, 0] if is_image else video
3,486
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3ImageVocabularyMapping: """ A class for mapping discrete image tokens from VQGAN to BPE tokens. """ def __init__(self, vocab_map): self.vocab_map = vocab_map self.eol_token_id = vocab_map.get("<|extra_200|>") self.image_token_id = vocab_map.get("<image>") @cached_property def image_tokens(self): return sorted([val for name, val in self.vocab_map.items() if name.startswith("<|visual token")]) @cached_property def image_tokens_str(self): return sorted([name for name, val in self.vocab_map.items() if name.startswith("<|visual token")]) @cached_property def img2bpe(self): return {int(token[-8:-2]): self.vocab_map[token] for token in self.image_tokens_str} @cached_property def bpe2img(self): return {v: k for k, v in self.img2bpe.items()}
3,487
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
@cached_property def bpe2img_mapping_tensor(self): mapping = torch.zeros(max(self.bpe2img.keys()) + 1, dtype=torch.int) for k, v in self.bpe2img.items(): mapping[k] = v return mapping @cached_property def img2bpe_mapping_tensor(self): mapping = torch.zeros(max(self.img2bpe.keys()) + 1, dtype=torch.int) for k, v in self.img2bpe.items(): mapping[k] = v return mapping def convert_img2bpe(self, img_batch: List[torch.Tensor]) -> torch.Tensor: device = img_batch.device eol_row = torch.ones((img_batch.shape[0], 1), dtype=torch.int) * self.eol_token_id img_tokens = self.img2bpe_mapping_tensor[img_batch.to("cpu")] img_tokens = torch.cat([img_tokens, eol_row], dim=-1) return img_tokens.to(device)
3,487
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
def convert_bpe2img(self, img_batch: torch.Tensor) -> torch.Tensor: device = img_batch.device img_batch = img_batch[..., :-1] # remove last row of EOL tokens img_tokens = self.bpe2img_mapping_tensor[img_batch.to("cpu")] return img_tokens.to(device)
3,487
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3PreTrainedModel(ChameleonPreTrainedModel, Emu3VQVAE): _no_split_modules = [ "Emu3DecoderLayer", ] _supports_flex_attn = True def _init_weights(self, module): std = self.config.get_text_config().initializer_range if isinstance(module, Emu3VQVAE): module.apply(module._init_weights) elif isinstance(module, (nn.Linear, nn.Conv2d)): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_()
3,488
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3TextModel(LlamaModel, Emu3PreTrainedModel): def __init__(self, config: Emu3Config): super().__init__(config) self.layers = nn.ModuleList( [Emu3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] )
3,489
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3ForCausalLM(LlamaForCausalLM, Emu3PreTrainedModel, GenerationMixin): config_class = Emu3TextConfig def __init__(self, config): super().__init__(config) self.model = Emu3TextModel(config)
3,490
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
@add_start_docstrings_to_model_forward(EMU3_TEXT_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class="Emu3TextConfig") def forward(**super_kwargs): r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. num_logits_to_keep (`int`, *optional*): Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
3,490
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
3,490
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
Returns: Example: ```python >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration >>> import torch >>> import requests >>> from PIL import Image >>> model = Emu3ForCausalLM.from_pretrained("BAAI/Emu3-Chat-hf", torch_dtype=torch.bfloat16) >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf") >>> inputs = processor(text=["Can you write me a poem about winter."], return_tensors="pt").to(model.device) >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False) >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0] ```""" super().forward()
3,490
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3ForConditionalGeneration(Emu3PreTrainedModel, GenerationMixin): _tied_weights_keys = ["text_model.lm_head.weight"] def __init__(self, config): super().__init__(config) self.text_model = Emu3ForCausalLM._from_config(config.text_config) self.vqmodel = Emu3VQVAE(config.vq_config) self.vocabulary_mapping = Emu3ImageVocabularyMapping(config.vocabulary_map) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.text_model.get_input_embeddings() def set_input_embeddings(self, value): self.text_model.set_input_embeddings(value) def get_image_tokens(self, pixel_values: torch.FloatTensor, image_sizes: torch.LongTensor): """ Tokenizes images into discrete tokens with VQGAN module. Converts obtained image tokens into BPE tokens and wraps with "boi" and "eoi" special tokens.
3,491
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input images. image_sizes (`torch.LongTensor` of shape `(batch_size, 2)`): The sizes of the images in the batch, being (height, width) for each image. """ image_tokens_list = self.vqmodel.encode(pixel_values, image_sizes) bpe_tokens_list = [self.vocabulary_mapping.convert_img2bpe(tokens).flatten() for tokens in image_tokens_list] bpe_tokens = torch.cat(bpe_tokens_list) return bpe_tokens @torch.no_grad def decode_image_tokens(self, image_tokens: torch.LongTensor, height: int, width: int): """ Decodes generated image tokens from language model to continuous pixel values with VQGAN module via upsampling.
3,491
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
Args: image_tokens (`torch.LongTensor` of shape `(batch_size, num_of_tokens)`): The tensors corresponding to the input images. height (`int`): Height of the generated image before upsampling. width (`int`): Width of the generated image before upsampling. """ sequences = image_tokens[:, :-3].view(-1, height, width + 1) image_tokens = self.vocabulary_mapping.convert_bpe2img(sequences) image = self.vqmodel.decode(image_tokens) return image
3,491
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
@add_start_docstrings_to_model_forward(EMU3_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids: torch.LongTensor = None, pixel_values: torch.FloatTensor = None, image_sizes: torch.Tensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, labels: Optional[torch.LongTensor] = None, num_logits_to_keep: int = 0, ) -> Union[Tuple, CausalLMOutputWithPast]: r""" Args:
3,491
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. num_logits_to_keep (`int`, *optional*): Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
3,491
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
Returns: Example: ```python >>> from transformers import Emu3Processor, Emu3ForConditionalGeneration >>> import torch >>> import requests >>> from PIL import Image >>> model = Emu3ForConditionalGeneration.from_pretrained("BAAI/Emu3-Chat-hf", torch_dtype=torch.bfloat16) >>> processor = Emu3Processor.from_pretrained("BAAI/Emu3-Chat-hf") >>> conversation = [ ... { ... "role": "system", ... "content": [ ... {"type": "text", "text": "You are a helpful assistant."}, ... ], ... }, ... { ... "role": "user", ... "content": [ ... {"type": "image"}, ... {"type": "text", "text": "Please describe the image."}, ... ], ... }, ... ]
3,491
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
>>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True) >>> image = Image.open(requests.get("https://www.ilankelman.org/stopsigns/australia.jpg", stream=True).raw) >>> inputs = processor(images=[image], text=[prompt], return_tensors="pt").to(model.device, torch.bfloat16) >>> generated_ids = model.generate(**inputs, max_new_tokens=100, do_sample=False) >>> processor.batch_decode(generated_ids, skip_special_tokens=True)[0] ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
3,491
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one" ) if pixel_values is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one" ) if pixel_values is not None: image_tokens = self.get_image_tokens(pixel_values, image_sizes) special_image_mask = input_ids == self.vocabulary_mapping.image_token_id image_tokens = image_tokens.to(input_ids.device, input_ids.dtype) input_ids = input_ids.masked_scatter(special_image_mask, image_tokens)
3,491
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.text_model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, num_logits_to_keep=num_logits_to_keep, ) return outputs
3,491
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modular_emu3.py
class Emu3RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Emu3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
3,492
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modeling_emu3.py
class Emu3MLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias) self.act_fn = ACT2FN[config.hidden_act] def forward(self, x): down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return down_proj
3,493
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modeling_emu3.py
class Emu3Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: Emu3Config, layer_idx: int): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads self.scaling = self.head_dim**-0.5 self.attention_dropout = config.attention_dropout self.is_causal = True
3,494
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modeling_emu3.py
self.q_proj = nn.Linear( config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias ) self.k_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.v_proj = nn.Linear( config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias ) self.o_proj = nn.Linear( config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias )
3,494
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modeling_emu3.py
def forward( self, hidden_states: torch.Tensor, position_embeddings: Tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_value: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2) key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2) value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
3,494
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modeling_emu3.py
if past_key_value is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False): logger.warning_once( "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to " 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' ) else: attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
3,494
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/modeling_emu3.py