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 call(self, context: tf.Tensor, latents: tf.Tensor) -> tf.Tensor: """ Runs Perceiver Self-Attention, with special (context, latents) appended along the `seq` dimension! Args: context (`tf.Tensor`): Tensor of shape `[bsz, seq, embed_dim]` representing long-form con...
Runs Perceiver Self-Attention, with special (context, latents) appended along the `seq` dimension! Args: context (`tf.Tensor`): Tensor of shape `[bsz, seq, embed_dim]` representing long-form context to resample. latents (`tf.Tensor`): Tensor of s...
call
python
huggingface/transformers
src/transformers/models/idefics/perceiver_tf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics/perceiver_tf.py
Apache-2.0
def __call__( self, images: Union[ImageInput, List[ImageInput], str, List[str], List[List[str]]] = None, text: Union[ TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput], List[List[TextInput]], List[List[P...
This method takes batched or non-batched prompts made of text and images and converts them into prompts that the model was trained on and prepares the image pixel values for the model to process. Args: images (`Union[ImageInput, List[ImageInput], str, List[str], List[List[str]]]`): ...
__call__
python
huggingface/transformers
src/transformers/models/idefics/processing_idefics.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics/processing_idefics.py
Apache-2.0
def call( self, inputs_embeds, attention_mask: Optional[tf.Tensor] = None, causal_attention_mask: Optional[tf.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, trainin...
Args: inputs_embeds (`tf.Tensor` 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_ids` ind...
call
python
huggingface/transformers
src/transformers/models/idefics/vision_tf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics/vision_tf.py
Apache-2.0
def get_resize_output_image_size(image, size, input_data_format) -> Tuple[int, int]: """ Get the output size of the image after resizing given a dictionary specifying the max and min sizes. Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Size of...
Get the output size of the image after resizing given a dictionary specifying the max and min sizes. Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Size of the output image containing the keys "shortest_edge" and "longest_edge". input_data...
get_resize_output_image_size
python
huggingface/transformers
src/transformers/models/idefics2/image_processing_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/image_processing_idefics2.py
Apache-2.0
def pad( self, images: List[np.ndarray], constant_values: Union[float, Iterable[float]] = 0, return_pixel_mask: bool = True, return_tensors: Optional[Union[str, TensorType]] = None, data_format: Optional[ChannelDimension] = None, input_data_format: Optional[Union[...
For a list of images, for each images, pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width. For each sample in the batch, pads the sample with empty images to the max_number of images per sample in the batch. Optionally returns a pixel mask. ...
pad
python
huggingface/transformers
src/transformers/models/idefics2/image_processing_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/image_processing_idefics2.py
Apache-2.0
def split_image( self, image: np.ndarray, input_data_format: Optional[Union[str, ChannelDimension]] = None, ): """ Split an image into 4 equal sub-images, and the concatenate that sequence with the original image. That means that a single image becomes a sequence of 5...
Split an image into 4 equal sub-images, and the concatenate that sequence with the original image. That means that a single image becomes a sequence of 5 images. This is a "trick" to spend more compute on each image with no changes in the vision encoder. Args: image (`np.nd...
split_image
python
huggingface/transformers
src/transformers/models/idefics2/image_processing_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/image_processing_idefics2.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_rescale: Optional[bool] = None, rescale_factor: Optional[float...
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/idefics2/image_processing_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/image_processing_idefics2.py
Apache-2.0
def forward( self, pixel_values, patch_attention_mask: Optional[torch.BoolTensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutput]: r""" ...
patch_attention_mask (`torch.BoolTensor` of shape `(batch_size, num_patches_height, num_patches_width)`, *optional*): The attention mask for the patches.
forward
python
huggingface/transformers
src/transformers/models/idefics2/modeling_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/modeling_idefics2.py
Apache-2.0
def forward( self, latents: torch.Tensor, context: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: bool = False, use_cach...
Runs Perceiver Self-Attention, with special (context, latents) appended along the `seq` dimension! Args: latents (`torch.Tensor`): Tensor of shape [bsz, n_latents, embed_dim] representing fixed length latents to compress to. context (`torch.Tensor`): Tensor of shape [bsz, seq, ...
forward
python
huggingface/transformers
src/transformers/models/idefics2/modeling_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/modeling_idefics2.py
Apache-2.0
def forward( self, context: torch.Tensor, attention_mask: torch.Tensor, ) -> torch.Tensor: r""" context (`torch.FloatTensor` of shape `(batch, seq_len, embed_dim)`): Input to the layer. """ # seq embed -> bsz seq embed latents = self.latent...
context (`torch.FloatTensor` of shape `(batch, seq_len, embed_dim)`): Input to the layer.
forward
python
huggingface/transformers
src/transformers/models/idefics2/modeling_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/modeling_idefics2.py
Apache-2.0
def enable_input_require_grads(self): """ Enables the gradients for the input embeddings. This is useful for lora when using gradient checkpointing. c.f. https://github.com/huggingface/peft/issues/1402#issuecomment-1913675032 Override to set output.requires_grad = True for both...
Enables the gradients for the input embeddings. This is useful for lora when using gradient checkpointing. c.f. https://github.com/huggingface/peft/issues/1402#issuecomment-1913675032 Override to set output.requires_grad = True for both the decoder's and vision model's embeddings. ...
enable_input_require_grads
python
huggingface/transformers
src/transformers/models/idefics2/modeling_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/modeling_idefics2.py
Apache-2.0
def get_image_features(self, pixel_values: torch.FloatTensor, pixel_attention_mask: torch.LongTensor = None): """ Encodes images into continuous embeddings that can be forwarded to the language model. Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image...
Encodes images into continuous embeddings that can be forwarded to the language model. Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input images. pixel_attention_mask (`t...
get_image_features
python
huggingface/transformers
src/transformers/models/idefics2/modeling_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/modeling_idefics2.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/idefics2/modeling_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/modeling_idefics2.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/idefics2/modeling_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/modeling_idefics2.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=None, **kwargs: Unpack[Idefics2ProcessorKwargs], ) -> Bat...
Processes the input prompts and returns a BatchEncoding. Example: ```python >>> import requests >>> from transformers import Idefics2Processor >>> from transformers.image_utils import load_image >>> processor = Idefics2Processor.from_pretrained("HuggingFaceM4/...
__call__
python
huggingface/transformers
src/transformers/models/idefics2/processing_idefics2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics2/processing_idefics2.py
Apache-2.0
def _resize_output_size_rescale_to_max_len( height: int, width: int, min_len: Optional[int] = 1, max_len: Optional[int] = None ) -> Tuple[int, int]: """ Get the output size of the image after resizing given a dictionary specifying the max and min sizes. Args: height (`int`): Height o...
Get the output size of the image after resizing given a dictionary specifying the max and min sizes. Args: height (`int`): Height of the input image. width (`int`): Width of the input image. min_len (`int`, *optional*, defaults to 1): Minimum size of ...
_resize_output_size_rescale_to_max_len
python
huggingface/transformers
src/transformers/models/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.py
Apache-2.0
def _resize_output_size_scale_below_upper_bound( height: int, width: int, max_len: Optional[Dict[str, int]] = None ) -> Tuple[int, int]: """ Get the output size of the image after resizing given a dictionary specifying the max and min sizes. Args: height (`int`): Height of the input ...
Get the output size of the image after resizing given a dictionary specifying the max and min sizes. Args: height (`int`): Height of the input image. width (`int`): Width of the input image. max_len (`Dict[str, int]`, *optional*, defaults to the maximum size of t...
_resize_output_size_scale_below_upper_bound
python
huggingface/transformers
src/transformers/models/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.py
Apache-2.0
def get_resize_output_image_size( image, resolution_max_side: int, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> Tuple[int, int]: """ Get the output size of the image after resizing given a dictionary specifying the max and min sizes. Args: image (`np.ndarray`): ...
Get the output size of the image after resizing given a dictionary specifying the max and min sizes. Args: image (`np.ndarray`): Image to resize. resolution_max_side (`int`): The longest edge of the image will be resized to this value. The shortest edge will be resized t...
get_resize_output_image_size
python
huggingface/transformers
src/transformers/models/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.py
Apache-2.0
def make_pixel_mask( image: np.ndarray, output_size: Tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None ) -> np.ndarray: """ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding. Args: image (`np.ndarray`): Image to m...
Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding. Args: image (`np.ndarray`): Image to make the pixel mask for. output_size (`Tuple[int, int]`): Output size of the mask.
make_pixel_mask
python
huggingface/transformers
src/transformers/models/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.py
Apache-2.0
def convert_to_rgb( image: np.ndarray, palette: Optional[PIL.ImagePalette.ImagePalette] = None, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> ImageInput: """ Converts an image to RGB format. Args: im...
Converts an image to RGB format. Args: image (`np.ndarray`): The image to convert. palette (List[int], *optional*): The palette to use if given. data_format (ChannelDimension or str, *optional*): The channel dimension format for the output image. If n...
convert_to_rgb
python
huggingface/transformers
src/transformers/models/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.py
Apache-2.0
def resize( self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling = PILImageResampling.LANCZOS, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> n...
Resize an image. The longest edge of the image is resized to size["longest_edge"], with the shortest edge resized to keep the input aspect ratio. Can also be used with size["height"] and size["width"]. Args: image (`np.ndarray`): Image to resize. size (`D...
resize
python
huggingface/transformers
src/transformers/models/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.py
Apache-2.0
def split_image( self, image, max_image_size: Dict[str, int], resample: PILImageResampling = PILImageResampling.LANCZOS, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ): """ ...
Split an image into squares of side max_image_size and the original image resized to max_image_size. That means that a single image becomes a sequence of images. This is a "trick" to spend more compute on each image with no changes in the vision encoder. 1) If one side of the original i...
split_image
python
huggingface/transformers
src/transformers/models/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.py
Apache-2.0
def resize_for_vision_encoder( self, image: np.ndarray, vision_encoder_max_size: int, resample: PILImageResampling = PILImageResampling.LANCZOS, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ...
Resize images to be multiples of `vision_encoder_max_size` while preserving the aspect ratio. Args: image (`np.ndarray`): Images to resize. vision_encoder_max_size (`int`): Maximum size of the output image. If the image is larger than this size, i...
resize_for_vision_encoder
python
huggingface/transformers
src/transformers/models/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.py
Apache-2.0
def pad( self, images: List[np.ndarray], constant_values: Union[float, Iterable[float]] = 0, return_pixel_mask: bool = True, return_tensors: Optional[Union[str, TensorType]] = None, data_format: Optional[ChannelDimension] = None, input_data_format: Optional[Union[...
For a list of images, for each images, pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width. For each sample in the batch, pads the sample with empty images to the max_number of images per sample in the batch. Optionally returns a pixel mask. ...
pad
python
huggingface/transformers
src/transformers/models/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.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/idefics3/image_processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/image_processing_idefics3.py
Apache-2.0
def inputs_merger( self, input_ids: torch.LongTensor, inputs_embeds: Optional[torch.Tensor], image_hidden_states: Optional[torch.Tensor], ): """ This method aims at merging the token embeddings with the image hidden states into one single sequence of vectors that are ...
This method aims at merging the token embeddings with the image hidden states into one single sequence of vectors that are fed to the transformer LM. The merging happens as follows: - The text token sequence is: `tok_1 tok_2 tok_3 <fake_token_around_image> <image> <image> ... <image> <fake_toke...
inputs_merger
python
huggingface/transformers
src/transformers/models/idefics3/modeling_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/modeling_idefics3.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/idefics3/modeling_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/modeling_idefics3.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/idefics3/modeling_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/modeling_idefics3.py
Apache-2.0
def _prompt_single_image(image_seq_len, fake_token_around_image, image_token, global_img_token): """Prompt with expanded image tokens for a single image.""" return ( f"{fake_token_around_image}" + f"{global_img_token}" + f"{image_token}" * image_seq_len + f"{fake_token_around_ima...
Prompt with expanded image tokens for a single image.
_prompt_single_image
python
huggingface/transformers
src/transformers/models/idefics3/processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/processing_idefics3.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=None, image_seq_len: Optional[int] = None, **kwargs: ...
Processes the input prompts and returns a BatchEncoding. Example: ```python >>> import requests >>> from transformers import Idefics3Processor >>> from transformers.image_utils import load_image >>> processor = Idefics3Processor.from_pretrained("HuggingFaceM4/...
__call__
python
huggingface/transformers
src/transformers/models/idefics3/processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/processing_idefics3.py
Apache-2.0
def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to Idefics3TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ batched_decode_output = self.tokenizer.batch_decode(*args, ...
This method forwards all its arguments to Idefics3TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information.
batch_decode
python
huggingface/transformers
src/transformers/models/idefics3/processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/processing_idefics3.py
Apache-2.0
def decode(self, *args, **kwargs): """ This method forwards all its arguments to Idefics3TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ decode_output = self.tokenizer.decode(*args, **kwargs) return s...
This method forwards all its arguments to Idefics3TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information.
decode
python
huggingface/transformers
src/transformers/models/idefics3/processing_idefics3.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/idefics3/processing_idefics3.py
Apache-2.0
def convert_old_keys_to_new_keys(state_dict_keys: Optional[dict] = None): """ Converts old keys to new keys using the mapping and dynamically removes the 'ijepa.' prefix if necessary. Args: state_dict_keys (dict): The keys from the state_dict to convert. Returns: dict: A mapping from o...
Converts old keys to new keys using the mapping and dynamically removes the 'ijepa.' prefix if necessary. Args: state_dict_keys (dict): The keys from the state_dict to convert. Returns: dict: A mapping from old keys to new keys.
convert_old_keys_to_new_keys
python
huggingface/transformers
src/transformers/models/ijepa/convert_ijepa_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/ijepa/convert_ijepa_to_hf.py
Apache-2.0
def write_model(model_name, output_dir, safe_serialization, push_to_hub, verify_logits): """ Copy/paste/tweak model's weights to our IJEPA structure. """ # define default IJEPA configuration config = get_ijepa_config(model_name) checkpoint_mapping = { "ijepa_vith14_1k": "https://dl.fba...
Copy/paste/tweak model's weights to our IJEPA structure.
write_model
python
huggingface/transformers
src/transformers/models/ijepa/convert_ijepa_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/ijepa/convert_ijepa_to_hf.py
Apache-2.0
def forward( self, input_ids: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, he...
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`): `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input sequence tokens in the ...
forward
python
huggingface/transformers
src/transformers/models/imagegpt/modeling_imagegpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/imagegpt/modeling_imagegpt.py
Apache-2.0
def forward( self, input_ids: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, he...
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`): `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input sequence tokens in the ...
forward
python
huggingface/transformers
src/transformers/models/imagegpt/modeling_imagegpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/imagegpt/modeling_imagegpt.py
Apache-2.0
def forward( self, input_ids: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, he...
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`): `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[0][0].shape[-2]` (`sequence_length` of input past key value states). Indices of input sequence tokens in the ...
forward
python
huggingface/transformers
src/transformers/models/imagegpt/modeling_imagegpt.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/imagegpt/modeling_imagegpt.py
Apache-2.0
def forward( self, attention_mask: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.LongTensor] = None, head_mask: Optional[torch.Tensor] = None, cross_attn_head_mask: Optional[torch.Tensor] =...
Args: attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are...
forward
python
huggingface/transformers
src/transformers/models/informer/modeling_informer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/informer/modeling_informer.py
Apache-2.0
def forward( self, past_values: torch.Tensor, past_time_features: torch.Tensor, past_observed_mask: torch.Tensor, static_categorical_features: Optional[torch.Tensor] = None, static_real_features: Optional[torch.Tensor] = None, future_values: Optional[torch.Tensor]...
past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`): Past values of the time series, that serve as context in order to predict the future. The sequence size of this tensor must be larger than the `context_length` of t...
forward
python
huggingface/transformers
src/transformers/models/informer/modeling_informer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/informer/modeling_informer.py
Apache-2.0
def forward( self, past_values: torch.Tensor, past_time_features: torch.Tensor, past_observed_mask: torch.Tensor, static_categorical_features: Optional[torch.Tensor] = None, static_real_features: Optional[torch.Tensor] = None, future_values: Optional[torch.Tensor]...
past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)` or `(batch_size, sequence_length, input_size)`): Past values of the time series, that serve as context in order to predict the future. The sequence size of this tensor must be larger than the `context_length` of t...
forward
python
huggingface/transformers
src/transformers/models/informer/modeling_informer.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/informer/modeling_informer.py
Apache-2.0
def forward( self, pixel_values: torch.FloatTensor, qformer_input_ids: torch.FloatTensor, qformer_attention_mask: Optional[torch.LongTensor] = None, input_ids: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_ids...
qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided to serve as text prompt, which the Q-Former model will encode. Indices ca...
forward
python
huggingface/transformers
src/transformers/models/instructblip/modeling_instructblip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblip/modeling_instructblip.py
Apache-2.0
def forward( self, pixel_values: torch.FloatTensor, qformer_input_ids: torch.FloatTensor, qformer_attention_mask: Optional[torch.LongTensor] = None, input_ids: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_ids...
qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided to serve as text prompt, which the Q-Former model will encode. Indices ca...
forward
python
huggingface/transformers
src/transformers/models/instructblip/modeling_instructblip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblip/modeling_instructblip.py
Apache-2.0
def generate( self, pixel_values: torch.FloatTensor, qformer_input_ids: Optional[torch.LongTensor] = None, qformer_attention_mask: Optional[torch.LongTensor] = None, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, i...
Overrides `generate` function to be able to use the model as a conditional generator. Args: pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width)): Input images to be processed. qformer_input_ids (`torch.LongTensor` of shape (batch...
generate
python
huggingface/transformers
src/transformers/models/instructblip/modeling_instructblip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblip/modeling_instructblip.py
Apache-2.0
def __call__( self, images: ImageInput = None, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, audio=None, videos=None, **kwargs: Unpack[InstructBlipProcessorKwargs], ) -> BatchFeature: """ This method uses [...
This method uses [`BlipImageProcessor.__call__`] method to prepare image(s) for the model, and [`BertTokenizerFast.__call__`] to prepare text for the model. Please refer to the docstring of the above two methods for more information. Args: images (`ImageInput`): ...
__call__
python
huggingface/transformers
src/transformers/models/instructblip/processing_instructblip.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblip/processing_instructblip.py
Apache-2.0
def from_vision_qformer_text_configs( cls, vision_config: InstructBlipVideoVisionConfig, qformer_config: InstructBlipVideoQFormerConfig, text_config: PretrainedConfig, **kwargs, ): r""" Instantiate a [`InstructBlipVideoConfig`] (or a derived class) from a Inst...
Instantiate a [`InstructBlipVideoConfig`] (or a derived class) from a InstructBlipVideo vision model, Q-Former and language model configurations. Returns: [`InstructBlipVideoConfig`]: An instance of a configuration object
from_vision_qformer_text_configs
python
huggingface/transformers
src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
Apache-2.0
def preprocess( self, images: VideoInput = None, 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 a video or batch of images/videos. Args: videos (`VideoInput`): Video frames to preprocess. Expects a single or batch of videos as a list of frames with pixel values ranging from 0 to 255. If passing in video with pixel values between 0 and 1, set...
preprocess
python
huggingface/transformers
src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
Apache-2.0
def forward( self, pixel_values: torch.FloatTensor, qformer_input_ids: torch.FloatTensor, qformer_attention_mask: Optional[torch.LongTensor] = None, input_ids: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_ids...
qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided to serve as text prompt, which the Q-Former model will encode. Indices ca...
forward
python
huggingface/transformers
src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
Apache-2.0
def forward( self, pixel_values: torch.FloatTensor, qformer_input_ids: torch.FloatTensor, qformer_attention_mask: Optional[torch.LongTensor] = None, input_ids: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_ids...
qformer_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of input sequence tokens in the vocabulary of the Q-Former. Input tokens can optionally be provided to serve as text prompt, which the Q-Former model will encode. Indices ca...
forward
python
huggingface/transformers
src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
Apache-2.0
def generate( self, pixel_values: torch.FloatTensor, qformer_input_ids: Optional[torch.LongTensor] = None, qformer_attention_mask: Optional[torch.LongTensor] = None, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, i...
Overrides `generate` function to be able to use the model as a conditional generator. Args: pixel_values (`torch.FloatTensor` of shape (batch_size, num_channels, height, width) or (batch_size, num_frames, num_channels, height, width)): Input images or videos to be processed...
generate
python
huggingface/transformers
src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
Apache-2.0
def forward( self, pixel_values: torch.FloatTensor, qformer_input_ids: torch.FloatTensor, qformer_attention_mask: Optional[torch.LongTensor] = None, input_ids: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.LongTensor] = None, decoder_input_ids...
```python >>> from transformers import InstructBlipVideoProcessor, InstructBlipVideoForConditionalGeneration >>> import torch >>> from huggingface_hub import hf_hub_download >>> import av >>> import numpy as np >>> def read_video_pyav(container, indices): ...
forward
python
huggingface/transformers
src/transformers/models/instructblipvideo/modular_instructblipvideo.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblipvideo/modular_instructblipvideo.py
Apache-2.0
def __call__( self, images: VideoInput = None, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, add_special_tokens: bool = True, padding: Union[bool, str, PaddingStrategy] = False, truncation: Union[bool, str, TruncationStrategy]...
This method uses [`InstructBlipVideoImageProcessor.__call__`] method to prepare image(s) or video(s) for the model, and [`BertTokenizerFast.__call__`] to prepare text for the model. Please refer to the docstring of the above two methods for more information.
__call__
python
huggingface/transformers
src/transformers/models/instructblipvideo/processing_instructblipvideo.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
Apache-2.0
def get_lm_type(path: str) -> Literal["qwen2", "llama"]: """ Determine the type of language model (either 'qwen2' or 'llama') based on a given model path. """ if path not in LM_TYPE_CORRESPONDENCE.keys(): base_config = AutoModel.from_pretrained(path, trust_remote_code=True).config lm_ar...
Determine the type of language model (either 'qwen2' or 'llama') based on a given model path.
get_lm_type
python
huggingface/transformers
src/transformers/models/internvl/convert_internvl_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/internvl/convert_internvl_weights_to_hf.py
Apache-2.0
def get_image_features( self, pixel_values: torch.FloatTensor, vision_feature_layer: Optional[Union[int, List[int]]] = None, vision_feature_select_strategy: Optional[str] = None, **kwargs, ): """ Obtains image last hidden states from the vision tower and apply...
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 (`int` or `List[...
get_image_features
python
huggingface/transformers
src/transformers/models/internvl/modeling_internvl.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/internvl/modeling_internvl.py
Apache-2.0
def pixel_shuffle(self, vision_features: torch.Tensor, scale_factor: float = 0.5): """Perform pixel shuffle downsampling on vision features. Args: vision_features (`torch.Tensor`): Input tensor of shape (batch_size, width, height, channels). scale_factor (`float`...
Perform pixel shuffle downsampling on vision features. Args: vision_features (`torch.Tensor`): Input tensor of shape (batch_size, width, height, channels). scale_factor (`float`, *optional*, defaults to `0.5`): Factor by which to downsample. Default is 0....
pixel_shuffle
python
huggingface/transformers
src/transformers/models/internvl/modeling_internvl.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/internvl/modeling_internvl.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/internvl/modeling_internvl.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/internvl/modeling_internvl.py
Apache-2.0
def _insert_media_placeholders( self, text: list[str], image_pixel_values, video_pixel_values, image_num_patches: list[int], video_num_patches: list[int], image_num_patches_indices: np.ndarray, video_num_patches_indices: np.ndarray, video_patch_ind...
Processes interleaved text with <image> and <video> placeholders, replacing them with appropriate image and video tokens while keeping track of the patches used.
_insert_media_placeholders
python
huggingface/transformers
src/transformers/models/internvl/processing_internvl.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/internvl/processing_internvl.py
Apache-2.0
def __call__( self, images: Optional[ImageInput] = None, text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None, audio=None, videos: Optional[VideoInput] = None, **kwargs: Unpack[InternVLProcessorKwargs], ) -> BatchFeature...
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to PreTrainedTokenizerFast's [`~PreTrainedTokenizerFast.__call__`] to encode the text if `text` is not `None`, otherwise encode default OCR queries which depends...
__call__
python
huggingface/transformers
src/transformers/models/internvl/processing_internvl.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/internvl/processing_internvl.py
Apache-2.0
def sample_indices_fn( self, metadata: VideoMetadata, num_frames: Optional[int] = None, initial_shift: Union[bool, float, int] = True ): """ The function to generate indices of frames to sample from a video. Args: metadata (`VideoMetadata`): `VideoMetadat...
The function to generate indices of frames to sample from a video. Args: metadata (`VideoMetadata`): `VideoMetadata` object containing metadata about the video, such as "total_num_frames" or "fps". num_frames (`int`, *optional*): Number of frames...
sample_indices_fn
python
huggingface/transformers
src/transformers/models/internvl/processing_internvl.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/internvl/processing_internvl.py
Apache-2.0
def _load_video_for_model( self, video: Union[str, "VideoInput"], num_frames: Optional[int], backend: str = "pyav", initial_shift: bool = True, **kwargs, ) -> np.array: """ Loads `video` to a numpy array. Args: video (`str` or `Vid...
Loads `video` to a numpy array. Args: video (`str` or `VideoInput`): The video to convert to the numpy array format. Can be a link to video or local path. num_frames (`int`, *optional*): Number of frames to sample uniformly. If not passed, the wh...
_load_video_for_model
python
huggingface/transformers
src/transformers/models/internvl/processing_internvl.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/internvl/processing_internvl.py
Apache-2.0
def load_balancing_loss_func( router_logits: Union[torch.Tensor, Tuple[torch.Tensor], None], num_experts: Optional[int] = None, top_k=2, attention_mask: Optional[torch.Tensor] = None, ) -> Union[torch.Tensor, int]: r""" Computes auxiliary load balancing loss as in Switch Transformer - implemente...
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch. See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing betw...
load_balancing_loss_func
python
huggingface/transformers
src/transformers/models/jamba/modeling_jamba.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jamba/modeling_jamba.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[HybridMambaAttentionDynamicCache] = None, output_attentions: Optional[bool] = False, output_rou...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, sequence_length)` where padding elements are indicated by 0. past_key_value ...
forward
python
huggingface/transformers
src/transformers/models/jamba/modeling_jamba.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jamba/modeling_jamba.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[HybridMambaAttentionDynamicCache] = None, inputs_embeds: Optional[torch.FloatTensor] ...
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/jamba/modeling_jamba.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jamba/modeling_jamba.py
Apache-2.0
def split_tensor(tensor, key): """Splits a merged tensor (qkv or kv) into separate tensors and creates keys for each part.""" if "qkv" in key: prefix_to_replace = "qkv" num_splits = 3 new_keys = ["q_proj", "k_proj", "v_proj"] elif "kv" in key: prefix_to_replace = "kv" ...
Splits a merged tensor (qkv or kv) into separate tensors and creates keys for each part.
split_tensor
python
huggingface/transformers
src/transformers/models/janus/convert_janus_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/convert_janus_weights_to_hf.py
Apache-2.0
def convert_state_dict_to_hf(state_dict): """Convert state dict keys to HF format.""" conversion_dict = convert_old_keys_to_new_keys(state_dict) converted_state_dict = {} for old_key, new_key in conversion_dict.items(): if new_key: if "qkv" in new_key or "kv" in new_key: # Detect m...
Convert state dict keys to HF format.
convert_state_dict_to_hf
python
huggingface/transformers
src/transformers/models/janus/convert_janus_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/convert_janus_weights_to_hf.py
Apache-2.0
def ensure_model_downloaded( repo_id: Optional[str] = None, revision: Optional[str] = None, local_dir: Optional[str] = None ) -> str: """ Ensures model files are downloaded locally, downloads them if not. Returns path to local files. Args: repo_id: The Hugging Face model repo ID (required i...
Ensures model files are downloaded locally, downloads them if not. Returns path to local files. Args: repo_id: The Hugging Face model repo ID (required if local_dir not provided) revision: Optional git revision to use local_dir: Optional local directory path where model files shoul...
ensure_model_downloaded
python
huggingface/transformers
src/transformers/models/janus/convert_janus_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/convert_janus_weights_to_hf.py
Apache-2.0
def load_model_state_dict(input_path: str) -> dict: """ Load model state dict, handling both single and sharded files. """ index_path = os.path.join(input_path, "pytorch_model.bin.index.json") single_file_path = os.path.join(input_path, "pytorch_model.bin") # Check if we have a sharded model ...
Load model state dict, handling both single and sharded files.
load_model_state_dict
python
huggingface/transformers
src/transformers/models/janus/convert_janus_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/convert_janus_weights_to_hf.py
Apache-2.0
def convert_model( repo_id=None, local_dir=None, text_model_id=None, output_dir=None, output_hub_path=None, safe_serialization=True, revision=None, ): """Convert and save the model weights, processor, and configuration.""" if output_dir is None and output_hub_path is None: ra...
Convert and save the model weights, processor, and configuration.
convert_model
python
huggingface/transformers
src/transformers/models/janus/convert_janus_weights_to_hf.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/convert_janus_weights_to_hf.py
Apache-2.0
def resize( self, image: np.ndarray, size: Union[Dict[str, int], int], resample: PILImageResampling = PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs...
Resize an image to dynamically calculated size. Args: image (`np.ndarray`): Image to resize. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): `PILImageResampling` filter to use when resizing the image e.g. `P...
resize
python
huggingface/transformers
src/transformers/models/janus/image_processing_janus.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/image_processing_janus.py
Apache-2.0
def pad_to_square( self, image: np.ndarray, background_color: Union[int, Tuple[int, int, int]] = 0, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.array: """ Pads an image t...
Pads an image to a square based on the longest edge. Args: image (`np.ndarray`): The image to pad. background_color (`int` or `Tuple[int, int, int]`, *optional*, defaults to 0): The color to use for the padding. Can be an integer for single chann...
pad_to_square
python
huggingface/transformers
src/transformers/models/janus/image_processing_janus.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/image_processing_janus.py
Apache-2.0
def postprocess( self, images: ImageInput, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[List[float]] = None, image_std: Optional[List[float]] = None, input_data_format:...
Applies post-processing to the decoded image tokens by reversing transformations applied during preprocessing.
postprocess
python
huggingface/transformers
src/transformers/models/janus/image_processing_janus.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/image_processing_janus.py
Apache-2.0
def decode(self, image_tokens: torch.LongTensor) -> torch.FloatTensor: """ Decodes quantized token IDs into pixel values. Args: image_tokens (torch.LongTensor): Batch of token IDs. Returns: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, ima...
Decodes quantized token IDs into pixel values. Args: image_tokens (torch.LongTensor): Batch of token IDs. Returns: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): Pixel values decoded from the token IDs. ...
decode
python
huggingface/transformers
src/transformers/models/janus/modeling_janus.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/modeling_janus.py
Apache-2.0
def decode_image_tokens(self, image_tokens: torch.Tensor): """ Decodes generated image tokens from language model to continuous pixel values with VQGAN module via upsampling. Args: image_tokens (`torch.LongTensor` of shape `(batch_size, num_of_tokens)`): The t...
Decodes generated image tokens from language model to continuous pixel values with VQGAN module via upsampling. Args: image_tokens (`torch.LongTensor` of shape `(batch_size, num_of_tokens)`): The tensors corresponding to the input images.
decode_image_tokens
python
huggingface/transformers
src/transformers/models/janus/modeling_janus.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/modeling_janus.py
Apache-2.0
def __call__( self, text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None, images: ImageInput = None, videos=None, audio=None, **kwargs: Unpack[JanusProcessorKwargs], ) -> BatchFeature: """ Main method to prepare fo...
Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text` and `kwargs` arguments to LlamaTokenizerFast's [`~LlamaTokenizerFast.__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/janus/processing_janus.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/janus/processing_janus.py
Apache-2.0
def __init__(self, num_experts: int, input_size: int, output_size: int) -> None: """ Initialize the JetMoeParallelExperts module. The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with many MoE libraries, such as [Megablock](https:...
Initialize the JetMoeParallelExperts module. The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and [ScatterMoE](https://github.com/shawntan/sca...
__init__
python
huggingface/transformers
src/transformers/models/jetmoe/modeling_jetmoe.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jetmoe/modeling_jetmoe.py
Apache-2.0
def forward(self, inputs, expert_size): """ Forward pass of the JetMoeParallelExperts module. Args: inputs (Tensor): Input tensor. expert_size: Expert size information. Returns: Tensor: Output tensor. """ ...
Forward pass of the JetMoeParallelExperts module. Args: inputs (Tensor): Input tensor. expert_size: Expert size information. Returns: Tensor: Output tensor.
forward
python
huggingface/transformers
src/transformers/models/jetmoe/modeling_jetmoe.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jetmoe/modeling_jetmoe.py
Apache-2.0
def __init__(self, input_size: int, num_experts: int, top_k: int): """ Initialize the top-k gating mechanism. Args: input_size (`int`): Size of the input. num_experts (`int`): Number of experts. top_k (`int`): N...
Initialize the top-k gating mechanism. Args: input_size (`int`): Size of the input. num_experts (`int`): Number of experts. top_k (`int`): Number of top experts to select.
__init__
python
huggingface/transformers
src/transformers/models/jetmoe/modeling_jetmoe.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jetmoe/modeling_jetmoe.py
Apache-2.0
def map(self, layer_input): """ Map inputs to attention experts according to routing decision and compute query projection inside each experts. """ # Compute gating topology bsz, length, emb_size = layer_input.size() layer_input = layer_input.reshape(-1, emb_size) # [bs...
Map inputs to attention experts according to routing decision and compute query projection inside each experts.
map
python
huggingface/transformers
src/transformers/models/jetmoe/modeling_jetmoe.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jetmoe/modeling_jetmoe.py
Apache-2.0
def reduce(self, layer_input, topo_info): """ Compute output projection inside each attention experts and merge the outputs of different experts. """ bsz, length, k, hidden_size = layer_input.size() layer_input = layer_input.reshape(-1, hidden_size) # [bsz * length * k, hidden_s...
Compute output projection inside each attention experts and merge the outputs of different experts.
reduce
python
huggingface/transformers
src/transformers/models/jetmoe/modeling_jetmoe.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jetmoe/modeling_jetmoe.py
Apache-2.0
def __init__(self, config: JetMoeConfig, layer_idx: Optional[int] = None): """ Initialize the JetMoeAttention module. Args: config: Configuration object with model hyperparameters. layer_idx: Index of the layer in the model. """ ...
Initialize the JetMoeAttention module. Args: config: Configuration object with model hyperparameters. layer_idx: Index of the layer in the model.
__init__
python
huggingface/transformers
src/transformers/models/jetmoe/modeling_jetmoe.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jetmoe/modeling_jetmoe.py
Apache-2.0
def forward( self, hidden_states: Optional[torch.FloatTensor], attention_mask: Optional[torch.FloatTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, use_cache: Optional[bool] = False, output_attentions: Option...
Forward pass of the JetMoeAttention module. Args: hidden_states (Optional[torch.FloatTensor]): Input hidden states. attention_mask (Optional[torch.FloatTensor]): Attention mask. layer_past (Optional[Tuple[torch.Tensor]]): Past layer state. use_cache (Opt...
forward
python
huggingface/transformers
src/transformers/models/jetmoe/modeling_jetmoe.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jetmoe/modeling_jetmoe.py
Apache-2.0
def __init__(self, config: JetMoeConfig, layer_idx: Optional[int] = None): """ Initialize the JetMoeBlock module. Args: config: Configuration object with model hyperparameters. """ super().__init__() self.input_layernorm = JetMoeRMSNorm(config...
Initialize the JetMoeBlock module. Args: config: Configuration object with model hyperparameters.
__init__
python
huggingface/transformers
src/transformers/models/jetmoe/modeling_jetmoe.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/jetmoe/modeling_jetmoe.py
Apache-2.0
def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, image_embeds: Optional[torch.Tensor] = None, image_embeds_position_mask: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, ...
image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0, 1]`: - 1 for places where to put the image features, - 0 for...
forward
python
huggingface/transformers
src/transformers/models/kosmos2/modeling_kosmos2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/kosmos2/modeling_kosmos2.py
Apache-2.0
def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, image_embeds: Optional[torch.Tensor] = None, image_embeds_position_mask: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, ...
image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0, 1]`: - 1 for places where to put the image features, - 0 for...
forward
python
huggingface/transformers
src/transformers/models/kosmos2/modeling_kosmos2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/kosmos2/modeling_kosmos2.py
Apache-2.0
def get_image_features( self, pixel_values: torch.FloatTensor, return_attentions: Optional[bool] = False, interpolate_pos_encoding: Optional[bool] = False, ): """ Encodes images into continuous embeddings that can be forwarded to the language model. Args: ...
Encodes images into continuous embeddings that can be forwarded to the language model. Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, image_size, image_size)`): The tensors corresponding to the input images. return_attentions (`bool...
get_image_features
python
huggingface/transformers
src/transformers/models/kosmos2/modeling_kosmos2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/kosmos2/modeling_kosmos2.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.Tensor] = None, input_ids: Optional[torch.Tensor] = None, image_embeds_position_mask: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, head_mask: Optional[torch.Tensor] = None, past_key_v...
image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0, 1]`: - 1 for places where to put the image features, - 0 for...
forward
python
huggingface/transformers
src/transformers/models/kosmos2/modeling_kosmos2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/kosmos2/modeling_kosmos2.py
Apache-2.0
def forward( self, pixel_values: Optional[torch.Tensor] = None, input_ids: Optional[torch.Tensor] = None, image_embeds_position_mask: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, head_mask: Optional[torch.Tensor] = None, past_key_v...
image_embeds_position_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to indicate the location in a sequence to insert the image features . Mask values selected in `[0, 1]`: - 1 for places where to put the image features, - 0 for...
forward
python
huggingface/transformers
src/transformers/models/kosmos2/modeling_kosmos2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/kosmos2/modeling_kosmos2.py
Apache-2.0
def __call__( self, images: ImageInput = None, text: Union[TextInput, List[TextInput]] = None, audio=None, videos=None, **kwargs: Unpack[Kosmos2ProcessorKwargs], ) -> BatchFeature: """ This method uses [`CLIPImageProcessor.__call__`] method to prepare ...
This method uses [`CLIPImageProcessor.__call__`] method to prepare image(s) for the model, and [`XLMRobertaTokenizerFast.__call__`] to prepare text for the model. Please refer to the docstring of the above two methods for more information. The rest of this documentation shows the argu...
__call__
python
huggingface/transformers
src/transformers/models/kosmos2/processing_kosmos2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/kosmos2/processing_kosmos2.py
Apache-2.0
def post_process_image_text_to_text(self, generated_outputs, skip_special_tokens=True, **kwargs): """ 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 o...
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/kosmos2/processing_kosmos2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/kosmos2/processing_kosmos2.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, bbox: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_m...
bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*): Bounding boxes of each input sequence tokens. Selected in the range `[0, config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, whe...
forward
python
huggingface/transformers
src/transformers/models/layoutlm/modeling_layoutlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlm/modeling_layoutlm.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, bbox: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_m...
bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*): Bounding boxes of each input sequence tokens. Selected in the range `[0, config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, whe...
forward
python
huggingface/transformers
src/transformers/models/layoutlm/modeling_layoutlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlm/modeling_layoutlm.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, bbox: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_m...
bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*): Bounding boxes of each input sequence tokens. Selected in the range `[0, config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, whe...
forward
python
huggingface/transformers
src/transformers/models/layoutlm/modeling_layoutlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlm/modeling_layoutlm.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, bbox: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_m...
bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*): Bounding boxes of each input sequence tokens. Selected in the range `[0, config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, whe...
forward
python
huggingface/transformers
src/transformers/models/layoutlm/modeling_layoutlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlm/modeling_layoutlm.py
Apache-2.0
def __init__(self, config, has_visual_segment_embedding=True): r""" has_visual_segment_embedding (`bool`, *optional*, defaults to `True`): Whether or not to add visual segment embeddings. """ super().__init__(config) self.num_labels = config.num_labels self.l...
has_visual_segment_embedding (`bool`, *optional*, defaults to `True`): Whether or not to add visual segment embeddings.
__init__
python
huggingface/transformers
src/transformers/models/layoutlm/modeling_layoutlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlm/modeling_layoutlm.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, bbox: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, head_m...
bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*): Bounding boxes of each input sequence tokens. Selected in the range `[0, config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, whe...
forward
python
huggingface/transformers
src/transformers/models/layoutlm/modeling_layoutlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlm/modeling_layoutlm.py
Apache-2.0
def call( self, input_ids: TFModelInputType | None = None, bbox: np.ndarray | tf.Tensor | None = None, attention_mask: np.ndarray | tf.Tensor | None = None, token_type_ids: np.ndarray | tf.Tensor | None = None, position_ids: np.ndarray | tf.Tensor | None = None, h...
start_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*): Labels for position (index) of the start of the labelled span for computing the token classification loss. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the...
call
python
huggingface/transformers
src/transformers/models/layoutlm/modeling_tf_layoutlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlm/modeling_tf_layoutlm.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 LayoutLM 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 LayoutLM 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 `N...
create_token_type_ids_from_sequences
python
huggingface/transformers
src/transformers/models/layoutlm/tokenization_layoutlm.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlm/tokenization_layoutlm.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, bbox: Optional[torch.LongTensor] = None, image: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids...
bbox (`torch.LongTensor` of shape `((batch_size, sequence_length), 4)`, *optional*): Bounding boxes of each input sequence tokens. Selected in the range `[0, config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1) format, w...
forward
python
huggingface/transformers
src/transformers/models/layoutlmv2/modeling_layoutlmv2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, bbox: Optional[torch.LongTensor] = None, image: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids...
input_ids (`torch.LongTensor` of shape `batch_size, sequence_length`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [Wha...
forward
python
huggingface/transformers
src/transformers/models/layoutlmv2/modeling_layoutlmv2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py
Apache-2.0
def forward( self, input_ids: Optional[torch.LongTensor] = None, bbox: Optional[torch.LongTensor] = None, image: Optional[torch.FloatTensor] = None, attention_mask: Optional[torch.FloatTensor] = None, token_type_ids: Optional[torch.LongTensor] = None, position_ids...
input_ids (`torch.LongTensor` of shape `batch_size, sequence_length`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [Wha...
forward
python
huggingface/transformers
src/transformers/models/layoutlmv2/modeling_layoutlmv2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py
Apache-2.0
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...
Pad encoded inputs (on left/right and up to predefined length or max length in the batch) Args: 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 opt...
_pad
python
huggingface/transformers
src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
https://github.com/huggingface/transformers/blob/master/src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
Apache-2.0