text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
nn.init.normal_(module.gate_ffn.data, std=std) | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
def _update_causal_mask(
self,
attention_mask: torch.Tensor,
input_tensor: torch.Tensor,
cache_position: torch.Tensor,
past_key_values: Cache,
output_attentions: bool,
):
if self.config._attn_implementation == "flash_attention_2":
if attention_mask is not None and (attention_mask == 0.0).any():
return attention_mask
return None
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
# to infer the attention mask.
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
using_static_cache = isinstance(past_key_values, StaticCache) | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
if AttentionMaskConverter._ignore_causal_mask_sdpa(
attention_mask,
inputs_embeds=input_tensor,
past_key_values_length=past_seen_tokens,
is_training=self.training,
):
return None
dtype, device = input_tensor.dtype, input_tensor.device
sequence_length = input_tensor.shape[1]
if using_static_cache:
target_length = past_key_values.get_max_cache_shape()
else:
target_length = (
attention_mask.shape[-1]
if isinstance(attention_mask, torch.Tensor)
else past_seen_tokens + sequence_length + 1
) | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
attention_mask,
sequence_length=sequence_length,
target_length=target_length,
dtype=dtype,
device=device,
cache_position=cache_position,
batch_size=input_tensor.shape[0],
) | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if (
self.config._attn_implementation == "sdpa"
and attention_mask is not None
and attention_mask.device.type == "cuda"
and not output_attentions
):
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
# Details: https://github.com/pytorch/pytorch/issues/110213
min_dtype = torch.finfo(dtype).min
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
return causal_mask | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
@staticmethod
# Copied from transformers.models.llama.modeling_llama.LlamaModel._prepare_4d_causal_attention_mask_with_cache_position
def _prepare_4d_causal_attention_mask_with_cache_position(
attention_mask: torch.Tensor,
sequence_length: int,
target_length: int,
dtype: torch.dtype,
device: torch.device,
cache_position: torch.Tensor,
batch_size: int,
**kwargs,
):
"""
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing. | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
Args:
attention_mask (`torch.Tensor`):
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
`(batch_size, 1, query_length, key_value_length)`.
sequence_length (`int`):
The sequence length being processed.
target_length (`int`):
The target length: when generating with static cache, the mask should be as long as the static cache,
to account for the 0 padding, the part of the cache that is not filled yet.
dtype (`torch.dtype`):
The dtype to use for the 4D attention mask.
device (`torch.device`):
The device to plcae the 4D attention mask on.
cache_position (`torch.Tensor`):
Indices depicting the position of the input sequence tokens in the sequence.
batch_size (`torch.Tensor`):
Batch size.
""" | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if attention_mask is not None and attention_mask.dim() == 4:
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
causal_mask = attention_mask
else:
min_dtype = torch.finfo(dtype).min
causal_mask = torch.full(
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
)
if sequence_length != 1:
causal_mask = torch.triu(causal_mask, diagonal=1)
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
if attention_mask is not None:
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
mask_length = attention_mask.shape[-1] | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
padding_mask = padding_mask == 0
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
padding_mask, min_dtype
) | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
return causal_mask | 3,373 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaVisionModel(MllamaPreTrainedModel):
config_class = MllamaVisionConfig
base_model_prefix = "vision_model"
def __init__(self, config: MllamaVisionConfig):
super().__init__(config)
self.image_size = config.image_size
self.patch_size = config.patch_size
self.max_num_tiles = config.max_num_tiles
self.hidden_size = config.hidden_size
self.num_channels = config.num_channels
self.intermediate_layers_indices = config.intermediate_layers_indices
self.num_patches = (self.image_size // self.patch_size) ** 2 + 1
self.scale = config.hidden_size**-0.5
self.patch_embedding = nn.Conv2d(
in_channels=config.num_channels,
out_channels=self.hidden_size,
kernel_size=self.patch_size,
stride=self.patch_size,
padding="valid",
bias=False,
) | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
self.class_embedding = nn.Parameter(self.scale * torch.randn(self.hidden_size))
self.gated_positional_embedding = MllamaPrecomputedPositionEmbedding(config)
self.pre_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(config, is_gated=True)
self.post_tile_positional_embedding = MllamaPrecomputedAspectRatioEmbedding(config, is_gated=True)
# layer norms
self.layernorm_pre = nn.LayerNorm(self.hidden_size)
self.layernorm_post = nn.LayerNorm(self.hidden_size)
# encoders
self.transformer = MllamaVisionEncoder(config, config.num_hidden_layers, is_gated=False)
self.global_transformer = MllamaVisionEncoder(config, config.num_global_layers, is_gated=True)
self.post_init()
def get_input_embeddings(self):
"""
This function is used to fetch the first embedding layer to activate grads on inputs.
"""
return self.patch_embedding | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def apply_class_embedding(self, hidden_state: torch.Tensor) -> torch.Tensor:
batch_size, _, hidden_size = hidden_state.shape
class_embedding = self.class_embedding.expand(batch_size, 1, hidden_size)
hidden_state = torch.cat([class_embedding, hidden_state], dim=1)
return hidden_state
@add_start_docstrings_to_model_forward(MLLAMA_VISION_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=BaseModelOutput, config_class="MllamaVisionConfig")
def forward(
self,
pixel_values: torch.Tensor,
aspect_ratio_ids: torch.Tensor,
aspect_ratio_mask: torch.Tensor,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[BaseModelOutput, Tuple[torch.Tensor, ...]]:
r"""
Returns:
Example: | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, MllamaVisionModel
>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaVisionModel.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, return_tensors="pt")
>>> output = model(**inputs) | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
>>> print(output.last_hidden_state.shape)
torch.Size([1, 1, 4, 1025, 7680])
```
"""
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
batch_size, num_concurrent_media, num_tiles, num_channels, height, width = pixel_values.shape
pixel_values = pixel_values.reshape(batch_size * num_concurrent_media * num_tiles, num_channels, height, width)
aspect_ratio_ids = aspect_ratio_ids.reshape(batch_size * num_concurrent_media, -1)
# Patch embedding
patch_embeds = self.patch_embedding(pixel_values.to(self.dtype).to(self.device))
hidden_state = patch_embeds.flatten(2).transpose(1, 2) | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# Tile embeddings
_, num_patches, dim = hidden_state.shape
hidden_state = hidden_state.reshape(batch_size * num_concurrent_media, num_tiles, -1, dim)
hidden_state = self.pre_tile_positional_embedding(hidden_state, aspect_ratio_ids)
# Add cls token
hidden_state = hidden_state.reshape(batch_size * num_concurrent_media * num_tiles, num_patches, dim)
hidden_state = self.apply_class_embedding(hidden_state)
num_patches += 1
# Position embeddings
hidden_state = hidden_state.reshape(batch_size * num_concurrent_media, num_tiles, num_patches, dim)
hidden_state = self.gated_positional_embedding(hidden_state, aspect_ratio_ids)
hidden_state = self.layernorm_pre(hidden_state) | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# Compute the number of tokens to pad
num_padding_patches = (8 - (hidden_state.shape[-2] % 8)) % 8
# Compute padding tuple for pad function
padding = (0, 0, 0, num_padding_patches) # (pad_left, pad_right, pad_left for dim -2, pad_right for dim -2)
# Pad the tensor
hidden_state = F.pad(hidden_state, padding, mode="constant", value=0)
slice_index = -num_padding_patches if num_padding_patches > 0 else None
# Prepare attention mask
attention_mask = aspect_ratio_mask.reshape(batch_size * num_concurrent_media, -1)
attention_mask = _prepare_aspect_ratio_attention_mask(
aspect_ratio_mask=attention_mask,
num_patches=self.num_patches,
target_length=hidden_state.shape[2],
dtype=self.dtype,
) | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# Apply encoder
hidden_state = hidden_state.view(batch_size * num_concurrent_media, -1, dim)
output = self.transformer(
hidden_state,
attention_mask=attention_mask,
output_hidden_states=True,
output_attentions=output_attentions,
)
hidden_state = output[0]
hidden_state = self.layernorm_post(hidden_state) | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# Apply global encoder
hidden_state = hidden_state.reshape(
batch_size * num_concurrent_media, num_tiles, num_patches + num_padding_patches, dim
)
hidden_state = self.post_tile_positional_embedding(hidden_state, aspect_ratio_ids)
hidden_state = hidden_state.reshape(
batch_size * num_concurrent_media, num_tiles * (num_patches + num_padding_patches), dim
)
global_output = self.global_transformer(
hidden_state,
attention_mask=attention_mask,
output_hidden_states=output_hidden_states,
output_attentions=output_attentions,
)
hidden_state = global_output[0] | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# Remove padding form hidden state
hidden_state = hidden_state.reshape(
batch_size * num_concurrent_media, num_tiles, num_patches + num_padding_patches, dim
)
hidden_state = hidden_state[:, :, :slice_index]
hidden_state = hidden_state.reshape(batch_size, num_concurrent_media, num_tiles, num_patches, dim)
# Collect intermediate layer outputs from encoder output
all_intermediate_hidden_states = [output[1][i] for i in self.intermediate_layers_indices]
intermediate_hidden_states = torch.stack(all_intermediate_hidden_states, dim=-1) | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# Remove padding from intermediate hidden states
intermediate_hidden_states = intermediate_hidden_states.reshape(
batch_size * num_concurrent_media, num_tiles, num_patches + num_padding_patches, -1
)
intermediate_hidden_states = intermediate_hidden_states[:, :, :slice_index]
intermediate_hidden_states = intermediate_hidden_states.reshape(
batch_size, num_concurrent_media, num_tiles, num_patches, -1
)
# Concatenate final hidden state and intermediate hidden states
hidden_state = torch.cat([hidden_state, intermediate_hidden_states], dim=-1)
if output_hidden_states:
hidden_states = tuple(all_intermediate_hidden_states) + tuple(global_output[1])
else:
hidden_states = None | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if output_attentions:
# global transformer in contrast to `self.transformer` doesn't always return hidden states so we might go index out-of-range
global_attn = tuple(global_output[2]) if output_hidden_states else tuple(global_output[1])
attentions = tuple(output[2]) + global_attn
else:
attentions = None
if not return_dict:
return tuple(v for v in [hidden_state, hidden_states, attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_state,
hidden_states=hidden_states,
attentions=attentions,
) | 3,374 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaTextModel(MllamaPreTrainedModel):
config_class = MllamaTextConfig
base_model_prefix = "language_model.model"
def __init__(self, config: MllamaTextConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size + 8, config.hidden_size, self.padding_idx)
self.cross_attention_layers = config.cross_attention_layers
layers = []
for layer_idx in range(config.num_hidden_layers):
if layer_idx in self.cross_attention_layers:
layers.append(MllamaCrossAttentionDecoderLayer(config, layer_idx))
else:
layers.append(MllamaSelfAttentionDecoderLayer(config, layer_idx)) | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
self.layers = nn.ModuleList(layers)
self.norm = MllamaTextRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = MllamaRotaryEmbedding(config=config)
self.gradient_checkpointing = False
self.post_init()
def get_input_embeddings(self):
return self.embed_tokens
def set_input_embeddings(self, value):
self.embed_tokens = value | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
@add_start_docstrings_to_model_forward(MLLAMA_TEXT_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=BaseModelOutputWithPast, config_class="MllamaTextConfig")
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
cross_attention_states: Optional[torch.FloatTensor] = None,
cross_attention_mask: Optional[torch.Tensor] = None,
full_text_row_masked_out_mask: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = 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, | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
) -> Union[Tuple, BaseModelOutputWithPast]:
""" | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
Returns:
Example:
```python
>>> from transformers import AutoProcessor, MllamaTextModel
>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaTextModel.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> text = "<|image|>If I had to write a haiku for this one"
>>> inputs = processor(text=text, return_tensors="pt")
>>> output = model(**inputs) | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
>>> print(output.last_hidden_state.shape)
torch.Size([1, 13, 4096])
```
"""
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
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if self.gradient_checkpointing and self.training and use_cache:
logger.warning_once(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
)
use_cache = False | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
hidden_states = inputs_embeds
if use_cache and past_key_values is None:
past_key_values = DynamicCache()
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
causal_mask = self._update_causal_mask(
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
)
# create position embeddings to be shared across the decoder layers
position_embeddings = self.rotary_emb(hidden_states, position_ids) | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# decoder layers
all_hidden_states = () if output_hidden_states else None
all_self_attns = () if output_attentions else None
next_decoder_cache = None
for idx, decoder_layer in enumerate(self.layers):
if output_hidden_states:
all_hidden_states += (hidden_states,)
# For text-only path we should skip cross attention layers.
# Let's check if the layer is cross attention layer and if we have cross attention states
# or cached cross attention states.
is_cross_attention_layer = idx in self.cross_attention_layers
is_cross_attention_cache_empty = past_key_values is None or (
past_key_values is not None and past_key_values.get_seq_length(idx) == 0
)
if is_cross_attention_layer and cross_attention_states is None and is_cross_attention_cache_empty:
continue | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if self.gradient_checkpointing and self.training:
layer_outputs = self._gradient_checkpointing_func(
decoder_layer.__call__,
hidden_states,
cross_attention_states,
cross_attention_mask,
causal_mask,
full_text_row_masked_out_mask,
position_ids,
past_key_values,
output_attentions,
use_cache,
cache_position,
position_embeddings,
)
else:
layer_outputs = decoder_layer(
hidden_states,
cross_attention_states=cross_attention_states,
cross_attention_mask=cross_attention_mask,
attention_mask=causal_mask,
full_text_row_masked_out_mask=full_text_row_masked_out_mask,
position_ids=position_ids, | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
past_key_value=past_key_values,
output_attentions=output_attentions,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
) | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
hidden_states = layer_outputs[0]
if use_cache:
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
if output_attentions:
all_self_attns += (layer_outputs[1],)
hidden_states = self.norm(hidden_states)
# add hidden states from the last decoder layer
if output_hidden_states:
all_hidden_states += (hidden_states,)
next_cache = next_decoder_cache if use_cache else None
if not return_dict:
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=next_cache,
hidden_states=all_hidden_states,
attentions=all_self_attns,
) | 3,375 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaForCausalLM(MllamaPreTrainedModel, GenerationMixin):
config_class = MllamaTextConfig
_supports_static_cache = True # only the LLM without cross attn can do compile
base_model_prefix = "language_model"
_tied_weights_keys = ["lm_head.weight"]
def __init__(self, config):
super().__init__(config.get_text_config())
self.text_config = config.get_text_config()
self.vocab_size = self.text_config.vocab_size
self.model = MllamaTextModel._from_config(self.text_config)
self.lm_head = nn.Linear(self.text_config.hidden_size, self.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self):
return self.model.embed_tokens
def set_input_embeddings(self, value):
self.model.embed_tokens = value
def get_output_embeddings(self):
return self.lm_head
def set_output_embeddings(self, new_embeddings):
self.lm_head = new_embeddings | 3,376 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def set_decoder(self, decoder):
self.model = decoder
def get_decoder(self):
return self.model | 3,376 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
@add_start_docstrings_to_model_forward(MLLAMA_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class="MllamaTextConfig")
def forward(
self,
input_ids: torch.LongTensor = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
cross_attention_states: Optional[torch.LongTensor] = None,
cross_attention_mask: Optional[torch.LongTensor] = None,
full_text_row_masked_out_mask: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = 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, | 3,376 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
num_logits_to_keep: int = 0,
**loss_kwargs,
) -> Union[Tuple, CausalLMOutputWithPast]:
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]`. | 3,376 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
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.
Returns:
Example:
```python
>>> from transformers import AutoTokenizer, MllamaForCausalLM
>>> model = MllamaForCausalLM.from_pretrained("Llama-3.2-11B-Vision")
>>> tokenizer = AutoTokenizer.from_pretrained("Llama-3.2-11B-Vision")
>>> prompt = "If I had to write a haiku, it would be:"
>>> inputs = tokenizer(prompt, return_tensors="pt") | 3,376 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=40, do_sample=True, temperature=0.6)
>>> result = tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
>>> print(result)
If I had to write a haiku, it would be: "Snowflakes gently fall" - simple, yet peaceful.
I love the idea of snowflakes gently falling, each one
```
"""
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,376 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
outputs = self.model(
input_ids=input_ids,
cross_attention_states=cross_attention_states,
attention_mask=attention_mask,
position_ids=position_ids,
cross_attention_mask=cross_attention_mask,
full_text_row_masked_out_mask=full_text_row_masked_out_mask,
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,
)
hidden_states = outputs[0]
logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]).float()
loss = None
if labels is not None:
loss = self.loss_function(logits, labels, self.vocab_size, **loss_kwargs) | 3,376 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if not return_dict:
output = (logits,) + outputs[1:]
return (loss,) + output if loss is not None else output
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
) | 3,376 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class MllamaForConditionalGeneration(MllamaPreTrainedModel, GenerationMixin):
_supports_quantized_cache = False # quant cache not supported in encoder-decoder setting
def __init__(self, config: MllamaConfig):
super().__init__(config)
self.vocab_size = config.text_config.vocab_size
self.hidden_size = config.text_config.hidden_size
self.max_num_tiles = config.vision_config.max_num_tiles
self.vision_output_dim = config.vision_config.vision_output_dim
self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1
self.vision_model = MllamaVisionModel._from_config(config.vision_config)
self.language_model = MllamaForCausalLM._from_config(config.text_config)
if self.language_model._tied_weights_keys is not None:
self._tied_weights_keys = [f"language_model.{k}" for k in self.language_model._tied_weights_keys] | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
self.multi_modal_projector = nn.Linear(
config.vision_config.vision_output_dim,
config.text_config.hidden_size,
bias=True,
)
self.post_init()
def get_input_embeddings(self):
return self.language_model.get_input_embeddings()
def set_input_embeddings(self, value):
self.language_model.set_input_embeddings(value)
def get_output_embeddings(self):
return self.language_model.get_output_embeddings()
def set_output_embeddings(self, new_embeddings):
self.language_model.set_output_embeddings(new_embeddings)
def set_decoder(self, decoder):
self.language_model.set_decoder(decoder)
def get_decoder(self):
return self.language_model.get_decoder() | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
@add_start_docstrings_to_model_forward(MLLAMA_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class="MllamaConfig")
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
aspect_ratio_mask: Optional[torch.Tensor] = None,
aspect_ratio_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
cross_attention_mask: Optional[torch.Tensor] = None,
cross_attention_states: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None, | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
num_logits_to_keep: int = 0,
) -> Union[Tuple, CausalLMOutputWithPast]:
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]`. | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
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.
Returns:
Example:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, MllamaForConditionalGeneration
>>> checkpoint = "meta-llama/Llama-3.2-11B-Vision"
>>> model = MllamaForConditionalGeneration.from_pretrained(checkpoint)
>>> processor = AutoProcessor.from_pretrained(checkpoint)
>>> prompt = "<|image|>If I had to write a haiku for this one"
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw) | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
>>> inputs = processor(text=prompt, images=image, return_tensors="pt")
>>> # Generate
>>> output = model.generate(**inputs, max_new_tokens=15)
>>> prompt_len = inputs.input_ids.shape[-1]
>>> generated_ids = output[:, prompt_len:]
>>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)
>>> print(generated_text)
[', it would be:.\\nA stop sign in Chinatown.\\n']
```
"""
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,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
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 and cross_attention_states is not None:
raise ValueError("`pixel_values` and `cross_attention_states` cannot be provided simultaneously") | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if pixel_values is not None:
if aspect_ratio_ids is None:
raise ValueError("`aspect_ratio_ids` must be provided if `pixel_values` is provided")
# get vision tokens from vision model
vision_outputs = self.vision_model(
pixel_values=pixel_values,
aspect_ratio_ids=aspect_ratio_ids,
aspect_ratio_mask=aspect_ratio_mask,
output_hidden_states=output_hidden_states,
output_attentions=output_attentions,
return_dict=return_dict,
)
cross_attention_states = vision_outputs[0]
cross_attention_states = self.multi_modal_projector(cross_attention_states).reshape(
-1, cross_attention_states.shape[-2], self.hidden_size
) | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
if cross_attention_mask is not None:
cross_attention_mask, full_text_row_masked_out_mask = _prepare_cross_attention_mask(
cross_attention_mask,
num_vision_tokens=self.vision_model.num_patches,
dtype=self.dtype,
)
else:
full_text_row_masked_out_mask = None
if cross_attention_mask is not None and cache_position is not None:
cross_attention_mask = cross_attention_mask[:, :, cache_position]
full_text_row_masked_out_mask = full_text_row_masked_out_mask[:, :, cache_position] | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
outputs = self.language_model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
cross_attention_states=cross_attention_states,
cross_attention_mask=cross_attention_mask,
full_text_row_masked_out_mask=full_text_row_masked_out_mask,
past_key_values=past_key_values,
use_cache=use_cache,
inputs_embeds=inputs_embeds,
labels=labels,
output_hidden_states=output_hidden_states,
output_attentions=output_attentions,
return_dict=return_dict,
cache_position=cache_position,
num_logits_to_keep=num_logits_to_keep,
)
return outputs | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
def prepare_inputs_for_generation(
self,
input_ids=None,
inputs_embeds=None,
attention_mask=None,
position_ids=None,
pixel_values=None,
aspect_ratio_ids=None,
aspect_ratio_mask=None,
cross_attention_mask=None,
past_key_values=None,
use_cache=False,
cache_position=None,
num_logits_to_keep=None,
**kwargs,
):
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
# Exception 1: when passing input_embeds, input_ids may be missing entries
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
if past_key_values is not None:
if inputs_embeds is not None: # Exception 1
input_ids = input_ids[:, -cache_position.shape[0] :]
elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
input_ids = input_ids[:, cache_position] | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# TODO: we have no attention_mask so this won't work, check if we really won't need attention mask and find another way
if attention_mask is not None and position_ids is None:
# create position_ids on the fly for batch generation
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids.masked_fill_(attention_mask == 0, 1)
if past_key_values:
position_ids = position_ids[:, -input_ids.shape[1] :]
# This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
position_ids = position_ids.clone(memory_format=torch.contiguous_format) | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
if inputs_embeds is not None and cache_position[0] == 0:
model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": None}
else:
# The clone here is for the same reason as for `position_ids`.
model_inputs = {"input_ids": input_ids.clone(memory_format=torch.contiguous_format), "inputs_embeds": None}
if num_logits_to_keep is not None:
model_inputs["num_logits_to_keep"] = num_logits_to_keep
model_inputs.update(
{
"position_ids": position_ids,
"cache_position": cache_position,
"past_key_values": past_key_values,
"use_cache": use_cache,
"attention_mask": attention_mask,
"cross_attention_mask": cross_attention_mask,
}
) | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# If we're in pre-fill or cacheless decoding step, then we need pixel_values and aspect ratios
# to compute image hidden states, otherwise they are cached within each cross attn layer
if cache_position[0] == 0:
model_inputs["pixel_values"] = pixel_values
model_inputs["aspect_ratio_ids"] = aspect_ratio_ids
model_inputs["aspect_ratio_mask"] = aspect_ratio_mask
return model_inputs
def _update_model_kwargs_for_generation(self, outputs, model_kwargs, is_encoder_decoder, **kwargs):
cross_attention_mask_prev = model_kwargs.get("cross_attention_mask", None)
model_kwargs = super()._update_model_kwargs_for_generation(
outputs=outputs,
model_kwargs=model_kwargs,
is_encoder_decoder=is_encoder_decoder,
**kwargs,
) | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
# add cross-attn mask for new token
if cross_attention_mask_prev is not None:
model_kwargs["cross_attention_mask"] = torch.cat(
[cross_attention_mask_prev, cross_attention_mask_prev[:, -1:, ...]], dim=1
)
return model_kwargs | 3,377 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/mllama/modeling_mllama.py |
class OmDetTurboTextKwargs(TextKwargs, total=False):
task: Optional[Union[str, List[str], TextInput, PreTokenizedInput]] | 3,378 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
class OmDetTurboProcessorKwargs(ProcessingKwargs, total=False):
text_kwargs: OmDetTurboTextKwargs
_defaults = {
"text_kwargs": {
"add_special_tokens": True,
"padding": "max_length",
"truncation": True,
"max_length": 77,
"stride": 0,
"return_overflowing_tokens": False,
"return_special_tokens_mask": False,
"return_offsets_mapping": False,
"return_token_type_ids": False,
"return_length": False,
"verbose": True,
"task": None,
},
"images_kwargs": {},
} | 3,379 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
class DictWithDeprecationWarning(dict):
message = (
"The `classes` key is deprecated for `OmDetTurboProcessor.post_process_grounded_object_detection` "
"output dict and will be removed in a 4.51.0 version. Please use `text_labels` instead."
)
def __getitem__(self, key):
if key == "classes":
warnings.warn(self.message, FutureWarning)
return super().__getitem__("text_labels")
return super().__getitem__(key)
def get(self, key, *args, **kwargs):
if key == "classes":
warnings.warn(self.message, FutureWarning)
return super().get("text_labels", *args, **kwargs)
return super().get(key, *args, **kwargs) | 3,380 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
class OmDetTurboProcessor(ProcessorMixin):
r"""
Constructs a OmDet-Turbo processor which wraps a Deformable DETR image processor and an AutoTokenizer into a
single processor.
[`OmDetTurboProcessor`] offers all the functionalities of [`DetrImageProcessor`] and
[`AutoTokenizer`]. See the docstring of [`~OmDetTurboProcessor.__call__`] and [`~OmDetTurboProcessor.decode`]
for more information.
Args:
image_processor (`DetrImageProcessor`):
An instance of [`DetrImageProcessor`]. The image processor is a required input.
tokenizer (`AutoTokenizer`):
An instance of ['PreTrainedTokenizer`]. The tokenizer is a required input.
"""
attributes = ["image_processor", "tokenizer"]
image_processor_class = "DetrImageProcessor"
tokenizer_class = "AutoTokenizer"
def __init__(self, image_processor, tokenizer):
super().__init__(image_processor, tokenizer) | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
def __call__(
self,
images: ImageInput = None,
text: Union[List[str], List[List[str]]] = None,
audio=None,
videos=None,
**kwargs: Unpack[OmDetTurboProcessorKwargs],
) -> BatchFeature:
"""
This method uses [*DetrImageProcessor.__call__] method to prepare image(s) for the model, and
[CLIPTokenizerFast.__call__] to prepare text for the model.
Please refer to the docstring of the above two methods for more information. | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
Args:
images (`ImageInput`):
Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255.
text (`Union[str, List[str], List[List[str]]]`):
The classes used to limit the scope of the open vocabulary detection. Expects a list of strings or a list
of list of strings. Batched classes can be of different lengths.
Examples: ["cat", "dog", "bird"], [["cat", "dog", "bird"], ["hat", "person"], ["car"]]
Kwargs:
task (`Union[str, List[str], TextInput, PreTokenizedInput]`):
The grounded text used to guide open vocabulary detection. Expects a single string or a list of strings.
Examples: "Detect a cat, a dog, and a bird.",[ "Detect everything.", "Detect trees and flowers."]
When not provided, the default task is "Detect [class1], [class2], [class3]" etc.
...
"""
if images is None or text is None: | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
raise ValueError("You have to specify both `images` and `text`") | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
output_kwargs = self._merge_kwargs(
OmDetTurboProcessorKwargs,
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
**kwargs,
)
if isinstance(text, str):
text = text.strip(" ").split(",")
if not (len(text) and isinstance(text[0], (list, tuple))):
text = [text]
task = output_kwargs["text_kwargs"].pop("task", None)
if task is None:
task = ["Detect {}.".format(", ".join(text_single)) for text_single in text]
elif not isinstance(task, (list, tuple)):
task = [task]
encoding_image_processor = self.image_processor(images, **output_kwargs["images_kwargs"])
tasks_encoding = self.tokenizer(text=task, **output_kwargs["text_kwargs"])
classes = text | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
classes_structure = torch.tensor([len(class_single) for class_single in classes], dtype=torch.long)
classes_flattened = [class_single for class_batch in classes for class_single in class_batch]
classes_encoding = self.tokenizer(text=classes_flattened, **output_kwargs["text_kwargs"])
encoding = BatchFeature()
encoding.update({f"tasks_{key}": value for key, value in tasks_encoding.items()})
encoding.update({f"classes_{key}": value for key, value in classes_encoding.items()})
encoding.update({"classes_structure": classes_structure})
encoding.update(encoding_image_processor)
return encoding | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
# Copied from transformers.models.blip.processing_blip.BlipProcessor.batch_decode with BertTokenizerFast->PreTrainedTokenizer
def batch_decode(self, *args, **kwargs):
"""
This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
refer to the docstring of this method for more information.
"""
return self.tokenizer.batch_decode(*args, **kwargs)
# Copied from transformers.models.blip.processing_blip.BlipProcessor.decode with BertTokenizerFast->PreTrainedTokenizer
def decode(self, *args, **kwargs):
"""
This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
the docstring of this method for more information.
"""
return self.tokenizer.decode(*args, **kwargs) | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
def _get_default_image_size(self) -> Tuple[int, int]:
height = (
self.image_processor.size["height"]
if "height" in self.image_processor.size
else self.image_processor.size["shortest_edge"]
)
width = (
self.image_processor.size["width"]
if "width" in self.image_processor.size
else self.image_processor.size["longest_edge"]
)
return height, width | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
@deprecate_kwarg("score_threshold", new_name="threshold", version="4.51.0")
@deprecate_kwarg("classes", new_name="text_labels", version="4.51.0")
def post_process_grounded_object_detection(
self,
outputs: "OmDetTurboObjectDetectionOutput",
text_labels: Optional[Union[List[str], List[List[str]]]] = None,
threshold: float = 0.3,
nms_threshold: float = 0.5,
target_sizes: Optional[Union[TensorType, List[Tuple]]] = None,
max_num_det: Optional[int] = None,
):
"""
Converts the raw output of [`OmDetTurboForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
bottom_right_x, bottom_right_y) format and get the associated text class. | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
Args:
outputs ([`OmDetTurboObjectDetectionOutput`]):
Raw outputs of the model.
text_labels (Union[List[str], List[List[str]]], *optional*):
The input classes names. If not provided, `text_labels` will be set to `None` in `outputs`.
threshold (float, defaults to 0.3):
Only return detections with a confidence score exceeding this threshold.
nms_threshold (float, defaults to 0.5):
The threshold to use for box non-maximum suppression. Value in [0, 1].
target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):
Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size
`(height, width)` of each image in the batch. If unset, predictions will not be resized.
max_num_det (`int`, *optional*):
The maximum number of detections to return.
Returns: | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
`List[Dict]`: A list of dictionaries, each dictionary containing the scores, classes and boxes for an image
in the batch as predicted by the model.
""" | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
batch_size = len(outputs.decoder_coord_logits)
# Inputs consistency check for target sizes
if target_sizes is None:
height, width = self._get_default_image_size()
target_sizes = [(height, width)] * batch_size
if any(len(image_size) != 2 for image_size in target_sizes):
raise ValueError(
"Each element of target_sizes must contain the size (height, width) of each image of the batch"
)
if len(target_sizes) != batch_size:
raise ValueError("Make sure that you pass in as many target sizes as output sequences")
# Inputs consistency check for text labels
if text_labels is not None and isinstance(text_labels[0], str):
text_labels = [text_labels]
if text_labels is not None and len(text_labels) != batch_size:
raise ValueError("Make sure that you pass in as many classes group as output sequences") | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
# Convert target_sizes to list for easier handling
if isinstance(target_sizes, torch.Tensor):
target_sizes = target_sizes.tolist()
batch_boxes = outputs.decoder_coord_logits
batch_logits = outputs.decoder_class_logits
batch_num_classes = outputs.classes_structure
batch_scores, batch_labels = compute_score(batch_logits) | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
results = []
for boxes, scores, image_size, image_num_classes in zip(
batch_boxes, batch_scores, target_sizes, batch_num_classes
):
boxes, scores, labels = _post_process_boxes_for_image(
boxes=boxes,
scores=scores,
labels=batch_labels,
image_num_classes=image_num_classes,
image_size=image_size,
threshold=threshold,
nms_threshold=nms_threshold,
max_num_det=max_num_det,
)
result = DictWithDeprecationWarning(
{"boxes": boxes, "scores": scores, "labels": labels, "text_labels": None}
)
results.append(result)
# Add text labels
if text_labels is not None:
for result, image_text_labels in zip(results, text_labels):
result["text_labels"] = [image_text_labels[idx] for idx in result["labels"]]
return results | 3,381 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/processing_omdet_turbo.py |
class OmDetTurboEncoderOutput(ModelOutput):
"""
Base class for outputs of the OmDetTurboHybridEncoder.
Args:
last_hidden_state (`torch.FloatTensor`):
Last hidden states of the encoder.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`. | 3,382 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
extracted_states (`Tuple[torch.FloatTensor]`):
The extracted states from the Feature Pyramid Network (FPN) and Path Aggregation Network (PAN) of the encoder.
"""
last_hidden_state: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
extracted_states: Tuple[torch.FloatTensor] = None | 3,382 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
class OmDetTurboDecoderOutput(ModelOutput):
"""
Base class for outputs of the OmDetTurboDecoder. | 3,383 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder.
decoder_coords (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
The predicted coordinates of the objects.
decoder_classes (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes)`):
The predicted classes of the objects.
encoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
The predicted coordinates of the objects from the encoder.
encoder_class_logits (`Tuple[torch.FloatTensor]`) of shape `(batch_size, num_queries, num_classes)`:
The predicted class of the objects from the encoder.
init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
The initial reference points. | 3,383 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
intermediate_reference_points (`Tuple[Tuple[torch.FloatTensor]]`):
The intermediate reference points.
hidden_states (`Optional[Tuple[torch.FloatTensor]]`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape
`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
plus the initial embedding outputs.
attentions (`Optional[Tuple[Tuple[torch.FloatTensor]]]`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of tuples of `torch.FloatTensor` (one for attention for each layer) of shape `(batch_size, num_heads,
sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the | 3,383 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
weighted average in the self-attention, cross-attention and multi-scale deformable attention heads.
""" | 3,383 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
last_hidden_state: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
decoder_coords: torch.FloatTensor = None
decoder_classes: torch.FloatTensor = None
encoder_coord_logits: torch.FloatTensor = None
encoder_class_logits: Tuple[torch.FloatTensor] = None
init_reference_points: torch.FloatTensor = None
intermediate_reference_points: Tuple[Tuple[torch.FloatTensor]] = None | 3,383 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
class OmDetTurboObjectDetectionOutput(ModelOutput):
"""
Output type of [`OmDetTurboObjectDetectionOutput`]. | 3,384 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
Args:
loss (`torch.FloatTensor`):
The loss value.
decoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
The predicted coordinates logits of the objects.
decoder_class_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes)`):
The predicted class of the objects.
init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
The initial reference points.
intermediate_reference_points (`Tuple[Tuple[torch.FloatTensor]]`):
The intermediate reference points.
encoder_coord_logits (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
The predicted coordinates of the objects from the encoder.
encoder_class_logits (`Tuple[torch.FloatTensor]`):
The predicted class of the objects from the encoder.
encoder_extracted_states (`torch.FloatTensor`): | 3,384 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
The extracted states from the Feature Pyramid Network (FPN) and Path Aggregation Network (PAN) of the encoder.
decoder_hidden_states (`Tuple[torch.FloatTensor]`, *optional*):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape
`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
plus the initial embedding outputs.
decoder_attentions (`Tuple[Tuple[torch.FloatTensor]]`, *optional*):
Tuple of tuples of `torch.FloatTensor` (one for attention for each layer) of shape `(batch_size, num_heads,
sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the
weighted average in the self-attention, cross-attention and multi-scale deformable attention heads.
encoder_hidden_states (`Tuple[torch.FloatTensor]`, *optional*): | 3,384 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of shape
`(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
plus the initial embedding outputs.
encoder_attentions (`Tuple[Tuple[torch.FloatTensor]]`, *optional*):
Tuple of tuples of `torch.FloatTensor` (one for attention for each layer) of shape `(batch_size, num_heads,
sequence_length, sequence_length)`. Attentions weights after the attention softmax, used to compute the
weighted average in the self-attention, cross-attention and multi-scale deformable attention heads.
classes_structure (`torch.LongTensor`, *optional*):
The number of queried classes for each image.
""" | 3,384 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
loss: torch.FloatTensor = None
decoder_coord_logits: torch.FloatTensor = None
decoder_class_logits: torch.FloatTensor = None
init_reference_points: torch.FloatTensor = None
intermediate_reference_points: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
encoder_coord_logits: torch.FloatTensor = None
encoder_class_logits: Tuple[torch.FloatTensor] = None
encoder_extracted_states: torch.FloatTensor = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
encoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
encoder_attentions: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
classes_structure: Optional[torch.LongTensor] = None | 3,384 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
class OmDetTurboLRUCache:
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
self.current_load = 0
def has(self, key) -> bool:
return key in self.cache
def get(self, key):
"""
Get the value of the key if the key exists in the cache, otherwise return None.
Move the key to the end of the cache to show that it was recently used.
"""
if key not in self.cache:
return None
self.cache.move_to_end(key)
return self.cache[key] | 3,385 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
def put(self, key, value) -> None:
"""
Add the key-value pair to the cache.
Move the key to the end of the cache to show that it was recently used.
If the cache is full, remove the first key (least recently used).
"""
if key not in self.cache:
self.current_load += 1
if self.current_load > self.capacity:
self.cache.popitem(last=False)
self.current_load -= 1
self.cache[key] = value
self.cache.move_to_end(key) | 3,385 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
class OmDetTurboLanguageBackbone(nn.Module):
def __init__(self, config: OmDetTurboConfig):
super().__init__()
self.model = AutoModel.from_config(config.text_config)
self.text_projection = nn.Parameter(torch.zeros(config.text_projection_in_dim, config.text_projection_out_dim)) | 3,386 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
def forward(self, hidden_states, mask=None, encode_type="task"):
text_outputs = self.model(hidden_states)
pooled_output = text_outputs[0]
if encode_type == "task":
if mask is None:
raise ValueError("mask is required for task encoding")
max_len = (mask != 0).sum(1).max().item()
truncated_mask = mask[:, :max_len]
truncated_output = pooled_output[:, :max_len, :]
return truncated_output.transpose(0, 1), truncated_mask
elif encode_type == "class":
max_pooled_output = pooled_output[torch.arange(pooled_output.shape[0]), hidden_states.argmax(dim=-1)]
projected_output = max_pooled_output @ self.text_projection
return projected_output
else:
raise ValueError(f"encode_type {encode_type} is not supported") | 3,386 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
class OmDetTurboVisionBackbone(nn.Module):
def __init__(self, config: OmDetTurboConfig):
super().__init__()
self.apply_layernorm_after_vision_backbone = config.apply_layernorm_after_vision_backbone
self.vision_backbone = load_backbone(config)
self.layer_norms = nn.ModuleList(
[nn.LayerNorm(in_channel_dim, eps=config.layer_norm_eps) for in_channel_dim in config.encoder_in_channels]
)
def forward(self, pixel_values):
outputs = self.vision_backbone(pixel_values).feature_maps
if self.apply_layernorm_after_vision_backbone:
outputs = [
layer_norm(output).permute(0, 3, 1, 2).contiguous()
for layer_norm, output in zip(self.layer_norms, outputs)
]
return outputs | 3,387 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
class MultiScaleDeformableAttentionFunction(Function):
@staticmethod
def forward(
context,
value,
value_spatial_shapes,
value_level_start_index,
sampling_locations,
attention_weights,
im2col_step,
):
context.im2col_step = im2col_step
output = MultiScaleDeformableAttention.ms_deform_attn_forward(
value,
value_spatial_shapes,
value_level_start_index,
sampling_locations,
attention_weights,
context.im2col_step,
)
context.save_for_backward(
value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights
)
return output | 3,388 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
@staticmethod
@once_differentiable
def backward(context, grad_output):
(
value,
value_spatial_shapes,
value_level_start_index,
sampling_locations,
attention_weights,
) = context.saved_tensors
grad_value, grad_sampling_loc, grad_attn_weight = MultiScaleDeformableAttention.ms_deform_attn_backward(
value,
value_spatial_shapes,
value_level_start_index,
sampling_locations,
attention_weights,
grad_output,
context.im2col_step,
)
return grad_value, None, None, grad_sampling_loc, grad_attn_weight, None | 3,388 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
class OmDetTurboMultiscaleDeformableAttention(nn.Module):
"""
Multiscale deformable attention as proposed in Deformable DETR.
"""
def __init__(self, config: OmDetTurboConfig, num_heads: int, n_points: int):
super().__init__()
kernel_loaded = MultiScaleDeformableAttention is not None
if is_torch_cuda_available() and is_ninja_available() and not kernel_loaded:
try:
load_cuda_kernels()
except Exception as e:
logger.warning(f"Could not load the custom kernel for multi-scale deformable attention: {e}") | 3,389 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
if config.d_model % num_heads != 0:
raise ValueError(
f"embed_dim (d_model) must be divisible by num_heads, but got {config.d_model} and {num_heads}"
)
dim_per_head = config.d_model // num_heads
# check if dim_per_head is power of 2
if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0):
warnings.warn(
"You'd better set embed_dim (d_model) in OmDetTurboMultiscaleDeformableAttention to make the"
" dimension of each attention head a power of 2 which is more efficient in the authors' CUDA"
" implementation."
)
self.im2col_step = 64
self.d_model = config.d_model
self.n_levels = config.num_feature_levels
self.n_heads = num_heads
self.n_points = n_points | 3,389 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
self.sampling_offsets = nn.Linear(config.d_model, num_heads * self.n_levels * n_points * 2)
self.attention_weights = nn.Linear(config.d_model, num_heads * self.n_levels * n_points)
self.value_proj = nn.Linear(config.d_model, config.d_model)
self.output_proj = nn.Linear(config.d_model, config.d_model)
self.disable_custom_kernels = config.disable_custom_kernels
def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Optional[Tensor]):
return tensor if position_embeddings is None else tensor + position_embeddings | 3,389 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states=None,
encoder_attention_mask=None,
position_embeddings: Optional[torch.Tensor] = None,
reference_points=None,
spatial_shapes=None,
spatial_shapes_list=None,
level_start_index=None,
output_attentions: bool = False,
):
# add position embeddings to the hidden states before projecting to queries and keys
if position_embeddings is not None:
hidden_states = self.with_pos_embed(hidden_states, position_embeddings) | 3,389 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
batch_size, num_queries, _ = hidden_states.shape
batch_size, sequence_length, _ = encoder_hidden_states.shape
# Ignore copy
total_elements = sum([shape[0] * shape[1] for shape in spatial_shapes_list])
if total_elements != sequence_length:
raise ValueError(
"Make sure to align the spatial shapes with the sequence length of the encoder hidden states"
) | 3,389 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
value = self.value_proj(encoder_hidden_states)
if attention_mask is not None:
# we invert the attention_mask
value = value.masked_fill(~attention_mask[..., None], float(0))
value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
sampling_offsets = self.sampling_offsets(hidden_states).view(
batch_size, num_queries, self.n_heads, self.n_levels, self.n_points, 2
)
attention_weights = self.attention_weights(hidden_states).view(
batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
)
attention_weights = F.softmax(attention_weights, -1).view(
batch_size, num_queries, self.n_heads, self.n_levels, self.n_points
)
# batch_size, num_queries, n_heads, n_levels, n_points, 2
num_coordinates = reference_points.shape[-1]
if num_coordinates == 2: | 3,389 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
sampling_locations = (
reference_points[:, :, None, :, None, :]
+ sampling_offsets / offset_normalizer[None, None, None, :, None, :]
)
elif num_coordinates == 4:
sampling_locations = (
reference_points[:, :, None, :, None, :2]
+ sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
)
else:
raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}") | 3,389 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/omdet_turbo/modeling_omdet_turbo.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.