text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
if input_ids is None and query_embeds is None: raise ValueError("You have to specify query_embeds when input_ids is None") # past_key_values_length past_key_values_length = ( past_key_values[0][0].shape[2] - self.config.query_length if past_key_values is not None else 0 ...
9,142
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, device) # If a 2D or 3D attenti...
9,142
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
if isinstance(encoder_attention_mask, list): encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask] elif encoder_attention_mask is None: encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) e...
9,142
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
# Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_lengt...
9,142
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, past_key_values=past_key_values, ...
9,142
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, past_key_values=encoder_outputs.past_key_values, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, ...
9,142
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
class InstructBlipVideoForConditionalGeneration(InstructBlipVideoPreTrainedModel, GenerationMixin): config_class = InstructBlipVideoConfig main_input_name = "pixel_values" def __init__(self, config: InstructBlipVideoConfig): super().__init__(config) self.vision_model = InstructBlipVideoVis...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
if language_model._keep_in_fp32_modules is not None: self._keep_in_fp32_modules.extend(language_model._keep_in_fp32_modules) self.language_model = language_model # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return sel...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
def _tie_weights(self): if not self.config.use_decoder_only_language_model: self.language_model.encoder.embed_tokens = self.language_model.shared self.language_model.decoder.embed_tokens = self.language_model.shared def _preprocess_accelerate(self): r""" Some pre-pro...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
if len(hf_device_map) > 1 and "language_model" not in hf_device_map and torch.cuda.device_count() > 1: # warn users about unexpected behavior when using multi-GPU + InstructBlipVideo + `accelerate`. logger.warning( "The `language_model` is not in the `hf_device_map` dictionary an...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
@add_start_docstrings_to_model_forward(INSTRUCTBLIPVIDEO_INPUTS_DOCSTRING) @replace_return_docstrings( output_type=InstructBlipVideoForConditionalGenerationModelOutput, config_class=InstructBlipVideoVisionConfig ) def forward( self, pixel_values: torch.FloatTensor, qformer_in...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.voc...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
Returns: Examples: ```python >>> from transformers import InstructBlipVideoProcessor, InstructBlipVideoForConditionalGeneration >>> import torch >>> from huggingface_hub import hf_hub_download >>> import av >>> import numpy as np
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
>>> def read_video_pyav(container, indices): ... ''' ... Decode the video with PyAV decoder. ... Args: ... container (`av.container.input.InputContainer`): PyAV container. ... indices (`List[int]`): List of frame indices to decode. ... Retu...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
>>> model = InstructBlipVideoForConditionalGeneration.from_pretrained("Salesforce/instructblip-vicuna-7b", device_map="auto") >>> processor = InstructBlipVideoProcessor.from_pretrained("Salesforce/instructblip-vicuna-7b") >>> file_path = hf_hub_download( ... repo_id="nielsr/video-demo", f...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
>>> outputs = model.generate( ... **inputs, ... do_sample=False, ... num_beams=5, ... max_length=256, ... repetition_penalty=1.5, ... length_penalty=1.0, ... ) >>> generated_text = processor.batch_decode(outputs, skip_special_tokens...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
vision_outputs = self.vision_model( pixel_values=pixel_values, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, interpolate_pos_encoding=interpolate_pos_encoding, ) image_embeds = vision_o...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
qformer_input_ids = qformer_input_ids.repeat_interleave(frames, dim=0) qformer_attention_mask = qformer_attention_mask.repeat_interleave(frames, dim=0) qformer_attention_mask = torch.cat([query_attention_mask, qformer_attention_mask], dim=1) query_outputs = self.qformer( input_ids=qf...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
# unbatch inputs back, each video-frame gets `num_query_tokens` seq length language_model_inputs = language_model_inputs.reshape(batch_size, self.config.num_query_tokens * frames, -1) language_model_attention_mask = torch.ones( language_model_inputs.size()[:-1], dtype=torch.long, device=lang...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
# if the model already has "video_token_index" then the input is expanded to account for image embeds # otherwise we expand manually by concatenating if getattr(self.config, "video_token_index", None) is not None: special_image_mask = (input_ids == self.config.video_token_index).unsqueeze(-1...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
attention_mask = torch.cat( [language_model_attention_mask, attention_mask.to(language_model_attention_mask.device)], dim=1 )
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
if self.config.use_decoder_only_language_model: outputs = self.language_model( inputs_embeds=inputs_embeds, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_di...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
loss = loss_fct(shift_logits.view(-1, self.config.text_config.vocab_size), shift_labels.view(-1)) else: outputs = self.language_model( inputs_embeds=inputs_embeds, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids, deco...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
return InstructBlipVideoForConditionalGenerationModelOutput( loss=loss, logits=logits, vision_outputs=vision_outputs, qformer_outputs=query_outputs, language_model_outputs=outputs, ) @torch.no_grad() def generate( self, pixel_v...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
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. qformer_input_ids (`torch.LongTensor` of shape (batch_size, sequence_length), *optional*):...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
Whether to interpolate the positional encoding of the image embeddings.
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
Returns: captions (list): A list of strings of length batch_size * num_captions. """ if hasattr(self, "hf_device_map"): # preprocess for `accelerate` self._preprocess_accelerate() # we process in a batched way, later unbatch it back (video has frames=4) ...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1) query_attention_mask = torch.ones(query_tokens.size()[:-1], dtype=torch.long, device=image_embeds.device) if qformer_attention_mask is None: qformer_attention_mask = torch.ones_like(qformer_input_ids) qformer_inp...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
language_model_inputs = self.language_projection(query_output) # unbatch the embeddings back by moving frames to seq-len language_model_inputs = language_model_inputs.reshape(batch_size, self.config.num_query_tokens * frames, -1) language_attention_mask = torch.ones( language_model_...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
# if the model already has "video_token_index" then the input is expanded to account for image embeds # otherwise we expand manually by concatenating if getattr(self.config, "video_token_index", None) is not None: special_image_mask = (input_ids == self.config.video_token_index).unsqueeze(-1...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
attention_mask = torch.cat( [language_attention_mask, attention_mask.to(language_attention_mask.device)], dim=1 )
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
# add image_embeds length to max_length, so that the final max_length in counted only on token embeds # -1 is to account for the prepended BOS after `generate.` if not self.language_model.config.is_encoder_decoder: generate_kwargs["max_length"] = ( generate_kw...
9,143
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
class InstructBlipVideoProcessor(ProcessorMixin): r""" Constructs an InstructBLIPVideo processor which wraps a InstructBLIP image processor and a LLaMa/T5 tokenizer into a single processor. [`InstructBlipVideoProcessor`] offers all the functionalities of [`InstructBlipVideoImageProcessor`] and [`AutoTo...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
Args: image_processor (`InstructBlipVideoImageProcessor`): An instance of [`InstructBlipVideoImageProcessor`]. The image processor is a required input. tokenizer (`AutoTokenizer`): An instance of ['PreTrainedTokenizer`]. The tokenizer is a required input. qformer_tokenize...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
def __init__(self, image_processor, tokenizer, qformer_tokenizer, num_query_tokens=None, **kwargs): if not hasattr(tokenizer, "video_token"): self.video_token = AddedToken("<video>", normalized=False, special=True) tokenizer.add_tokens([self.video_token], special_tokens=True) els...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
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]...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
[`BertTokenizerFast.__call__`] to prepare text for the model.
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
Please refer to the docstring of the above two methods for more information. """ if images is None and text is None: raise ValueError("You have to specify at least one of images or text.") encoding = BatchFeature() if text is not None: if isinstance(text, str): ...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
_text_encoding = self.tokenizer( text=text, add_special_tokens=add_special_tokens, padding=padding, truncation=truncation, max_length=max_length, stride=stride, pad_to_multiple_of=pad_to_multiple_of, ...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
# if we know how many query tokens, expand text inside processor. We need this hacky manipulation # because BLIP expects image tokens to be at the beginning even before BOS token if self.num_query_tokens is not None and images is not None: text_encoding = {} video...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
logger.warning_once( "Expanding inputs for video tokens in InstructBLIPVideo should be done in processing. " "Please follow instruction here (https://gist.github.com/zucchini-nlp/65f22892b054dc0d68228af56fbeaac2) to update your InstructBLIPVideo model. " ...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
# cast to desired return tensors type after concatenating text_encoding = BatchEncoding(text_encoding, tensor_type=return_tensors) encoding.update(text_encoding) qformer_text_encoding = self.qformer_tokenizer( text=text, add_special_tokens=add_special_...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
) encoding["qformer_input_ids"] = qformer_text_encoding.pop("input_ids") encoding["qformer_attention_mask"] = qformer_text_encoding.pop("attention_mask")
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
if images is not None: image_encoding = self.image_processor(images, return_tensors=return_tensors) encoding.update(image_encoding) return encoding # Copied from transformers.models.blip.processing_blip.BlipProcessor.batch_decode with BertTokenizerFast->PreTrainedTokenizer def ...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
# Copied from transformers.models.blip.processing_blip.BlipProcessor.decode with BertTokenizerFast->PreTrainedTokenizer def decode(self, *args, **kwargs): """ This method forwards all its arguments to PreTrainedTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of thi...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
# overwrite to save the Q-Former tokenizer in a separate folder def save_pretrained(self, save_directory, **kwargs): if os.path.isfile(save_directory): raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file") os.makedirs(save_directory, exist_ok=True) ...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
# overwrite to load the Q-Former tokenizer from a separate folder @classmethod def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): processor = super().from_pretrained(pretrained_model_name_or_path, **kwargs) # if return_unused_kwargs a tuple is returned where the second element i...
9,144
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/processing_instructblipvideo.py
class InstructBlipVideoVisionConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`InstructBlipVideoVisionModel`]. It is used to instantiate a InstructBlipVideo vision encoder according to the specified arguments, defining the model architecture. Instantiating ...
9,145
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
Args: hidden_size (`int`, *optional*, defaults to 1408): Dimensionality of the encoder layers and the pooler layer. intermediate_size (`int`, *optional*, defaults to 6144): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. num_hid...
9,145
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
`"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported. to 1e-5): The epsilon used by the layer normalization layers. layer_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the layer normalization layers. attention_dropout (`float`, *optional*, defaults ...
9,145
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
Example: ```python >>> from transformers import InstructBlipVideoVisionConfig, InstructBlipVideoVisionModel >>> # Initializing a InstructBlipVideoVisionConfig with Salesforce/instruct-blip-flan-t5 style configuration >>> configuration = InstructBlipVideoVisionConfig() >>> # Initializing a Instruc...
9,145
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
def __init__( self, hidden_size=1408, intermediate_size=6144, num_hidden_layers=39, num_attention_heads=16, image_size=224, patch_size=14, hidden_act="gelu", layer_norm_eps=1e-6, attention_dropout=0.0, initializer_range=1e-10, ...
9,145
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
class InstructBlipVideoQFormerConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`InstructBlipVideoQFormerModel`]. It is used to instantiate a InstructBlipVideo Querying Transformer (Q-Former) model according to the specified arguments, defining the model arc...
9,146
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
Args: vocab_size (`int`, *optional*, defaults to 30522): Vocabulary size of the Q-Former model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling the model. hidden_size (`int`, *optional*, defaults to 768): Dimensio...
9,146
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. hidden_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout probability for all fully connected layers in the embeddings,...
9,146
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
The epsilon used by the layer normalization layers. pad_token_id (`int`, *optional*, defaults to 0): Token id used for padding sequences. position_embedding_type (`str`, *optional*, defaults to `"absolute"`): Type of position embedding. Choose one of `"absolute"`, `"relative_key"...
9,146
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
encoder_hidden_size (`int`, *optional*, defaults to 1408): The hidden size of the hidden states for cross-attention.
9,146
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
Examples: ```python >>> from transformers import InstructBlipVideoQFormerConfig, InstructBlipVideoQFormerModel >>> # Initializing a InstructBlipVideo Salesforce/instruct-blip-flan-t5 style configuration >>> configuration = InstructBlipVideoQFormerConfig() >>> # Initializing a model (with random w...
9,146
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
def __init__( self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, ...
9,146
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob ...
9,146
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
class InstructBlipVideoConfig(PretrainedConfig): r""" [`InstructBlipVideoConfig`] is the configuration class to store the configuration of a [`InstructBlipVideoForConditionalGeneration`]. It is used to instantiate a Instructblipvideo model according to the specified arguments, defining the vision model,...
9,147
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
Args: vision_config (`dict`, *optional*): Dictionary of configuration options used to initialize [`InstructBlipVideoVisionConfig`]. qformer_config (`dict`, *optional*): Dictionary of configuration options used to initialize [`InstructBlipVideoQFormerConfig`]. text_config ...
9,147
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
>>> # Initializing a InstructBlipVideoConfig with Salesforce/instruct-blip-flan-t5 style configuration >>> configuration = InstructBlipVideoConfig() >>> # Initializing a InstructBlipVideoForConditionalGeneration (with random weights) from the Salesforce/instruct-blip-flan-t5 style configuration >>> model =...
9,147
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
model_type = "instructblipvideo" sub_configs = { "text_config": AutoConfig, "qformer_config": InstructBlipVideoQFormerConfig, "vision_config": InstructBlipVideoVisionConfig, } def __init__( self, vision_config=None, qformer_config=None, text_config=No...
9,147
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
self.vision_config = InstructBlipVideoVisionConfig(**vision_config) self.qformer_config = InstructBlipVideoQFormerConfig(**qformer_config) text_model_type = text_config["model_type"] if "model_type" in text_config else "opt" self.text_config = CONFIG_MAPPING[text_model_type](**text_config) ...
9,147
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
@classmethod def from_vision_qformer_text_configs( cls, vision_config: InstructBlipVideoVisionConfig, qformer_config: InstructBlipVideoQFormerConfig, text_config: PretrainedConfig, **kwargs, ): r""" Instantiate a [`InstructBlipVideoConfig`] (or a derived c...
9,147
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/configuration_instructblipvideo.py
class InstructBlipVideoImageProcessor(BaseImageProcessor): r""" Constructs a InstructBLIPVideo image processor.
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the `do_resize` parameter in the `preprocess` method. size (`dict`, *optional*, defaults to `{"height": 384, "width": 3...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`): Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be overridden by the `rescale_factor` parameter in the `preprocess` method. do_normalize (`bool`, *optional*, defaults ...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`): Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` metho...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
model_input_names = ["pixel_values"] def __init__( self, do_resize: bool = True, size: Dict[str, int] = None, resample: PILImageResampling = PILImageResampling.BICUBIC, do_rescale: bool = True, rescale_factor: Union[int, float] = 1 / 255, do_normalize: bool =...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
self.do_resize = do_resize self.size = size self.resample = resample self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.do_normalize = do_normalize self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN self.image_std = im...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels,...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
Returns: `np.ndarray`: The resized image. """ size = get_size_dict(size) if "height" not in size or "width" not in size: raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}") output_size = (size["height"], size["...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
# Ignore copy @filter_out_non_signature_kwargs() 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_facto...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
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 `do_rescale=False`. do_resize (`bool`, *optional*, ...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
Resampling filter to use if resizing the video. Only has an effect if `do_resize` is set to `True`. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the video values between [0 - 1]. rescale_factor (`float`, *optional*, defaults to `self.rescale_...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`): Whether to convert the image to RGB. return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return. Can be one of: - Unset: Return a list of `np.ndarray`. ...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - Unset: Use the channel dimension format of the input image. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor do_normalize = do_normalize if do_normalize is not None else self.do_normalize image_mean = image_mean if image_mean is not None else self.image_mean image_std = image_std if image_std is not None else self.im...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
size = size if size is not None else self.size size = get_size_dict(size, default_to_square=False) videos = make_batched_videos(images) validate_preprocess_arguments( do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, ...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
pixel_values = [ [ self._preprocess_image( image=frame, do_resize=do_resize, size=size, resample=resample, do_rescale=do_rescale, rescale_factor=rescale_factor, ...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
# Ignore copy def _preprocess_image( self, image: ImageInput = 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, ...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
if do_rescale and is_scaled_image(image): logger.warning_once( "It looks like you are trying to rescale already rescaled video frames. If the input" " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again." ) if in...
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
return image
9,148
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/instructblipvideo/image_processing_instructblipvideo.py
class GPT2Tokenizer(PreTrainedTokenizer): """ Construct a GPT-2 tokenizer. Based on byte-level Byte-Pair-Encoding. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will be encoded differently whether it is at the beginning of the sentence (wi...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
Args: vocab_file (`str`): Path to the vocabulary file. merges_file (`str`): Path to the merges file. errors (`str`, *optional*, defaults to `"replace"`): Paradigm to follow when decoding bytes to UTF-8. See [bytes.decode](https://docs.python.org/3/...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
add_prefix_space (`bool`, *optional*, defaults to `False`): Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. (GPT2 tokenizer detect beginning of words by the preceding space). add_bos_token (`bool`, *optional*, defaults to...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
vocab_files_names = VOCAB_FILES_NAMES model_input_names = ["input_ids", "attention_mask"] def __init__( self, vocab_file, merges_file, errors="replace", unk_token="<|endoftext|>", bos_token="<|endoftext|>", eos_token="<|endoftext|>", pad_token=Non...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
with open(vocab_file, encoding="utf-8") as vocab_handle: self.encoder = json.load(vocab_handle) self.decoder = {v: k for k, v in self.encoder.items()} self.errors = errors # how to handle errors in decoding self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v: k for...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
super().__init__( errors=errors, unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, pad_token=pad_token, add_prefix_space=add_prefix_space, add_bos_token=add_bos_token, **kwargs, ) @property def ...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
while True: bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf"))) if bigram not in self.bpe_ranks: break first, second = bigram new_word = [] i = 0 while i < len(word): try: ...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
if word[i] == first and i < len(word) - 1 and word[i + 1] == second: new_word.append(first + second) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) word = new_word ...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False ) -> List[int]: """ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding special tokens...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
Returns: `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=Tru...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
def _tokenize(self, text): """Tokenize a string.""" bpe_tokens = [] for token in re.findall(self.pat, text): token = "".join( self.byte_encoder[b] for b in token.encode("utf-8") ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
def convert_tokens_to_string(self, tokens): """Converts a sequence of tokens (string) in a single string.""" text = "".join(tokens) text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors) return text def save_vocabulary(self, save_directory: str, f...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py
index = 0 with open(merge_file, "w", encoding="utf-8") as writer: writer.write("#version: 0.2\n") for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]): if index != token_index: logger.warning( f"Sa...
9,149
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/gpt2/tokenization_gpt2.py