text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
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, ) -> Tuple[torc...
3,446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
if past_key_value is not None: # sin and cos are specific to RoPE models; cache_position 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, ca...
3,446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
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,446
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
class Olmo2MLP(nn.Module): def __init__(self, config): super().__init__() self.config = config self.hidden_size = config.hidden_size self.intermediate_size = config.intermediate_size self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self...
3,447
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
class Olmo2DecoderLayer(nn.Module): def __init__(self, config: Olmo2Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = Olmo2Attention(config=config, layer_idx=layer_idx) self.mlp = Olmo2MLP(config) self.post_attention_layernorm...
3,448
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.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, ...
3,448
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
# Self Attention hidden_states, 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_cac...
3,448
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
class Olmo2RotaryEmbedding(nn.Module): def __init__(self, config: Olmo2Config, device=None): super().__init__() # BC: "rope_type" was originally "type" if hasattr(config, "rope_scaling") and config.rope_scaling is not None: self.rope_type = config.rope_scaling.get("rope_type", co...
3,449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
def _dynamic_frequency_update(self, position_ids, device): """ dynamic RoPE layers should recompute `inv_freq` in the following situations: 1 - growing beyond the cached sequence length (allow scaling) 2 - the current sequence length is in the original scale (avoid losing precision with ...
3,449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset # This .to() is needed if the model has been moved to a device after being initialized (because # the buffer is automatically moved, but not the original copy) self.original_inv_f...
3,449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
# 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...
3,449
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
class Olmo2PreTrainedModel(PreTrainedModel): config_class = Olmo2Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Olmo2DecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn_2 = True _supports_sdpa = True _supp...
3,450
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
class Olmo2Model(Olmo2PreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Olmo2DecoderLayer`] Args: config: Olmo2Config """ def __init__(self, config: Olmo2Config): super().__init__(config) self.padding_idx = config.p...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
def set_input_embeddings(self, value): self.embed_tokens = value
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
@add_start_docstrings_to_model_forward(OLMO2_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if self.gradient_checkpointing and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient check...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
causal_mask = self._update_causal_mask( attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions ) hidden_states = inputs_embeds # create position embeddings to be shared across the decoder layers position_embeddings = self.rotary_emb(hidden_states,...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.__call__, hidden_states, causal_mask, position_ids, past_key_values, ...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
hidden_states = layer_outputs[0] if output_attentions: all_self_attns += (layer_outputs[1],) hidden_states = self.norm(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) ...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
def _update_causal_mask( self, attention_mask: torch.Tensor, input_tensor: torch.Tensor, cache_position: torch.Tensor, past_key_values: Cache, output_attentions: bool, ): if self.config._attn_implementation == "flash_attention_2": if attention_mask...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions: if AttentionMaskConverter._ignore_causal_mask_sdpa( attention_mask, ...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D). causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position( attention_mask, sequence_length=sequence_length, target_length=target_length, dtype=dtype, dev...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
if ( self.config._attn_implementation == "sdpa" and attention_mask is not None and attention_mask.device.type == "cuda" and not output_attentions ): # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows whe...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
@staticmethod def _prepare_4d_causal_attention_mask_with_cache_position( attention_mask: torch.Tensor, sequence_length: int, target_length: int, dtype: torch.dtype, device: torch.device, cache_position: torch.Tensor, batch_size: int, **kwargs, ): ...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
Args: attention_mask (`torch.Tensor`): A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`. sequence_length (`int`): The sequence length being processed. ...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
if attention_mask is not None and attention_mask.dim() == 4: # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing. causal_mask = attention_mask else: min_dtype = torch.finfo(dtype).min causal_mask = torch.full(...
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :] padding_mask = padding_mask == 0 causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( padding_mask, min_dtype )
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
return causal_mask
3,451
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
3,452
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
class Olmo2ForCausalLM(Olmo2PreTrainedModel, GenerationMixin): _tied_weights_keys = ["lm_head.weight"] _tp_plan = {"lm_head": "colwise_rep"} def __init__(self, config): super().__init__(config) self.model = Olmo2Model(config) self.vocab_size = config.vocab_size self.lm_head ...
3,453
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
@add_start_docstrings_to_model_forward(OLMO2_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional...
3,453
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
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 ...
3,453
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.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, whic...
3,453
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.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." ```""" ...
3,453
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.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, ...
3,453
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.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_sta...
3,453
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modeling_olmo2.py
class Olmo2Config(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`Olmo2Model`]. It is used to instantiate an OLMo2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar c...
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
Args: vocab_size (`int`, *optional*, defaults to 50304): Vocabulary size of the Olmo2 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Olmo2Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimens...
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be construc...
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
The standard deviation of the truncated_normal_initializer for initializing all weight matrices. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. ...
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update `max_position_embeddings` to the expected new maximum. See the following thread for more information...
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
The epsilon used by the rms normalization layers.
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
```python >>> from transformers import Olmo2Model, Olmo2Config >>> # Initializing a Olmo2 7B style configuration >>> configuration = Olmo2Config() >>> # Initializing a model from the Olmo2 7B style configuration >>> model = Olmo2Model(configuration) >>> # Accessing the model configuration ...
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
def __init__( self, vocab_size=50304, hidden_size=4096, intermediate_size=11008, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=None, hidden_act="silu", max_position_embeddings=2048, initializer_range=0.02, use_ca...
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
# for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.use_cache = use_cache self.rope_...
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2: raise ValueError( "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}" ) rope_scaling_type = self.rope_scaling.get("type", None) rope_scal...
3,454
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/configuration_olmo2.py
class Olmo2Config(OlmoConfig): r""" This is the configuration class to store the configuration of a [`Olmo2Model`]. It is used to instantiate an OLMo2 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configu...
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
Args: vocab_size (`int`, *optional*, defaults to 50304): Vocabulary size of the Olmo2 model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`Olmo2Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimens...
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be construc...
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
The standard deviation of the truncated_normal_initializer for initializing all weight matrices. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. ...
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update `max_position_embeddings` to the expected new maximum. See the following thread for more information...
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
The epsilon used by the rms normalization layers.
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
```python >>> from transformers import Olmo2Model, Olmo2Config >>> # Initializing a Olmo2 7B style configuration >>> configuration = Olmo2Config() >>> # Initializing a model from the Olmo2 7B style configuration >>> model = Olmo2Model(configuration) >>> # Accessing the model configuration ...
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
def __init__( self, vocab_size=50304, hidden_size=4096, intermediate_size=11008, num_hidden_layers=32, num_attention_heads=32, num_key_value_heads=None, hidden_act="silu", max_position_embeddings=2048, initializer_range=0.02, use_ca...
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
initializer_range=initializer_range, use_cache=use_cache, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, rope_theta=rope_theta, rope_scaling=rope_scaling, ...
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
self.rms_norm_eps = rms_norm_eps del self.clip_qkv
3,455
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
class Olmo2RMSNorm(LlamaRMSNorm): pass
3,456
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
class Olmo2Attention(OlmoAttention): def __init__(self, config: Olmo2Config, layer_idx: Optional[int] = None): super().__init__(config, layer_idx=layer_idx) self.q_norm = Olmo2RMSNorm(config.num_attention_heads * self.head_dim, config.rms_norm_eps) self.k_norm = Olmo2RMSNorm(config.num_key_v...
3,457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
query_states = self.q_norm(self.q_proj(hidden_states)) key_states = self.k_norm(self.k_proj(hidden_states)) value_states = self.v_proj(hidden_states) query_states = query_states.view(hidden_shape).transpose(1, 2) key_states = key_states.view(hidden_shape).transpose(1, 2) value_s...
3,457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.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_attentio...
3,457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
attn_output = attn_output.reshape(*input_shape, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
3,457
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
class Olmo2DecoderLayer(OlmoDecoderLayer): def __init__(self, config: Olmo2Config, layer_idx: int): super().__init__(config, layer_idx=layer_idx) self.post_attention_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.post_feedforward_layernorm = Olmo2RMSNorm(config.hi...
3,458
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.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, ...
3,458
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
# Self Attention hidden_states, 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_cac...
3,458
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
class Olmo2Model(OlmoModel): def __init__(self, config: Olmo2Config): super().__init__(config) self.norm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.layers = nn.ModuleList( [Olmo2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)...
3,459
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
class Olmo2ForCausalLM(OlmoForCausalLM): pass
3,460
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/olmo2/modular_olmo2.py
class Emu3ImageProcessor(BaseImageProcessor): r""" Constructs a Emu3 image processor that dynamically resizes images based on the original images.
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`): Resampling filter to use when resizing the image. do_rescale (`bool`, *option...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
Standard deviation to use if normalizing the image. This is a float or list of floats for each channel in the image. do_convert_rgb (`bool`, *optional*, defaults to `True`): Whether to convert the image to RGB. do_pad (`bool`, *optional*, defaults to `True`): Whether to pad t...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
model_input_names = ["pixel_values"]
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
def __init__( self, do_resize: bool = True, resample: PILImageResampling = PILImageResampling.BICUBIC, do_rescale: bool = True, rescale_factor: Union[int, float] = 1 / 255, do_normalize: bool = True, image_mean: Optional[Union[float, List[float]]] = None, ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
self.max_pixels = max_pixels self.spatial_factor = spatial_factor self.size = {"min_pixels": min_pixels, "max_pixels": max_pixels} self.do_convert_rgb = do_convert_rgb
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
def _preprocess( self, images: Union[ImageInput, VideoInput], do_resize: bool = None, resample: PILImageResampling = None, do_rescale: bool = None, rescale_factor: float = None, do_normalize: bool = None, image_mean: Optional[Union[float, List[float]]] = N...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
Args: images (`ImageInput`): Image or batch of images to preprocess. Expects pixel values ranging from 0 to 255. If pixel values range from 0 to 1, set `do_rescale=False`. vision_info (`List[Dict]`, *optional*): Optional list of dictionaries containing additional ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
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`): Mean to use if normalizing the image. Can be a float or a list of floats corresponding to the ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
- `"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 (`Ch...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
if do_convert_rgb: images = [convert_to_rgb(image) for image in images] # All transformations expect numpy arrays. images = [to_numpy_array(image) for image in images] if is_scaled_image(images[0]) and do_rescale: logger.warning_once( "It looks like you ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
height, width = get_image_size(images[0], channel_dim=input_data_format) resized_height, resized_width = height, width processed_images = [] for image in images: if do_resize: resized_height, resized_width = smart_resize( height, ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) processed_images.append(image) images = np.array(processed_images) return images def _pad_for_batching( self, pixel_values: List[np.ndarray], image_sizes: List[List[int]...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
Args: pixel_values (`List[np.ndarray]`): An array of pixel values of each images of shape (`batch_size`, `num_patches`, `image_in_3D`) image_sizes (`List[List[int]]`): A list of sizes for each image in `pixel_values` in (height, width) format. data_for...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. If unset, will use the inferred format of the input image.
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
Returns: List[`np.ndarray`]: The padded images. """ max_shape = ( max([size[0] for size in image_sizes]), max([size[1] for size in image_sizes]), ) pixel_values = [ pad( image, padding=((0, max_shape[0] - si...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
def preprocess( self, images: ImageInput, do_resize: bool = None, size: Dict[str, int] = None, resample: PILImageResampling = None, do_rescale: bool = None, rescale_factor: float = None, do_normalize: bool = None, image_mean: Optional[Union[float, ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
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 ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
Whether to normalize the image. image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`): 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_s...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
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 ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.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,...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
""" do_resize = do_resize if do_resize is not None else self.do_resize size = size if size is not None else self.size resample = resample if resample is not None else self.resample do_rescale = do_rescale if do_rescale is not None else self.do_rescale rescale_factor = rescale_fac...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
if images is not None and not valid_images(images): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) validate_preprocess_arguments( rescale_factor=rescale_fact...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
pixel_values = [] for image in images: image = self._preprocess( image, do_resize=do_resize, resample=resample, do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
def postprocess( self, images: ImageInput, 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...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
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`): Image mea...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.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,...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
images = make_list_of_images(images) if isinstance(images[0], Image.Image): return images if len(images) > 1 else images[0] if input_data_format is None: # We assume that all images have the same channel dimension format. input_data_format = infer_channel_dimension_f...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
if do_normalize and do_rescale and return_tensors == "PIL.Image.Image": image = to_channel_dimension_format(image, ChannelDimension.LAST, input_channel_dim=input_data_format) pixel_values.append(Image.fromarray(image)) else: pixel_values.extend(image) ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
def unnormalize( self, image: np.array, image_mean: Union[float, Iterable[float]], image_std: Union[float, Iterable[float]], input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.array: """ Unnormalizes `image` using the mean and standard d...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
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 `ChannelDimens...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py
if isinstance(image_mean, Iterable): if len(image_mean) != num_channels: raise ValueError(f"mean must have {num_channels} elements if it is an iterable, got {len(image_mean)}") else: image_mean = [image_mean] * num_channels if isinstance(image_std, Iterable): ...
3,461
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/models/emu3/image_processing_emu3.py