bugfix
Browse files97 unmodified lines9899100101102103104105106107108109110111112113114115125 unmodified lines2412422432442452462472482492508 unmodified lines2592602612622632642654 unmodified lines27027127227327427527645 unmodified lines322323324325326327328329330331332333334335336337338339340341342343344345346347616 unmodified lines96496596696796896997097197297397474 unmodified lines10491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109926 unmodified lines1126112711281129113011311132242 unmodified lines137513761377137813791380138152 unmodified lines1434143514361437143814391440144114421443144445 unmodified lines149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151497 unmodified linesclass MotifRotaryEmbeddingWithCache(nn.Module):"""Rotary positional embedding module with caching for efficiency.Args:dim (int): Dimensionality of the embedding.max_position_embeddings (int): Maximum sequence length for caching. Default is 2048.base (int): Base for computing inverse frequency. Default is 10000.device (torch.device, optional): Device for tensor storage.Methods:forward(x, seq_len=None):Computes cosine and sine embeddings for input sequence length.Automatically updates cache if `seq_len` exceeds cached length.Attributes:inv_freq (torch.Tensor): Inverse frequency tensor for position encoding.cos_cached (torch.Tensor): Cached cosine embeddings.125 unmodified linesdef rotate_half(x):"""Rotates half of the dimensions of the input tensor using torch.roll and in-place negation.Args:x (torch.Tensor): The input tensor.Returns:torch.Tensor: A tensor where the latter half of the dimensions are negatedand moved before the first half.8 unmodified linesdef apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1, fused_rope=True):"""Applies rotary position embeddings to the input tensors.Args:q (torch.Tensor): Query tensor of shape (B, NH, S, D_KV).k (torch.Tensor): Key tensor of shape (B, NH, S, D_KV).4 unmodified linesfused_rope (bool, optional): If True, applies fused rotary embeddings using`moreh_ops.apply_rotary_emb`. If False, computes rotary embeddings manually.Defaults to False.Returns:Tuple[torch.Tensor, torch.Tensor]: Returns transformed query and key tensors after applying rotary embeddings."""45 unmodified linesclass MotifAttention(nn.Module):"""Differential Attention (DiffAttention) module.Implements the Differential Attention from"DIFFERENTIAL TRANSFORMER" (https://arxiv.org/pdf/2410.05258).OverviewStandard transformers often over-allocate attention to irrelevant context.DiffAttention addresses this by computing attention as the difference betweentwo separate softmax attention maps, effectively canceling noise and promotingsparse, structured attention patterns.Reference Implementationhttps://github.com/microsoft/unilm/tree/master/Diff-TransformerArgsThe differential attention mechanism computes attention as the difference of two softmax attention scores, weighted by a learnable scalar λ.λ is re-parameterized as λ = exp(λ_q1 · λ_k1) − exp(λ_q2 · λ_k2) + λ_init.- lambda_q1, lambda_q2 (nn.Parameter): Learnable vectors used to compute the first and second components of λ for query transformations.- lambda_k1, lambda_k2 (nn.Parameter): Learnable vectors used to compute the first and second components of λ for key transformations.- lambda_init (float): A constant used for initializing λ, typically set as λ_init = 0.8 − 0.6 × exp(−0.3 × (layer_index − 1))."""def __init__(self, config: MotifConfig, layer_idx: Optional[int] = None):616 unmodified linesThis model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usageand behavior.Parameters:config ([`MotifConfig`]):Model configuration class with all the parameters of the model. Initializing with a config file does not74 unmodified linesinput_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provideit.Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.[What are input IDs?](../glossary#input-ids)attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:- 1 for tokens that are **not masked**,- 0 for tokens that are **masked**.[What are attention masks?](../glossary#attention-mask)Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see`past_key_values`).If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for moreinformation on the default strategy.- 1 indicates the head is **not masked**,- 0 indicates the head is **masked**.position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,config.n_positions - 1]`.[What are position IDs?](../glossary#position-ids)past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attentionblocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.Two formats are allowed:- a [`~cache_utils.Cache`] instance, see our[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors ofshape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacycache format.The model will output the same cache format that is fed as input. If no `past_key_values` are passed, thelegacy cache format will be returned.If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don'thave their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`of shape `(batch_size, sequence_length)`.26 unmodified linesclass MotifModel(MotifPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MotifDecoderLayer`]Args:config: MotifConfig"""242 unmodified lines"""Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.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)`.52 unmodified linesself.multi_token_heads = config.multi_token_headsself.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)else:self.tokenwise_last_layers = nn.ModuleList([MotifDecoderLayer(config, config.num_hidden_layers - 1) for _ in range(self.multi_token_heads)])self.tokenwise_lm_heads = nn.ModuleList([nn.Linear(config.hidden_size, config.vocab_size, bias=False) for _ in range(self.multi_token_heads)])# Initialize weights and apply final processingself.post_init()45 unmodified linesLabels 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]`.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 thattoken can save memory, which becomes pretty significant for long sequences or large vocabulary size.Returns:Example:```python>>> from transformers import AutoTokenizer, MotifForCausalLM>>> model = MotifForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS, trust_remote_code = True)>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER, trust_remote_code = True)>>> prompt = "Hey, are you conscious? Can you talk to me?">>> inputs = tokenizer(prompt, return_tensors="pt")>>> # 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]97 unmodified lines9899100101102103104105106107108109110111112125 unmodified lines2382392402412422432442458 unmodified lines2542552562572582594 unmodified lines26426526626726826945 unmodified lines315316317318319320321322323324325326327328329330331332333334335616 unmodified lines95295395495595695795895996074 unmodified lines10351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107326 unmodified lines110011011102110311041105242 unmodified lines13481349135013511352135352 unmodified lines14061407140814091410141145 unmodified lines14571458145914601461146214631464146514661467146814691470147114721473147497 unmodified linesclass MotifRotaryEmbeddingWithCache(nn.Module):"""Rotary positional embedding module with caching for efficiency.Args:dim (int): Dimensionality of the embedding.max_position_embeddings (int): Maximum sequence length for caching. Default is 2048.base (int): Base for computing inverse frequency. Default is 10000.device (torch.device, optional): Device for tensor storage.Methods:forward(x, seq_len=None):Computes cosine and sine embeddings for input sequence length.Automatically updates cache if `seq_len` exceeds cached length.Attributes:inv_freq (torch.Tensor): Inverse frequency tensor for position encoding.cos_cached (torch.Tensor): Cached cosine embeddings.125 unmodified linesdef rotate_half(x):"""Rotates half of the dimensions of the input tensor using torch.roll and in-place negation.Args:x (torch.Tensor): The input tensor.Returns:torch.Tensor: A tensor where the latter half of the dimensions are negatedand moved before the first half.8 unmodified linesdef apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1, fused_rope=True):"""Applies rotary position embeddings to the input tensors.Args:q (torch.Tensor): Query tensor of shape (B, NH, S, D_KV).k (torch.Tensor): Key tensor of shape (B, NH, S, D_KV).4 unmodified linesfused_rope (bool, optional): If True, applies fused rotary embeddings using`moreh_ops.apply_rotary_emb`. If False, computes rotary embeddings manually.Defaults to False.Returns:Tuple[torch.Tensor, torch.Tensor]: Returns transformed query and key tensors after applying rotary embeddings."""45 unmodified linesclass MotifAttention(nn.Module):"""Differential Attention (DiffAttention) module.Implements the Differential Attention from"DIFFERENTIAL TRANSFORMER" (https://arxiv.org/pdf/2410.05258).OverviewStandard transformers often over-allocate attention to irrelevant context.DiffAttention addresses this by computing attention as the difference betweentwo separate softmax attention maps, effectively canceling noise and promotingsparse, structured attention patterns.Reference Implementationhttps://github.com/microsoft/unilm/tree/master/Diff-TransformerArgsThe differential attention mechanism computes attention as the difference of two softmax attention scores, weighted by a learnable scalar λ.λ is re-parameterized as λ = exp(λ_q1 · λ_k1) − exp(λ_q2 · λ_k2) + λ_init.- lambda_q1, lambda_q2 (nn.Parameter): Learnable vectors used to compute the first and second components of λ for query transformations.- lambda_k1, lambda_k2 (nn.Parameter): Learnable vectors used to compute the first and second components of λ for key transformations.- lambda_init (float): A constant used for initializing λ, typically set as λ_init = 0.8 − 0.6 × exp(−0.3 × (layer_index − 1))."""def __init__(self, config: MotifConfig, layer_idx: Optional[int] = None):616 unmodified linesThis model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usageand behavior.Parameters:config ([`MotifConfig`]):Model configuration class with all the parameters of the model. Initializing with a config file does not74 unmodified linesinput_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provideit.Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.[What are input IDs?](../glossary#input-ids)attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:- 1 for tokens that are **not masked**,- 0 for tokens that are **masked**.[What are attention masks?](../glossary#attention-mask)Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and[`PreTrainedTokenizer.__call__`] for details.If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see`past_key_values`).If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for moreinformation on the default strategy.- 1 indicates the head is **not masked**,- 0 indicates the head is **masked**.position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,config.n_positions - 1]`.[What are position IDs?](../glossary#position-ids)past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attentionblocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.Two formats are allowed:- a [`~cache_utils.Cache`] instance, see our[kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors ofshape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacycache format.The model will output the same cache format that is fed as input. If no `past_key_values` are passed, thelegacy cache format will be returned.If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don'thave their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`of shape `(batch_size, sequence_length)`.26 unmodified linesclass MotifModel(MotifPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MotifDecoderLayer`]Args:config: MotifConfig"""242 unmodified lines"""Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.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)`.52 unmodified linesself.multi_token_heads = config.multi_token_headsself.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)# Initialize weights and apply final processingself.post_init()45 unmodified linesLabels 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]`.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 thattoken can save memory, which becomes pretty significant for long sequences or large vocabulary size.Returns:Example:```python>>> from transformers import AutoTokenizer, MotifForCausalLM>>> model = MotifForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS, trust_remote_code = True)>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER, trust_remote_code = True)>>> prompt = "Hey, are you conscious? Can you talk to me?">>> inputs = tokenizer(prompt, return_tensors="pt")>>> # 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]
modeling_motif.py-40