adalbertojunior commited on
Commit
4af4594
1 Parent(s): 38f0712

Upload 7 files

Browse files
added_tokens.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "<|im_start|>": 32000
3
+ }
configuration_dusmistral.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """ Mistral model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ MISTRAL_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "mistralai/Mistral-7B-v0.1": "https://huggingface.co/mistralai/Mistral-7B-v0.1/resolve/main/config.json",
25
+ "mistralai/Mistral-7B-Instruct-v0.1": "https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1/resolve/main/config.json",
26
+ }
27
+
28
+
29
+ class DusMistralConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`MistralModel`]. It is used to instantiate an
32
+ Mistral model according to the specified arguments, defining the model architecture. Instantiating a configuration
33
+ with the defaults will yield a similar configuration to that of the Mistral-7B-v0.1 or Mistral-7B-Instruct-v0.1.
34
+
35
+ [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1)
36
+ [mistralai/Mistral-7B-Instruct-v0.1](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1)
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+
42
+ Args:
43
+ vocab_size (`int`, *optional*, defaults to 32000):
44
+ Vocabulary size of the Mistral model. Defines the number of different tokens that can be represented by the
45
+ `inputs_ids` passed when calling [`MistralModel`]
46
+ hidden_size (`int`, *optional*, defaults to 4096):
47
+ Dimension of the hidden representations.
48
+ intermediate_size (`int`, *optional*, defaults to 14336):
49
+ Dimension of the MLP representations.
50
+ num_hidden_layers (`int`, *optional*, defaults to 32):
51
+ Number of hidden layers in the Transformer encoder.
52
+ num_attention_heads (`int`, *optional*, defaults to 32):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ num_key_value_heads (`int`, *optional*, defaults to 8):
55
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
56
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
57
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
58
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
59
+ by meanpooling all the original heads within that group. For more details checkout [this
60
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
61
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
62
+ The non-linear activation function (function or string) in the decoder.
63
+ max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
64
+ The maximum sequence length that this model might ever be used with. Mistral's sliding window attention
65
+ allows sequence of up to 4096*32 tokens.
66
+ initializer_range (`float`, *optional*, defaults to 0.02):
67
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
68
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
69
+ The epsilon used by the rms normalization layers.
70
+ use_cache (`bool`, *optional*, defaults to `True`):
71
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
72
+ relevant if `config.is_decoder=True`.
73
+ pad_token_id (`int`, *optional*):
74
+ The id of the padding token.
75
+ bos_token_id (`int`, *optional*, defaults to 1):
76
+ The id of the "beginning-of-sequence" token.
77
+ eos_token_id (`int`, *optional*, defaults to 2):
78
+ The id of the "end-of-sequence" token.
79
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
80
+ Whether the model's input and output word embeddings should be tied.
81
+ rope_theta (`float`, *optional*, defaults to 10000.0):
82
+ The base period of the RoPE embeddings.
83
+ sliding_window (`int`, *optional*, defaults to 4096):
84
+ Sliding window attention window size. If not specified, will default to `4096`.
85
+ attention_dropout (`float`, *optional*, defaults to 0.0):
86
+ The dropout ratio for the attention probabilities.
87
+
88
+ ```python
89
+ >>> from transformers import MistralModel, MistralConfig
90
+
91
+ >>> # Initializing a Mistral 7B style configuration
92
+ >>> configuration = MistralConfig()
93
+
94
+ >>> # Initializing a model from the Mistral 7B style configuration
95
+ >>> model = MistralModel(configuration)
96
+
97
+ >>> # Accessing the model configuration
98
+ >>> configuration = model.config
99
+ ```"""
100
+
101
+ model_type = "mistral"
102
+ keys_to_ignore_at_inference = ["past_key_values"]
103
+
104
+ def __init__(
105
+ self,
106
+ vocab_size=32000,
107
+ hidden_size=4096,
108
+ intermediate_size=14336,
109
+ num_hidden_layers=32,
110
+ num_attention_heads=32,
111
+ num_key_value_heads=8,
112
+ hidden_act="silu",
113
+ max_position_embeddings=4096 * 32,
114
+ initializer_range=0.02,
115
+ rms_norm_eps=1e-6,
116
+ use_cache=True,
117
+ pad_token_id=None,
118
+ bos_token_id=1,
119
+ eos_token_id=2,
120
+ tie_word_embeddings=False,
121
+ rope_theta=10000.0,
122
+ sliding_window=4096,
123
+ attention_dropout=0.0,
124
+ layer_order=[(0, 24), (12, 24), (8, 32)],
125
+ **kwargs,
126
+ ):
127
+ self.vocab_size = vocab_size
128
+ self.max_position_embeddings = max_position_embeddings
129
+ self.hidden_size = hidden_size
130
+ self.intermediate_size = intermediate_size
131
+ self.num_hidden_layers = num_hidden_layers
132
+ self.num_attention_heads = num_attention_heads
133
+ self.sliding_window = sliding_window
134
+
135
+ # for backward compatibility
136
+ if num_key_value_heads is None:
137
+ num_key_value_heads = num_attention_heads
138
+
139
+ self.num_key_value_heads = num_key_value_heads
140
+ self.hidden_act = hidden_act
141
+ self.initializer_range = initializer_range
142
+ self.rms_norm_eps = rms_norm_eps
143
+ self.use_cache = use_cache
144
+ self.rope_theta = rope_theta
145
+ self.attention_dropout = attention_dropout
146
+ self.layer_order=layer_order
147
+
148
+ super().__init__(
149
+ pad_token_id=pad_token_id,
150
+ bos_token_id=bos_token_id,
151
+ eos_token_id=eos_token_id,
152
+ tie_word_embeddings=tie_word_embeddings,
153
+ **kwargs,
154
+ )
modeling_dusmistral.py ADDED
@@ -0,0 +1,1389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Mistral model."""
21
+ import inspect
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
35
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.utils import (
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ is_flash_attn_2_available,
41
+ is_flash_attn_greater_or_equal_2_10,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+ from .configuration_dusmistral import DusMistralConfig
46
+
47
+
48
+ if is_flash_attn_2_available():
49
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
50
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
51
+
52
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+ _CONFIG_FOR_DOC = "MistralConfig"
58
+
59
+
60
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
61
+ def _get_unpad_data(attention_mask):
62
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
63
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
64
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
65
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
66
+ return (
67
+ indices,
68
+ cu_seqlens,
69
+ max_seqlen_in_batch,
70
+ )
71
+
72
+
73
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Mistral
74
+ class DusMistralRMSNorm(nn.Module):
75
+ def __init__(self, hidden_size, eps=1e-6):
76
+ """
77
+ DusMistralRMSNorm is equivalent to T5LayerNorm
78
+ """
79
+ super().__init__()
80
+ self.weight = nn.Parameter(torch.ones(hidden_size))
81
+ self.variance_epsilon = eps
82
+
83
+ def forward(self, hidden_states):
84
+ input_dtype = hidden_states.dtype
85
+ hidden_states = hidden_states.to(torch.float32)
86
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
87
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
88
+ return self.weight * hidden_states.to(input_dtype)
89
+
90
+
91
+ # copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->DusMistral
92
+ # TODO @Arthur no longer copied from LLama after static cache
93
+ class DusMistralRotaryEmbedding(nn.Module):
94
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
95
+ super().__init__()
96
+
97
+ self.dim = dim
98
+ self.max_position_embeddings = max_position_embeddings
99
+ self.base = base
100
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
101
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
102
+
103
+ # Build here to make `torch.jit.trace` work.
104
+ self._set_cos_sin_cache(
105
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
106
+ )
107
+
108
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
109
+ self.max_seq_len_cached = seq_len
110
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
111
+
112
+ freqs = torch.outer(t, self.inv_freq)
113
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
114
+ emb = torch.cat((freqs, freqs), dim=-1)
115
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
116
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
117
+
118
+ def forward(self, x, seq_len=None):
119
+ # x: [bs, num_attention_heads, seq_len, head_size]
120
+ if seq_len > self.max_seq_len_cached:
121
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
122
+
123
+ return (
124
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
125
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
126
+ )
127
+
128
+
129
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
130
+ def rotate_half(x):
131
+ """Rotates half the hidden dims of the input."""
132
+ x1 = x[..., : x.shape[-1] // 2]
133
+ x2 = x[..., x.shape[-1] // 2 :]
134
+ return torch.cat((-x2, x1), dim=-1)
135
+
136
+
137
+ # copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
138
+ # TODO @Arthur no longer copied from LLama after static cache
139
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
140
+ """Applies Rotary Position Embedding to the query and key tensors.
141
+
142
+ Args:
143
+ q (`torch.Tensor`): The query tensor.
144
+ k (`torch.Tensor`): The key tensor.
145
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
146
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
147
+ position_ids (`torch.Tensor`):
148
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
149
+ used to pass offsetted position ids when working with a KV-cache.
150
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
151
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
152
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
153
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
154
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
155
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
156
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
157
+ Returns:
158
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
159
+ """
160
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
161
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
162
+ q_embed = (q * cos) + (rotate_half(q) * sin)
163
+ k_embed = (k * cos) + (rotate_half(k) * sin)
164
+ return q_embed, k_embed
165
+
166
+
167
+ class DusMistralMLP(nn.Module):
168
+ def __init__(self, config):
169
+ super().__init__()
170
+ self.config = config
171
+ self.hidden_size = config.hidden_size
172
+ self.intermediate_size = config.intermediate_size
173
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
174
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
175
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
176
+ self.act_fn = ACT2FN[config.hidden_act]
177
+
178
+ def forward(self, x):
179
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
180
+
181
+
182
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
183
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
184
+ """
185
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
186
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
187
+ """
188
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
189
+ if n_rep == 1:
190
+ return hidden_states
191
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
192
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
193
+
194
+
195
+ class DusMistralAttention(nn.Module):
196
+ """
197
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
198
+ and "Generating Long Sequences with Sparse Transformers".
199
+ """
200
+
201
+ def __init__(self, config: DusMistralConfig, layer_idx: Optional[int] = None):
202
+ super().__init__()
203
+ self.config = config
204
+ self.layer_idx = layer_idx
205
+ if layer_idx is None:
206
+ logger.warning_once(
207
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
208
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
209
+ "when creating this class."
210
+ )
211
+
212
+ self.hidden_size = config.hidden_size
213
+ self.num_heads = config.num_attention_heads
214
+ self.head_dim = self.hidden_size // self.num_heads
215
+ self.num_key_value_heads = config.num_key_value_heads
216
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
217
+ self.max_position_embeddings = config.max_position_embeddings
218
+ self.rope_theta = config.rope_theta
219
+ self.is_causal = True
220
+ self.attention_dropout = config.attention_dropout
221
+
222
+ if (self.head_dim * self.num_heads) != self.hidden_size:
223
+ raise ValueError(
224
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
225
+ f" and `num_heads`: {self.num_heads})."
226
+ )
227
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
228
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
229
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
230
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
231
+
232
+ self.rotary_emb = DusMistralRotaryEmbedding(
233
+ self.head_dim,
234
+ max_position_embeddings=self.max_position_embeddings,
235
+ base=self.rope_theta,
236
+ )
237
+
238
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
239
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
240
+
241
+ def forward(
242
+ self,
243
+ hidden_states: torch.Tensor,
244
+ attention_mask: Optional[torch.Tensor] = None,
245
+ position_ids: Optional[torch.LongTensor] = None,
246
+ past_key_value: Optional[Cache] = None,
247
+ output_attentions: bool = False,
248
+ use_cache: bool = False,
249
+ **kwargs,
250
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
251
+ if "padding_mask" in kwargs:
252
+ warnings.warn(
253
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
254
+ )
255
+ bsz, q_len, _ = hidden_states.size()
256
+
257
+ query_states = self.q_proj(hidden_states)
258
+ key_states = self.k_proj(hidden_states)
259
+ value_states = self.v_proj(hidden_states)
260
+
261
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
262
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
263
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
264
+
265
+ kv_seq_len = key_states.shape[-2]
266
+ if past_key_value is not None:
267
+ if self.layer_idx is None:
268
+ raise ValueError(
269
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
270
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
271
+ "with a layer index."
272
+ )
273
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
274
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
275
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
276
+
277
+ if past_key_value is not None:
278
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
279
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
280
+
281
+ # repeat k/v heads if n_kv_heads < n_heads
282
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
283
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
284
+
285
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
286
+
287
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
288
+ raise ValueError(
289
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
290
+ f" {attn_weights.size()}"
291
+ )
292
+
293
+ if attention_mask is not None:
294
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
295
+ raise ValueError(
296
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
297
+ )
298
+
299
+ attn_weights = attn_weights + attention_mask
300
+
301
+ # upcast attention to fp32
302
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
303
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
304
+ attn_output = torch.matmul(attn_weights, value_states)
305
+
306
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
307
+ raise ValueError(
308
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
309
+ f" {attn_output.size()}"
310
+ )
311
+
312
+ attn_output = attn_output.transpose(1, 2).contiguous()
313
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
314
+
315
+ attn_output = self.o_proj(attn_output)
316
+
317
+ if not output_attentions:
318
+ attn_weights = None
319
+
320
+ return attn_output, attn_weights, past_key_value
321
+
322
+
323
+ class DusMistralFlashAttention2(DusMistralAttention):
324
+ """
325
+ DusMistral flash attention module. This module inherits from `DusMistralAttention` as the weights of the module stays
326
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
327
+ flash attention and deal with padding tokens in case the input contains any of them.
328
+ """
329
+
330
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
331
+ def __init__(self, *args, **kwargs):
332
+ super().__init__(*args, **kwargs)
333
+
334
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
335
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
336
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
337
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
338
+
339
+ def forward(
340
+ self,
341
+ hidden_states: torch.Tensor,
342
+ attention_mask: Optional[torch.Tensor] = None,
343
+ position_ids: Optional[torch.LongTensor] = None,
344
+ past_key_value: Optional[Cache] = None,
345
+ output_attentions: bool = False,
346
+ use_cache: bool = False,
347
+ **kwargs,
348
+ ):
349
+ if "padding_mask" in kwargs:
350
+ warnings.warn(
351
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
352
+ )
353
+
354
+ # overwrite attention_mask with padding_mask
355
+ attention_mask = kwargs.pop("padding_mask")
356
+ bsz, q_len, _ = hidden_states.size()
357
+
358
+ query_states = self.q_proj(hidden_states)
359
+ key_states = self.k_proj(hidden_states)
360
+ value_states = self.v_proj(hidden_states)
361
+
362
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
363
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
364
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
365
+
366
+ kv_seq_len = key_states.shape[-2]
367
+ if past_key_value is not None:
368
+ if self.layer_idx is None:
369
+ raise ValueError(
370
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
371
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
372
+ "with a layer index."
373
+ )
374
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
375
+
376
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
377
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
378
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
379
+
380
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
381
+
382
+ use_sliding_windows = (
383
+ _flash_supports_window_size
384
+ and getattr(self.config, "sliding_window", None) is not None
385
+ and kv_seq_len > self.config.sliding_window
386
+ )
387
+
388
+ if not _flash_supports_window_size:
389
+ logger.warning_once(
390
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
391
+ " make sure to upgrade flash-attn library."
392
+ )
393
+
394
+ if past_key_value is not None:
395
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
396
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
397
+ if (
398
+ getattr(self.config, "sliding_window", None) is not None
399
+ and kv_seq_len > self.config.sliding_window
400
+ and cache_has_contents
401
+ ):
402
+ slicing_tokens = 1 - self.config.sliding_window
403
+
404
+ past_key = past_key_value[self.layer_idx][0]
405
+ past_value = past_key_value[self.layer_idx][1]
406
+
407
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
408
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
409
+
410
+ if past_key.shape[-2] != self.config.sliding_window - 1:
411
+ raise ValueError(
412
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
413
+ f" {past_key.shape}"
414
+ )
415
+
416
+ if attention_mask is not None:
417
+ attention_mask = attention_mask[:, slicing_tokens:]
418
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
419
+
420
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
421
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
422
+
423
+ # repeat k/v heads if n_kv_heads < n_heads
424
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
425
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
426
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
427
+
428
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
429
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
430
+ # cast them back in float16 just to be sure everything works as expected.
431
+ input_dtype = query_states.dtype
432
+ if input_dtype == torch.float32:
433
+ if torch.is_autocast_enabled():
434
+ target_dtype = torch.get_autocast_gpu_dtype()
435
+ # Handle the case where the model is quantized
436
+ elif hasattr(self.config, "_pre_quantization_dtype"):
437
+ target_dtype = self.config._pre_quantization_dtype
438
+ else:
439
+ target_dtype = self.q_proj.weight.dtype
440
+
441
+ logger.warning_once(
442
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
443
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
444
+ f" {target_dtype}."
445
+ )
446
+
447
+ query_states = query_states.to(target_dtype)
448
+ key_states = key_states.to(target_dtype)
449
+ value_states = value_states.to(target_dtype)
450
+
451
+ # Reashape to the expected shape for Flash Attention
452
+ query_states = query_states.transpose(1, 2)
453
+ key_states = key_states.transpose(1, 2)
454
+ value_states = value_states.transpose(1, 2)
455
+
456
+ attn_output = self._flash_attention_forward(
457
+ query_states,
458
+ key_states,
459
+ value_states,
460
+ attention_mask,
461
+ q_len,
462
+ dropout=dropout_rate,
463
+ use_sliding_windows=use_sliding_windows,
464
+ )
465
+
466
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
467
+ attn_output = self.o_proj(attn_output)
468
+
469
+ if not output_attentions:
470
+ attn_weights = None
471
+
472
+ return attn_output, attn_weights, past_key_value
473
+
474
+ def _flash_attention_forward(
475
+ self,
476
+ query_states,
477
+ key_states,
478
+ value_states,
479
+ attention_mask,
480
+ query_length,
481
+ dropout=0.0,
482
+ softmax_scale=None,
483
+ use_sliding_windows=False,
484
+ ):
485
+ """
486
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
487
+ first unpad the input, then computes the attention scores and pad the final attention scores.
488
+
489
+ Args:
490
+ query_states (`torch.Tensor`):
491
+ Input query states to be passed to Flash Attention API
492
+ key_states (`torch.Tensor`):
493
+ Input key states to be passed to Flash Attention API
494
+ value_states (`torch.Tensor`):
495
+ Input value states to be passed to Flash Attention API
496
+ attention_mask (`torch.Tensor`):
497
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
498
+ position of padding tokens and 1 for the position of non-padding tokens.
499
+ dropout (`float`):
500
+ Attention dropout
501
+ softmax_scale (`float`, *optional*):
502
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
503
+ use_sliding_windows (`bool`, *optional*):
504
+ Whether to activate sliding window attention.
505
+ """
506
+ if not self._flash_attn_uses_top_left_mask:
507
+ causal = self.is_causal
508
+ else:
509
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
510
+ causal = self.is_causal and query_length != 1
511
+
512
+ # Contains at least one padding token in the sequence
513
+ if attention_mask is not None:
514
+ batch_size = query_states.shape[0]
515
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
516
+ query_states, key_states, value_states, attention_mask, query_length
517
+ )
518
+
519
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
520
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
521
+
522
+ if not use_sliding_windows:
523
+ attn_output_unpad = flash_attn_varlen_func(
524
+ query_states,
525
+ key_states,
526
+ value_states,
527
+ cu_seqlens_q=cu_seqlens_q,
528
+ cu_seqlens_k=cu_seqlens_k,
529
+ max_seqlen_q=max_seqlen_in_batch_q,
530
+ max_seqlen_k=max_seqlen_in_batch_k,
531
+ dropout_p=dropout,
532
+ softmax_scale=softmax_scale,
533
+ causal=causal,
534
+ )
535
+ else:
536
+ attn_output_unpad = flash_attn_varlen_func(
537
+ query_states,
538
+ key_states,
539
+ value_states,
540
+ cu_seqlens_q=cu_seqlens_q,
541
+ cu_seqlens_k=cu_seqlens_k,
542
+ max_seqlen_q=max_seqlen_in_batch_q,
543
+ max_seqlen_k=max_seqlen_in_batch_k,
544
+ dropout_p=dropout,
545
+ softmax_scale=softmax_scale,
546
+ causal=causal,
547
+ window_size=(self.config.sliding_window, self.config.sliding_window),
548
+ )
549
+
550
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
551
+ else:
552
+ if not use_sliding_windows:
553
+ attn_output = flash_attn_func(
554
+ query_states,
555
+ key_states,
556
+ value_states,
557
+ dropout,
558
+ softmax_scale=softmax_scale,
559
+ causal=causal,
560
+ )
561
+ else:
562
+ attn_output = flash_attn_func(
563
+ query_states,
564
+ key_states,
565
+ value_states,
566
+ dropout,
567
+ softmax_scale=softmax_scale,
568
+ causal=causal,
569
+ window_size=(self.config.sliding_window, self.config.sliding_window),
570
+ )
571
+
572
+ return attn_output
573
+
574
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
575
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
576
+
577
+ # On the first iteration we need to properly re-create the padding mask
578
+ # by slicing it on the proper place
579
+ if kv_seq_len != attention_mask.shape[-1]:
580
+ attention_mask_num_tokens = attention_mask.shape[-1]
581
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
582
+
583
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
584
+
585
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
586
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
587
+
588
+ if query_length == kv_seq_len:
589
+ query_layer = index_first_axis(
590
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
591
+ )
592
+ cu_seqlens_q = cu_seqlens_k
593
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
594
+ indices_q = indices_k
595
+ elif query_length == 1:
596
+ max_seqlen_in_batch_q = 1
597
+ cu_seqlens_q = torch.arange(
598
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
599
+ ) # There is a memcpy here, that is very bad.
600
+ indices_q = cu_seqlens_q[:-1]
601
+ query_layer = query_layer.squeeze(1)
602
+ else:
603
+ # The -q_len: slice assumes left padding.
604
+ attention_mask = attention_mask[:, -query_length:]
605
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
606
+
607
+ return (
608
+ query_layer,
609
+ key_layer,
610
+ value_layer,
611
+ indices_q,
612
+ (cu_seqlens_q, cu_seqlens_k),
613
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
614
+ )
615
+
616
+
617
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->DusMistral
618
+ # TODO @Arthur no longer copied from LLama after static cache
619
+ class DusMistralSdpaAttention(DusMistralAttention):
620
+ """
621
+ DusMistral attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
622
+ `DusMistralAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
623
+ SDPA API.
624
+ """
625
+
626
+ # Adapted from DusMistralAttention.forward
627
+ def forward(
628
+ self,
629
+ hidden_states: torch.Tensor,
630
+ attention_mask: Optional[torch.Tensor] = None,
631
+ position_ids: Optional[torch.LongTensor] = None,
632
+ past_key_value: Optional[Cache] = None,
633
+ output_attentions: bool = False,
634
+ use_cache: bool = False,
635
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
636
+ if output_attentions:
637
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
638
+ logger.warning_once(
639
+ "DusMistralModel is using DusMistralSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
640
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
641
+ )
642
+ return super().forward(
643
+ hidden_states=hidden_states,
644
+ attention_mask=attention_mask,
645
+ position_ids=position_ids,
646
+ past_key_value=past_key_value,
647
+ output_attentions=output_attentions,
648
+ use_cache=use_cache,
649
+ )
650
+
651
+ bsz, q_len, _ = hidden_states.size()
652
+
653
+ query_states = self.q_proj(hidden_states)
654
+ key_states = self.k_proj(hidden_states)
655
+ value_states = self.v_proj(hidden_states)
656
+
657
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
658
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
659
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
660
+
661
+ kv_seq_len = key_states.shape[-2]
662
+ if past_key_value is not None:
663
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
664
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
665
+
666
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
667
+
668
+ if past_key_value is not None:
669
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
670
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
671
+
672
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
673
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
674
+
675
+ if attention_mask is not None:
676
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
677
+ raise ValueError(
678
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
679
+ )
680
+
681
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
682
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
683
+ if query_states.device.type == "cuda" and attention_mask is not None:
684
+ query_states = query_states.contiguous()
685
+ key_states = key_states.contiguous()
686
+ value_states = value_states.contiguous()
687
+
688
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
689
+ query_states,
690
+ key_states,
691
+ value_states,
692
+ attn_mask=attention_mask,
693
+ dropout_p=self.attention_dropout if self.training else 0.0,
694
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
695
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
696
+ )
697
+
698
+ attn_output = attn_output.transpose(1, 2).contiguous()
699
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
700
+
701
+ attn_output = self.o_proj(attn_output)
702
+
703
+ return attn_output, None, past_key_value
704
+
705
+
706
+ MISTRAL_ATTENTION_CLASSES = {
707
+ "eager": DusMistralAttention,
708
+ "flash_attention_2": DusMistralFlashAttention2,
709
+ "sdpa": DusMistralSdpaAttention,
710
+ }
711
+
712
+
713
+ class DusMistralDecoderLayer(nn.Module):
714
+ def __init__(self, config: DusMistralConfig, layer_idx: int):
715
+ super().__init__()
716
+ self.hidden_size = config.hidden_size
717
+
718
+ self.self_attn = MISTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
719
+
720
+ self.mlp = DusMistralMLP(config)
721
+ self.input_layernorm = DusMistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
722
+ self.post_attention_layernorm = DusMistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
723
+
724
+ def forward(
725
+ self,
726
+ hidden_states: torch.Tensor,
727
+ attention_mask: Optional[torch.Tensor] = None,
728
+ position_ids: Optional[torch.LongTensor] = None,
729
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
730
+ output_attentions: Optional[bool] = False,
731
+ use_cache: Optional[bool] = False,
732
+ **kwargs,
733
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
734
+ if "padding_mask" in kwargs:
735
+ warnings.warn(
736
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
737
+ )
738
+ """
739
+ Args:
740
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
741
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
742
+ `(batch, sequence_length)` where padding elements are indicated by 0.
743
+ output_attentions (`bool`, *optional*):
744
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
745
+ returned tensors for more detail.
746
+ use_cache (`bool`, *optional*):
747
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
748
+ (see `past_key_values`).
749
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
750
+ """
751
+
752
+ residual = hidden_states
753
+
754
+ hidden_states = self.input_layernorm(hidden_states)
755
+
756
+ # Self Attention
757
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
758
+ hidden_states=hidden_states,
759
+ attention_mask=attention_mask,
760
+ position_ids=position_ids,
761
+ past_key_value=past_key_value,
762
+ output_attentions=output_attentions,
763
+ use_cache=use_cache,
764
+ )
765
+ hidden_states = residual + hidden_states
766
+
767
+ # Fully Connected
768
+ residual = hidden_states
769
+ hidden_states = self.post_attention_layernorm(hidden_states)
770
+ hidden_states = self.mlp(hidden_states)
771
+ hidden_states = residual + hidden_states
772
+
773
+ outputs = (hidden_states,)
774
+
775
+ if output_attentions:
776
+ outputs += (self_attn_weights,)
777
+
778
+ if use_cache:
779
+ outputs += (present_key_value,)
780
+
781
+ return outputs
782
+
783
+
784
+ MISTRAL_START_DOCSTRING = r"""
785
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
786
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
787
+ etc.)
788
+
789
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
790
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
791
+ and behavior.
792
+
793
+ Parameters:
794
+ config ([`DusMistralConfig`]):
795
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
796
+ load the weights associated with the model, only the configuration. Check out the
797
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
798
+ """
799
+
800
+
801
+ @add_start_docstrings(
802
+ "The bare DusMistral Model outputting raw hidden-states without any specific head on top.",
803
+ MISTRAL_START_DOCSTRING,
804
+ )
805
+ class DusMistralPreTrainedModel(PreTrainedModel):
806
+ config_class = DusMistralConfig
807
+ base_model_prefix = "model"
808
+ supports_gradient_checkpointing = True
809
+ _no_split_modules = ["DusMistralDecoderLayer"]
810
+ _skip_keys_device_placement = "past_key_values"
811
+ _supports_flash_attn_2 = True
812
+ _supports_sdpa = True
813
+ _supports_cache_class = True
814
+
815
+ def _init_weights(self, module):
816
+ std = self.config.initializer_range
817
+ if isinstance(module, nn.Linear):
818
+ module.weight.data.normal_(mean=0.0, std=std)
819
+ if module.bias is not None:
820
+ module.bias.data.zero_()
821
+ elif isinstance(module, nn.Embedding):
822
+ module.weight.data.normal_(mean=0.0, std=std)
823
+ if module.padding_idx is not None:
824
+ module.weight.data[module.padding_idx].zero_()
825
+
826
+
827
+ MISTRAL_INPUTS_DOCSTRING = r"""
828
+ Args:
829
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
830
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
831
+ it.
832
+
833
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
834
+ [`PreTrainedTokenizer.__call__`] for details.
835
+
836
+ [What are input IDs?](../glossary#input-ids)
837
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
838
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
839
+
840
+ - 1 for tokens that are **not masked**,
841
+ - 0 for tokens that are **masked**.
842
+
843
+ [What are attention masks?](../glossary#attention-mask)
844
+
845
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
846
+ [`PreTrainedTokenizer.__call__`] for details.
847
+
848
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
849
+ `past_key_values`).
850
+
851
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
852
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
853
+ information on the default strategy.
854
+
855
+ - 1 indicates the head is **not masked**,
856
+ - 0 indicates the head is **masked**.
857
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
858
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
859
+ config.n_positions - 1]`.
860
+
861
+ [What are position IDs?](../glossary#position-ids)
862
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
863
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
864
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
865
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
866
+
867
+ Two formats are allowed:
868
+ - a [`~cache_utils.Cache`] instance;
869
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
870
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
871
+ cache format.
872
+
873
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
874
+ legacy cache format will be returned.
875
+
876
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
877
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
878
+ of shape `(batch_size, sequence_length)`.
879
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
880
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
881
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
882
+ model's internal embedding lookup matrix.
883
+ use_cache (`bool`, *optional*):
884
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
885
+ `past_key_values`).
886
+ output_attentions (`bool`, *optional*):
887
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
888
+ tensors for more detail.
889
+ output_hidden_states (`bool`, *optional*):
890
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
891
+ more detail.
892
+ return_dict (`bool`, *optional*):
893
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
894
+ """
895
+
896
+
897
+ @add_start_docstrings(
898
+ "The bare DusMistral Model outputting raw hidden-states without any specific head on top.",
899
+ MISTRAL_START_DOCSTRING,
900
+ )
901
+ class DusMistralModel(DusMistralPreTrainedModel):
902
+ """
903
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DusMistralDecoderLayer`]
904
+
905
+ Args:
906
+ config: DusMistralConfig
907
+ """
908
+
909
+ def __init__(self, config: DusMistralConfig):
910
+ super().__init__(config)
911
+ self.padding_idx = config.pad_token_id
912
+ self.vocab_size = config.vocab_size
913
+ self.layer_order = config.layer_order
914
+
915
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
916
+ self.layers = nn.ModuleList(
917
+ [DusMistralDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
918
+ )
919
+ self._attn_implementation = config._attn_implementation
920
+ self.norm = DusMistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
921
+
922
+ self.gradient_checkpointing = False
923
+ # Initialize weights and apply final processing
924
+ self.post_init()
925
+
926
+ def get_input_embeddings(self):
927
+ return self.embed_tokens
928
+
929
+ def set_input_embeddings(self, value):
930
+ self.embed_tokens = value
931
+
932
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
933
+ def forward(
934
+ self,
935
+ input_ids: torch.LongTensor = None,
936
+ attention_mask: Optional[torch.Tensor] = None,
937
+ position_ids: Optional[torch.LongTensor] = None,
938
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
939
+ inputs_embeds: Optional[torch.FloatTensor] = None,
940
+ use_cache: Optional[bool] = None,
941
+ output_attentions: Optional[bool] = None,
942
+ output_hidden_states: Optional[bool] = None,
943
+ return_dict: Optional[bool] = None,
944
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
945
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
946
+ output_hidden_states = (
947
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
948
+ )
949
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
950
+
951
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
952
+
953
+ # retrieve input_ids and inputs_embeds
954
+ if input_ids is not None and inputs_embeds is not None:
955
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
956
+ elif input_ids is not None:
957
+ batch_size, seq_length = input_ids.shape
958
+ elif inputs_embeds is not None:
959
+ batch_size, seq_length, _ = inputs_embeds.shape
960
+ else:
961
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
962
+
963
+ if self.gradient_checkpointing and self.training:
964
+ if use_cache:
965
+ logger.warning_once(
966
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
967
+ )
968
+ use_cache = False
969
+
970
+ past_key_values_length = 0
971
+
972
+ if use_cache:
973
+ use_legacy_cache = not isinstance(past_key_values, Cache)
974
+ if use_legacy_cache:
975
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
976
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
977
+
978
+ if position_ids is None:
979
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
980
+ position_ids = torch.arange(
981
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
982
+ )
983
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
984
+ else:
985
+ position_ids = position_ids.view(-1, seq_length).long()
986
+
987
+ if inputs_embeds is None:
988
+ inputs_embeds = self.embed_tokens(input_ids)
989
+
990
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
991
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
992
+ if is_padding_right:
993
+ raise ValueError(
994
+ "You are attempting to perform batched generation with padding_side='right'"
995
+ " this may lead to unexpected behaviour for Flash Attention version of DusMistral. Make sure to "
996
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
997
+ )
998
+
999
+ if self._attn_implementation == "flash_attention_2":
1000
+ # 2d mask is passed through the layers
1001
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1002
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1003
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1004
+ # the manual implementation that requires a 4D causal mask in all cases.
1005
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1006
+ attention_mask,
1007
+ (batch_size, seq_length),
1008
+ inputs_embeds,
1009
+ past_key_values_length,
1010
+ )
1011
+ else:
1012
+ # 4d mask is passed through the layers
1013
+ attention_mask = _prepare_4d_causal_attention_mask(
1014
+ attention_mask,
1015
+ (batch_size, seq_length),
1016
+ inputs_embeds,
1017
+ past_key_values_length,
1018
+ sliding_window=self.config.sliding_window,
1019
+ )
1020
+
1021
+ hidden_states = inputs_embeds
1022
+
1023
+ # decoder layers
1024
+ all_hidden_states = () if output_hidden_states else None
1025
+ all_self_attns = () if output_attentions else None
1026
+ next_decoder_cache = None
1027
+
1028
+ for start, end in self.layer_order:
1029
+ for layer_idx in range(start, min(end, len(self.layers))):
1030
+ decoder_layer = self.layers[layer_idx]
1031
+ if output_hidden_states:
1032
+ all_hidden_states += (hidden_states,)
1033
+
1034
+ if self.gradient_checkpointing and self.training:
1035
+ layer_outputs = self._gradient_checkpointing_func(
1036
+ decoder_layer.__call__,
1037
+ hidden_states,
1038
+ attention_mask,
1039
+ position_ids,
1040
+ past_key_values,
1041
+ output_attentions,
1042
+ use_cache,
1043
+ )
1044
+ else:
1045
+ layer_outputs = decoder_layer(
1046
+ hidden_states,
1047
+ attention_mask=attention_mask,
1048
+ position_ids=position_ids,
1049
+ past_key_value=past_key_values,
1050
+ output_attentions=output_attentions,
1051
+ use_cache=use_cache,
1052
+ )
1053
+
1054
+ hidden_states = layer_outputs[0]
1055
+
1056
+ if use_cache:
1057
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1058
+
1059
+ if output_attentions:
1060
+ all_self_attns += (layer_outputs[1],)
1061
+
1062
+ hidden_states = self.norm(hidden_states)
1063
+
1064
+ # add hidden states from the last decoder layer
1065
+ if output_hidden_states:
1066
+ all_hidden_states += (hidden_states,)
1067
+
1068
+ next_cache = None
1069
+ if use_cache:
1070
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1071
+
1072
+ if not return_dict:
1073
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1074
+ return BaseModelOutputWithPast(
1075
+ last_hidden_state=hidden_states,
1076
+ past_key_values=next_cache,
1077
+ hidden_states=all_hidden_states,
1078
+ attentions=all_self_attns,
1079
+ )
1080
+
1081
+
1082
+ class DusMistralForCausalLM(DusMistralPreTrainedModel):
1083
+ _tied_weights_keys = ["lm_head.weight"]
1084
+
1085
+ def __init__(self, config):
1086
+ super().__init__(config)
1087
+ self.model = DusMistralModel(config)
1088
+ self.vocab_size = config.vocab_size
1089
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1090
+
1091
+ # Initialize weights and apply final processing
1092
+ self.post_init()
1093
+
1094
+ def get_input_embeddings(self):
1095
+ return self.model.embed_tokens
1096
+
1097
+ def set_input_embeddings(self, value):
1098
+ self.model.embed_tokens = value
1099
+
1100
+ def get_output_embeddings(self):
1101
+ return self.lm_head
1102
+
1103
+ def set_output_embeddings(self, new_embeddings):
1104
+ self.lm_head = new_embeddings
1105
+
1106
+ def set_decoder(self, decoder):
1107
+ self.model = decoder
1108
+
1109
+ def get_decoder(self):
1110
+ return self.model
1111
+
1112
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1113
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1114
+ def forward(
1115
+ self,
1116
+ input_ids: torch.LongTensor = None,
1117
+ attention_mask: Optional[torch.Tensor] = None,
1118
+ position_ids: Optional[torch.LongTensor] = None,
1119
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1120
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1121
+ labels: Optional[torch.LongTensor] = None,
1122
+ use_cache: Optional[bool] = None,
1123
+ output_attentions: Optional[bool] = None,
1124
+ output_hidden_states: Optional[bool] = None,
1125
+ return_dict: Optional[bool] = None,
1126
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1127
+ r"""
1128
+ Args:
1129
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1130
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1131
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1132
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1133
+
1134
+ Returns:
1135
+
1136
+ Example:
1137
+
1138
+ ```python
1139
+ >>> from transformers import AutoTokenizer, DusMistralForCausalLM
1140
+
1141
+ >>> model = DusMistralForCausalLM.from_pretrained("mistralai/DusMistral-7B-v0.1")
1142
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/DusMistral-7B-v0.1")
1143
+
1144
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1145
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1146
+
1147
+ >>> # Generate
1148
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1149
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1150
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1151
+ ```"""
1152
+
1153
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1154
+ output_hidden_states = (
1155
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1156
+ )
1157
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1158
+
1159
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1160
+ outputs = self.model(
1161
+ input_ids=input_ids,
1162
+ attention_mask=attention_mask,
1163
+ position_ids=position_ids,
1164
+ past_key_values=past_key_values,
1165
+ inputs_embeds=inputs_embeds,
1166
+ use_cache=use_cache,
1167
+ output_attentions=output_attentions,
1168
+ output_hidden_states=output_hidden_states,
1169
+ return_dict=return_dict,
1170
+ )
1171
+
1172
+ hidden_states = outputs[0]
1173
+ logits = self.lm_head(hidden_states)
1174
+ logits = logits.float()
1175
+
1176
+ loss = None
1177
+ if labels is not None:
1178
+ # Shift so that tokens < n predict n
1179
+ shift_logits = logits[..., :-1, :].contiguous()
1180
+ shift_labels = labels[..., 1:].contiguous()
1181
+ # Flatten the tokens
1182
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1183
+ shift_labels = shift_labels.view(-1)
1184
+ # Ensure tensors are on the same device
1185
+ shift_labels = shift_labels.to(shift_logits.device)
1186
+ loss_fct = CrossEntropyLoss()
1187
+ loss = loss_fct(shift_logits, shift_labels)
1188
+
1189
+ if not return_dict:
1190
+ output = (logits,) + outputs[1:]
1191
+ return (loss,) + output if loss is not None else output
1192
+
1193
+ return CausalLMOutputWithPast(
1194
+ loss=loss,
1195
+ logits=logits,
1196
+ past_key_values=outputs.past_key_values,
1197
+ hidden_states=outputs.hidden_states,
1198
+ attentions=outputs.attentions,
1199
+ )
1200
+
1201
+ def prepare_inputs_for_generation(
1202
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1203
+ ):
1204
+ # Omit tokens covered by past_key_values
1205
+ if past_key_values is not None:
1206
+ if isinstance(past_key_values, Cache):
1207
+ cache_length = past_key_values.get_seq_length()
1208
+ past_length = past_key_values.seen_tokens
1209
+ max_cache_length = past_key_values.get_max_length()
1210
+ else:
1211
+ cache_length = past_length = past_key_values[0][0].shape[2]
1212
+ max_cache_length = None
1213
+
1214
+ # Keep only the unprocessed tokens:
1215
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1216
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1217
+ # input)
1218
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1219
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1220
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1221
+ # input_ids based on the past_length.
1222
+ elif past_length < input_ids.shape[1]:
1223
+ input_ids = input_ids[:, past_length:]
1224
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1225
+
1226
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1227
+ if (
1228
+ max_cache_length is not None
1229
+ and attention_mask is not None
1230
+ and cache_length + input_ids.shape[1] > max_cache_length
1231
+ ):
1232
+ attention_mask = attention_mask[:, -max_cache_length:]
1233
+
1234
+ position_ids = kwargs.get("position_ids", None)
1235
+ if attention_mask is not None and position_ids is None:
1236
+ # create position_ids on the fly for batch generation
1237
+ position_ids = attention_mask.long().cumsum(-1) - 1
1238
+ position_ids.masked_fill_(attention_mask == 0, 1)
1239
+ if past_key_values:
1240
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1241
+
1242
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1243
+ if inputs_embeds is not None and past_key_values is None:
1244
+ model_inputs = {"inputs_embeds": inputs_embeds}
1245
+ else:
1246
+ model_inputs = {"input_ids": input_ids}
1247
+
1248
+ model_inputs.update(
1249
+ {
1250
+ "position_ids": position_ids,
1251
+ "past_key_values": past_key_values,
1252
+ "use_cache": kwargs.get("use_cache"),
1253
+ "attention_mask": attention_mask,
1254
+ }
1255
+ )
1256
+ return model_inputs
1257
+
1258
+ @staticmethod
1259
+ def _reorder_cache(past_key_values, beam_idx):
1260
+ reordered_past = ()
1261
+ for layer_past in past_key_values:
1262
+ reordered_past += (
1263
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1264
+ )
1265
+ return reordered_past
1266
+
1267
+
1268
+ @add_start_docstrings(
1269
+ """
1270
+ The DusMistral Model transformer with a sequence classification head on top (linear layer).
1271
+
1272
+ [`DusMistralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1273
+ (e.g. GPT-2) do.
1274
+
1275
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1276
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1277
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1278
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1279
+ each row of the batch).
1280
+ """,
1281
+ MISTRAL_START_DOCSTRING,
1282
+ )
1283
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->DusMistral, LLAMA->MISTRAL
1284
+ class DusMistralForSequenceClassification(DusMistralPreTrainedModel):
1285
+ def __init__(self, config):
1286
+ super().__init__(config)
1287
+ self.num_labels = config.num_labels
1288
+ self.model = DusMistralModel(config)
1289
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1290
+
1291
+ # Initialize weights and apply final processing
1292
+ self.post_init()
1293
+
1294
+ def get_input_embeddings(self):
1295
+ return self.model.embed_tokens
1296
+
1297
+ def set_input_embeddings(self, value):
1298
+ self.model.embed_tokens = value
1299
+
1300
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1301
+ def forward(
1302
+ self,
1303
+ input_ids: torch.LongTensor = None,
1304
+ attention_mask: Optional[torch.Tensor] = None,
1305
+ position_ids: Optional[torch.LongTensor] = None,
1306
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1307
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1308
+ labels: Optional[torch.LongTensor] = None,
1309
+ use_cache: Optional[bool] = None,
1310
+ output_attentions: Optional[bool] = None,
1311
+ output_hidden_states: Optional[bool] = None,
1312
+ return_dict: Optional[bool] = None,
1313
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1314
+ r"""
1315
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1316
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1317
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1318
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1319
+ """
1320
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1321
+
1322
+ transformer_outputs = self.model(
1323
+ input_ids,
1324
+ attention_mask=attention_mask,
1325
+ position_ids=position_ids,
1326
+ past_key_values=past_key_values,
1327
+ inputs_embeds=inputs_embeds,
1328
+ use_cache=use_cache,
1329
+ output_attentions=output_attentions,
1330
+ output_hidden_states=output_hidden_states,
1331
+ return_dict=return_dict,
1332
+ )
1333
+ hidden_states = transformer_outputs[0]
1334
+ logits = self.score(hidden_states)
1335
+
1336
+ if input_ids is not None:
1337
+ batch_size = input_ids.shape[0]
1338
+ else:
1339
+ batch_size = inputs_embeds.shape[0]
1340
+
1341
+ if self.config.pad_token_id is None and batch_size != 1:
1342
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1343
+ if self.config.pad_token_id is None:
1344
+ sequence_lengths = -1
1345
+ else:
1346
+ if input_ids is not None:
1347
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1348
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1349
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1350
+ sequence_lengths = sequence_lengths.to(logits.device)
1351
+ else:
1352
+ sequence_lengths = -1
1353
+
1354
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1355
+
1356
+ loss = None
1357
+ if labels is not None:
1358
+ labels = labels.to(logits.device)
1359
+ if self.config.problem_type is None:
1360
+ if self.num_labels == 1:
1361
+ self.config.problem_type = "regression"
1362
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1363
+ self.config.problem_type = "single_label_classification"
1364
+ else:
1365
+ self.config.problem_type = "multi_label_classification"
1366
+
1367
+ if self.config.problem_type == "regression":
1368
+ loss_fct = MSELoss()
1369
+ if self.num_labels == 1:
1370
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1371
+ else:
1372
+ loss = loss_fct(pooled_logits, labels)
1373
+ elif self.config.problem_type == "single_label_classification":
1374
+ loss_fct = CrossEntropyLoss()
1375
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1376
+ elif self.config.problem_type == "multi_label_classification":
1377
+ loss_fct = BCEWithLogitsLoss()
1378
+ loss = loss_fct(pooled_logits, labels)
1379
+ if not return_dict:
1380
+ output = (pooled_logits,) + transformer_outputs[1:]
1381
+ return ((loss,) + output) if loss is not None else output
1382
+
1383
+ return SequenceClassifierOutputWithPast(
1384
+ loss=loss,
1385
+ logits=pooled_logits,
1386
+ past_key_values=transformer_outputs.past_key_values,
1387
+ hidden_states=transformer_outputs.hidden_states,
1388
+ attentions=transformer_outputs.attentions,
1389
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|im_end|>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<|im_end|>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dadfd56d766715c61d2ef780a525ab43b8e6da4de6865bda3d95fdef5e134055
3
+ size 493443
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff