text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
class VideoLlavaForConditionalGeneration(VideoLlavaPreTrainedModel, GenerationMixin): def __init__(self, config: VideoLlavaConfig): super().__init__(config) self.video_tower = AutoModel.from_config(config.vision_config) self.image_tower = AutoModel.from_config(config.vision_config) self.multi_modal_projector = VideoLlavaMultiModalProjector(config) self.vocab_size = config.text_config.vocab_size self.language_model = AutoModelForCausalLM.from_config(config.text_config) if self.language_model._tied_weights_keys is not None: self._tied_weights_keys = [f"language_model.{k}" for k in self.language_model._tied_weights_keys] self.pad_token_id = self.config.pad_token_id if self.config.pad_token_id is not None else -1 self.post_init() def get_input_embeddings(self): return self.language_model.get_input_embeddings() def set_input_embeddings(self, value): self.language_model.set_input_embeddings(value)
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
def get_output_embeddings(self): return self.language_model.get_output_embeddings() def set_output_embeddings(self, new_embeddings): self.language_model.set_output_embeddings(new_embeddings) def set_decoder(self, decoder): self.language_model.set_decoder(decoder) def get_decoder(self): return self.language_model.get_decoder() def _merge_input_ids_with_visual_features( self, visual_features, inputs_embeds, input_ids, attention_mask, labels, num_frames=1 ): num_images, num_image_patches, embed_dim = visual_features.shape batch_size, sequence_length = input_ids.shape left_padding = not torch.sum(input_ids[:, -1] == torch.tensor(self.pad_token_id)) special_vision_token = self.config.video_token_index if num_frames > 1 else self.config.image_token_index
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
# 1. Create a mask to know where special image tokens are special_image_token_mask = input_ids == special_vision_token num_special_image_tokens = torch.sum(special_image_token_mask, dim=-1) # Compute the maximum embed dimension max_seq_len = (num_special_image_tokens.max() * (num_image_patches * num_frames - 1)) + sequence_length batch_indices, non_image_indices = torch.where(input_ids != special_vision_token)
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
# 2. Compute the positions where text should be written # Calculate new positions for text tokens in merged image-text sequence. # `special_image_token_mask` identifies image tokens. Each image token will be replaced by `nb_text_tokens_per_images - 1` text tokens. # `torch.cumsum` computes how each image token shifts subsequent text token positions. # - 1 to adjust for zero-based indexing, as `cumsum` inherently increases indices by one. new_token_positions = ( torch.cumsum((special_image_token_mask * (num_image_patches * num_frames - 1) + 1), dim=-1) - 1 ) nb_image_pad = max_seq_len - 1 - new_token_positions[:, -1] if left_padding: new_token_positions += nb_image_pad[:, None] # offset for left padding text_to_overwrite = new_token_positions[batch_indices, non_image_indices]
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
# 3. Create the full embedding, already padded to the maximum position # expand input ids so that the second "merge" with videos does not fail final_embedding = torch.zeros( batch_size, max_seq_len, embed_dim, dtype=inputs_embeds.dtype, device=inputs_embeds.device ) final_attention_mask = torch.zeros( batch_size, max_seq_len, dtype=attention_mask.dtype, device=inputs_embeds.device ) final_input_ids = torch.full( (batch_size, max_seq_len), self.pad_token_id, dtype=input_ids.dtype, device=inputs_embeds.device ) # In case the Vision model or the Language model has been offloaded to CPU, we need to manually # set the corresponding tensors into their correct target device. target_device = inputs_embeds.device batch_indices, non_image_indices, text_to_overwrite = ( batch_indices.to(target_device), non_image_indices.to(target_device),
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
text_to_overwrite.to(target_device), ) attention_mask = attention_mask.to(target_device)
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
# 4. Fill the embeddings based on the mask. If we have ["hey" "<image>", "how", "are"] # we need to index copy on [0, 577, 578, 579] for the text and [1:576] for the image features final_embedding[batch_indices, text_to_overwrite] = inputs_embeds[batch_indices, non_image_indices] final_attention_mask[batch_indices, text_to_overwrite] = attention_mask[batch_indices, non_image_indices] final_input_ids[batch_indices, text_to_overwrite] = input_ids[batch_indices, non_image_indices] if labels is not None: final_labels = torch.full( (batch_size, max_seq_len), self.config.ignore_index, dtype=input_ids.dtype, device=input_ids.device ) final_labels[batch_indices, text_to_overwrite] = labels[batch_indices, non_image_indices] else: final_labels = None
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
# 5. Fill the embeddings corresponding to the images. Anything that is still zeros needs filling image_to_overwrite = torch.full((batch_size, max_seq_len), True, dtype=torch.bool, device=inputs_embeds.device) image_to_overwrite[batch_indices, text_to_overwrite] = False if left_padding: image_to_overwrite &= image_to_overwrite.cumsum(-1) - 1 >= nb_image_pad[:, None].to(target_device) else: mask = torch.ones_like(image_to_overwrite, dtype=torch.bool).cumsum(-1) - 1 padding_mask = mask <= new_token_positions[:, -1:].to(target_device) image_to_overwrite &= padding_mask
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
if image_to_overwrite.sum() != visual_features.shape[:-1].numel(): visual_type = "videos" if num_frames == 8 else "images" num_images //= num_frames raise ValueError( f"The input provided to the model are wrong. The number of {visual_type} tokens is {torch.sum(special_image_token_mask)} while" f" the number of {visual_type} given to the model is {num_images}. This prevents correct indexing and breaks batch generation." ) final_embedding[image_to_overwrite] = visual_features.contiguous().reshape(-1, embed_dim).to(target_device) final_attention_mask |= image_to_overwrite position_ids = (final_attention_mask.cumsum(-1) - 1).masked_fill_((final_attention_mask == 0), 1) return final_embedding, final_attention_mask, final_labels, position_ids, final_input_ids
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
def get_image_features( self, pixel_values_images: torch.FloatTensor, vision_feature_layer: int, vision_feature_select_strategy: str ): """ Obtains image last hidden states from the vision tower and apply multimodal projection. Args: pixel_values_images (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`) The tensors corresponding to the input images. vision_feature_layer (`int`): The index of the layer to select the vision feature. vision_feature_select_strategy (`str`): The feature selection strategy used to select the vision feature from the vision backbone. Can be one of `"default"` or `"full"` Returns: image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`). """
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
image_outputs = self.image_tower(pixel_values_images, output_hidden_states=True) image_outputs = image_outputs.hidden_states[vision_feature_layer].squeeze(1) if vision_feature_select_strategy == "default": image_outputs = image_outputs[:, 1:] elif vision_feature_select_strategy == "full": image_outputs = image_outputs else: raise ValueError(f"Unexpected select feature strategy: {self.config.vision_feature_select_strategy}") image_features = self.multi_modal_projector(image_outputs) return image_features def get_video_features(self, pixel_values_videos: torch.FloatTensor, vision_feature_layer: int): """ Obtains video last hidden states from the vision tower and apply multimodal projection.
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
Args: pixel_values_videos (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`) The tensors corresponding to the input videos. vision_feature_layer (`int`): The index of the layer to select the vision feature. Returns: video_features (`torch.Tensor`): Video feature tensor of shape `(num_videos * num_frames, image_length, embed_dim)`). frames (`int`): Number of frames the videos have. """ batch_size_vid, num_frames, channels, height, width = pixel_values_videos.shape pixel_values = pixel_values_videos.reshape(batch_size_vid * num_frames, channels, height, width) video_outputs = self.video_tower(pixel_values, output_hidden_states=True) video_features = video_outputs.hidden_states[vision_feature_layer].squeeze(1) video_features = self.multi_modal_projector(video_features) return video_features, num_frames
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
@add_start_docstrings_to_model_forward(VIDEO_LLAVA_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=VideoLlavaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids: torch.LongTensor = None, pixel_values_images: torch.FloatTensor = None, pixel_values_videos: 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: Optional[torch.FloatTensor] = None, vision_feature_layer: Optional[int] = None, vision_feature_select_strategy: Optional[str] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None,
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
num_logits_to_keep: int = 0, ) -> Union[Tuple, VideoLlavaCausalLMOutputWithPast]: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
num_logits_to_keep (`int`, *optional*): Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. Returns: Example: ```python >>> from PIL import Image >>> import requests >>> import numpy as np >>> import av >>> from huggingface_hub import hf_hub_download >>> from transformers import VideoLlavaProcessor, VideoLlavaForConditionalGeneration
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.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. ... Returns: ... result (np.ndarray): np array of decoded frames of shape (num_frames, height, width, 3). ... ''' ... frames = [] ... container.seek(0) ... start_index = indices[0] ... end_index = indices[-1] ... for i, frame in enumerate(container.decode(video=0)): ... if i > end_index: ... break ... if i >= start_index and i in indices: ... frames.append(frame) ... return np.stack([x.to_ndarray(format="rgb24") for x in frames])
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
>>> model = VideoLlavaForConditionalGeneration.from_pretrained("LanguageBind/Video-LLaVA-7B-hf") >>> processor = VideoLlavaProcessor.from_pretrained("LanguageBind/Video-LLaVA-7B-hf") >>> prompt = "USER: <video>\nWhy is this video funny? ASSISTANT:" >>> video_path = hf_hub_download(repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset") >>> container = av.open(video_path) >>> # sample uniformly 8 frames from the video >>> total_frames = container.streams.video[0].frames >>> indices = np.arange(0, total_frames, total_frames / 8).astype(int) >>> clip = read_video_pyav(container, indices) >>> inputs = processor(text=prompt, videos=clip, return_tensors="pt")
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
>>> # Generate >>> generate_ids = model.generate(**inputs, max_length=80) >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "USER: Why is this video funny? ASSISTANT: The video is funny because the baby is playing with a Wii remote while sitting on the floor, and the baby is wearing glasses.Ъ. The baby's actions are amusing because it is a young child trying to interact with a video game, which is not a typical activity for a" >>> # to generate from image and video mix >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> prompt = [ ... "USER: <image>\nHow many cats do you see? ASSISTANT:", ... "USER: <video>\nWhy is this video funny? ASSISTANT:" ... ] >>> inputs = processor(text=prompt, images=image, videos=clip, padding=True, return_tensors="pt")
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
>>> # Generate >>> generate_ids = model.generate(**inputs, max_length=50) >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True) ['USER: How many cats do you see? ASSISTANT: There are two cats visible in the image. (or three, if you count the one in the background).', 'USER: Why is this video funny? ASSISTANT: The video is funny because it shows a baby sitting on a bed and playing with a Wii remote.Ъ. The baby is holding the remote'] ``` """
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict vision_feature_layer = ( vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer ) vision_feature_select_strategy = ( vision_feature_select_strategy if vision_feature_select_strategy is not None else self.config.vision_feature_select_strategy ) if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
if (pixel_values_images is not None or pixel_values_videos is not None) and inputs_embeds is not None: raise ValueError( "You cannot specify both `pixel_values_images`/`pixel_values_videos` and `inputs_embeds` at the same " "time, and must specify either one" ) if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids)
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
if pixel_values_images is not None: image_features = self.get_image_features( pixel_values_images, vision_feature_layer=vision_feature_layer, vision_feature_select_strategy=vision_feature_select_strategy, ) n_image_tokens = (input_ids == self.config.image_token_index).sum().item() n_image_features = image_features.shape[0] * image_features.shape[1] if n_image_tokens != n_image_features: raise ValueError( f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}" ) special_image_mask = (input_ids == self.config.image_token_index).unsqueeze(-1) special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device) image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
if pixel_values_videos is not None: video_features, num_frames = self.get_video_features( pixel_values_videos=pixel_values_videos, vision_feature_layer=vision_feature_layer ) n_video_tokens = (input_ids == self.config.video_token_index).sum().item() n_video_features = video_features.shape[0] * video_features.shape[1] if n_video_tokens != n_video_features: raise ValueError( f"Video features and video tokens do not match: tokens: {n_video_tokens}, features {n_video_features}" ) special_image_mask = (input_ids == self.config.video_token_index).unsqueeze(-1) special_image_mask = special_image_mask.expand_as(inputs_embeds).to(inputs_embeds.device) video_features = video_features.to(inputs_embeds.device, inputs_embeds.dtype) inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, video_features)
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
outputs = self.language_model( attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, num_logits_to_keep=num_logits_to_keep, ) logits = outputs[0]
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
loss = None if labels is not None: # Shift so that tokens < n predict n if attention_mask is not None: # we use the input attention mask to shift the logits and labels, because it is 2D. # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft shift_attention_mask = attention_mask[:, -(logits.shape[1] - 1) :].to(logits.device) shift_logits = logits[..., :-1, :][shift_attention_mask.to(logits.device) != 0].contiguous() shift_labels = labels[..., 1:][shift_attention_mask.to(labels.device) != 0].contiguous() else: shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = nn.CrossEntropyLoss() loss = loss_fct( shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1).to(shift_logits.device)
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
)
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return VideoLlavaCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, image_hidden_states=image_features if pixel_values_images is not None else None, video_hidden_states=video_features if pixel_values_videos is not None else None, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, inputs_embeds=None, pixel_values_images=None, pixel_values_videos=None, attention_mask=None, cache_position=None, num_logits_to_keep=None, **kwargs, ): # Overwritten -- in specific circumstances we don't want to forward image inputs to the model
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
model_inputs = self.language_model.prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, num_logits_to_keep=num_logits_to_keep, **kwargs, ) if cache_position[0] == 0: # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore # Otherwise we need pixel values to be passed to model model_inputs["pixel_values_images"] = pixel_values_images model_inputs["pixel_values_videos"] = pixel_values_videos return model_inputs
3,023
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/modeling_video_llava.py
class VideoLlavaImageProcessor(BaseImageProcessor): r""" Constructs a CLIP image processor.
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.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 `do_resize` in the `preprocess` method. size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`): Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess` method. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`): Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method. do_center_crop (`bool`, *optional*, defaults to `True`): Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the `preprocess` method.
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
crop_size (`Dict[str, int]` *optional*, defaults to 224): Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess` method. do_rescale (`bool`, *optional*, defaults to `True`): Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in the `preprocess` method. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`): Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess` method. do_normalize (`bool`, *optional*, defaults to `True`): Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method. image_mean (`float` or `List[float]`, *optional*, defaults to `[0.48145466, 0.4578275, 0.40821073]`):
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
Mean 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_mean` parameter in the `preprocess` method. image_std (`float` or `List[float]`, *optional*, defaults to `[0.26862954, 0.26130258, 0.27577711]`): 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` method. Can be overridden by the `image_std` parameter in the `preprocess` method. do_convert_rgb (`bool`, *optional*, defaults to `True`): Whether to convert the image to RGB. """
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
model_input_names = ["pixel_values"] def __init__( self, do_resize: bool = True, size: Dict[str, int] = None, resample: PILImageResampling = PILImageResampling.BICUBIC, do_center_crop: bool = True, crop_size: Dict[str, int] = None, do_rescale: bool = True, rescale_factor: Union[int, float] = 1 / 255, do_normalize: bool = True, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, do_convert_rgb: bool = True, **kwargs, ) -> None: super().__init__(**kwargs) size = size if size is not None else {"shortest_edge": 224} size = get_size_dict(size, default_to_square=False) crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224} crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
self.do_resize = do_resize self.size = size self.resample = resample self.do_center_crop = do_center_crop self.crop_size = crop_size 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 = image_std if image_std is not None else OPENAI_CLIP_STD self.do_convert_rgb = do_convert_rgb def resize( self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling = PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio.
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Size of the output image. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): Resampling filter to use when resiizing the image. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format of the input image. If not provided, it will be inferred. """ default_to_square = True if "shortest_edge" in size: size = size["shortest_edge"] default_to_square = False elif "height" in size and "width" in size: size = (size["height"], size["width"]) else:
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
output_size = get_resize_output_image_size( image, size=size, default_to_square=default_to_square, input_data_format=input_data_format, ) return resize( image, size=output_size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs, )
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
@filter_out_non_signature_kwargs() def preprocess( self, images: List[ImageInput] = None, videos: List[VideoInput] = None, do_resize: bool = None, size: Dict[str, int] = None, resample: PILImageResampling = None, do_center_crop: bool = None, crop_size: int = None, do_rescale: bool = None, rescale_factor: float = None, do_normalize: bool = None, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, do_convert_rgb: bool = None, return_tensors: Optional[Union[str, TensorType]] = None, data_format: Optional[ChannelDimension] = ChannelDimension.FIRST, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> PIL.Image.Image: """ Preprocess an image or batch of images.
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
Args: images (`ImageInput`, *optional*): List of images to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`. videos (`VideoInput`, *optional*): List of videos to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If passing in videos with pixel values between 0 and 1, set `do_rescale=False`. do_resize (`bool`, *optional*, defaults to `self.do_resize`): Whether to resize the image. size (`Dict[str, int]`, *optional*, defaults to `self.size`): Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio. resample (`int`, *optional*, defaults to `self.resample`):
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only has an effect if `do_resize` is set to `True`. do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`): Whether to center crop the image. crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`): Size of the center crop. Only has an effect if `do_center_crop` is set to `True`. do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the image. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): Rescale factor to rescale the image by if `do_rescale` is set to `True`. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): Whether to normalize the image. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`. image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`): Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to `True`. 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`. - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"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, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
- `"none"` or `ChannelDimension.NONE`: image in (height, width) format. """ do_resize = do_resize if do_resize is not None else self.do_resize size = size if size is not None else self.size size = get_size_dict(size, param_name="size", default_to_square=False) resample = resample if resample is not None else self.resample do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop crop_size = crop_size if crop_size is not None else self.crop_size crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True) do_rescale = do_rescale if do_rescale is not None else self.do_rescale 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
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
image_std = image_std if image_std is not None else self.image_std do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
if images is not None: images = make_list_of_images(images) if videos is not None: videos = make_batched_videos(videos) if (videos is not None and not valid_images(videos)) or (images is not None and not valid_images(images)): raise ValueError( "Invalid input type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." )
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
data = {} if videos is not None: pixel_values_videos = [ [ self._preprocess_image( image=frame, do_resize=do_resize, size=size, resample=resample, do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_center_crop=do_center_crop, crop_size=crop_size, do_convert_rgb=do_convert_rgb, data_format=data_format, input_data_format=input_data_format, ) for frame in video ] for video in videos ] data["pixel_values_videos"] = pixel_values_videos
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
if images is not None: pixel_values_images = [ self._preprocess_image( image=image, do_resize=do_resize, size=size, resample=resample, do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_center_crop=do_center_crop, crop_size=crop_size, do_convert_rgb=do_convert_rgb, data_format=data_format, input_data_format=input_data_format, ) for image in images ] data["pixel_values_images"] = pixel_values_images encoded_outputs = BatchFeature(data, tensor_type=return_tensors) return encoded_outputs
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
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, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, List[float]]] = None, image_std: Optional[Union[float, List[float]]] = None, do_center_crop: bool = None, crop_size: int = None, do_convert_rgb: bool = None, data_format: ChannelDimension = ChannelDimension.FIRST, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: validate_preprocess_arguments( do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_center_crop=do_center_crop,
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
crop_size=crop_size, do_resize=do_resize, size=size, resample=resample, )
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
# PIL RGBA images are converted to RGB if do_convert_rgb: image = convert_to_rgb(image) # All transformations expect numpy arrays. image = to_numpy_array(image) if do_rescale and is_scaled_image(image): logger.warning_once( "It looks like you are trying to rescale already rescaled images/video frames. If the input" " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again." ) if input_data_format is None: # We assume that all images have the same channel dimension format. input_data_format = infer_channel_dimension_format(image) if do_resize: image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format) if do_center_crop: image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
if do_rescale: image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format) if do_normalize: image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format) image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) return image
3,024
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/image_processing_video_llava.py
class VideoLlavaConfig(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`VideoLlavaForConditionalGeneration`]. It is used to instantiate an VideoLlava model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the like LanguageBind/Video-LLaVA-7B-hf. e.g. [LanguageBind/Video-LLaVA-7B-hf](https://huggingface.co/LanguageBind/Video-LLaVA-7B-hf) Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.
3,025
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/configuration_video_llava.py
Args: vision_config (`VideoLlavaVisionConfig`, *optional*): Custom vision config or dict. Defaults to `CLIPVisionConfig` if not indicated. text_config (`Union[AutoConfig, dict]`, *optional*): The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`. Defaults to `LlamaConfig` if not indicated. ignore_index (`int`, *optional*, defaults to -100): The ignore index for the loss function. image_token_index (`int`, *optional*, defaults to 32000): The image token index to encode the image prompt. video_token_index (`int`, *optional*, defaults to 32001): The video token index to encode the image prompt. projector_hidden_act (`str`, *optional*, defaults to `"gelu"`): The activation function used by the multimodal projector. vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
3,025
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/configuration_video_llava.py
The feature selection strategy used to select the vision feature from the CLIP backbone. Can be either "full" to select all features or "default" to select features without `CLS`. vision_feature_layer (`int`, *optional*, defaults to -2): The index of the layer to select the vision feature. image_seq_length (`int`, *optional*, defaults to 256): Sequence length of one image embedding. video_seq_length (`int`, *optional*, defaults to 2056): Sequence length of one video embedding. multimodal_projector_bias (`bool`, *optional*, defaults to `True`): Whether to use bias in the multimodal projector.
3,025
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/configuration_video_llava.py
Example: ```python >>> from transformers import VideoLlavaForConditionalGeneration, VideoLlavaConfig, CLIPVisionConfig, LlamaConfig >>> # Initializing a CLIP-vision config >>> vision_config = CLIPVisionConfig() >>> # Initializing a Llama config >>> text_config = LlamaConfig() >>> # Initializing a VideoLlava video_llava-1.5-7b style configuration >>> configuration = VideoLlavaConfig(vision_config, text_config) >>> # Initializing a model from the video_llava-1.5-7b style configuration >>> model = VideoLlavaForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "video_llava" sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig}
3,025
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/configuration_video_llava.py
def __init__( self, vision_config=None, text_config=None, ignore_index=-100, image_token_index=32000, video_token_index=32001, projector_hidden_act="gelu", vision_feature_select_strategy="default", vision_feature_layer=-2, image_seq_length=256, video_seq_length=2056, multimodal_projector_bias=True, **kwargs, ): self.ignore_index = ignore_index self.image_token_index = image_token_index self.video_token_index = video_token_index self.projector_hidden_act = projector_hidden_act self.vision_feature_select_strategy = vision_feature_select_strategy self.vision_feature_layer = vision_feature_layer self.image_seq_length = image_seq_length self.video_seq_length = video_seq_length self.multimodal_projector_bias = multimodal_projector_bias self.vision_config = vision_config
3,025
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/configuration_video_llava.py
if isinstance(self.vision_config, dict): if "model_type" not in vision_config: vision_config["model_type"] = "clip_vision_model" logger.warning("Key=`model_type` not found in vision config, setting it to `clip_vision_model`") self.vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config) elif vision_config is None: self.vision_config = CONFIG_MAPPING["clip_vision_model"]( intermediate_size=4096, hidden_size=1024, patch_size=14, image_size=224, num_hidden_layers=24, num_attention_heads=16, vocab_size=32000, projection_dim=768, )
3,025
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/configuration_video_llava.py
if isinstance(text_config, dict): if "model_type" not in text_config: text_config["model_type"] = "llama" logger.warning("Key=`model_type` not found in text config, setting it to `llama`") text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config) elif text_config is None: text_config = CONFIG_MAPPING["llama"]() self.text_config = text_config super().__init__(**kwargs)
3,025
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/video_llava/configuration_video_llava.py
class CohereLayerNorm(nn.Module): def __init__(self, hidden_size=None, eps=1e-5, bias=False): """The hidden size can be a tuple or an int. The tuple is used for QKNorm to normalize across head_dim""" super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) mean = hidden_states.mean(-1, keepdim=True) variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True) hidden_states = (hidden_states - mean) * torch.rsqrt(variance + self.variance_epsilon) hidden_states = self.weight.to(torch.float32) * hidden_states return hidden_states.to(input_dtype)
3,026
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
class CohereRotaryEmbedding(LlamaRotaryEmbedding): @torch.no_grad() def forward(self, x, position_ids): if "dynamic" in self.rope_type: self._dynamic_frequency_update(position_ids, device=x.device) # Core RoPE block inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1) position_ids_expanded = position_ids[:, None, :].float() # Force float32 (see https://github.com/huggingface/transformers/pull/29285) device_type = x.device.type device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.repeat_interleave(freqs, 2, dim=-1) # diff from Llama: we interleave() instead of cat() cos = emb.cos() sin = emb.sin()
3,027
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention cos = cos * self.attention_scaling sin = sin * self.attention_scaling return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
3,027
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
class CohereMLP(LlamaMLP): def __init__(self, config): super().__init__(config) self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
3,028
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
class CohereAttention(LlamaAttention): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: CohereConfig, layer_idx: Optional[int] = None): super().__init__(config, layer_idx) self.use_qk_norm = config.use_qk_norm if self.use_qk_norm: # When sharding the model using Tensor Parallelism, need to be careful to use n_local_heads self.q_norm = CohereLayerNorm( hidden_size=(config.num_attention_heads, self.head_dim), eps=config.layer_norm_eps ) self.k_norm = CohereLayerNorm( hidden_size=(config.num_key_value_heads, self.head_dim), eps=config.layer_norm_eps )
3,029
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
def forward( self, hidden_states: torch.Tensor, position_embeddings: Tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor], past_key_value: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: input_shape = hidden_states.shape[:-1] hidden_shape = (*input_shape, -1, self.head_dim) query_states = self.q_proj(hidden_states).view(hidden_shape) key_states = self.k_proj(hidden_states).view(hidden_shape) value_states = self.v_proj(hidden_states).view(hidden_shape) if self.use_qk_norm: # main diff from Llama query_states = self.q_norm(query_states) key_states = self.k_norm(key_states)
3,029
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_value is not None: # sin and cos are specific to RoPE models; position_ids needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
3,029
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False): logger.warning_once( "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to " 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' ) else: attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, **kwargs, )
3,029
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
3,029
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
class CohereDecoderLayer(nn.Module): def __init__(self, config: CohereConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = CohereAttention(config=config, layer_idx=layer_idx) self.mlp = CohereMLP(config) self.input_layernorm = CohereLayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
3,030
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, cache_position: Optional[torch.LongTensor] = None, position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC **kwargs: Unpack[FlashAttentionKwargs], ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: """ 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_size, sequence_length)` if flash attention is used or `(batch_size, 1,
3,030
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
query_sequence_length, key_sequence_length)` if default attention is used. past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*): Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
3,030
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
with `head_dim` being the embedding dimension of each attention head. """ residual = hidden_states
3,030
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
hidden_states = self.input_layernorm(hidden_states) # Self Attention hidden_states_attention, self_attn_weights = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, position_embeddings=position_embeddings, **kwargs, ) # Fully Connected hidden_states_mlp = self.mlp(hidden_states) # Add everything together hidden_states = residual + hidden_states_attention + hidden_states_mlp outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,) return outputs
3,030
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
class CohereModel(LlamaModel): def __init__(self, config: CohereConfig): super().__init__(config) self.layers = nn.ModuleList( [CohereDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.rotary_emb = CohereRotaryEmbedding(config=config) self.norm = CohereLayerNorm(hidden_size=(config.hidden_size), eps=config.layer_norm_eps)
3,031
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
3,032
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
class CohereForCausalLM(LlamaForCausalLM): def __init__(self, config): super().__init__(config) self.model = CohereModel(config) self.logit_scale = config.logit_scale self.tie_word_embeddings = config.tie_word_embeddings
3,033
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, num_logits_to_keep: int = 0, **kwargs: Unpack[KwargsForCausalLM], ) -> Union[Tuple, CausalLMOutputWithPast]: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
3,033
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
3,033
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
num_logits_to_keep (`int`, *optional*): Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. Returns: Example: ```python >> from transformers import AutoTokenizer, CohereForCausalLM >> model = CohereForCausalLM.from_pretrained("CohereForAI/c4ai-command-r-v01") >> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01") >> prompt = "Hey, are you conscious? Can you talk to me?" >> inputs = tokenizer(prompt, return_tensors="pt")
3,033
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
>> # Generate >> generate_ids = model.generate(inputs.input_ids, max_length=30) >> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict
3,033
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, **kwargs, ) hidden_states = outputs[0] # Only compute necessary logits, and do not upcast them to float if we are not computing the loss logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :]) logits = logits * self.logit_scale # main diff from Llama loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
3,033
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
3,033
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/modular_cohere.py
class CohereTokenizerFast(PreTrainedTokenizerFast): """ Construct a Cohere tokenizer. Based on byte-level Byte-Pair-Encoding. This uses notably ByteFallback and NFC normalization. ```python >>> from transformers import AutoTokenizer >>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01") >>> tokenizer.encode("Hello this is a test") [5, 28339, 2075, 1801, 1671, 3282] ``` If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the values of the first token and final token of an encoded sequence will not be correct). For more details, checkout [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since the model was not pretrained this way, it might yield a decrease in performance. <Tip> When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`. </Tip> This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
Args: vocab_file (`str`, *optional*): Path to the vocabulary file. merges_file (`str`, *optional*): Path to the merges file. tokenizer_file (`str`, *optional*): [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that contains everything needed to load the tokenizer. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`): Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra spaces. unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<UNK>"`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<BOS_TOKEN>"`):
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<|END_OF_TURN_TOKEN|>"`): The end of sequence token. add_bos_token (`bool`, *optional*, defaults to `True`): Whether or not to add an `bos_token` at the start of sequences. add_eos_token (`bool`, *optional*, defaults to `False`): Whether or not to add an `eos_token` at the end of sequences. use_default_system_prompt (`bool`, *optional*, defaults to `False`): Whether or not the default system prompt for Cohere tokenizer should be used. add_prefix_space (`bool`, *optional*, defaults to `False`): Whether or not the tokenizer should automatically add a prefix space """
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP padding_side = "left" model_input_names = ["input_ids", "attention_mask"] slow_tokenizer_class = None # No `max_model_input_sizes`
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
def __init__( self, vocab_file=None, merges_file=None, tokenizer_file=None, clean_up_tokenization_spaces=False, unk_token="<UNK>", bos_token="<BOS_TOKEN>", eos_token="<|END_OF_TURN_TOKEN|>", add_bos_token=True, add_eos_token=False, use_default_system_prompt=False, add_prefix_space=False, **kwargs, ): super().__init__( vocab_file=vocab_file, merges_file=merges_file, tokenizer_file=tokenizer_file, clean_up_tokenization_spaces=clean_up_tokenization_spaces, unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, add_bos_token=add_bos_token, add_eos_token=add_eos_token, use_default_system_prompt=use_default_system_prompt, add_prefix_space=add_prefix_space, **kwargs, ) self._add_bos_token = add_bos_token
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
self._add_eos_token = add_eos_token self.update_post_processor() self.use_default_system_prompt = use_default_system_prompt self.vocab_file = vocab_file self.grounded_generation_template = kwargs.pop("grounded_generation_template", None) self.tool_use_template = kwargs.pop("tool_use_template", None)
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
# TODO @ArthurZucker this can only work one way for now, to update later-on. Tests should also properly # check this as they were green before. pre_tok_state = pickle.dumps(self.backend_tokenizer.pre_tokenizer) decoder_state = pickle.dumps(self.backend_tokenizer.decoder) if add_prefix_space: pre_tok_state = pre_tok_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true') decoder_state = decoder_state.replace(b'"add_prefix_space":false', b'"add_prefix_space": true') self.backend_tokenizer.pre_tokenizer = pickle.loads(pre_tok_state) self.backend_tokenizer.decoder = pickle.loads(decoder_state) self.add_prefix_space = add_prefix_space
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding: is_split_into_words = kwargs.get("is_split_into_words", False) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._batch_encode_plus(*args, **kwargs) def _encode_plus(self, *args, **kwargs) -> BatchEncoding: is_split_into_words = kwargs.get("is_split_into_words", False) if not (self.add_prefix_space or not is_split_into_words): raise Exception( f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._encode_plus(*args, **kwargs)
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
def update_post_processor(self): """ Updates the underlying post processor with the current `bos_token` and `eos_token`. """ bos = self.bos_token bos_token_id = self.bos_token_id if bos is None and self.add_bos_token: raise ValueError("add_bos_token = True but bos_token = None") eos = self.eos_token eos_token_id = self.eos_token_id if eos is None and self.add_eos_token: raise ValueError("add_eos_token = True but eos_token = None") single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}" pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
special_tokens = [] if self.add_bos_token: special_tokens.append((bos, bos_token_id)) if self.add_eos_token: special_tokens.append((eos, eos_token_id)) self._tokenizer.post_processor = processors.TemplateProcessing( single=single, pair=pair, special_tokens=special_tokens ) @property def add_eos_token(self): return self._add_eos_token @property def add_bos_token(self): return self._add_bos_token @add_eos_token.setter def add_eos_token(self, value): self._add_eos_token = value self.update_post_processor() @add_bos_token.setter def add_bos_token(self, value): self._add_bos_token = value self.update_post_processor() def apply_tool_use_template( self, conversation: Union[List[Dict[str, str]]], tools: List[Dict], **kwargs, ) -> Union[str, List[int]]: """Create a Command-R tool-use prompt.
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
Once rendered, the prompt instructs the model to generate a list of actions to perform on a set of user supplied tools to help carry out the user's requests. Conceptually, this works in the same way as `apply_chat_format`, but takes an additional `tools` parameter. Converts a chat in the form of a list of dictionaries with `"role"` and `"content"` keys and a list of available tools for the model to use into a prompt string, or a list of token ids. This method will use the tokenizer's `default_tool_use_template` template specified at the class level. You can override the default template using the `tool_use_template` kwarg but the quality of your results may decrease.
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
Args: conversation (Union[List[Dict[str, str]]]): A list of dicts with "role" and "content" keys, representing the chat history so far. tools (List[Dict]): a list of tools to render into the prompt for the model to choose from. See an example at the bottom of the docstring. The format should be: * name (str): The name of the tool to be called. Valid names contain only the characters a-z, A-Z, 0-9, _ and must not begin with a digit. * description (str): The description of what the tool does, the model uses the description to choose when and how to call the function. * parameter_definitions (List[Dict]): The input parameters of the tool. Accepts a dictionary where the key is the name of the parameter and the value is the parameter spec.
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
Valid parameter names contain only the characters a-z, A-Z, 0-9, _ and must not begin with a digit. Parameter specs are as follows: * description (str): The description of the parameter. * type (str): the type of the parameter - most effective for python builtin data types, such as 'str', 'bool' * required: boolean: Denotes whether the parameter is always present (required) or not. Defaults to not required. add_generation_prompt (bool, *optional*): Whether to end the prompt with the token(s) that indicate the start of an assistant message. This is useful when you want to generate a response from the model. Note that this argument will be passed to the chat template, and so it must be supported in the template for this argument to have any effect. tokenize (`bool`, defaults to `True`):
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
Whether to tokenize the output. If `False`, the output will be a string. padding (`bool`, defaults to `False`): Whether to pad sequences to the maximum length. Has no effect if tokenize is `False`. truncation (`bool`, defaults to `False`): Whether to truncate sequences at the maximum length. Has no effect if tokenize is `False`. max_length (`int`, *optional*): Maximum length (in tokens) to use for padding or truncation. Has no effect if tokenize is `False`. If not specified, the tokenizer's `max_length` attribute will be used as a default. return_tensors (`str` or [`~utils.TensorType`], *optional*): If set, will return tensors of a particular framework. Has no effect if tokenize is `False`. Acceptable values are: - `'tf'`: Return TensorFlow `tf.Tensor` objects. - `'pt'`: Return PyTorch `torch.Tensor` objects.
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
- `'np'`: Return NumPy `np.ndarray` objects. - `'jax'`: Return JAX `jnp.ndarray` objects. return_dict (`bool`, *optional*, defaults to `False`): Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`. **tokenizer_kwargs: Additional kwargs to pass to the tokenizer.
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
Returns: `str`: A rendered prompt string. or if tokenize=True: `List[int]`: A list of token ids representing the tokenized chat so far, including control tokens. This output is ready to pass to the model, either directly or via methods like `generate()`. Examples:
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py
```python >> tokenizer = CohereTokenizerFast.from_pretrained("CohereForAI/c4ai-command-r-v01") >> tools = [ { "name": "internet_search", "description": "Returns a list of relevant document snippets for a textual query retrieved from the internet", "parameter_definitions": { "query": { "description": "Query to search the internet with", "type": "str", "required": True } } }, { "name': "directly_answer", "description": "Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history", "parameter_definitions": {} } ] >> conversation = [ {"role": "user", "content": "Whats the biggest penguin in the world?"} ]
3,034
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/cohere/tokenization_cohere_fast.py