code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _pad( self, encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding], max_length: Optional[int] = None, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, pad_to_multiple_of: Optional[int] = None, padding_side: Optional[str] = None, return_at...
Args: Pad encoded inputs (on left/right and up to predefined length or max length in the batch) encoded_inputs: Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`). max_length: maximum length of the returned list and opti...
_pad
python
huggingface/transformers
src/transformers/models/markuplm/tokenization_markuplm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/markuplm/tokenization_markuplm.py
Apache-2.0
def to_dict(self) -> Dict[str, Any]: """ Serializes this instance to a Python dictionary. This method calls the superclass method and then removes the `_max_size` attribute from the dictionary. """ image_processor_dict = super().to_dict() image_processor_dict.pop("_max_si...
Serializes this instance to a Python dictionary. This method calls the superclass method and then removes the `_max_size` attribute from the dictionary.
to_dict
python
huggingface/transformers
src/transformers/models/mask2former/image_processing_mask2former.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mask2former/image_processing_mask2former.py
Apache-2.0
def post_process_instance_segmentation( self, outputs, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, target_sizes: Optional[List[Tuple[int, int]]] = None, return_coco_annotation: Optional[bool] = False, retu...
Converts the output of [`Mask2FormerForUniversalSegmentationOutput`] into instance segmentation predictions. Only supports PyTorch. If instances could overlap, set either return_coco_annotation or return_binary_maps to `True` to get the correct segmentation result. Args: ou...
post_process_instance_segmentation
python
huggingface/transformers
src/transformers/models/mask2former/image_processing_mask2former.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mask2former/image_processing_mask2former.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, position_embeddings: Optional[torch.Tensor] = None, reference_points=None, spatial_shapes_list=None, level_start_index=None, output_attentions: bool = False, ): """ ...
Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Input to the layer. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Attention mask. position_embeddings (`torch.Flo...
forward
python
huggingface/transformers
src/transformers/models/mask2former/modeling_mask2former.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mask2former/modeling_mask2former.py
Apache-2.0
def get_reference_points(spatial_shapes_list, valid_ratios, device): """ Get reference points for each feature map. Used in decoder. Args: spatial_shapes_list (`list` of `tuple`): Spatial shapes of the backbone feature maps as a list of tuples. valid_rati...
Get reference points for each feature map. Used in decoder. Args: spatial_shapes_list (`list` of `tuple`): Spatial shapes of the backbone feature maps as a list of tuples. valid_ratios (`torch.FloatTensor`): Valid ratios of each feature map, has ...
get_reference_points
python
huggingface/transformers
src/transformers/models/mask2former/modeling_mask2former.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mask2former/modeling_mask2former.py
Apache-2.0
def forward( self, inputs_embeds=None, attention_mask=None, position_embeddings=None, spatial_shapes_list=None, level_start_index=None, valid_ratios=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r...
Args: inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Flattened feature map (output of the backbone + projection layer) that is passed to the encoder. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *opt...
forward
python
huggingface/transformers
src/transformers/models/mask2former/modeling_mask2former.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mask2former/modeling_mask2former.py
Apache-2.0
def forward( self, inputs_embeds: Optional[torch.Tensor] = None, multi_stage_positional_embeddings: Optional[torch.Tensor] = None, pixel_embeddings: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, query_position_embeddings: Optional[to...
Args: inputs_embeds (`torch.FloatTensor` of shape `(num_queries, batch_size, hidden_size)`): The query embeddings that are passed into the decoder. multi_stage_positional_embeddings (`torch.FloatTensor` of shape `(height*width, batch_size, num_channels)`): ...
forward
python
huggingface/transformers
src/transformers/models/mask2former/modeling_mask2former.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mask2former/modeling_mask2former.py
Apache-2.0
def forward( self, pixel_values: Tensor, mask_labels: Optional[List[Tensor]] = None, class_labels: Optional[List[Tensor]] = None, pixel_mask: Optional[Tensor] = None, output_hidden_states: Optional[bool] = None, output_auxiliary_logits: Optional[bool] = None, ...
mask_labels (`List[torch.Tensor]`, *optional*): List of mask labels of shape `(num_labels, height, width)` to be fed to a model class_labels (`List[torch.LongTensor]`, *optional*): list of target class labels of shape `(num_labels, height, width)` to be fed to a model. They iden...
forward
python
huggingface/transformers
src/transformers/models/mask2former/modeling_mask2former.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mask2former/modeling_mask2former.py
Apache-2.0
def post_process_instance_segmentation( self, outputs, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, target_sizes: Optional[List[Tuple[int, int]]] = None, return_coco_annotation: Optional[bool] = False, retu...
Converts the output of [`MaskFormerForInstanceSegmentationOutput`] into instance segmentation predictions. Only supports PyTorch. If instances could overlap, set either return_coco_annotation or return_binary_maps to `True` to get the correct segmentation result. Args: outp...
post_process_instance_segmentation
python
huggingface/transformers
src/transformers/models/maskformer/image_processing_maskformer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/maskformer/image_processing_maskformer.py
Apache-2.0
def __init__( self, num_labels: int, matcher: MaskFormerHungarianMatcher, weight_dict: Dict[str, float], eos_coef: float, ): """ The MaskFormer Loss. The loss is computed very similar to DETR. The process happens in two steps: 1) we compute hungarian a...
The MaskFormer Loss. The loss is computed very similar to DETR. The process happens in two steps: 1) we compute hungarian assignment between ground truth masks and the outputs of the model 2) we supervise each pair of matched ground-truth / prediction (supervise class and mask) Args: ...
__init__
python
huggingface/transformers
src/transformers/models/maskformer/modeling_maskformer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/maskformer/modeling_maskformer.py
Apache-2.0
def forward( self, masks_queries_logits: Tensor, class_queries_logits: Tensor, mask_labels: List[Tensor], class_labels: List[Tensor], auxiliary_predictions: Optional[Dict[str, Tensor]] = None, ) -> Dict[str, Tensor]: """ This performs the loss computat...
This performs the loss computation. Args: masks_queries_logits (`torch.Tensor`): A tensor of shape `batch_size, num_queries, height, width` class_queries_logits (`torch.Tensor`): A tensor of shape `batch_size, num_queries, num_labels` ...
forward
python
huggingface/transformers
src/transformers/models/maskformer/modeling_maskformer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/maskformer/modeling_maskformer.py
Apache-2.0
def forward( self, pixel_values: Tensor, pixel_mask: Optional[Tensor] = None, output_hidden_states: Optional[bool] = None, output_attentions: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> MaskFormerModelOutput: r""" Examples: ...
Examples: ```python >>> from transformers import AutoImageProcessor, MaskFormerModel >>> from PIL import Image >>> import requests >>> # load MaskFormer fine-tuned on ADE20k semantic segmentation >>> image_processor = AutoImageProcessor.from_pretrained("faceboo...
forward
python
huggingface/transformers
src/transformers/models/maskformer/modeling_maskformer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/maskformer/modeling_maskformer.py
Apache-2.0
def forward( self, pixel_values: Tensor, mask_labels: Optional[List[Tensor]] = None, class_labels: Optional[List[Tensor]] = None, pixel_mask: Optional[Tensor] = None, output_auxiliary_logits: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ...
mask_labels (`List[torch.Tensor]`, *optional*): List of mask labels of shape `(num_labels, height, width)` to be fed to a model class_labels (`List[torch.LongTensor]`, *optional*): list of target class labels of shape `(num_labels, height, width)` to be fed to a model. They iden...
forward
python
huggingface/transformers
src/transformers/models/maskformer/modeling_maskformer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/maskformer/modeling_maskformer.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.LongTensor] = None, head_mask: Optional[torch.Tensor] = None, ...
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__ca...
forward
python
huggingface/transformers
src/transformers/models/mbart/modeling_mbart.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mbart/modeling_mbart.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.FloatTensor] = None, head_mask: Optional[torch.Tensor] = None,...
cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **mas...
forward
python
huggingface/transformers
src/transformers/models/mbart/modeling_mbart.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mbart/modeling_mbart.py
Apache-2.0
def __init__(self, config, add_binary_head=True): r""" add_binary_head (`bool`, *optional*, defaults to `True`): Whether or not to add a binary head. """ super().__init__(config) self.bert = MegatronBertModel(config) self.cls = MegatronBertPreTrainingHeads(co...
add_binary_head (`bool`, *optional*, defaults to `True`): Whether or not to add a binary head.
__init__
python
huggingface/transformers
src/transformers/models/megatron_bert/modeling_megatron_bert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/megatron_bert/modeling_megatron_bert.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, ...
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the ...
forward
python
huggingface/transformers
src/transformers/models/megatron_bert/modeling_megatron_bert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/megatron_bert/modeling_megatron_bert.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, ...
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` ...
forward
python
huggingface/transformers
src/transformers/models/megatron_bert/modeling_megatron_bert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/megatron_bert/modeling_megatron_bert.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, ...
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see `input_ids` docstring). Indices should be in `[0, 1]`: - 0 indicates sequence B is a continuation ...
forward
python
huggingface/transformers
src/transformers/models/megatron_bert/modeling_megatron_bert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/megatron_bert/modeling_megatron_bert.py
Apache-2.0
def transformers_to_megatron_fix_query_key_value_ordering( param, checkpoint_version, num_splits, num_heads, hidden_size ): """ Permutes layout of param tensor to the one compatible with respective NVIDIA Megatron-LM checkpoint versions. Input is [num_splits * num_heads * hidden_size, :] and output is [...
Permutes layout of param tensor to the one compatible with respective NVIDIA Megatron-LM checkpoint versions. Input is [num_splits * num_heads * hidden_size, :] and output is [num_heads * hidden_size * num_splits, :] for version 1.0 and [num_heads * num_splits * hidden_size, :] for version 2.0 and later. I...
transformers_to_megatron_fix_query_key_value_ordering
python
huggingface/transformers
src/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py
Apache-2.0
def forward( self, pixel_values: torch.FloatTensor, output_attentions: Optional[bool] = None, output_a3_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple[torch.FloatTensor], MgpstrModel...
output_a3_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of a3 modules. See `a3_attentions` under returned tensors for more detail. Example: ```python >>> from transformers import ( ... MgpstrProcessor, ... ...
forward
python
huggingface/transformers
src/transformers/models/mgp_str/modeling_mgp_str.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mgp_str/modeling_mgp_str.py
Apache-2.0
def __call__(self, text=None, images=None, return_tensors=None, **kwargs): """ When used in normal mode, this method forwards all its arguments to ViTImageProcessor's [`~ViTImageProcessor.__call__`] and returns its output. This method also forwards the `text` and `kwargs` arguments to Mg...
When used in normal mode, this method forwards all its arguments to ViTImageProcessor's [`~ViTImageProcessor.__call__`] and returns its output. This method also forwards the `text` and `kwargs` arguments to MgpstrTokenizer's [`~MgpstrTokenizer.__call__`] if `text` is not `None` to encode the te...
__call__
python
huggingface/transformers
src/transformers/models/mgp_str/processing_mgp_str.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mgp_str/processing_mgp_str.py
Apache-2.0
def _get_output_length(self, input_length: torch.LongTensor) -> torch.LongTensor: """ Return the length of the output of the MimiConv1d. """ # padding size n_frames = (input_length - self.kernel_size + self.padding_total) / self.stride + 1 n_frames = torch.ceil(n_frames)....
Return the length of the output of the MimiConv1d.
_get_output_length
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def forward( self, hidden_states: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, use_cache: Optional[bool] = None, ...
Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Embedded representation that will be contextualized by the model attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): ...
forward
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def _prepare_4d_causal_attention_mask_with_cache_position( attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, cache_position: torch.Tensor, batch_size: int, config: MimiConfig, past_key_values: Cache, ): ...
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. Args: attention_mask (`torch.Tensor`): A 2D attention mask of sh...
_prepare_4d_causal_attention_mask_with_cache_position
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def encode(self, embeddings: torch.Tensor, num_quantizers: Optional[int] = None) -> torch.Tensor: """ Encode a given input tensor with the specified frame rate at the given number of quantizers / codebooks. The RVQ encode method sets the appropriate number of quantizers to use and returns indice...
Encode a given input tensor with the specified frame rate at the given number of quantizers / codebooks. The RVQ encode method sets the appropriate number of quantizers to use and returns indices for each quantizer.
encode
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def decode(self, codes: torch.Tensor) -> torch.Tensor: """Decode the given codes of shape [B, K, T] to the quantized representation.""" quantized_out = torch.tensor(0.0, device=codes.device) codes = codes.transpose(0, 1) for i, indices in enumerate(codes): layer = self.layers...
Decode the given codes of shape [B, K, T] to the quantized representation.
decode
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def _encode_frame( self, input_values: torch.Tensor, num_quantizers: int, padding_mask: int, past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, return_dict: Optional[bool] = None, ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: """ ...
Encodes the given input using the underlying VQVAE. The padding mask is required to compute the correct scale.
_encode_frame
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def get_encoded_length(self, input_length: torch.LongTensor) -> torch.LongTensor: """ Return the number of frames of the encoded audio waveform. """ output_length = input_length # encoder for layer_name in self.encoder._mimiconv1d_layer_names: output_length =...
Return the number of frames of the encoded audio waveform.
get_encoded_length
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def get_audio_codes_mask(self, padding_mask: torch.Tensor, padding_side: str = "right"): """ Get the mask for the audio codes from the original padding mask. """ encoded_lengths = self.get_encoded_length(padding_mask.sum(dim=-1)) audio_codes_mask = torch.arange(encoded_lengths.m...
Get the mask for the audio codes from the original padding mask.
get_audio_codes_mask
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def encode( self, input_values: torch.Tensor, padding_mask: Optional[torch.Tensor] = None, num_quantizers: Optional[float] = None, encoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple[tor...
Encodes the input audio waveform into discrete codes. Args: input_values (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`): Float values of the input audio waveform. padding_mask (`torch.Tensor` of shape `(batch_size, channels, sequence_length)...
encode
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def decode( self, audio_codes: torch.Tensor, padding_mask: Optional[torch.Tensor] = None, decoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple[torch.Tensor, torch.Tensor], MimiDecoderOutput]: ...
Decodes the given frames into an output audio waveform. Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be trimmed. Args: audio_codes (`torch.LongTensor` of shape `(batch_size, num_quantizers, codes_length)`, *option...
decode
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def forward( self, input_values: torch.Tensor, padding_mask: Optional[torch.Tensor] = None, num_quantizers: Optional[int] = None, audio_codes: Optional[torch.Tensor] = None, encoder_past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, decoder_p...
input_values (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`, *optional*): Raw audio input converted to Float. padding_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Indicates which inputs are to be ignored due to padding, whe...
forward
python
huggingface/transformers
src/transformers/models/mimi/modeling_mimi.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mimi/modeling_mimi.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, position_embeddings: Tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_att...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`): Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`...
forward
python
huggingface/transformers
src/transformers/models/minimax/modeling_minimax.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/minimax/modeling_minimax.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: 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 (`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 ...
forward
python
huggingface/transformers
src/transformers/models/minimax/modeling_minimax.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/minimax/modeling_minimax.py
Apache-2.0
def map_old_key_to_new(old_key): """Map of a key of the original state dict to the equivalent key in HF format""" for pattern, replacement in STATE_DICT_MAPPING.items(): new_key, n_replace = re.subn(pattern, replacement, old_key) # Early exit of the loop if n_replace > 0: ret...
Map of a key of the original state dict to the equivalent key in HF format
map_old_key_to_new
python
huggingface/transformers
src/transformers/models/mistral/convert_mistral_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/convert_mistral_weights_to_hf.py
Apache-2.0
def permute_for_rope(tensor, n_heads, dim1, dim2): """Permute the weights for the ROPE formulation.""" tensor = tensor.view(n_heads, dim1 // n_heads // 2, 2, dim2) tensor = tensor.transpose(1, 2) tensor = tensor.reshape(dim1, dim2) return tensor
Permute the weights for the ROPE formulation.
permute_for_rope
python
huggingface/transformers
src/transformers/models/mistral/convert_mistral_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/convert_mistral_weights_to_hf.py
Apache-2.0
def convert_state_dict(original_state_dict: dict, config: MistralConfig): """Convert a state dict file, when a single `nn.Module` is never sharded in different files (usual case).""" new_dict = {} num_attention_heads = config.num_attention_heads hidden_size = config.hidden_size head_dim = config.he...
Convert a state dict file, when a single `nn.Module` is never sharded in different files (usual case).
convert_state_dict
python
huggingface/transformers
src/transformers/models/mistral/convert_mistral_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/convert_mistral_weights_to_hf.py
Apache-2.0
def get_concat_dim(key): """Return the dimension to concatenate the weights on.""" concat_dim_1 = [ r"model.embed_tokens.weight", r"model.layers.(\d+).self_attn.o_proj.weight", r"model.layers.(\d+).mlp.down_proj.weight", ] if any(re.search(pattern, key) for pattern in concat_dim_...
Return the dimension to concatenate the weights on.
get_concat_dim
python
huggingface/transformers
src/transformers/models/mistral/convert_mistral_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/convert_mistral_weights_to_hf.py
Apache-2.0
def convert_state_dict_sharded(loaded_shards: list[dict], config: MistralConfig): """Convert the state dict, when a single `nn.Module` is sharded across different files.""" new_dict = {} num_shards = len(loaded_shards) n_heads = config.num_attention_heads dim = config.hidden_size dims_per_head...
Convert the state dict, when a single `nn.Module` is sharded across different files.
convert_state_dict_sharded
python
huggingface/transformers
src/transformers/models/mistral/convert_mistral_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/convert_mistral_weights_to_hf.py
Apache-2.0
def convert_and_write_model(input_dir: str, output_dir: str, max_position_embeddings: int, modules_are_split: bool): """Convert the model and save it (this implicitly save the config as well).""" params = read_json(os.path.join(input_dir, "params.json")) config = convert_config(params, max_position_embeddin...
Convert the model and save it (this implicitly save the config as well).
convert_and_write_model
python
huggingface/transformers
src/transformers/models/mistral/convert_mistral_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/convert_mistral_weights_to_hf.py
Apache-2.0
def convert_and_write_tokenizer(input_dir: str, output_dir: str, tokenizer_template_name: str = ""): """Convert the tokenizer and save it.""" # Tekken format if "tekken.json" in os.listdir(input_dir): tokenizer_file = os.path.join(input_dir, "tekken.json") tokenizer = convert_tekken_tokenize...
Convert the tokenizer and save it.
convert_and_write_tokenizer
python
huggingface/transformers
src/transformers/models/mistral/convert_mistral_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/convert_mistral_weights_to_hf.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Opt...
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 ...
forward
python
huggingface/transformers
src/transformers/models/mistral/modeling_mistral.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/modeling_mistral.py
Apache-2.0
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`tf.Tensor`): The query tensor. k (`tf.Tensor`): The key tensor. cos (`tf.Tensor`): The cosine part of the rotary embedding. sin (...
Applies Rotary Position Embedding to the query and key tensors. Args: q (`tf.Tensor`): The query tensor. k (`tf.Tensor`): The key tensor. cos (`tf.Tensor`): The cosine part of the rotary embedding. sin (`tf.Tensor`): The sine part of the rotary embedding. position_ids (`tf.T...
apply_rotary_pos_emb
python
huggingface/transformers
src/transformers/models/mistral/modeling_tf_mistral.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/modeling_tf_mistral.py
Apache-2.0
def call( self, hidden_states: tf.Tensor, attention_mask: Optional[tf.Tensor] = None, position_ids: Optional[tf.Tensor] = None, past_key_value: Optional[Tuple[tf.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, ...
Args: hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`tf.Tensor`, *optional*): attention mask of size `(batch, sequence_length)` where padding elements are indicated by 0. output_attentions (`bool`, *opt...
call
python
huggingface/transformers
src/transformers/models/mistral/modeling_tf_mistral.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/modeling_tf_mistral.py
Apache-2.0
def call( self, input_ids: Optional[tf.Tensor] = None, attention_mask: Optional[tf.Tensor] = None, position_ids: Optional[tf.Tensor] = None, past_key_values: Optional[List[tf.Tensor]] = None, inputs_embeds: Optional[tf.Tensor] = None, labels: Optional[tf.Tensor] =...
labels (`tf.Tensor` 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 (ma...
call
python
huggingface/transformers
src/transformers/models/mistral/modeling_tf_mistral.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/modeling_tf_mistral.py
Apache-2.0
def call( self, input_ids: Optional[tf.Tensor] = None, attention_mask: Optional[tf.Tensor] = None, position_ids: Optional[tf.Tensor] = None, past_key_values: Optional[List[tf.Tensor]] = None, inputs_embeds: Optional[tf.Tensor] = None, labels: Optional[tf.Tensor] =...
labels (`tf.Tensor` 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 (ma...
call
python
huggingface/transformers
src/transformers/models/mistral/modeling_tf_mistral.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral/modeling_tf_mistral.py
Apache-2.0
def get_image_features( self, pixel_values: torch.FloatTensor, image_sizes: torch.Tensor, vision_feature_layer: Optional[Union[int, List[int]]] = None, **kwargs, ): """ Obtains image last hidden states from the vision tower and apply multimodal projection. ...
Obtains image last hidden states from the vision tower and apply multimodal projection. Args: pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`): The tensors corresponding to the input images. vision_feature_layer (`Union[int, Li...
get_image_features
python
huggingface/transformers
src/transformers/models/mistral3/modeling_mistral3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral3/modeling_mistral3.py
Apache-2.0
def forward( self, input_ids: torch.LongTensor = None, pixel_values: torch.FloatTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds:...
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 ...
forward
python
huggingface/transformers
src/transformers/models/mistral3/modeling_mistral3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mistral3/modeling_mistral3.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: 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 (`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 ...
forward
python
huggingface/transformers
src/transformers/models/mixtral/modeling_mixtral.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mixtral/modeling_mixtral.py
Apache-2.0
def get_mlcd_config(model_name: str) -> MLCDVisionConfig: """ Create a configuration for the MLCD model based on the model name. """ assert model_name in COMMON_CONFIG_PARAMS, f"Model {model_name} not found in the list of COMMON_CONFIG_PARAMS." config_params = COMMON_CONFIG_PARAMS[model_name] co...
Create a configuration for the MLCD model based on the model name.
get_mlcd_config
python
huggingface/transformers
src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
Apache-2.0
def get_mlcd_image_processor(model_name: str) -> CLIPImageProcessor: """ Create an image processor for the MLCD model based on the model name. """ assert model_name in COMMON_CONFIG_PARAMS, f"Model {model_name} not found in the list of COMMON_CONFIG_PARAMS." config_params = COMMON_CONFIG_PARAMS[mode...
Create an image processor for the MLCD model based on the model name.
get_mlcd_image_processor
python
huggingface/transformers
src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
Apache-2.0
def flatten_nested_dict(params: dict, parent_key: str = "", sep: str = ".") -> dict: """ Flatten a nested original checkpoint dictionary into a flat dictionary. """ items = [] for k, v in params.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections...
Flatten a nested original checkpoint dictionary into a flat dictionary.
flatten_nested_dict
python
huggingface/transformers
src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
Apache-2.0
def split_resblocks_layers(state_dict: dict) -> dict: """ Split the resblocks weight into layers. In some cases they are concatenated in the original checkpoints. """ # Make shallow copy state_dict = state_dict.copy() # Split resblocks weight into layers keys = list(state_dict.keys()) ...
Split the resblocks weight into layers. In some cases they are concatenated in the original checkpoints.
split_resblocks_layers
python
huggingface/transformers
src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
Apache-2.0
def chunk_qkv_for_attn(state_dict: dict) -> dict: """ Chunk the q/k/v weights and biases for the attention layers. """ # Make shallow copy state_dict = state_dict.copy() # Read and process q/k/v weights and biases keys = list(state_dict.keys()) for key in keys: if ".in_proj." in ...
Chunk the q/k/v weights and biases for the attention layers.
chunk_qkv_for_attn
python
huggingface/transformers
src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
Apache-2.0
def convert_mlcd_checkpoint(model_name, input_dir, output_dir, verify_hidden_state=True, push_to_hub=False): """ Copy/paste/tweak model's weights to our MLCD structure. """ # Define MLCD configuration config = get_mlcd_config(model_name) checkpoint = MODEL_NAME_TO_CHECKPOINT_PATH[model_name] ...
Copy/paste/tweak model's weights to our MLCD structure.
convert_mlcd_checkpoint
python
huggingface/transformers
src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/convert_mlcd_weights_to_hf.py
Apache-2.0
def forward(self, num_patches_height: int, num_patches_width: int) -> torch.Tensor: """ Calculate the Rotary Position Embedding (RoPE) for MLCDVisionModel based on the grid size. Args: num_patches_height (int): Number of patches in the height dimension. num_patches_width...
Calculate the Rotary Position Embedding (RoPE) for MLCDVisionModel based on the grid size. Args: num_patches_height (int): Number of patches in the height dimension. num_patches_width (int): Number of patches in the width dimension. Returns: torch.Tensor: R...
forward
python
huggingface/transformers
src/transformers/models/mlcd/modeling_mlcd.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/modeling_mlcd.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, position_embeddings: Tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ) -> Tuple[torch.FloatTensor]: """ Args: hidden_states...
Args: hidden_states (`torch.FloatTensor`): Input to the layer of shape `(batch, seq_len, embed_dim)`. Represents the hidden states from the previous layer or the input embeddings. position_embeddings (`Tuple[torch.Tensor, torch.Tensor]`): ...
forward
python
huggingface/transformers
src/transformers/models/mlcd/modeling_mlcd.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/modeling_mlcd.py
Apache-2.0
def forward( self, inputs_embeds: torch.FloatTensor, position_embeddings: Tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional...
Args: inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_...
forward
python
huggingface/transformers
src/transformers/models/mlcd/modeling_mlcd.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/modeling_mlcd.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPooling]: r""" Example: ...
Example: ```python >>> import requests >>> from PIL import Image >>> from transformers import AutoProcessor, MLCDVisionModel >>> model = MLCDVisionModel.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14-448") >>> processor = AutoProcessor.from_pretrained("Deep...
forward
python
huggingface/transformers
src/transformers/models/mlcd/modeling_mlcd.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mlcd/modeling_mlcd.py
Apache-2.0
def pre_compute_positional_embedding(embedding): """ Instead of iterating of the batch of images, and the ratios inside, we pre-compute the positional embeddings depending on the aspect ratio id. This is done to support `torch.compile` and efficient inference / training with different aspect ratios. ...
Instead of iterating of the batch of images, and the ratios inside, we pre-compute the positional embeddings depending on the aspect ratio id. This is done to support `torch.compile` and efficient inference / training with different aspect ratios.
pre_compute_positional_embedding
python
huggingface/transformers
src/transformers/models/mllama/convert_mllama_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/convert_mllama_weights_to_hf.py
Apache-2.0
def is_param_different_across_shards(key): """ Return `True` if the parameter is different across checkpoint shards and needs to be concatenated. """ patterns = [r"vision_model.patch_embedding.weight",r"vision_model.(transformer|global_transformer).layers.(\d+).self_attn.(q|k|v|o)_proj.weight",r"vis...
Return `True` if the parameter is different across checkpoint shards and needs to be concatenated.
is_param_different_across_shards
python
huggingface/transformers
src/transformers/models/mllama/convert_mllama_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/convert_mllama_weights_to_hf.py
Apache-2.0
def interpolate_positional_embedding( embeddings: torch.Tensor, vision_tile_size: int, vision_patch_size: int ) -> torch.Tensor: """ This method allows to interpolate the pre-trained position embeddings, to be able to use the model on higher resolution images. """ cls_embedding, positional_embed...
This method allows to interpolate the pre-trained position embeddings, to be able to use the model on higher resolution images.
interpolate_positional_embedding
python
huggingface/transformers
src/transformers/models/mllama/convert_mllama_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/convert_mllama_weights_to_hf.py
Apache-2.0
def get_all_supported_aspect_ratios(max_image_tiles: int) -> List[Tuple[int, int]]: """ Computes all allowed aspect ratios for a given maximum number of input tiles. This function calculates all possible arrangements of tiles that can be formed within the constraint of the maximum number of tiles. Each...
Computes all allowed aspect ratios for a given maximum number of input tiles. This function calculates all possible arrangements of tiles that can be formed within the constraint of the maximum number of tiles. Each arrangement is represented by its aspect ratio (width/height) and the corresponding ti...
get_all_supported_aspect_ratios
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
def get_image_size_fit_to_canvas( image_height: int, image_width: int, canvas_height: int, canvas_width: int, tile_size: int, ) -> Tuple[int, int]: """ Calculates the new size of an image to fit within a canvas while maintaining aspect ratio. This function calculates the optimal size fo...
Calculates the new size of an image to fit within a canvas while maintaining aspect ratio. This function calculates the optimal size for an image to fit within a canvas defined by canvas_height and canvas_width, while ensuring that the image dimensions are not smaller than tile_size. If the image is l...
get_image_size_fit_to_canvas
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
def split_to_tiles(image: np.ndarray, num_tiles_height: int, num_tiles_width: int) -> np.ndarray: """ Split an image into a specified number of tiles along its width and height dimensions. Args: image (`np.ndarray`): Input image with shape (num_channels, height, width). num_tile...
Split an image into a specified number of tiles along its width and height dimensions. Args: image (`np.ndarray`): Input image with shape (num_channels, height, width). num_tiles_height (`int`): Number of tiles to split the image into along its height. num_tiles...
split_to_tiles
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
def build_aspect_ratio_mask(aspect_ratios: List[List[Tuple[int, int]]], max_image_tiles: int) -> np.ndarray: """ Builds a mask for the aspect ratios of the images. Args: aspect_ratios (`List[List[Tuple[int, int]]]`): A list of lists containing aspect ratios for each image in the batch. ...
Builds a mask for the aspect ratios of the images. Args: aspect_ratios (`List[List[Tuple[int, int]]]`): A list of lists containing aspect ratios for each image in the batch. Each aspect ratio is represented as a tuple of (width, height) in terms of number of tiles. max_...
build_aspect_ratio_mask
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
def pack_images( batch_images: List[List[np.ndarray]], max_image_tiles: int, ) -> Tuple[np.ndarray, List[List[int]]]: """ Stack a list of lists of images with variable lengths into a numpy array, applying zero padding as needed. Each list in the input represents a batch sample, and each image within...
Stack a list of lists of images with variable lengths into a numpy array, applying zero padding as needed. Each list in the input represents a batch sample, and each image within a list is expected to be pre-split into tiles. The resulting array will have a shape of (batch_size, max_num_images, max_ima...
pack_images
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
def pack_aspect_ratios(aspect_ratios: List[List[Tuple[int, int]]], pad_value: int = 1) -> np.ndarray: """ Stack a list of aspect ratios into a numpy array. Args: aspect_ratios (`List[List[Tuple[int, int]]]`): A list of aspect ratios. pad_value (`int`, *optional*, defaults to 1):...
Stack a list of aspect ratios into a numpy array. Args: aspect_ratios (`List[List[Tuple[int, int]]]`): A list of aspect ratios. pad_value (`int`, *optional*, defaults to 1): The value to pad the aspect ratios with. Returns: `np.ndarray`: The asp...
pack_aspect_ratios
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
def convert_aspect_ratios_to_ids(aspect_ratios: List[List[Tuple[int, int]]], max_image_tiles: int) -> np.ndarray: """ Convert aspect ratio tuples to unique ids. For batch padding we use 0, because there might be different number of images in each batch. The aspect ratio ids start from 1, with 1 corresp...
Convert aspect ratio tuples to unique ids. For batch padding we use 0, because there might be different number of images in each batch. The aspect ratio ids start from 1, with 1 corresponding to the first supported aspect ratio. Args: aspect_ratios (`List[List[Tuple[int, int]]]`): ...
convert_aspect_ratios_to_ids
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
def to_channel_dimension_format( image: np.ndarray, channel_dim: Union[ChannelDimension, str], input_channel_dim: Optional[Union[ChannelDimension, str]] = None, ) -> np.ndarray: """ Converts `image` to the channel dimension format specified by `channel_dim`. Args: image (`numpy.ndarray`...
Converts `image` to the channel dimension format specified by `channel_dim`. Args: image (`numpy.ndarray`): The image to have its channel dimension set. channel_dim (`ChannelDimension`): The channel dimension format to use. input_channel_dim (`ChannelDimension`,...
to_channel_dimension_format
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
def preprocess( self, images: ImageInput, do_convert_rgb: Optional[bool] = None, do_resize: Optional[bool] = None, size: Optional[Dict[str, int]] = None, resample: Optional[PILImageResampling] = None, do_rescale: Optional[bool] = None, rescale_factor: Opti...
Preprocess a batch of images. Args: images (`ImageInput`): A list of images to preprocess. do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`): Whether to convert the image to RGB. do_resize (`bool`, *optional*, def...
preprocess
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
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...
Pad an image to the `size` x `aspect_ratio`. For example, if size is {height: 224, width: 224} and aspect ratio is (1, 2), the image will be padded to 224x448. Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Size of ...
pad
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
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...
Resizes an image to fit within a tiled canvas while maintaining its aspect ratio. The optimal canvas size is calculated based on the maximum number of tiles and the tile size. The function first determines the best tile arrangement for the image, then resizes the image to fit within th...
resize
python
huggingface/transformers
src/transformers/models/mllama/image_processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/image_processing_mllama.py
Apache-2.0
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[BaseModelOutpu...
aspect_ratio_ids (`torch.Tensor` of shape `(batch_size, max_num_images)`, *optional*): Aspect ratio ids used to select the appropriate precomputed tile embeddings based on the aspect ratio of each input image. These ids correspond to indices in the model's list of supported aspect ratio...
forward
python
huggingface/transformers
src/transformers/models/mllama/modeling_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/modeling_mllama.py
Apache-2.0
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...
cross_attention_states (`torch.FloatTensor`, *optional*): Output of the vision model, used for cross-attention. This tensor contains the processed image features that the language model will attend to. cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_n...
forward
python
huggingface/transformers
src/transformers/models/mllama/modeling_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/modeling_mllama.py
Apache-2.0
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.LongTensor] = None, cross_attention_mask: Optional[torch.LongTensor] = N...
cross_attention_states (`torch.FloatTensor`, *optional*): Output of the vision model, used for cross-attention. This tensor contains the processed image features that the language model will attend to. cross_attention_mask (`torch.Tensor` of shape `(batch_size, seq_length, max_n...
forward
python
huggingface/transformers
src/transformers/models/mllama/modeling_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/modeling_mllama.py
Apache-2.0
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, cro...
aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*): Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`: - 1 for tiles that are **not masked**, - 0 for tiles that are **masked**. as...
forward
python
huggingface/transformers
src/transformers/models/mllama/modeling_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/modeling_mllama.py
Apache-2.0
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, cro...
aspect_ratio_mask (`torch.Tensor` of shape `(batch_size, max_num_images, max_num_tiles)`, *optional*): Mask to avoid performing attention on padding tiles. Mask values selected in `[0, 1]`: - 1 for tiles that are **not masked**, - 0 for tiles that are **masked**. as...
forward
python
huggingface/transformers
src/transformers/models/mllama/modeling_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/modeling_mllama.py
Apache-2.0
def get_cross_attention_token_mask(input_ids: List[int], image_token_id: int) -> List[List[int]]: """ Generate a cross-attention token mask for image tokens in the input sequence. This function identifies the positions of image tokens in the input sequence and creates a mask that defines which subseque...
Generate a cross-attention token mask for image tokens in the input sequence. This function identifies the positions of image tokens in the input sequence and creates a mask that defines which subsequent tokens each image token should attend to. Args: input_ids (List[int]): A list of token id...
get_cross_attention_token_mask
python
huggingface/transformers
src/transformers/models/mllama/processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/processing_mllama.py
Apache-2.0
def convert_sparse_cross_attention_mask_to_dense( cross_attention_token_mask: List[List[List[int]]], num_tiles: List[List[int]], max_num_tiles: int, length: int, ) -> np.ndarray: """ Convert the cross attention mask indices to a cross attention mask 4D array. This function takes a sparse re...
Convert the cross attention mask indices to a cross attention mask 4D array. This function takes a sparse representation of cross attention masks and converts it to a dense 4D numpy array. The sparse representation is a nested list structure that defines attention ranges for each image in each batch item....
convert_sparse_cross_attention_mask_to_dense
python
huggingface/transformers
src/transformers/models/mllama/processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/processing_mllama.py
Apache-2.0
def build_string_from_input(prompt: str, bos_token: str, image_token: str) -> str: """ Builds a string from the input prompt by adding `bos_token` if not already present. Args: prompt (`str`): The input prompt string. bos_token (`str`): The beginning of sentence toke...
Builds a string from the input prompt by adding `bos_token` if not already present. Args: prompt (`str`): The input prompt string. bos_token (`str`): The beginning of sentence token to be added. image_token (`str`): The image token used to identify t...
build_string_from_input
python
huggingface/transformers
src/transformers/models/mllama/processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/processing_mllama.py
Apache-2.0
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...
Main method to prepare text(s) and image(s) to be fed as input to the model. This method forwards the `text` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] if `text` is not `None` to encode the text. To prepare the image(s), this method forwards the `images` argume...
__call__
python
huggingface/transformers
src/transformers/models/mllama/processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/processing_mllama.py
Apache-2.0
def post_process_image_text_to_text( self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs ): """ Post-process the output of the model to decode the text. Args: generated_outputs (`torch.Tensor` or `np.ndarray`): ...
Post-process the output of the model to decode the text. 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_lengt...
post_process_image_text_to_text
python
huggingface/transformers
src/transformers/models/mllama/processing_mllama.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mllama/processing_mllama.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, ...
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the ...
forward
python
huggingface/transformers
src/transformers/models/mobilebert/modeling_mobilebert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilebert/modeling_mobilebert.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None, ...
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair (see `input_ids` docstring) Indices should be in `[0, 1]`. - 0 indicates sequence B is a continuation o...
forward
python
huggingface/transformers
src/transformers/models/mobilebert/modeling_mobilebert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilebert/modeling_mobilebert.py
Apache-2.0
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A MobileBERT sequence pair mask has the following format:...
Create a mask from the two sequences passed to be used in a sequence-pair classification task. A MobileBERT sequence pair mask has the following format: ``` 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second sequence | ``` If `token_ids_1` is ...
create_token_type_ids_from_sequences
python
huggingface/transformers
src/transformers/models/mobilebert/tokenization_mobilebert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilebert/tokenization_mobilebert.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, SemanticSegmenterOutput]: r""" labels (`torch.LongTensor` ...
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*): Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy). ...
forward
python
huggingface/transformers
src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilenet_v2/modeling_mobilenet_v2.py
Apache-2.0
def preprocess( self, images: ImageInput, segmentation_maps: Optional[ImageInput] = None, do_resize: Optional[bool] = None, size: Optional[Dict[str, int]] = None, resample: PILImageResampling = None, do_rescale: Optional[bool] = None, rescale_factor: Optio...
Preprocess an image or batch of images. Args: images (`ImageInput`): Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`. ...
preprocess
python
huggingface/transformers
src/transformers/models/mobilevit/image_processing_mobilevit.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilevit/image_processing_mobilevit.py
Apache-2.0
def post_process_semantic_segmentation(self, outputs, target_sizes: Optional[List[Tuple]] = None): """ Converts the output of [`MobileViTForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch. Args: outputs ([`MobileViTForSemanticSegmentation`]): ...
Converts the output of [`MobileViTForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch. Args: outputs ([`MobileViTForSemanticSegmentation`]): Raw outputs of the model. target_sizes (`List[Tuple]` of length `batch_size`, *optional*): ...
post_process_semantic_segmentation
python
huggingface/transformers
src/transformers/models/mobilevit/image_processing_mobilevit.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilevit/image_processing_mobilevit.py
Apache-2.0
def __init__(self, config: MobileViTConfig, expand_output: bool = True): r""" expand_output (`bool`, *optional*, defaults to `True`): Whether to expand the output of the model using a 1x1 convolution. If `True`, the model will apply an additional 1x1 convolution to expand the out...
expand_output (`bool`, *optional*, defaults to `True`): Whether to expand the output of the model using a 1x1 convolution. If `True`, the model will apply an additional 1x1 convolution to expand the output channels from `config.neck_hidden_sizes[5]` to `config.neck_hidden_sizes[6]`. ...
__init__
python
huggingface/transformers
src/transformers/models/mobilevit/modeling_mobilevit.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilevit/modeling_mobilevit.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, SemanticSegmenterOutput]: r""" labels (`torch.LongTensor` ...
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*): Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy). ...
forward
python
huggingface/transformers
src/transformers/models/mobilevit/modeling_mobilevit.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilevit/modeling_mobilevit.py
Apache-2.0
def __init__(self, config: MobileViTV2Config, expand_output: bool = True): r""" expand_output (`bool`, *optional*, defaults to `True`): Whether to expand the output of the model. If `True`, the model will output pooled features in addition to hidden states. If `False`, only the h...
expand_output (`bool`, *optional*, defaults to `True`): Whether to expand the output of the model. If `True`, the model will output pooled features in addition to hidden states. If `False`, only the hidden states will be returned.
__init__
python
huggingface/transformers
src/transformers/models/mobilevitv2/modeling_mobilevitv2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilevitv2/modeling_mobilevitv2.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, SemanticSegmenterOutput]: r""" labels (`torch.LongTensor` ...
labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*): Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy). ...
forward
python
huggingface/transformers
src/transformers/models/mobilevitv2/modeling_mobilevitv2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/mobilevitv2/modeling_mobilevitv2.py
Apache-2.0
def apply_rotary_unpadded( qkv, cos, sin, cu_seqlens: Optional[torch.Tensor] = None, max_seqlen: Optional[int] = None, ): """ Arguments: qkv: (total_nnz, 3, nheads, headdim) - input tensor for packed QKV. cos, sin: (seqlen_rotary, rotary_dim / 2) interleaved: if True,...
Arguments: qkv: (total_nnz, 3, nheads, headdim) - input tensor for packed QKV. cos, sin: (seqlen_rotary, rotary_dim / 2) interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of 1st half and 2nd half (GPT-NeoX style). inplace: if True, apply...
apply_rotary_unpadded
python
huggingface/transformers
src/transformers/models/modernbert/modeling_modernbert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/modernbert/modeling_modernbert.py
Apache-2.0
def __init__( self, dim: int, base: float = 10000.0, max_seqlen: Optional[int] = None, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None, ): """ max_seqlen: if max_seqlen, device, and dtype are provided, we precompute the cos_s...
max_seqlen: if max_seqlen, device, and dtype are provided, we precompute the cos_sin_cache up to max_seqlen. If the max_seqlen, device, or dtype during training/inference differ, the cos_sin_cache will be recomputed during the forward pass.
__init__
python
huggingface/transformers
src/transformers/models/modernbert/modeling_modernbert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/modernbert/modeling_modernbert.py
Apache-2.0
def forward( self, qkv: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: Optional[int] = None, ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: """ Apply rotary embedding *inplace* to qkv. qkv: (total_nnz, 3, nheads, headdim) cu_seqlens:...
Apply rotary embedding *inplace* to qkv. qkv: (total_nnz, 3, nheads, headdim) cu_seqlens: (batch + 1,) cumulative sequence lengths max_seqlen: int max seq length in the batch
forward
python
huggingface/transformers
src/transformers/models/modernbert/modeling_modernbert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/modernbert/modeling_modernbert.py
Apache-2.0
def _unpad_modernbert_input( inputs: torch.Tensor, attention_mask: torch.Tensor, position_ids: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, Optional[torch.Tensor], Optional[torch.Tensor]]: """ Remove padding from ...
Remove padding from input sequences. Args: inputs: (batch, seqlen, ...) or (batch, seqlen) attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid. position_ids: (batch, seqlen), int, position ids labels: (batch, seqlen), int, labels Returns: ...
_unpad_modernbert_input
python
huggingface/transformers
src/transformers/models/modernbert/modeling_modernbert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/modernbert/modeling_modernbert.py
Apache-2.0
def _pad_modernbert_output( inputs: torch.Tensor, indices: torch.Tensor, batch: int, seqlen: int, ) -> torch.Tensor: """ Add padding to sequences. Args: inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask. indices: (total_n...
Add padding to sequences. Args: inputs: (total_nnz, ...) or (total_nnz,), where total_nnz = number of tokens selected in attention_mask. indices: (total_nnz) batch: int, batch size seqlen: int, max sequence length Returns: padded_inputs: (batch, seqlen, ...) or (ba...
_pad_modernbert_output
python
huggingface/transformers
src/transformers/models/modernbert/modeling_modernbert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/modernbert/modeling_modernbert.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, sliding_window_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, inputs_embeds: Optional[torch.Tensor] = None, indic...
sliding_window_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding or far-away tokens. In ModernBert, only every few layers perform global attention, while the rest perform local attention. This mask is used to avoid ...
forward
python
huggingface/transformers
src/transformers/models/modernbert/modeling_modernbert.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/modernbert/modeling_modernbert.py
Apache-2.0