text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
num_tiles_height, num_tiles_width = aspect_ratio
image = split_to_tiles(image, num_tiles_height, num_tiles_width)
sample_images.append(image)
sample_aspect_ratios.append((num_tiles_height, num_tiles_width))
batch_images.append(sample_images)
batc... | 3,350 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/image_processing_mllama.py |
# images (np.ndarray) with shape (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width)
# aspect_ratio_ids (np.ndarray) with shape (batch_size, max_num_images) - aspect ratio ids for each image, padded to max_num_images with 0
# num_tiles (List[List[int]]) with (batch_size, num... | 3,350 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/image_processing_mllama.py |
def pad(
self,
image: np.ndarray,
size: Dict[str, int],
aspect_ratio: Tuple[int, int],
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> np.ndarray:
"""
Pad an image to th... | 3,350 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/image_processing_mllama.py |
Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Size of the output image.
aspect_ratio (`Tuple[int, int]`):
The aspect ratio of the image.
data_format (`str` or `ChannelDimension`, *optional*):
... | 3,350 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/image_processing_mllama.py |
image_height, image_width = get_image_size(image, channel_dim=input_data_format)
num_tiles_height, num_tiles_width = aspect_ratio
padded_height = num_tiles_height * size["height"]
padded_width = num_tiles_width * size["width"]
pad_size = ((0, padded_height - image_height), (0, padded_wid... | 3,350 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/image_processing_mllama.py |
def resize(
self,
image: np.ndarray,
size: Dict[str, int],
max_image_tiles: int,
resample: PILImageResampling = PILImageResampling.BILINEAR,
data_format: Optional[Union[str, ChannelDimension]] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = Non... | 3,350 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/image_processing_mllama.py |
Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Size of the output image.
max_image_tiles (`int`):
The maximum number of tiles to split the image into.
resample (`PILImageResampling`, *optional*, defaul... | 3,350 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/image_processing_mllama.py |
image_height, image_width = get_image_size(image, channel_dim=input_data_format)
tile_size = size["height"]
canvas_height, canvas_width = get_optimal_tiled_canvas(
image_height=image_height,
image_width=image_width,
max_image_tiles=max_image_tiles,
tile_s... | 3,350 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/image_processing_mllama.py |
class MllamaImagesKwargs(ImagesKwargs, total=False):
max_image_tiles: Optional[int] | 3,351 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
class MllamaProcessorKwargs(ProcessingKwargs, total=False):
images_kwargs: MllamaImagesKwargs
_defaults = {
"image_kwargs": {
"max_image_tiles": 4,
},
} | 3,352 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
class MllamaProcessor(ProcessorMixin):
r"""
Constructs a Mllama processor which wraps [`MllamaImageProcessor`] and
[`PretrainedTokenizerFast`] into a single processor that inherits both the image processor and
tokenizer functionalities. See the [`~MllamaProcessor.__call__`] and [`~OwlViTProcessor.decode... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
Args:
image_processor ([`MllamaImageProcessor`]):
The image processor is a required input.
tokenizer ([`PreTrainedTokenizer`, `PreTrainedTokenizerFast`]):
The tokenizer is a required input.
"""
attributes = ["image_processor", "tokenizer"]
image_processor_class = "M... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
self.python_token = "<|python_tag|>"
self.python_token_id = tokenizer.convert_tokens_to_ids(self.python_token)
self.bos_token = tokenizer.bos_token
self.chat_template = tokenizer.chat_template
super().__init__(image_processor, tokenizer) | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
def __call__(
self,
images: Optional[ImageInput] = None,
text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None,
audio=None,
videos=None,
**kwargs: Unpack[MllamaProcessorKwargs],
) -> BatchFeature:
"""
Main... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.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 ... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
- `'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: | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
- **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 `t... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
text_kwargs = output_kwargs["text_kwargs"]
images_kwargs = output_kwargs["images_kwargs"]
common_kwargs = output_kwargs["common_kwargs"]
data = {}
if text is not None:
if isinstance(text, str):
text = [text]
elif not (isinstance(text, (list, tuple... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
n_images_in_images = [0]
if images is not None:
images = make_list_of_images(images)
n_images_in_images = [len(sample) for sample in images]
if text is not None:
if any(batch_img == 0 for batch_img in n_images_in_text) and not all(
batch_img == 0 for ... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
if images is not None:
image_features = self.image_processor(images, **images_kwargs)
num_tiles = image_features.pop("num_tiles")
data.update(image_features)
# Create cross attention mask
if images is not None and text is not None:
cross_attention_token_m... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
return batch_feature
def batch_decode(self, *args, **kwargs):
"""
This method forwards all its arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
refer to the docstring of this method for more information.
"""
return self.tokenizer.batch_dec... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
Args:
generated_outputs (`torch.Tensor` or `np.ndarray`):
The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
or `(sequence_length,)`.
Returns:
`List[str]`: The decoded text.
... | 3,353 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/processing_mllama.py |
class MllamaVisionConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MllamaVisionModel`]. It is used to instantiate an
Mllama vision model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults ... | 3,354 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
Args:
hidden_size (`int`, *optional*, defaults to 1280):
Dimensionality of the encoder layers and the pooler layer.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"... | 3,354 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
intermediate_size (`int`, *optional*, defaults to 5120):
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
vision_output_dim (`int`, *optional*, defaults to 7680):
Dimensionality of the vision model output. Includes output of transformer
... | 3,354 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
Indices of intermediate layers of transformer encoder from which to extract and output features.
These output features are concatenated with final hidden state of transformer encoder.
supported_aspect_ratios (`List[List[int]]`, *optional*):
List of supported aspect ratios for image split... | 3,354 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
Example:
```python
>>> from transformers import MllamaVisionConfig, MllamaVisionModel
>>> # Initializing a Llama config
>>> config = MllamaVisionConfig()
>>> # Initializing a vision model from the mllama-11b style configuration
>>> model = MllamaVisionModel(config)
>>> # Accessing the mo... | 3,354 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
def __init__(
self,
hidden_size: int = 1280,
hidden_act: str = "gelu",
num_hidden_layers: int = 32,
num_global_layers: int = 8,
num_attention_heads: int = 16,
num_channels: int = 3,
intermediate_size: int = 5120,
vision_output_dim: int = 7680,
... | 3,354 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
if intermediate_layers_indices is None:
intermediate_layers_indices = [3, 7, 15, 23, 30]
self.hidden_size = hidden_size
self.hidden_act = hidden_act
self.num_hidden_layers = num_hidden_layers
self.num_channels = num_channels
self.intermediate_size = intermediate_size... | 3,354 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
class MllamaTextConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MllamaTextModel`]. It is used to instantiate an
Mllama text model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will y... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
Args:
vocab_size (`int`, *optional*, defaults to 128256):
Vocabulary size of the Mllama text model. Defines the maximum number of different tokens that can be represented
by the `inputs_ids` passed when calling [`MllamaTextModel`].
hidden_size (`int`, *optional*, defaults to 4096... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
This is the number of key_value heads that should be used to implement Grouped Query Attention. If not
specified, will default to `num_attention_heads`.
intermediate_size (`int`, *optional*, defaults to 14336):
Dimensionality of the "intermediate" (often named feed-forward) layer in the ... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
'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 ... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
`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... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.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
`low_freq_factor` (`float`, *optional*):
Only used with 'llama3'. Scaling factor applied to low frequency c... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether to tie weight embeddings
cross_attention_layers (`List[int]`, *optional*):
... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
Example:
```python
>>> from transformers import MllamaTextModel, MllamaTextConfig
>>> # Initializing a Mllama text config
>>> config = MllamaTextConfig()
>>> # Initializing a model from the Mllama text configuration
>>> model = MllamaTextModel(config)
>>> # Accessing the model configurat... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
def __init__(
self,
vocab_size: int = 128256,
hidden_size: int = 4096,
hidden_act: str = "silu",
num_hidden_layers: int = 40,
num_attention_heads: int = 32,
num_key_value_heads: int = 8,
intermediate_size: int = 14_336,
rope_theta: float = 500_000,... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
self.vocab_size = vocab_size
self.num_hidden_layers = num_hidden_layers
self.cross_attention_layers = cross_attention_layers
self.hidden_size = hidden_size
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.initializer_range... | 3,355 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
class MllamaConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`MllamaForConditionalGeneration`]. It is used to instantiate an
Mllama model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults ... | 3,356 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
Args:
vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `MllamaVisionConfig`):
The config object or dictionary of the vision backbone.
text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `MllamaTextConfig`):
The config object or dictionary of the text ... | 3,356 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
>>> # Initializing a model from the mllama-11b style configuration
>>> model = MllamaForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "mllama"
sub_configs = {"text_config": MllamaTextConfig, "vision_config": Ml... | 3,356 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
if text_config is None:
self.text_config = MllamaTextConfig()
logger.info("text_config is None, using default mllama text config")
elif isinstance(text_config, dict):
self.text_config = MllamaTextConfig(**text_config)
elif isinstance(text_config, MllamaTextConfig):
... | 3,356 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/configuration_mllama.py |
class MllamaPrecomputedAspectRatioEmbedding(nn.Module):
def __init__(self, config: MllamaVisionConfig, is_gated: bool = True):
super().__init__()
self.max_num_tiles = config.max_num_tiles
self.hidden_size = config.hidden_size
self.max_aspect_ratio_id = config.max_aspect_ratio_id
... | 3,357 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaPrecomputedPositionEmbedding(nn.Module):
def __init__(self, config: MllamaVisionConfig):
super().__init__()
self.max_num_tiles = config.max_num_tiles
self.max_aspect_ratio_id = config.max_aspect_ratio_id
self.num_patches = (config.image_size // config.patch_size) ** 2 + 1... | 3,358 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def forward(self, hidden_state: torch.Tensor, aspect_ratio_ids: torch.Tensor) -> torch.Tensor:
# position embeddings
gated_position_embedding = (1 - self.gate.tanh()) * self.embedding
hidden_state = hidden_state + gated_position_embedding.view(1, 1, self.num_patches, self.hidden_size)
#... | 3,358 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaVisionMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden... | 3,359 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaVisionAttention(nn.Module):
def __init__(self, config: MllamaVisionConfig):
super().__init__()
self.embed_dim = config.hidden_size
self.num_heads = config.attention_heads
self.head_dim = config.hidden_size // config.attention_heads
self.q_proj = nn.Linear(self.e... | 3,360 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
batch_size, q_seq_len, _ = query.shape
_, kv_seq_len, _ = key.shape
query = query.view(batch_size, q_seq_len, self.num_heads, self.head_dim).transpose(1, 2)
key = key.view(batch_size, kv_seq_len, self.num_heads, self.head_dim).transpose(1, 2)
value = value.view(batch_size, kv_seq_len, s... | 3,360 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
output = self.o_proj(attn_output)
if not output_attentions:
attn_weights = None
return output, attn_weights | 3,360 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaVisionSdpaAttention(MllamaVisionAttention):
# Adapted from MllamaVisionAttention
def forward(
self,
hidden_state: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = None,
) -> torch.Tensor:
# TODO: Improve this warning w... | 3,361 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
attention_mask=attention_mask,
output_attentions=output_attentions,
) | 3,361 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
query = self.q_proj(hidden_state)
key = self.k_proj(hidden_state)
value = self.v_proj(hidden_state)
batch_size, q_seq_len, _ = query.shape
_, kv_seq_len, _ = key.shape
query = query.view(batch_size, q_seq_len, self.num_heads, self.head_dim)
key = key.view(batch_size, kv... | 3,361 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaVisionEncoderLayer(nn.Module):
def __init__(self, config: MllamaVisionConfig, is_gated: bool = False):
super().__init__()
self.hidden_size = config.hidden_size
self.num_attention_heads = config.attention_heads
self.is_gated = is_gated
self.intermediate_size = con... | 3,362 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def forward(
self,
hidden_state: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = None,
):
# Self Attention
residual = hidden_state
hidden_state = self.input_layernorm(hidden_state)
hidden_state, attn_weights = sel... | 3,362 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaVisionEncoder(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`MllamaEncoderLayer`].
Args:
config: MllamaConfig
"""
def __init__(self, config: MllamaVisionConfig, num_layers=32, is_gated=False):
su... | 3,363 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutput]:
r"""
... | 3,363 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**. | 3,363 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
[What are attention masks?](../glossary#attention-mask)
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optiona... | 3,363 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
encoder_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
for encoder_layer in self.layers:
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if self.gradient_checkpointing and self.training... | 3,363 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states, hidden_states=encoder_st... | 3,363 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaTextRMSNorm(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
MllamaTextRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_state... | 3,364 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaTextCrossAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
config: Optional[MllamaTextConfig] = None,
layer_idx: Optional[int] = None,
):
super().__init__()
self.config = config
self.num_... | 3,365 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
self.o_proj = nn.L... | 3,365 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def forward(
self,
hidden_states: torch.Tensor,
cross_attention_states: Optional[torch.Tensor] = None,
past_key_value: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
use_cache: bool = None,
cache_pos... | 3,365 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if cross_attention_states is not None:
key_states = self.k_proj(cross_attention_states)
value_states = self.v_proj(cross_attention_states)
key_states = key_states.view(bsz, -1, self.num_key_value_heads, self.head_dim).transpose(1, 2)
value_states = value_states.view(bsz, ... | 3,365 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
key_states = self.k_norm(key_states)
if past_key_value is not None:
# if we have a new image + new tokens, we only computed key_states on that new image
# we still update the cross key states, past_image, new_image. And use it!
key_states, value_states = past_... | 3,365 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if attention_mask is not None: # no matter the length, we just slice it
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
... | 3,365 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaTextCrossSdpaAttention(MllamaTextCrossAttention):
"""
Mllama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
`MllamaTextCrossAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
SDPA A... | 3,366 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# Adapted from MllamaTextCrossAttention.forward
def forward(
self,
hidden_states: torch.Tensor,
cross_attention_states: Optional[torch.Tensor] = None,
past_key_value: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = Fals... | 3,366 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
)
return super().forward(
hidden_states=hidden_states,
cross_... | 3,366 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states)
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
query_states = self.q_norm(query_states)
if cross_attention_states is not None:
key_states = self.k_proj... | 3,366 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if past_key_value is not None:
# if we have a new image + new tokens, we only computed key_states on that new image
# we still update the cross key states, past_image, new_image. And use it!
key_states, value_states = past_key_value.update(
key_states,... | 3,366 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
# Reference: https://github.com/pytorch/pytorch/issues/112577.
if query_states.device.type == "cuda" and attention_mask is not None:
query_states = query_states.contiguou... | 3,366 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
attn_output = torch.nn.functional.scaled_dot_product_attention(
query_states,
key_states,
value_states,
attn_mask=attention_mask,
dropout_p=self.dropout if self.training else 0.0,
is_causal=is_causal,
)
attn_output = attn_output.tr... | 3,366 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaTextSelfAttention(nn.Module):
def __init__(self, config: MllamaTextConfig, layer_idx: int):
super().__init__()
self.config = config
self.num_heads = config.num_attention_heads
self.dropout = config.dropout
self.hidden_size = config.hidden_size
self.num_key... | 3,367 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
position_embeddings: torch.Tensor,
output_attentions: bool = False,
use_cache: bool = False,
past_key_value=None,
cache_position=None,
**kwargs,
):
bsz, q_len... | 3,367 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.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, ca... | 3,367 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# upcast attention to fp32
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output... | 3,367 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaTextSelfSdpaAttention(MllamaTextSelfAttention):
# Adapted from MllamaTextSelfAttention
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
position_embeddings: torch.Tensor,
output_attentions: bool = False,
use_cache: bool = F... | 3,368 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
)
return super().forward(
hidden_states=hidden_states,
attent... | 3,368 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
key_states = key_states.v... | 3,368 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
key_states = repeat_kv(key_states, self.num_key_value_groups)
value_states = repeat_kv(value_states, self.num_key_value_groups)
causal_mask = attention_mask
if attention_mask is not None:
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
# SDPA with memory-efficien... | 3,368 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
is_causal = True if ca... | 3,368 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaTextMLP(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=False)
... | 3,369 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaSelfAttentionDecoderLayer(nn.Module):
def __init__(self, config: MllamaTextConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = MLLAMA_TEXT_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
s... | 3,370 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def forward(
self,
hidden_states: torch.Tensor,
cross_attention_states: Optional[torch.Tensor] = None,
cross_attention_mask: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
full_text_row_masked_out_mask: Optional[Tuple[torch.Tensor, torch.Ten... | 3,370 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
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.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all atte... | 3,370 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
with `head_dim` being the embedding dimension of each attention head.
kwargs (`dict`, *optional*):
Arbitrary kwargs to be ignored, used for FSDP and other methods that injec... | 3,370 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, self_attn_weights, present_key_value = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=past_key_value... | 3,370 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaCrossAttentionDecoderLayer(torch.nn.Module):
"""Cross-attention transformer block with tanh-gated attention and feedforward."""
def __init__(self, config: MllamaTextConfig, layer_idx: int) -> None:
super().__init__()
self.layer_idx = layer_idx
self.cross_attn = MLLAMA_TEXT_C... | 3,371 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def forward(
self,
hidden_states: torch.Tensor,
cross_attention_states: torch.Tensor,
cross_attention_mask: torch.Tensor,
attention_mask: torch.Tensor,
full_text_row_masked_out_mask: Tuple[torch.Tensor, torch.Tensor],
position_ids: Optional[torch.LongTensor] = Non... | 3,371 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
hidden_states, attn_weights, past_key_value = self.cross_attn(
hidden_states=hidden_states,
attention_mask=cross_attention_mask,
cross_attention_states=cross_attention_states,
past_key_value=past_key_value,
output_attentions=output_attentions,
cach... | 3,371 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
return outputs | 3,371 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaRotaryEmbedding(nn.Module):
def __init__(self, config: MllamaTextConfig, device=None):
super().__init__()
self.rope_type = config.rope_scaling["rope_type"]
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
... | 3,372 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def _dynamic_frequency_update(self, position_ids, device):
"""
dynamic RoPE layers should recompute `inv_freq` in the following situations:
1 - growing beyond the cached sequence length (allow scaling)
2 - the current sequence length is in the original scale (avoid losing precision with ... | 3,372 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
self.max_seq_len_cached = self.original_max_seq_len
@torch.no_grad()
def forward(self, x, position_ids):
... | 3,372 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# Core RoPE block
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
device_type = x.device.type
device... | 3,372 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaPreTrainedModel(PreTrainedModel):
config_class = MllamaConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = [
"MllamaVisionEncoderLayer",
"MllamaCrossAttentionDecoderLayer",
"MllamaSelfAttentionDecoderLayer",
]
_support... | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def _init_weights(self, module):
std = self.config.get_text_config().initializer_range
if 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,... | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.