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 preprocess( self, images: ImageInput, segmentation_maps: Optional[ImageInput] = None, do_resize: Optional[bool] = None, size: Optional[Dict[str, int]] = None, mask_size: Optional[Dict[str, int]] = None, resample: Optional["PILImageResampling"] = None, ...
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/sam/image_processing_sam.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam/image_processing_sam.py
Apache-2.0
def filter_masks( self, masks, iou_scores, original_size, cropped_box_image, pred_iou_thresh=0.88, stability_score_thresh=0.95, mask_threshold=0, stability_score_offset=1, return_tensors="pt", ): """ Filters the predicte...
Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability score needs to be greater than `stability_score_thresh`. The method also conve...
filter_masks
python
huggingface/transformers
src/transformers/models/sam/image_processing_sam.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam/image_processing_sam.py
Apache-2.0
def _filter_masks_pt( self, masks, iou_scores, original_size, cropped_box_image, pred_iou_thresh=0.88, stability_score_thresh=0.95, mask_threshold=0, stability_score_offset=1, ): """ Filters the predicted masks by selecting only...
Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability score needs to be greater than `stability_score_thresh`. The method also conve...
_filter_masks_pt
python
huggingface/transformers
src/transformers/models/sam/image_processing_sam.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam/image_processing_sam.py
Apache-2.0
def _filter_masks_tf( self, masks, iou_scores, original_size, cropped_box_image, pred_iou_thresh=0.88, stability_score_thresh=0.95, mask_threshold=0, stability_score_offset=1, ): """ Filters the predicted masks by selecting only...
Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability score needs to be greater than `stability_score_thresh`. The method also conve...
_filter_masks_tf
python
huggingface/transformers
src/transformers/models/sam/image_processing_sam.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam/image_processing_sam.py
Apache-2.0
def get_image_embeddings( self, pixel_values, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ): r""" Returns the image embeddings by passing the pixel values through the vision encoder. Args: pixel_values (`...
Returns the image embeddings by passing the pixel values through the vision encoder. Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Input pixel values output_attentions (`bool`, *optional*): Whether...
get_image_embeddings
python
huggingface/transformers
src/transformers/models/sam/modeling_sam.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam/modeling_sam.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.FloatTensor] = None, input_points: Optional[torch.FloatTensor] = None, input_labels: Optional[torch.LongTensor] = None, input_boxes: Optional[torch.FloatTensor] = None, input_masks: Optional[torch.LongTensor] = None, ...
input_points (`torch.FloatTensor` of shape `(batch_size, num_points, 2)`): Input 2D spatial points, this is used by the prompt encoder to encode the prompt. Generally yields to much better results. The points can be obtained by passing a list of list of list to the processor that will ...
forward
python
huggingface/transformers
src/transformers/models/sam/modeling_sam.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam/modeling_sam.py
Apache-2.0
def get_decomposed_rel_pos( self, query: tf.Tensor, rel_pos_h: tf.Tensor, rel_pos_w: tf.Tensor, q_size: Tuple[int, int], k_size: Tuple[int, int], ) -> tf.Tensor: """ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. http...
Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py Args: query (`tf.Tensor`): query q in the attention layer with shape (batch_size...
get_decomposed_rel_pos
python
huggingface/transformers
src/transformers/models/sam/modeling_tf_sam.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam/modeling_tf_sam.py
Apache-2.0
def __init__(self, config, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False): """ A transformer block with four layers: (1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on sparse inputs (4) cross attention...
A transformer block with four layers: (1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on sparse inputs (4) cross attention of dense inputs -> sparse inputs Arguments: config (`SamHQMaskDecoderConfig`): ...
__init__
python
huggingface/transformers
src/transformers/models/sam_hq/modeling_sam_hq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam_hq/modeling_sam_hq.py
Apache-2.0
def forward( self, image_embeddings: torch.Tensor, image_positional_embeddings: torch.Tensor, sparse_prompt_embeddings: torch.Tensor, dense_prompt_embeddings: torch.Tensor, multimask_output: bool, hq_token_only: bool, intermediate_embeddings: Optional[List...
Predict high-quality masks given image and prompt embeddings. Args: image_embeddings (`torch.Tensor`): The embeddings from the image encoder. image_positional_embedding (`torch.Tensor`): Positional encoding with the shape of image_embeddings. ...
forward
python
huggingface/transformers
src/transformers/models/sam_hq/modeling_sam_hq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam_hq/modeling_sam_hq.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.FloatTensor] = None, input_points: Optional[torch.FloatTensor] = None, input_labels: Optional[torch.LongTensor] = None, input_boxes: Optional[torch.FloatTensor] = None, input_masks: Optional[torch.LongTensor] = None, ...
input_points (`torch.FloatTensor` of shape `(batch_size, num_points, 2)`): Input 2D spatial points, this is used by the prompt encoder to encode the prompt. Generally yields to much better results. The points can be obtained by passing a list of list of list to the processor that will ...
forward
python
huggingface/transformers
src/transformers/models/sam_hq/modeling_sam_hq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam_hq/modeling_sam_hq.py
Apache-2.0
def _normalize_and_convert( self, encoding_image_processor, original_sizes, input_points=None, input_labels=None, input_boxes=None, return_tensors="pt", point_pad_value=-10, ): """ Normalize and convert the image processor output to the...
Normalize and convert the image processor output to the expected format.
_normalize_and_convert
python
huggingface/transformers
src/transformers/models/sam_hq/processing_samhq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam_hq/processing_samhq.py
Apache-2.0
def _normalize_coordinates( self, target_size: int, coords: np.ndarray, original_size, is_bounding_box=False ) -> np.ndarray: """ Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H,W) format. """ old_h, old_w = original_size ...
Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H,W) format.
_normalize_coordinates
python
huggingface/transformers
src/transformers/models/sam_hq/processing_samhq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam_hq/processing_samhq.py
Apache-2.0
def _preprocess_input(self, inputs, error_message, expected_nesting=1, dtype=None): """ Preprocess input by converting torch tensors to numpy arrays and validating structure. Args: inputs: The input to process error_message: Error message if validation fails ...
Preprocess input by converting torch tensors to numpy arrays and validating structure. Args: inputs: The input to process error_message: Error message if validation fails expected_nesting: Expected nesting level (1 for points/labels, 2 for boxes) dtype: ...
_preprocess_input
python
huggingface/transformers
src/transformers/models/sam_hq/processing_samhq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam_hq/processing_samhq.py
Apache-2.0
def _to_tensor(self, array, min_dim, return_tensors): """ Convert numpy array to tensor and ensure proper dimensionality. Args: array: The numpy array to convert min_dim: The minimum number of dimensions the result should have return_tensors: The type of tenso...
Convert numpy array to tensor and ensure proper dimensionality. Args: array: The numpy array to convert min_dim: The minimum number of dimensions the result should have return_tensors: The type of tensors to return (e.g., "pt" for PyTorch tensors) Returns: ...
_to_tensor
python
huggingface/transformers
src/transformers/models/sam_hq/processing_samhq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam_hq/processing_samhq.py
Apache-2.0
def _normalize_batch_coordinates(self, inputs, original_sizes, is_bounding_box=False): """ Normalize coordinates based on original sizes. Args: inputs: List of coordinate arrays original_sizes: Original sizes of the images is_bounding_box: Whether inputs are b...
Normalize coordinates based on original sizes. Args: inputs: List of coordinate arrays original_sizes: Original sizes of the images is_bounding_box: Whether inputs are bounding boxes Returns: Normalized coordinates as list
_normalize_batch_coordinates
python
huggingface/transformers
src/transformers/models/sam_hq/processing_samhq.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sam_hq/processing_samhq.py
Apache-2.0
def __call__( self, raw_speech: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]], padding: Union[bool, str, PaddingStrategy] = True, pad_to_multiple_of: Optional[int] = 2, max_length: Optional[int] = None, truncation: bool = False, return_tensor...
Main method to featurize and prepare for the model one or several sequence(s). Args: raw_speech (`np.ndarray`, `torch.Tensor`, `List[float]`, `List[np.ndarray]`, `List[torch.Tensor]`, `List[List[float]]`, `List[List[List[float]]]`): The sequence or batch of sequ...
__call__
python
huggingface/transformers
src/transformers/models/seamless_m4t/feature_extraction_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/feature_extraction_seamless_m4t.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool = False, ) -> torch.Tensor: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` ...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very l...
forward
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very l...
forward
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def __init__( self, config: SeamlessM4TConfig, embed_tokens: Optional[nn.Embedding] = None, is_t2u_encoder: bool = False, ): r""" embed_tokens (`nn.Embedding`, *optional*): Input embedding is_t2u_encoder (`bool`, *optional*, defaults to `False`): ...
embed_tokens (`nn.Embedding`, *optional*): Input embedding is_t2u_encoder (`bool`, *optional*, defaults to `False`): indicates if it belongs to the text-to-units model, in which case it won't have input embeddings
__init__
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: O...
Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTra...
forward
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def __init__( self, config: SeamlessM4TConfig, embed_tokens_decoder: Optional[nn.Embedding] = None, ): r""" embed_tokens_decoder (`nn.Embedding`, *optional*): input embedding of the decoder. """ super().__init__(config) self.encoder = Seam...
embed_tokens_decoder (`nn.Embedding`, *optional*): input embedding of the decoder.
__init__
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def generate( self, input_ids=None, tgt_lang=None, generation_config=None, logits_processor=None, stopping_criteria=None, prefix_allowed_tokens_fn=None, synced_gpus=False, **kwargs, ): """ Generates sequences of token ids. ...
Generates sequences of token ids. <Tip warning={true}> Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the model's default generation configuration. You can override any `generation_config` by passing the corresponding ...
generate
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def generate( self, input_features=None, tgt_lang=None, generation_config=None, logits_processor=None, stopping_criteria=None, prefix_allowed_tokens_fn=None, synced_gpus=False, **kwargs, ): """ Generates sequences of token ids. ...
Generates sequences of token ids. <Tip warning={true}> Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the model's default generation configuration. You can override any `generation_config` by passing the corresponding ...
generate
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def generate( self, input_ids: Optional[torch.Tensor] = None, return_intermediate_token_ids: Optional[bool] = None, tgt_lang: Optional[str] = None, spkr_id: Optional[int] = 0, **kwargs, ) -> Union[torch.Tensor, SeamlessM4TGenerationOutput]: """ Generat...
Generates translated audio waveforms. <Tip> This method successively calls the `.generate` function of two different sub-models. You can specify keyword arguments at two different levels: general arguments that will be passed to both models, or prefixed arguments that will be ...
generate
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def generate( self, input_features: Optional[torch.Tensor] = None, return_intermediate_token_ids: Optional[bool] = None, tgt_lang: Optional[str] = None, spkr_id: Optional[int] = 0, **kwargs, ) -> Union[torch.Tensor, SeamlessM4TGenerationOutput]: """ Ge...
Generates translated audio waveforms. <Tip> This method successively calls the `.generate` function of two different sub-models. You can specify keyword arguments at two different levels: general arguments that will be passed to both models, or prefixed arguments that will be ...
generate
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def __init__(self, config, current_modality="text"): r""" current_modality (`str`, *optional*, defaults to `"text"`): Default modality. Used to initialize the model. """ super().__init__(config) self.shared = nn.Embedding(config.vocab_size, config.hidden_size, config...
current_modality (`str`, *optional*, defaults to `"text"`): Default modality. Used to initialize the model.
__init__
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def generate( self, input_ids: Optional[torch.Tensor] = None, input_features: Optional[torch.Tensor] = None, return_intermediate_token_ids: Optional[bool] = None, tgt_lang: Optional[str] = None, spkr_id: Optional[int] = 0, generate_speech: Optional[bool] = True, ...
Generates translated token ids and/or translated audio waveforms. <Tip> This method successively calls the `.generate` function of two different sub-models. You can specify keyword arguments at two different levels: general arguments that will be passed to both models, or prefixed arg...
generate
python
huggingface/transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
Apache-2.0
def __call__(self, text=None, audios=None, src_lang=None, tgt_lang=None, **kwargs): """ Main method to prepare for the model one or several sequences(s) and audio(s). This method forwards the `text` and `kwargs` arguments to SeamlessM4TTokenizerFast's [`~SeamlessM4TTokenizerFast.__call__`] if `t...
Main method to prepare for the model one or several sequences(s) and audio(s). This method forwards the `text` and `kwargs` arguments to SeamlessM4TTokenizerFast's [`~SeamlessM4TTokenizerFast.__call__`] if `text` is not `None` to encode the text. To prepare the audio(s), this method forwards th...
__call__
python
huggingface/transformers
src/transformers/models/seamless_m4t/processing_seamless_m4t.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t/processing_seamless_m4t.py
Apache-2.0
def load_model(save_dir, model_type, repo_id): """ Meta SeamlessM4Tv2 is made of 8 main components: - speech_encoder (#1) and speech_encoder_frontend (#2) - t2u_model (#3) - text_encoder (#4) and text_encoder_frontend (#5) - text_decoder (#6) [and text_decoder_frontend (#5) = equals to text_enco...
Meta SeamlessM4Tv2 is made of 8 main components: - speech_encoder (#1) and speech_encoder_frontend (#2) - t2u_model (#3) - text_encoder (#4) and text_encoder_frontend (#5) - text_decoder (#6) [and text_decoder_frontend (#5) = equals to text_encoder_frontend] - final_proj (#7) - vocoder (#8)...
load_model
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/convert_fairseq2_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/convert_fairseq2_to_hf.py
Apache-2.0
def format_speech_generation_kwargs(kwargs): """ Format kwargs for SeamlessM4Tv2 models that generate speech, attribute kwargs to either the text generation or the speech generation models. Args: kwargs (`dict`)`: Keyword arguments are of two types: - Without a pre...
Format kwargs for SeamlessM4Tv2 models that generate speech, attribute kwargs to either the text generation or the speech generation models. Args: kwargs (`dict`)`: Keyword arguments are of two types: - Without a prefix, they will be entered as `**kwargs` for the `gen...
format_speech_generation_kwargs
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def _apply_chunk_attention(self, attention_mask, hidden_states): """ Creates a chunk attention mask. It creates a mask to prevent attention across chunks, ensuring that each position attends only to positions within its own chunk. If a left chunk overlap is specified (`speech_encoder_chu...
Creates a chunk attention mask. It creates a mask to prevent attention across chunks, ensuring that each position attends only to positions within its own chunk. If a left chunk overlap is specified (`speech_encoder_chunk_size` in the configuration), the attention mask is adjusted accordingly t...
_apply_chunk_attention
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, padding_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ) -> torch.Tensor: """ Args: hidden_states (`torch.FloatTensor`):...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very l...
forward
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def _indices_to_subwords(self, input_ids): """ Returns the corresponding text string for each input id. """ if not hasattr(self.generation_config, "id_to_text"): raise ValueError( """This model generation config doesn't have a `id_to_text` key which maps ...
Returns the corresponding text string for each input id.
_indices_to_subwords
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def _get_char_input_ids(self, input_ids, subwords_batch, char_count_per_id, pad_token_id=0, unk_token_id=1): """ Returns the corresponding character input id for each character of `subwords_batch`. Args: input_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`): ...
Returns the corresponding character input id for each character of `subwords_batch`. Args: input_ids (`torch.Tensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. subwords_batch (`List[List[str]]` of shape `(batch...
_get_char_input_ids
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def _hard_upsample(self, hidden_states, durations): """ Repeats the time dimension of each sample in the batch based on the corresponding duration. Args: hidden_states (`torch.Tensor` of shape `(batch_size, sequence_length, *)`, *optional*): The sequence to repeat, w...
Repeats the time dimension of each sample in the batch based on the corresponding duration. Args: hidden_states (`torch.Tensor` of shape `(batch_size, sequence_length, *)`, *optional*): The sequence to repeat, where `*` is any number of sequence-specific dimensions includin...
_hard_upsample
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def forward( self, char_input_ids: Optional[torch.LongTensor] = None, char_count_per_id: Optional[torch.LongTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ...
Args: char_input_ids (`torch.LongTensor` of shape `(batch_size, char_sequence_length)`): Character indices. The correspondence between characters and indices can be found in `char_to_id`, a dictionary in the generation configuration. char_count_per_id (`t...
forward
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, char_input_ids: Optional[torch.LongTensor] = None, char_count_per_id: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor...
char_input_ids (`torch.LongTensor` of shape `(batch_size, char_sequence_length)`): Character indices. The correspondence between characters and indices can be found in `char_to_id`, a dictionary in the generation configuration. char_count_per_id (`torch.LongTensor` of shape `(ba...
forward
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def forward( self, input_ids: torch.LongTensor, speaker_id: torch.Tensor, lang_id: torch.Tensor ) -> Tuple[torch.Tensor]: """ Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. ...
Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`SeamlessM4Tv2TextToUnitForConditionalGeneration`]. [What are input IDs?](../glossary#in...
forward
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def generate( self, input_ids: Optional[torch.Tensor] = None, return_intermediate_token_ids: Optional[bool] = None, tgt_lang: Optional[str] = None, speaker_id: Optional[int] = 0, **kwargs, ) -> Union[torch.Tensor, SeamlessM4Tv2GenerationOutput]: """ Ge...
Generates translated audio waveforms. <Tip> This method successively calls the `.generate` function of two different sub-models. You can specify keyword arguments at two different levels: general arguments that will be passed to both models, or prefixed arguments that will be ...
generate
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def generate( self, input_features: Optional[torch.Tensor] = None, return_intermediate_token_ids: Optional[bool] = None, tgt_lang: Optional[str] = None, speaker_id: Optional[int] = 0, **kwargs, ) -> Union[torch.Tensor, SeamlessM4Tv2GenerationOutput]: """ ...
Generates translated audio waveforms. <Tip> This method successively calls the `.generate` function of two different sub-models. You can specify keyword arguments at two different levels: general arguments that will be passed to both models, or prefixed arguments that will be ...
generate
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def generate( self, input_ids: Optional[torch.Tensor] = None, input_features: Optional[torch.Tensor] = None, return_intermediate_token_ids: Optional[bool] = None, tgt_lang: Optional[str] = None, speaker_id: Optional[int] = 0, generate_speech: Optional[bool] = True...
Generates translated token ids and/or translated audio waveforms. <Tip> This method successively calls the `.generate` function of two different sub-models. You can specify keyword arguments at two different levels: general arguments that will be passed to both models, or prefixed arg...
generate
python
huggingface/transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
Apache-2.0
def post_process_semantic_segmentation(self, outputs, target_sizes: Optional[List[Tuple]] = None): """ Converts the output of [`SegformerForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch. Args: outputs ([`SegformerForSemanticSegmentation`]): ...
Converts the output of [`SegformerForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch. Args: outputs ([`SegformerForSemanticSegmentation`]): Raw outputs of the model. target_sizes (`List[Tuple]` of length `batch_size`, *optional*): ...
post_process_semantic_segmentation
python
huggingface/transformers
src/transformers/models/segformer/image_processing_segformer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/segformer/image_processing_segformer.py
Apache-2.0
def forward( self, pixel_values: torch.FloatTensor, labels: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, SemanticSegmenterOutput]: ...
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/segformer/modeling_segformer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/segformer/modeling_segformer.py
Apache-2.0
def mask_to_rgb( self, image: np.ndarray, palette: Optional[List[Tuple[int, int]]] = None, data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """Converts a segmentation map to RGB format. Args: image (`np.ndarray`): ...
Converts a segmentation map to RGB format. Args: image (`np.ndarray`): Segmentation map with dimensions (height, width) where pixel values represent the class index. palette (`List[Tuple[int, int]]`, *optional*, defaults to `None`): Palette to use to conv...
mask_to_rgb
python
huggingface/transformers
src/transformers/models/seggpt/image_processing_seggpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seggpt/image_processing_seggpt.py
Apache-2.0
def _preprocess_step( self, images: ImageInput, do_resize: Optional[bool] = None, size: Optional[Dict[str, int]] = None, resample: PILImageResampling = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[...
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_step
python
huggingface/transformers
src/transformers/models/seggpt/image_processing_seggpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seggpt/image_processing_seggpt.py
Apache-2.0
def preprocess( self, images: Optional[ImageInput] = None, prompt_images: Optional[ImageInput] = None, prompt_masks: Optional[ImageInput] = None, do_resize: Optional[bool] = None, size: Optional[Dict[str, int]] = None, resample: PILImageResampling = None, ...
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/seggpt/image_processing_seggpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seggpt/image_processing_seggpt.py
Apache-2.0
def post_process_semantic_segmentation( self, outputs, target_sizes: Optional[List[Tuple[int, int]]] = None, num_labels: Optional[int] = None ): """ Converts the output of [`SegGptImageSegmentationOutput`] into segmentation maps. Only supports PyTorch. Args: outp...
Converts the output of [`SegGptImageSegmentationOutput`] into segmentation maps. Only supports PyTorch. Args: outputs ([`SegGptImageSegmentationOutput`]): Raw outputs of the model. target_sizes (`List[Tuple[int, int]]`, *optional*): List ...
post_process_semantic_segmentation
python
huggingface/transformers
src/transformers/models/seggpt/image_processing_seggpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seggpt/image_processing_seggpt.py
Apache-2.0
def forward( self, pixel_values: torch.Tensor, prompt_pixel_values: torch.Tensor, prompt_masks: torch.Tensor, bool_masked_pos: Optional[torch.BoolTensor] = None, feature_ensemble: Optional[bool] = None, embedding_type: Optional[str] = None, labels: Optiona...
prompt_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Prompt pixel values. Prompt pixel values can be obtained using [`AutoImageProcessor`]. See [`SegGptImageProcessor.__call__`] for details. prompt_masks (`torch.FloatTensor` of shape `(...
forward
python
huggingface/transformers
src/transformers/models/seggpt/modeling_seggpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seggpt/modeling_seggpt.py
Apache-2.0
def forward( self, prompt_masks: torch.FloatTensor, pred_masks: torch.FloatTensor, labels: torch.FloatTensor, bool_masked_pos: torch.BoolTensor, ): """Computes the L1 loss between the predicted masks and the ground truth masks. Args: prompt_masks ...
Computes the L1 loss between the predicted masks and the ground truth masks. Args: prompt_masks (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values from mask prompt. pred_masks (`torch.FloatTensor` of shape `(batch_size, num_channels...
forward
python
huggingface/transformers
src/transformers/models/seggpt/modeling_seggpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seggpt/modeling_seggpt.py
Apache-2.0
def forward( self, pixel_values: torch.Tensor, prompt_pixel_values: torch.Tensor, prompt_masks: torch.Tensor, bool_masked_pos: Optional[torch.BoolTensor] = None, feature_ensemble: Optional[bool] = None, embedding_type: Optional[str] = None, labels: Optiona...
prompt_pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Prompt pixel values. Prompt pixel values can be obtained using [`AutoImageProcessor`]. See [`SegGptImageProcessor.__call__`] for details. prompt_masks (`torch.FloatTensor` of shape `(...
forward
python
huggingface/transformers
src/transformers/models/seggpt/modeling_seggpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/seggpt/modeling_seggpt.py
Apache-2.0
def __init__(self, config, target_lang: Optional[str] = None): r""" target_lang (`str`, *optional*): Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or adapter.<lang>.bin. Only relevant when using an instance of [`SEWForCTC`] wi...
target_lang (`str`, *optional*): Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or adapter.<lang>.bin. Only relevant when using an instance of [`SEWForCTC`] with adapters. Uses 'eng' by default.
__init__
python
huggingface/transformers
src/transformers/models/sew/modeling_sew.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sew/modeling_sew.py
Apache-2.0
def forward( self, input_values: Optional[torch.Tensor], attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, labels: Optional[torch.Tensor] = None...
input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip insta...
forward
python
huggingface/transformers
src/transformers/models/sew/modeling_sew.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sew/modeling_sew.py
Apache-2.0
def __init__(self, config, target_lang: Optional[str] = None): r""" target_lang (`str`, *optional*): Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or adapter.<lang>.bin. Only relevant when using an instance of [`SEWDForCTC`] w...
target_lang (`str`, *optional*): Language id of adapter weights. Adapter weights are stored in the format adapter.<lang>.safetensors or adapter.<lang>.bin. Only relevant when using an instance of [`SEWDForCTC`] with adapters. Uses 'eng' by default.
__init__
python
huggingface/transformers
src/transformers/models/sew_d/modeling_sew_d.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sew_d/modeling_sew_d.py
Apache-2.0
def forward( self, input_values: Optional[torch.Tensor], attention_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, labels: Optional[torch.Tensor] = None...
input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip insta...
forward
python
huggingface/transformers
src/transformers/models/sew_d/modeling_sew_d.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/sew_d/modeling_sew_d.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Union[List[torch.FloatTensor], Cach...
Returns: A `ShieldGemma2ImageClassifierOutputWithNoAttention` instance containing the logits and probabilities associated with the model predicting the `Yes` or `No` token as the response to that prompt, captured in the following properties. * `logits` (`t...
forward
python
huggingface/transformers
src/transformers/models/shieldgemma2/modeling_shieldgemma2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/shieldgemma2/modeling_shieldgemma2.py
Apache-2.0
def __init__( self, image_processor, tokenizer, chat_template=None, image_seq_length=256, policy_definitions=None, **kwargs ): """A processor for the ShieldGemma 2 model. Args: image_processor: The image processor to use, typically a `Gemma3ImageProcessorFast` instance. ...
A processor for the ShieldGemma 2 model. Args: image_processor: The image processor to use, typically a `Gemma3ImageProcessorFast` instance. tokenizer: The tokenizer to use, typically a `GemmaTokenizerFast` instance. chat_template: The chat template to use with this processo...
__init__
python
huggingface/transformers
src/transformers/models/shieldgemma2/processing_shieldgemma2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/shieldgemma2/processing_shieldgemma2.py
Apache-2.0
def __call__( self, images: ImageInput = None, text=None, videos=None, audio=None, **kwargs: Unpack[ShieldGemma2ProcessorKwargs], ) -> BatchFeature: """Generates a batch of inputs from the provided images. ShieldGemma was trained to classify image con...
Generates a batch of inputs from the provided images. ShieldGemma was trained to classify image content for policy compliance using a specific prompt construction. This processor generates a batch of such prompts from the provided images by: 1. Creating a list of conversations, one for each `...
__call__
python
huggingface/transformers
src/transformers/models/shieldgemma2/processing_shieldgemma2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/shieldgemma2/processing_shieldgemma2.py
Apache-2.0
def split_encoderblock_layers(state_dict: dict) -> dict: """ Split the encoderblock weight into layers. In some cases they are concatenated in the original checkpoints. """ # Make shallow copy state_dict = state_dict.copy() # Split encoderblock weight into layers keys = list(state_dict.k...
Split the encoderblock weight into layers. In some cases they are concatenated in the original checkpoints.
split_encoderblock_layers
python
huggingface/transformers
src/transformers/models/siglip/convert_siglip_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/convert_siglip_to_hf.py
Apache-2.0
def convert_siglip_checkpoint(model_name, pytorch_dump_folder_path, verify_logits=True, push_to_hub=False): """ Copy/paste/tweak model's weights to our SigLIP structure. """ # Define default SigLIP configuration config = get_siglip_config(model_name) # Get checkpoint checkpoint = model_nam...
Copy/paste/tweak model's weights to our SigLIP structure.
convert_siglip_checkpoint
python
huggingface/transformers
src/transformers/models/siglip/convert_siglip_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/convert_siglip_to_hf.py
Apache-2.0
def preprocess( self, images: ImageInput, do_resize: Optional[bool] = None, size: Optional[Dict[str, int]] = None, resample: PILImageResampling = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] ...
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/siglip/image_processing_siglip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/image_processing_siglip.py
Apache-2.0
def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ) -> BaseModelOutputWithPool...
Examples: ```python >>> from transformers import AutoTokenizer, SiglipTextModel >>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224") >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224") >>> # important: make sure to ...
forward
python
huggingface/transformers
src/transformers/models/siglip/modeling_siglip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/modeling_siglip.py
Apache-2.0
def forward( self, pixel_values, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, interpolate_pos_encoding: bool = False, ) -> BaseModelOutputWithPooling: r""" Examples: ```python >>> from PIL import Image...
Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, SiglipVisionModel >>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224") >>> processor = AutoProcessor.from_pretrained("google...
forward
python
huggingface/transformers
src/transformers/models/siglip/modeling_siglip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/modeling_siglip.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, return_loss: Optional[bool] = None, output_attentions...
return_loss (`bool`, *optional*): Whether or not to return the contrastive loss. Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, AutoModel >>> import torch >>> model = AutoModel....
forward
python
huggingface/transformers
src/transformers/models/siglip/modeling_siglip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/modeling_siglip.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, interpolate_pos_encoding: bool = False, ) -> ImageClassifierOutput: r"...
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the image classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.n...
forward
python
huggingface/transformers
src/transformers/models/siglip/modeling_siglip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/modeling_siglip.py
Apache-2.0
def __call__( self, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, images: ImageInput = None, padding: Union[bool, str, PaddingStrategy] = False, truncation: Union[bool, str, TruncationStrategy] = None, max_length: Optional[int...
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to SiglipTokenizer's [`~SiglipTokenizer.__call__`] if `text` is not `None` to encode the text. To prepare the image(s), this method forwards the `images` argumen...
__call__
python
huggingface/transformers
src/transformers/models/siglip/processing_siglip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/processing_siglip.py
Apache-2.0
def canonicalize_text(self, text, *, keep_punctuation_exact_string=None): """Returns canonicalized `text` (puncuation removed). Args: text (`str`): String to be canonicalized. keep_punctuation_exact_string (`str`, *optional*): If provided, then th...
Returns canonicalized `text` (puncuation removed). Args: text (`str`): String to be canonicalized. keep_punctuation_exact_string (`str`, *optional*): If provided, then this exact string is kept. For example providing '{}' will keep any occurrences of '{}'...
canonicalize_text
python
huggingface/transformers
src/transformers/models/siglip/tokenization_siglip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/tokenization_siglip.py
Apache-2.0
def tokenize(self, text: "TextInput", add_special_tokens=False, **kwargs) -> List[str]: """ Converts a string to a list of tokens. """ tokens = super().tokenize(SPIECE_UNDERLINE + text.replace(SPIECE_UNDERLINE, " "), **kwargs) if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE...
Converts a string to a list of tokens.
tokenize
python
huggingface/transformers
src/transformers/models/siglip/tokenization_siglip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip/tokenization_siglip.py
Apache-2.0
def get_siglip2_config(model_name: str) -> Siglip2Config: """ Create a configuration for the Siglip2 model based on the model name. """ _, variant, patch, _ = model_name.split("-") patch_size = int(patch[-2:]) num_patches = 256 common_options = COMMON_CONFIG_PARAMS[variant] vision_conf...
Create a configuration for the Siglip2 model based on the model name.
get_siglip2_config
python
huggingface/transformers
src/transformers/models/siglip2/convert_siglip2_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/convert_siglip2_to_hf.py
Apache-2.0
def merge_qkv_for_head(state_dict: dict, config: Siglip2Config) -> dict: """ Merge the q/k/v weights and biases for the attention head. """ # Make shallow copy state_dict = state_dict.copy() # Read and process q/k/v weights and biases qkv_weights, qkv_biases = [], [] for name in ["query"...
Merge the q/k/v weights and biases for the attention head.
merge_qkv_for_head
python
huggingface/transformers
src/transformers/models/siglip2/convert_siglip2_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/convert_siglip2_to_hf.py
Apache-2.0
def create_image(width, height): """ Helper function to create an image with a blue circle on a red background. """ image = Image.new("RGB", (width, height), color="red") draw = ImageDraw.Draw(image) center_x = image.width // 2 center_y = image.height // 2 radius = min(center_x, center_y...
Helper function to create an image with a blue circle on a red background.
create_image
python
huggingface/transformers
src/transformers/models/siglip2/convert_siglip2_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/convert_siglip2_to_hf.py
Apache-2.0
def convert_siglip2_checkpoint(model_name, pytorch_dump_folder_path, verify_logits=True, push_to_hub=False): """ Copy/paste/tweak model's weights to our Siglip2 structure. """ # Define Siglip2 configuration config = get_siglip2_config(model_name) checkpoint = MODEL_NAME_TO_CHECKPOINT_PATH[mode...
Copy/paste/tweak model's weights to our Siglip2 structure.
convert_siglip2_checkpoint
python
huggingface/transformers
src/transformers/models/siglip2/convert_siglip2_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/convert_siglip2_to_hf.py
Apache-2.0
def get_image_size_for_max_num_patches( image_height: int, image_width: int, patch_size: int, max_num_patches: int, eps: float = 1e-5 ) -> Tuple[int, int]: """ Determine image size based on max number of patches, ensure dimensions are divisible by patch size and image is at least 1 patch. Args: ...
Determine image size based on max number of patches, ensure dimensions are divisible by patch size and image is at least 1 patch. Args: image_height (`int`): Original image height. image_width (`int`): Original image width. patch_size (`int`): Patch ...
get_image_size_for_max_num_patches
python
huggingface/transformers
src/transformers/models/siglip2/image_processing_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/image_processing_siglip2.py
Apache-2.0
def convert_image_to_patches(image: np.ndarray, patch_size: int) -> np.ndarray: """ Convert 3D array image of shape (image_height, image_width, num_channels) into 2D array of patches of shape (num_patches_height * num_patches_width, patch_size * patch_size * num_channels). """ image_height, image_wi...
Convert 3D array image of shape (image_height, image_width, num_channels) into 2D array of patches of shape (num_patches_height * num_patches_width, patch_size * patch_size * num_channels).
convert_image_to_patches
python
huggingface/transformers
src/transformers/models/siglip2/image_processing_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/image_processing_siglip2.py
Apache-2.0
def pad_along_first_dim(array: np.ndarray, target_length: int, pad_value: int = 0) -> Tuple[np.ndarray, np.ndarray]: """ Pad the array along the first dimension. """ current_length = array.shape[0] padding_length = target_length - current_length mask = np.ones((target_length,), dtype=np.int32) ...
Pad the array along the first dimension.
pad_along_first_dim
python
huggingface/transformers
src/transformers/models/siglip2/image_processing_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/image_processing_siglip2.py
Apache-2.0
def preprocess( self, images: ImageInput, do_resize: Optional[bool] = None, resample: Optional["PILImageResampling"] = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optiona...
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/siglip2/image_processing_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/image_processing_siglip2.py
Apache-2.0
def convert_image_to_patches(image: "torch.Tensor", patch_size: int) -> "torch.Tensor": """ Convert 3D tensor image of shape (num_channels, image_height, image_width) into 2D tensor of patches of shape (num_patches_height * num_patches_width, patch_size * patch_size * num_channels). """ num_channels...
Convert 3D tensor image of shape (num_channels, image_height, image_width) into 2D tensor of patches of shape (num_patches_height * num_patches_width, patch_size * patch_size * num_channels).
convert_image_to_patches
python
huggingface/transformers
src/transformers/models/siglip2/image_processing_siglip2_fast.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/image_processing_siglip2_fast.py
Apache-2.0
def pad_along_first_dim( tensor: "torch.Tensor", target_length: int, pad_value: int = 0 ) -> Tuple["torch.Tensor", "torch.Tensor"]: """ Pad the tensor along the first dimension. """ current_length = tensor.shape[0] padding_length = target_length - current_length mask = torch.ones((target_len...
Pad the tensor along the first dimension.
pad_along_first_dim
python
huggingface/transformers
src/transformers/models/siglip2/image_processing_siglip2_fast.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/image_processing_siglip2_fast.py
Apache-2.0
def resize_positional_embeddings( positional_embeddings: torch.Tensor, spatial_shapes: torch.LongTensor, max_length: int, ) -> torch.Tensor: """ Resize positional embeddings to image-specific size and pad to a fixed size. Args: positional_embeddings (`tor...
Resize positional embeddings to image-specific size and pad to a fixed size. Args: positional_embeddings (`torch.Tensor`): Position embeddings of shape (height, width, embed_dim) spatial_shapes (`torch.LongTensor`): Spatial shapes of shape (batch...
resize_positional_embeddings
python
huggingface/transformers
src/transformers/models/siglip2/modeling_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/modeling_siglip2.py
Apache-2.0
def forward(self, pixel_values: torch.FloatTensor, spatial_shapes: torch.LongTensor) -> torch.Tensor: """ Args: pixel_values (`torch.FloatTensor`): Pixel values of shape (batch_size, max_num_patches, num_channels * patch_size * patch_size) spatial_shapes (`List[Tu...
Args: pixel_values (`torch.FloatTensor`): Pixel values of shape (batch_size, max_num_patches, num_channels * patch_size * patch_size) spatial_shapes (`List[Tuple[int, int]]`): Spatial shapes of shape (batch_size, 2) to resize the positional embeddings to ...
forward
python
huggingface/transformers
src/transformers/models/siglip2/modeling_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/modeling_siglip2.py
Apache-2.0
def forward( self, pixel_values: torch.FloatTensor, attention_mask: torch.Tensor, spatial_shapes: torch.LongTensor, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ) -> BaseModelOutputWithPooling: r""" spatial_sha...
spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`): Tensor containing the spatial dimensions (height, width) of the input images.
forward
python
huggingface/transformers
src/transformers/models/siglip2/modeling_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/modeling_siglip2.py
Apache-2.0
def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ) -> BaseModelOutputWithPool...
Examples: ```python >>> from transformers import AutoTokenizer, Siglip2TextModel >>> model = Siglip2TextModel.from_pretrained("google/siglip2-base-patch16-224") >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip2-base-patch16-224") >>> # important: make sure...
forward
python
huggingface/transformers
src/transformers/models/siglip2/modeling_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/modeling_siglip2.py
Apache-2.0
def forward( self, pixel_values: torch.FloatTensor, pixel_attention_mask: torch.Tensor, spatial_shapes: torch.LongTensor, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ) -> BaseModelOutputWithPooling: r""" pixel...
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*): Mask to avoid performing attention on padding pixel indices. spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`): Tensor containing the spatial dimensions (height, width...
forward
python
huggingface/transformers
src/transformers/models/siglip2/modeling_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/modeling_siglip2.py
Apache-2.0
def get_text_features( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ) -> torch.FloatTe...
Returns: text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by applying the projection layer to the pooled output of [`Siglip2TextModel`]. Examples: ```python >>> from transformers import AutoTokenizer, AutoMode...
get_text_features
python
huggingface/transformers
src/transformers/models/siglip2/modeling_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/modeling_siglip2.py
Apache-2.0
def get_image_features( self, pixel_values: Optional[torch.FloatTensor] = None, pixel_attention_mask: Optional[torch.Tensor] = None, spatial_shapes: Optional[torch.LongTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, ...
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*): Mask to avoid performing attention on padding pixel indices. spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`): Tensor containing the spatial dimensions (height, width...
get_image_features
python
huggingface/transformers
src/transformers/models/siglip2/modeling_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/modeling_siglip2.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, pixel_attention_mask: Optional[torch.Tensor] = None, spatial_shapes: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, ...
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*): Mask to avoid performing attention on padding pixel indices. spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`): Tensor containing the spatial dimensions (height, width...
forward
python
huggingface/transformers
src/transformers/models/siglip2/modeling_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/modeling_siglip2.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.Tensor] = None, pixel_attention_mask: Optional[torch.Tensor] = None, spatial_shapes: Optional[torch.LongTensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_s...
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*): Mask to avoid performing attention on padding pixel indices. spatial_shapes (`torch.LongTensor` of shape `(batch_size, 2)`): Tensor containing the spatial dimensions (height, width...
forward
python
huggingface/transformers
src/transformers/models/siglip2/modeling_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/modeling_siglip2.py
Apache-2.0
def __call__( self, images: Optional[Union[ImageInput, List[ImageInput], List[List[ImageInput]]]] = None, text: Optional[Union[TextInput, "PreTokenizedInput", List[TextInput], List["PreTokenizedInput"]]] = None, audio=None, videos=None, **kwargs: Unpack[Siglip2ProcessorKw...
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to GemmaTokenizerFast's [`~GemmaTokenizerFast.__call__`] if `text` is not `None` to encode the text. To prepare the image(s), this method forwards the `images` a...
__call__
python
huggingface/transformers
src/transformers/models/siglip2/processing_siglip2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/siglip2/processing_siglip2.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: PILImageResampling = None, do_image_splitting: Optional[bool] = None, do_rescale: Optional[b...
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*, defa...
preprocess
python
huggingface/transformers
src/transformers/models/smolvlm/image_processing_smolvlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/smolvlm/image_processing_smolvlm.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, ...
pixel_attention_mask (`torch.Tensor` of shape `(batch_size, image_size, image_size)`, *optional*): Mask to avoid performing attention on padding pixel indices. image_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The hidden sta...
forward
python
huggingface/transformers
src/transformers/models/smolvlm/modeling_smolvlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/smolvlm/modeling_smolvlm.py
Apache-2.0
def __call__( self, images: Union[ImageInput, List[ImageInput], List[List[ImageInput]]] = None, text: Union[TextInput, "PreTokenizedInput", List[TextInput], List["PreTokenizedInput"]] = None, audio=None, videos: VideoInput = None, **kwargs: Unpack[SmolVLMProcessorKwargs],...
Processes the input prompts and returns a BatchEncoding. Example: ```python >>> import requests >>> from transformers import SmolVLMProcessor >>> from transformers.image_utils import load_image >>> processor = SmolVLMProcessor.from_pretrained("HuggingFaceM4/Sm...
__call__
python
huggingface/transformers
src/transformers/models/smolvlm/processing_smolvlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/smolvlm/processing_smolvlm.py
Apache-2.0
def _process_messages_for_chat_template( self, conversations: List[List[Dict[str, str]]], batch_images: List[ImageInput], batch_videos: List[VideoInput], batch_video_metadata: List[List[Dict[str, any]]], **chat_template_kwargs, ): """ Used within `appl...
Used within `apply_chat_template` when a model has special way to process conversation history. For example, video models might want to specify in the prompt the duration of video or which frame indices at which timestamps were sampled. This information cannot be accessed before the video is lo...
_process_messages_for_chat_template
python
huggingface/transformers
src/transformers/models/smolvlm/processing_smolvlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/smolvlm/processing_smolvlm.py
Apache-2.0
def smolvlm_sample_indices_fn(metadata, max_frames, target_fps, skip_secs=0): """ Example sampling function which: - Uses `max_frames` (if provided) or calculates it from `fps` and metadata. - Applies a basic center-skip if fewer frames than available, otherwise optionally skips `skip_secs` ...
Example sampling function which: - Uses `max_frames` (if provided) or calculates it from `fps` and metadata. - Applies a basic center-skip if fewer frames than available, otherwise optionally skips `skip_secs` from both the start and end. - Uniformly samples the desired number of frames b...
smolvlm_sample_indices_fn
python
huggingface/transformers
src/transformers/models/smolvlm/video_processing_smolvlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/smolvlm/video_processing_smolvlm.py
Apache-2.0
def get_max_height_width(videos: list["torch.Tensor"]) -> List[int]: """ Get the maximum height and width across all videos in a batch. """ max_height = max_width = float("-inf") for video in videos: height, width = video.size()[-2:] max_height = max(height, max_height) max_w...
Get the maximum height and width across all videos in a batch.
get_max_height_width
python
huggingface/transformers
src/transformers/models/smolvlm/video_processing_smolvlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/smolvlm/video_processing_smolvlm.py
Apache-2.0
def get_resize_output_image_size( video, resolution_max_side: int, ) -> tuple[int, int]: """ Get the output size of the video after resizing given a dictionary specifying the max and min sizes. Args: video (`np.ndarray`): Video to resize. resolution_max_side (`int`): ...
Get the output size of the video after resizing given a dictionary specifying the max and min sizes. Args: video (`np.ndarray`): Video to resize. resolution_max_side (`int`): The longest edge of the video will be resized to this value. The shortest edge will be resized t...
get_resize_output_image_size
python
huggingface/transformers
src/transformers/models/smolvlm/video_processing_smolvlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/smolvlm/video_processing_smolvlm.py
Apache-2.0
def resize( self, video: "torch.Tensor", size: SizeDict, interpolation: "F.InterpolationMode" = None, antialias: bool = True, **kwargs, ) -> "torch.Tensor": """ Resize an video to `(size["height"], size["width"])`. Args: video (`tor...
Resize an video to `(size["height"], size["width"])`. Args: video (`torch.Tensor`): Video to resize. size (`SizeDict`): Dictionary in the format `{"height": int, "width": int}` specifying the size of the output video. resample (`Interp...
resize
python
huggingface/transformers
src/transformers/models/smolvlm/video_processing_smolvlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/smolvlm/video_processing_smolvlm.py
Apache-2.0
def pad( self, video: "torch.Tensor", padded_size: tuple[int, int], fill: int = 0, return_pixel_mask: bool = True, ): """Pads the sample with empty video to the padded_size Args: video (`torch.Tensor`): Video to pad. pad...
Pads the sample with empty video to the padded_size Args: video (`torch.Tensor`): Video to pad. padded_size (`Tuple[int, int]`): Height and width to pad. fill (`int`, *optional*): The value to use for the padding. re...
pad
python
huggingface/transformers
src/transformers/models/smolvlm/video_processing_smolvlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/smolvlm/video_processing_smolvlm.py
Apache-2.0
def forward( self, hidden_states: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.LongTensor] = None, head_mask: Optional[torch.Tensor]...
Args: hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, feature_size)`): Features extracted from the speech or text input by the decoder prenet. attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): ...
forward
python
huggingface/transformers
src/transformers/models/speecht5/modeling_speecht5.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/speecht5/modeling_speecht5.py
Apache-2.0
def forward( self, input_values: Optional[torch.Tensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_values: Optional[torch.Tensor] = None, decoder_attention_mask: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] = None...
input_values (`torch.Tensor` of shape `(batch_size, sequence_length)`): Depending on which encoder is being used, the `input_values` are either: float values of the input raw speech waveform, or indices of input sequence tokens in the vocabulary, or hidden states. decoder_input_...
forward
python
huggingface/transformers
src/transformers/models/speecht5/modeling_speecht5.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/speecht5/modeling_speecht5.py
Apache-2.0
def forward( self, input_values: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] ...
input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Float values of input raw speech waveform. Values can be obtained by loading a *.flac* or *.wav* audio file into an array of type `List[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (*pip insta...
forward
python
huggingface/transformers
src/transformers/models/speecht5/modeling_speecht5.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/speecht5/modeling_speecht5.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_values: Optional[torch.FloatTensor] = None, decoder_attention_mask: Optional[torch.LongTensor] = None, head_mask: Optional[torch.FloatTensor] ...
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`SpeechT5Tokenizer`]. See [`~PreTrainedTokenizer.encode`] and [`~PreTrainedTokenizer.__call__`] for details. ...
forward
python
huggingface/transformers
src/transformers/models/speecht5/modeling_speecht5.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/speecht5/modeling_speecht5.py
Apache-2.0