crumb commited on
Commit
c57abb5
1 Parent(s): 95fc11e

Upload MistralForCausalLM

Browse files
config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MistralForCausalLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_thoughtformer.MistralConfig",
7
+ "AutoModelForCausalLM": "modeling_thoughtformer.MistralForCausalLM"
8
+ },
9
+ "bos_token_id": 1,
10
+ "eos_token_id": 2,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 896,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 2280,
15
+ "max_position_embeddings": 16384,
16
+ "model_type": "mistral",
17
+ "num_attention_heads": 14,
18
+ "num_hidden_layers": 6,
19
+ "num_key_value_heads": 2,
20
+ "rms_norm_eps": 1e-06,
21
+ "rope_theta": 10000.0,
22
+ "sliding_window": 4096,
23
+ "thoughts": 4,
24
+ "tie_word_embeddings": true,
25
+ "torch_dtype": "float32",
26
+ "transformers_version": "4.34.0.dev0",
27
+ "use_cache": true,
28
+ "vocab_size": 32064
29
+ }
configuration_thoughtformer.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 MistralConfig(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
+
86
+
87
+ ```python
88
+ >>> from transformers import MistralModel, MistralConfig
89
+
90
+ >>> # Initializing a Mistral 7B style configuration
91
+ >>> configuration = MistralConfig()
92
+
93
+ >>> # Initializing a model from the Mistral 7B style configuration
94
+ >>> model = MistralModel(configuration)
95
+
96
+ >>> # Accessing the model configuration
97
+ >>> configuration = model.config
98
+ ```"""
99
+
100
+ model_type = "mistral"
101
+ keys_to_ignore_at_inference = ["past_key_values"]
102
+
103
+ def __init__(
104
+ self,
105
+ vocab_size=32000,
106
+ hidden_size=4096,
107
+ intermediate_size=14336,
108
+ num_hidden_layers=32,
109
+ num_attention_heads=32,
110
+ num_key_value_heads=8,
111
+ hidden_act="silu",
112
+ max_position_embeddings=4096 * 32,
113
+ initializer_range=0.02,
114
+ rms_norm_eps=1e-6,
115
+ use_cache=True,
116
+ pad_token_id=None,
117
+ bos_token_id=1,
118
+ eos_token_id=2,
119
+ tie_word_embeddings=False,
120
+ rope_theta=10000.0,
121
+ sliding_window=4096,
122
+ thoughts=1,
123
+ **kwargs,
124
+ ):
125
+ self.thoughts = thoughts
126
+ self.vocab_size = vocab_size
127
+ self.max_position_embeddings = max_position_embeddings
128
+ self.hidden_size = hidden_size
129
+ self.intermediate_size = intermediate_size
130
+ self.num_hidden_layers = num_hidden_layers
131
+ self.num_attention_heads = num_attention_heads
132
+ self.sliding_window = sliding_window
133
+
134
+ # for backward compatibility
135
+ if num_key_value_heads is None:
136
+ num_key_value_heads = num_attention_heads
137
+
138
+ self.num_key_value_heads = num_key_value_heads
139
+ self.hidden_act = hidden_act
140
+ self.initializer_range = initializer_range
141
+ self.rms_norm_eps = rms_norm_eps
142
+ self.use_cache = use_cache
143
+ self.rope_theta = rope_theta
144
+
145
+ super().__init__(
146
+ pad_token_id=pad_token_id,
147
+ bos_token_id=bos_token_id,
148
+ eos_token_id=eos_token_id,
149
+ tie_word_embeddings=tie_word_embeddings,
150
+ **kwargs,
151
+ )
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.34.0.dev0"
6
+ }
modeling_thoughtformer.py ADDED
@@ -0,0 +1,1289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (
35
+ add_start_docstrings,
36
+ add_start_docstrings_to_model_forward,
37
+ # is_flash_attn_2_available,
38
+ logging,
39
+ replace_return_docstrings,
40
+ )
41
+ from .configuration_thoughtformer import MistralConfig
42
+
43
+
44
+ # if is_flash_attn_2_available():
45
+ # from flash_attn import flash_attn_func, flash_attn_varlen_func
46
+ # from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
47
+
48
+ # _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
49
+
50
+
51
+ logger = logging.get_logger(__name__)
52
+
53
+ _CONFIG_FOR_DOC = "MistralConfig"
54
+
55
+
56
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
57
+ def _get_unpad_data(padding_mask):
58
+ seqlens_in_batch = padding_mask.sum(dim=-1, dtype=torch.int32)
59
+ indices = torch.nonzero(padding_mask.flatten(), as_tuple=False).flatten()
60
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
61
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
62
+ return (
63
+ indices,
64
+ cu_seqlens,
65
+ max_seqlen_in_batch,
66
+ )
67
+
68
+
69
+ def _make_sliding_window_causal_mask(
70
+ input_ids_shape: torch.Size,
71
+ dtype: torch.dtype,
72
+ device: torch.device,
73
+ past_key_values_length: int = 0,
74
+ sliding_window: int = 4096,
75
+ ):
76
+ """
77
+ Make causal mask used for sliding window attention
78
+ """
79
+ bsz, tgt_len = input_ids_shape
80
+
81
+ tensor = torch.full(
82
+ (tgt_len, tgt_len),
83
+ fill_value=1,
84
+ device=device,
85
+ )
86
+ mask = torch.tril(tensor, diagonal=0)
87
+ # make the mask banded to account for sliding window
88
+ mask = torch.triu(mask, diagonal=-sliding_window)
89
+ mask = torch.log(mask).to(dtype)
90
+
91
+ if past_key_values_length > 0:
92
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
93
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
94
+
95
+
96
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
97
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
98
+ """
99
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
100
+ """
101
+ bsz, src_len = mask.size()
102
+ tgt_len = tgt_len if tgt_len is not None else src_len
103
+
104
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
105
+
106
+ inverted_mask = 1.0 - expanded_mask
107
+
108
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
109
+
110
+
111
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Mistral
112
+ class MistralRMSNorm(nn.Module):
113
+ def __init__(self, hidden_size, eps=1e-6):
114
+ """
115
+ MistralRMSNorm is equivalent to T5LayerNorm
116
+ """
117
+ super().__init__()
118
+ self.weight = nn.Parameter(torch.ones(hidden_size))
119
+ self.variance_epsilon = eps
120
+
121
+ def forward(self, hidden_states):
122
+ input_dtype = hidden_states.dtype
123
+ hidden_states = hidden_states.to(torch.float32)
124
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
125
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
126
+ return self.weight * hidden_states.to(input_dtype)
127
+
128
+
129
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Mistral
130
+ class MistralRotaryEmbedding(nn.Module):
131
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
132
+ super().__init__()
133
+
134
+ self.dim = dim
135
+ self.max_position_embeddings = max_position_embeddings
136
+ self.base = base
137
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
138
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
139
+
140
+ # Build here to make `torch.jit.trace` work.
141
+ self._set_cos_sin_cache(
142
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
143
+ )
144
+
145
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
146
+ self.max_seq_len_cached = seq_len
147
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
148
+
149
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
150
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
151
+ emb = torch.cat((freqs, freqs), dim=-1)
152
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
153
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
154
+
155
+ def forward(self, x, seq_len=None):
156
+ # x: [bs, num_attention_heads, seq_len, head_size]
157
+ if seq_len > self.max_seq_len_cached:
158
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
159
+
160
+ return (
161
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
162
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
163
+ )
164
+
165
+
166
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
167
+ def rotate_half(x):
168
+ """Rotates half the hidden dims of the input."""
169
+ x1 = x[..., : x.shape[-1] // 2]
170
+ x2 = x[..., x.shape[-1] // 2 :]
171
+ return torch.cat((-x2, x1), dim=-1)
172
+
173
+
174
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
175
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
176
+ cos = cos[position_ids].unsqueeze(1) # [seq_len, dim] -> [batch_size, 1, seq_len, head_dim]
177
+ sin = sin[position_ids].unsqueeze(1)
178
+ q_embed = (q * cos) + (rotate_half(q) * sin)
179
+ k_embed = (k * cos) + (rotate_half(k) * sin)
180
+ return q_embed, k_embed
181
+
182
+
183
+ class MistralMLP(nn.Module):
184
+ def __init__(self, config):
185
+ super().__init__()
186
+ self.config = config
187
+ self.hidden_size = config.hidden_size
188
+ self.intermediate_size = config.intermediate_size
189
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
190
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
191
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
192
+ self.act_fn = ACT2FN[config.hidden_act]
193
+
194
+ def forward(self, x):
195
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
196
+
197
+
198
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
199
+ """
200
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
201
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
202
+ """
203
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
204
+ if n_rep == 1:
205
+ return hidden_states
206
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
207
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
208
+
209
+
210
+ class MistralAttention(nn.Module):
211
+ """
212
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
213
+ and "Generating Long Sequences with Sparse Transformers".
214
+ """
215
+
216
+ def __init__(self, config: MistralConfig):
217
+ super().__init__()
218
+ self.config = config
219
+ self.hidden_size = config.hidden_size
220
+ self.num_heads = config.num_attention_heads
221
+ self.head_dim = self.hidden_size // self.num_heads
222
+ self.num_key_value_heads = config.num_key_value_heads
223
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
224
+ self.max_position_embeddings = config.max_position_embeddings
225
+ self.rope_theta = config.rope_theta
226
+
227
+ if (self.head_dim * self.num_heads) != self.hidden_size:
228
+ raise ValueError(
229
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
230
+ f" and `num_heads`: {self.num_heads})."
231
+ )
232
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
233
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
234
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
235
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
236
+
237
+ self.rotary_emb = MistralRotaryEmbedding(
238
+ self.head_dim,
239
+ max_position_embeddings=self.max_position_embeddings,
240
+ base=self.rope_theta,
241
+ )
242
+
243
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
244
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
245
+
246
+ def forward(
247
+ self,
248
+ hidden_states: torch.Tensor,
249
+ attention_mask: Optional[torch.Tensor] = None,
250
+ position_ids: Optional[torch.LongTensor] = None,
251
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
252
+ output_attentions: bool = False,
253
+ use_cache: bool = False,
254
+ padding_mask: Optional[torch.Tensor] = None,
255
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
256
+ bsz, q_len, _ = hidden_states.size()
257
+
258
+ query_states = self.q_proj(hidden_states)
259
+ key_states = self.k_proj(hidden_states)
260
+ value_states = self.v_proj(hidden_states)
261
+
262
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
263
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
264
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
265
+
266
+ kv_seq_len = key_states.shape[-2]
267
+ if past_key_value is not None:
268
+ kv_seq_len += past_key_value[0].shape[-2]
269
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
270
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
271
+
272
+ if past_key_value is not None:
273
+ # reuse k, v, self_attention
274
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
275
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
276
+
277
+ past_key_value = (key_states, value_states) if use_cache else None
278
+
279
+ # repeat k/v heads if n_kv_heads < n_heads
280
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
281
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
282
+
283
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
284
+
285
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
286
+ raise ValueError(
287
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
288
+ f" {attn_weights.size()}"
289
+ )
290
+
291
+ if attention_mask is not None:
292
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
293
+ raise ValueError(
294
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
295
+ )
296
+
297
+ attn_weights = attn_weights + attention_mask
298
+
299
+ # upcast attention to fp32
300
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
301
+ attn_output = torch.matmul(attn_weights, value_states)
302
+
303
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
304
+ raise ValueError(
305
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
306
+ f" {attn_output.size()}"
307
+ )
308
+
309
+ attn_output = attn_output.transpose(1, 2).contiguous()
310
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
311
+
312
+ attn_output = self.o_proj(attn_output)
313
+
314
+ if not output_attentions:
315
+ attn_weights = None
316
+
317
+ return attn_output, attn_weights, past_key_value
318
+
319
+
320
+ class MistralFlashAttention2(MistralAttention):
321
+ """
322
+ Mistral flash attention module. This module inherits from `MistralAttention` as the weights of the module stays
323
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
324
+ flash attention and deal with padding tokens in case the input contains any of them.
325
+ """
326
+
327
+ def forward(
328
+ self,
329
+ hidden_states: torch.Tensor,
330
+ attention_mask: Optional[torch.Tensor] = None,
331
+ position_ids: Optional[torch.LongTensor] = None,
332
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
333
+ output_attentions: bool = False,
334
+ use_cache: bool = False,
335
+ padding_mask: Optional[torch.LongTensor] = None,
336
+ ):
337
+ bsz, q_len, _ = hidden_states.size()
338
+
339
+ query_states = self.q_proj(hidden_states)
340
+ key_states = self.k_proj(hidden_states)
341
+ value_states = self.v_proj(hidden_states)
342
+
343
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
344
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
345
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
346
+
347
+ kv_seq_len = key_states.shape[-2]
348
+ if past_key_value is not None:
349
+ kv_seq_len += past_key_value[0].shape[-2]
350
+
351
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
352
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
353
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
354
+
355
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
356
+
357
+ use_sliding_windows = (
358
+ _flash_supports_window_size
359
+ and hasattr(self.config, "sliding_window") is not None
360
+ and kv_seq_len > self.config.sliding_window
361
+ )
362
+
363
+ if not _flash_supports_window_size:
364
+ logger.warning_once(
365
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
366
+ " make sure to upgrade flash-attn library."
367
+ )
368
+
369
+ if past_key_value is not None:
370
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
371
+ if hasattr(self.config, "sliding_window") and kv_seq_len > self.config.sliding_window:
372
+ slicing_tokens = kv_seq_len - self.config.sliding_window
373
+
374
+ past_key = past_key_value[0]
375
+ past_value = past_key_value[1]
376
+
377
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
378
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
379
+
380
+ if past_key.shape[-2] != self.config.sliding_window - 1:
381
+ raise ValueError(
382
+ f"past key much have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
383
+ f" {past_key.shape}"
384
+ )
385
+
386
+ past_key_value = (past_key, past_value)
387
+
388
+ if padding_mask is not None:
389
+ padding_mask = padding_mask[:, slicing_tokens:]
390
+ padding_mask = torch.cat([padding_mask, torch.ones_like(padding_mask[:, -1:])], dim=-1)
391
+
392
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
393
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
394
+
395
+ past_key_value = (key_states, value_states) if use_cache else None
396
+
397
+ # repeat k/v heads if n_kv_heads < n_heads
398
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
399
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
400
+
401
+ # TODO: Mistral does not have dropout in the config??
402
+ # It is recommended to use dropout with FA according to the docs
403
+ # when training.
404
+ dropout_rate = 0.0 # if not self.training else self.attn_dropout
405
+
406
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
407
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
408
+ # cast them back in float16 just to be sure everything works as expected.
409
+ input_dtype = query_states.dtype
410
+ if input_dtype == torch.float32:
411
+ logger.warning_once(
412
+ "The input hidden states seems to be silently casted in float32, this might be related to"
413
+ " the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
414
+ " float16."
415
+ )
416
+
417
+ query_states = query_states.to(torch.float16)
418
+ key_states = key_states.to(torch.float16)
419
+ value_states = value_states.to(torch.float16)
420
+
421
+ # Reashape to the expected shape for Flash Attention
422
+ query_states = query_states.transpose(1, 2)
423
+ key_states = key_states.transpose(1, 2)
424
+ value_states = value_states.transpose(1, 2)
425
+
426
+ attn_output = self._flash_attention_forward(
427
+ query_states,
428
+ key_states,
429
+ value_states,
430
+ padding_mask,
431
+ q_len,
432
+ dropout=dropout_rate,
433
+ use_sliding_windows=use_sliding_windows,
434
+ )
435
+
436
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
437
+ attn_output = self.o_proj(attn_output)
438
+
439
+ if not output_attentions:
440
+ attn_weights = None
441
+
442
+ return attn_output, attn_weights, past_key_value
443
+
444
+ def _flash_attention_forward(
445
+ self,
446
+ query_states,
447
+ key_states,
448
+ value_states,
449
+ padding_mask,
450
+ query_length,
451
+ dropout=0.0,
452
+ softmax_scale=None,
453
+ use_sliding_windows=False,
454
+ ):
455
+ """
456
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
457
+ first unpad the input, then computes the attention scores and pad the final attention scores.
458
+
459
+ Args:
460
+ query_states (`torch.Tensor`):
461
+ Input query states to be passed to Flash Attention API
462
+ key_states (`torch.Tensor`):
463
+ Input key states to be passed to Flash Attention API
464
+ value_states (`torch.Tensor`):
465
+ Input value states to be passed to Flash Attention API
466
+ padding_mask (`torch.Tensor`):
467
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
468
+ position of padding tokens and 1 for the position of non-padding tokens.
469
+ dropout (`int`, *optional*):
470
+ Attention dropout
471
+ softmax_scale (`float`, *optional*):
472
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
473
+ use_sliding_windows (`bool`, *optional*):
474
+ Whether to activate sliding window attention.
475
+ """
476
+ # Contains at least one padding token in the sequence
477
+ if padding_mask is not None:
478
+ batch_size = query_states.shape[0]
479
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
480
+ query_states, key_states, value_states, padding_mask, query_length
481
+ )
482
+
483
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
484
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
485
+
486
+ if not use_sliding_windows:
487
+ attn_output_unpad = flash_attn_varlen_func(
488
+ query_states,
489
+ key_states,
490
+ value_states,
491
+ cu_seqlens_q=cu_seqlens_q,
492
+ cu_seqlens_k=cu_seqlens_k,
493
+ max_seqlen_q=max_seqlen_in_batch_q,
494
+ max_seqlen_k=max_seqlen_in_batch_k,
495
+ dropout_p=dropout,
496
+ softmax_scale=softmax_scale,
497
+ causal=True,
498
+ )
499
+ else:
500
+ attn_output_unpad = flash_attn_varlen_func(
501
+ query_states,
502
+ key_states,
503
+ value_states,
504
+ cu_seqlens_q=cu_seqlens_q,
505
+ cu_seqlens_k=cu_seqlens_k,
506
+ max_seqlen_q=max_seqlen_in_batch_q,
507
+ max_seqlen_k=max_seqlen_in_batch_k,
508
+ dropout_p=dropout,
509
+ softmax_scale=softmax_scale,
510
+ causal=True,
511
+ window_size=(self.config.sliding_window, self.config.sliding_window),
512
+ )
513
+
514
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
515
+ else:
516
+ if not use_sliding_windows:
517
+ attn_output = flash_attn_func(
518
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=True
519
+ )
520
+ else:
521
+ attn_output = flash_attn_func(
522
+ query_states,
523
+ key_states,
524
+ value_states,
525
+ dropout,
526
+ softmax_scale=softmax_scale,
527
+ causal=True,
528
+ window_size=(self.config.sliding_window, self.config.sliding_window),
529
+ )
530
+
531
+ return attn_output
532
+
533
+ def _upad_input(self, query_layer, key_layer, value_layer, padding_mask, query_length):
534
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
535
+
536
+ # On the first iteration we need to properly re-create the padding mask
537
+ # by slicing it on the proper place
538
+ if kv_seq_len != padding_mask.shape[-1]:
539
+ padding_mask_num_tokens = padding_mask.shape[-1]
540
+ padding_mask = padding_mask[:, padding_mask_num_tokens - kv_seq_len :]
541
+
542
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(padding_mask)
543
+
544
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
545
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
546
+
547
+ if query_length == kv_seq_len:
548
+ query_layer = index_first_axis(
549
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
550
+ )
551
+ cu_seqlens_q = cu_seqlens_k
552
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
553
+ indices_q = indices_k
554
+ elif query_length == 1:
555
+ max_seqlen_in_batch_q = 1
556
+ cu_seqlens_q = torch.arange(
557
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
558
+ ) # There is a memcpy here, that is very bad.
559
+ indices_q = cu_seqlens_q[:-1]
560
+ query_layer = query_layer.squeeze(1)
561
+ else:
562
+ # The -q_len: slice assumes left padding.
563
+ padding_mask = padding_mask[:, -query_length:]
564
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, padding_mask)
565
+
566
+ return (
567
+ query_layer,
568
+ key_layer,
569
+ value_layer,
570
+ indices_q,
571
+ (cu_seqlens_q, cu_seqlens_k),
572
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
573
+ )
574
+
575
+
576
+ class MistralDecoderLayer(nn.Module):
577
+ def __init__(self, config: MistralConfig):
578
+ super().__init__()
579
+ self.hidden_size = config.hidden_size
580
+ self.self_attn = (
581
+ MistralAttention(config=config)
582
+ if not getattr(config, "_flash_attn_2_enabled", False)
583
+ else MistralFlashAttention2(config)
584
+ )
585
+ self.mlp = MistralMLP(config)
586
+ self.input_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
587
+ self.post_attention_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
588
+
589
+ def forward(
590
+ self,
591
+ hidden_states: torch.Tensor,
592
+ attention_mask: Optional[torch.Tensor] = None,
593
+ position_ids: Optional[torch.LongTensor] = None,
594
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
595
+ output_attentions: Optional[bool] = False,
596
+ use_cache: Optional[bool] = False,
597
+ padding_mask: Optional[torch.Tensor] = None,
598
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
599
+ """
600
+ Args:
601
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
602
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
603
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
604
+ output_attentions (`bool`, *optional*):
605
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
606
+ returned tensors for more detail.
607
+ use_cache (`bool`, *optional*):
608
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
609
+ (see `past_key_values`).
610
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
611
+ """
612
+
613
+ residual = hidden_states
614
+
615
+ hidden_states = self.input_layernorm(hidden_states)
616
+
617
+ # Self Attention
618
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
619
+ hidden_states=hidden_states,
620
+ attention_mask=attention_mask,
621
+ position_ids=position_ids,
622
+ past_key_value=past_key_value,
623
+ output_attentions=output_attentions,
624
+ use_cache=use_cache,
625
+ padding_mask=padding_mask,
626
+ )
627
+ hidden_states = residual + hidden_states
628
+
629
+ # Fully Connected
630
+ residual = hidden_states
631
+ hidden_states = self.post_attention_layernorm(hidden_states)
632
+ hidden_states = self.mlp(hidden_states)
633
+ hidden_states = residual + hidden_states
634
+
635
+ outputs = (hidden_states,)
636
+
637
+ if output_attentions:
638
+ outputs += (self_attn_weights,)
639
+
640
+ if use_cache:
641
+ outputs += (present_key_value,)
642
+
643
+ return outputs
644
+
645
+
646
+ MISTRAL_START_DOCSTRING = r"""
647
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
648
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
649
+ etc.)
650
+
651
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
652
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
653
+ and behavior.
654
+
655
+ Parameters:
656
+ config ([`MistralConfig`]):
657
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
658
+ load the weights associated with the model, only the configuration. Check out the
659
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
660
+ """
661
+
662
+
663
+ @add_start_docstrings(
664
+ "The bare Mistral Model outputting raw hidden-states without any specific head on top.",
665
+ MISTRAL_START_DOCSTRING,
666
+ )
667
+ class MistralPreTrainedModel(PreTrainedModel):
668
+ config_class = MistralConfig
669
+ base_model_prefix = "model"
670
+ supports_gradient_checkpointing = True
671
+ _no_split_modules = ["MistralDecoderLayer"]
672
+ _skip_keys_device_placement = "past_key_values"
673
+ _supports_flash_attn_2 = True
674
+
675
+ def _init_weights(self, module):
676
+ std = self.config.initializer_range
677
+ if isinstance(module, nn.Linear):
678
+ module.weight.data.normal_(mean=0.0, std=std)
679
+ if module.bias is not None:
680
+ module.bias.data.zero_()
681
+ elif isinstance(module, nn.Embedding):
682
+ module.weight.data.normal_(mean=0.0, std=std)
683
+ if module.padding_idx is not None:
684
+ module.weight.data[module.padding_idx].zero_()
685
+
686
+ def _set_gradient_checkpointing(self, module, value=False):
687
+ if isinstance(module, MistralModel):
688
+ module.gradient_checkpointing = value
689
+
690
+
691
+ MISTRAL_INPUTS_DOCSTRING = r"""
692
+ Args:
693
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
694
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
695
+ it.
696
+
697
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
698
+ [`PreTrainedTokenizer.__call__`] for details.
699
+
700
+ [What are input IDs?](../glossary#input-ids)
701
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
702
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
703
+
704
+ - 1 for tokens that are **not masked**,
705
+ - 0 for tokens that are **masked**.
706
+
707
+ [What are attention masks?](../glossary#attention-mask)
708
+
709
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
710
+ [`PreTrainedTokenizer.__call__`] for details.
711
+
712
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
713
+ `past_key_values`).
714
+
715
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
716
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
717
+ information on the default strategy.
718
+
719
+ - 1 indicates the head is **not masked**,
720
+ - 0 indicates the head is **masked**.
721
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
722
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
723
+ config.n_positions - 1]`.
724
+
725
+ [What are position IDs?](../glossary#position-ids)
726
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
727
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
728
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
729
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
730
+
731
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
732
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
733
+
734
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
735
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
736
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
737
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
738
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
739
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
740
+ model's internal embedding lookup matrix.
741
+ use_cache (`bool`, *optional*):
742
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
743
+ `past_key_values`).
744
+ output_attentions (`bool`, *optional*):
745
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
746
+ tensors for more detail.
747
+ output_hidden_states (`bool`, *optional*):
748
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
749
+ more detail.
750
+ return_dict (`bool`, *optional*):
751
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
752
+ """
753
+
754
+
755
+ @add_start_docstrings(
756
+ "The bare Mistral Model outputting raw hidden-states without any specific head on top.",
757
+ MISTRAL_START_DOCSTRING,
758
+ )
759
+ class MistralModel(MistralPreTrainedModel):
760
+ """
761
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]
762
+
763
+ Args:
764
+ config: MistralConfig
765
+ """
766
+
767
+ def __init__(self, config: MistralConfig):
768
+ super().__init__(config)
769
+ self.padding_idx = config.pad_token_id
770
+ self.vocab_size = config.vocab_size
771
+
772
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
773
+ self.layers = nn.ModuleList([MistralDecoderLayer(config) for _ in range(config.num_hidden_layers)])
774
+ self.norm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
775
+
776
+ self.gradient_checkpointing = False
777
+ # Initialize weights and apply final processing
778
+ self.post_init()
779
+
780
+ def get_input_embeddings(self):
781
+ return self.embed_tokens
782
+
783
+ def set_input_embeddings(self, value):
784
+ self.embed_tokens = value
785
+
786
+ def _prepare_decoder_attention_mask(
787
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length, sliding_window
788
+ ):
789
+ # create causal mask
790
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
791
+ combined_attention_mask = None
792
+ if input_shape[-1] > 1:
793
+ combined_attention_mask = _make_sliding_window_causal_mask(
794
+ input_shape,
795
+ inputs_embeds.dtype,
796
+ device=inputs_embeds.device,
797
+ past_key_values_length=past_key_values_length,
798
+ sliding_window=sliding_window,
799
+ )
800
+
801
+ if attention_mask is not None:
802
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
803
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
804
+ inputs_embeds.device
805
+ )
806
+ combined_attention_mask = (
807
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
808
+ )
809
+
810
+ return combined_attention_mask
811
+
812
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
813
+ def forward(
814
+ self,
815
+ input_ids: torch.LongTensor = None,
816
+ attention_mask: Optional[torch.Tensor] = None,
817
+ position_ids: Optional[torch.LongTensor] = None,
818
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
819
+ inputs_embeds: Optional[torch.FloatTensor] = None,
820
+ use_cache: Optional[bool] = None,
821
+ output_attentions: Optional[bool] = None,
822
+ output_hidden_states: Optional[bool] = None,
823
+ return_dict: Optional[bool] = None,
824
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
825
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
826
+ output_hidden_states = (
827
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
828
+ )
829
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
830
+
831
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
832
+
833
+ # retrieve input_ids and inputs_embeds
834
+ if input_ids is not None and inputs_embeds is not None:
835
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
836
+ elif input_ids is not None:
837
+ batch_size, seq_length = input_ids.shape
838
+ elif inputs_embeds is not None:
839
+ batch_size, seq_length, _ = inputs_embeds.shape
840
+ else:
841
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
842
+
843
+ seq_length_with_past = seq_length
844
+ past_key_values_length = 0
845
+
846
+ if past_key_values is not None:
847
+ past_key_values_length = past_key_values[0][0].shape[2]
848
+ seq_length_with_past = seq_length_with_past + past_key_values_length
849
+
850
+ if position_ids is None:
851
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
852
+ position_ids = torch.arange(
853
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
854
+ )
855
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
856
+ else:
857
+ position_ids = position_ids.view(-1, seq_length).long()
858
+
859
+ if inputs_embeds is None:
860
+ inputs_embeds = self.embed_tokens(input_ids)
861
+
862
+ padding_mask = None
863
+
864
+ # embed positions
865
+ if attention_mask is None:
866
+ attention_mask = torch.ones(
867
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
868
+ )
869
+ elif 0 in attention_mask:
870
+ padding_mask = attention_mask
871
+
872
+ if (
873
+ padding_mask is not None
874
+ and hasattr(self.config, "_flash_attn_2_enabled")
875
+ and self.config._flash_attn_2_enabled
876
+ ):
877
+ is_padding_right = padding_mask[:, -1].sum().item() != batch_size
878
+ if is_padding_right:
879
+ raise ValueError(
880
+ "You are attempting to perform batched generation with padding_side='right'"
881
+ " this may lead to unexpected behaviour for Flash Attention version of Mistral. Make sure to "
882
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
883
+ )
884
+
885
+ attention_mask = self._prepare_decoder_attention_mask(
886
+ attention_mask,
887
+ (batch_size, seq_length),
888
+ inputs_embeds,
889
+ past_key_values_length,
890
+ sliding_window=self.config.sliding_window,
891
+ )
892
+
893
+ hidden_states = inputs_embeds
894
+
895
+ if self.gradient_checkpointing and self.training:
896
+ if use_cache:
897
+ logger.warning_once(
898
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
899
+ )
900
+ use_cache = False
901
+
902
+ # decoder layers
903
+ all_hidden_states = () if output_hidden_states else None
904
+ all_self_attns = () if output_attentions else None
905
+ next_decoder_cache = () if use_cache else None
906
+
907
+ for idx, decoder_layer in enumerate(self.layers):
908
+ if output_hidden_states:
909
+ all_hidden_states += (hidden_states,)
910
+
911
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
912
+
913
+ if self.gradient_checkpointing and self.training:
914
+
915
+ def create_custom_forward(module):
916
+ def custom_forward(*inputs):
917
+ # None for past_key_value
918
+ return module(*inputs, past_key_value, output_attentions, padding_mask=padding_mask)
919
+
920
+ return custom_forward
921
+
922
+ layer_outputs = torch.utils.checkpoint.checkpoint(
923
+ create_custom_forward(decoder_layer),
924
+ hidden_states,
925
+ attention_mask,
926
+ position_ids,
927
+ )
928
+ else:
929
+ layer_outputs = decoder_layer(
930
+ hidden_states,
931
+ attention_mask=attention_mask,
932
+ position_ids=position_ids,
933
+ past_key_value=past_key_value,
934
+ output_attentions=output_attentions,
935
+ use_cache=use_cache,
936
+ padding_mask=padding_mask,
937
+ )
938
+
939
+ hidden_states = layer_outputs[0]
940
+
941
+ if use_cache:
942
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
943
+
944
+ if output_attentions:
945
+ all_self_attns += (layer_outputs[1],)
946
+
947
+ hidden_states = self.norm(hidden_states)
948
+
949
+ # add hidden states from the last decoder layer
950
+ if output_hidden_states:
951
+ all_hidden_states += (hidden_states,)
952
+
953
+ next_cache = next_decoder_cache if use_cache else None
954
+ if not return_dict:
955
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
956
+ return BaseModelOutputWithPast(
957
+ last_hidden_state=hidden_states,
958
+ past_key_values=next_cache,
959
+ hidden_states=all_hidden_states,
960
+ attentions=all_self_attns,
961
+ )
962
+
963
+
964
+ class MistralForCausalLM(MistralPreTrainedModel):
965
+ _tied_weights_keys = ["lm_head.weight"]
966
+
967
+ def __init__(self, config):
968
+ super().__init__(config)
969
+ self.model = MistralModel(config)
970
+ self.vocab_size = config.vocab_size + config.thoughts
971
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
972
+
973
+ # Initialize weights and apply final processing
974
+ self.post_init()
975
+
976
+ def get_input_embeddings(self):
977
+ return self.model.embed_tokens
978
+
979
+ def set_input_embeddings(self, value):
980
+ self.model.embed_tokens = value
981
+
982
+ def get_output_embeddings(self):
983
+ return self.lm_head
984
+
985
+ def set_output_embeddings(self, new_embeddings):
986
+ self.lm_head = new_embeddings
987
+
988
+ def set_decoder(self, decoder):
989
+ self.model = decoder
990
+
991
+ def get_decoder(self):
992
+ return self.model
993
+
994
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
995
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
996
+ def forward(
997
+ self,
998
+ input_ids: torch.LongTensor = None,
999
+ attention_mask: Optional[torch.Tensor] = None,
1000
+ position_ids: Optional[torch.LongTensor] = None,
1001
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1002
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1003
+ labels: Optional[torch.LongTensor] = None,
1004
+ use_cache: Optional[bool] = None,
1005
+ output_attentions: Optional[bool] = None,
1006
+ output_hidden_states: Optional[bool] = None,
1007
+ return_dict: Optional[bool] = None,
1008
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1009
+ r"""
1010
+ Args:
1011
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1012
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1013
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1014
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1015
+
1016
+ Returns:
1017
+
1018
+ Example:
1019
+
1020
+ ```python
1021
+ >>> from transformers import AutoTokenizer, MistralForCausalLM
1022
+
1023
+ >>> model = MistralForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1024
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1025
+
1026
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1027
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1028
+
1029
+ >>> # Generate
1030
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1031
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1032
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1033
+ ```"""
1034
+
1035
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1036
+ output_hidden_states = (
1037
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1038
+ )
1039
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1040
+
1041
+ # interleave thought tokens
1042
+ device = input_ids.device
1043
+ # input_ids = input_ids.tolist()
1044
+ # final_ids = []
1045
+ # for sequence in input_ids:
1046
+ # median_inputs = []
1047
+ # for id in sequence:
1048
+ # median_inputs.append(id)
1049
+ # for i in range(self.config.thoughts):
1050
+ # median_inputs.append(self.config.vocab_size - (self.config.thoughts-i-1))
1051
+ # final_ids.append(median_inputs)
1052
+ # input_ids = torch.tensor(final_ids).long().to(device).detach()
1053
+
1054
+ concat_ids = []
1055
+ final = []
1056
+ for i in range(self.config.thoughts):
1057
+ concat_ids.append(
1058
+ self.config.vocab_size - i - 1
1059
+ )
1060
+ final = []
1061
+ for i in input_ids.tolist():
1062
+ median = []
1063
+ for j in i:
1064
+ median.append(j)
1065
+ median += concat_ids
1066
+ final.append(median)
1067
+ input_ids_new = torch.tensor(final).to(device).long()
1068
+ # print(input_ids.shape)
1069
+ attention_mask = torch.ones_like(input_ids)
1070
+
1071
+
1072
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1073
+ outputs = self.model(
1074
+ input_ids=input_ids_new,
1075
+ # attention_mask=attention_mask,
1076
+ attention_mask=None, # manual override to get rid of pesky errors
1077
+ position_ids=position_ids,
1078
+ past_key_values=past_key_values,
1079
+ inputs_embeds=inputs_embeds,
1080
+ use_cache=use_cache,
1081
+ output_attentions=output_attentions,
1082
+ output_hidden_states=output_hidden_states,
1083
+ return_dict=return_dict,
1084
+ )
1085
+
1086
+ hidden_states = outputs[0]
1087
+
1088
+ # separate the normal tokens causally transformed positions out of the thought soup
1089
+ _lm_logits = self.lm_head(hidden_states)
1090
+ indices = torch.arange(1, _lm_logits.size(1), self.config.thoughts+1).long()
1091
+ # indices = range(1,lm_logits.size(1),self.config.thoughts+1)
1092
+ logits = _lm_logits[:,indices,:].float()
1093
+
1094
+ loss = None
1095
+ if labels is not None:
1096
+ # Shift so that tokens < n predict n
1097
+ shift_logits = logits[..., :-1, :].contiguous()
1098
+ shift_labels = labels[..., 1:].contiguous()
1099
+ # Flatten the tokens
1100
+ loss_fct = CrossEntropyLoss()
1101
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1102
+ shift_labels = shift_labels.view(-1)
1103
+ # Enable model parallelism
1104
+ shift_labels = shift_labels.to(shift_logits.device)
1105
+ loss = loss_fct(shift_logits, shift_labels)
1106
+
1107
+ if not return_dict:
1108
+ output = (logits,) + outputs[1:]
1109
+ return (loss,) + output if loss is not None else output
1110
+
1111
+ return CausalLMOutputWithPast(
1112
+ loss=loss,
1113
+ logits=logits,
1114
+ past_key_values=outputs.past_key_values,
1115
+ hidden_states=outputs.hidden_states,
1116
+ attentions=outputs.attentions,
1117
+ )
1118
+
1119
+ def prepare_inputs_for_generation(
1120
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1121
+ ):
1122
+ # Omit tokens covered by past_key_values
1123
+ if past_key_values:
1124
+ past_length = past_key_values[0][0].shape[2]
1125
+
1126
+ # Some generation methods already pass only the last input ID
1127
+ if input_ids.shape[1] > past_length:
1128
+ remove_prefix_length = past_length
1129
+ else:
1130
+ # Default to old behavior: keep only final ID
1131
+ remove_prefix_length = input_ids.shape[1] - 1
1132
+
1133
+ input_ids = input_ids[:, remove_prefix_length:]
1134
+
1135
+ position_ids = kwargs.get("position_ids", None)
1136
+ if attention_mask is not None and position_ids is None:
1137
+ # create position_ids on the fly for batch generation
1138
+ position_ids = attention_mask.long().cumsum(-1) - 1
1139
+ position_ids.masked_fill_(attention_mask == 0, 1)
1140
+ if past_key_values:
1141
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1142
+
1143
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1144
+ if inputs_embeds is not None and past_key_values is None:
1145
+ model_inputs = {"inputs_embeds": inputs_embeds}
1146
+ else:
1147
+ model_inputs = {"input_ids": input_ids}
1148
+
1149
+ model_inputs.update(
1150
+ {
1151
+ "position_ids": position_ids,
1152
+ "past_key_values": past_key_values,
1153
+ "use_cache": kwargs.get("use_cache"),
1154
+ "attention_mask": attention_mask,
1155
+ }
1156
+ )
1157
+ return model_inputs
1158
+
1159
+ @staticmethod
1160
+ def _reorder_cache(past_key_values, beam_idx):
1161
+ reordered_past = ()
1162
+ for layer_past in past_key_values:
1163
+ reordered_past += (
1164
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1165
+ )
1166
+ return reordered_past
1167
+
1168
+
1169
+ @add_start_docstrings(
1170
+ """
1171
+ The Mistral Model transformer with a sequence classification head on top (linear layer).
1172
+
1173
+ [`MistralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1174
+ (e.g. GPT-2) do.
1175
+
1176
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1177
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1178
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1179
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1180
+ each row of the batch).
1181
+ """,
1182
+ MISTRAL_START_DOCSTRING,
1183
+ )
1184
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Mistral, LLAMA->MISTRAL
1185
+ class MistralForSequenceClassification(MistralPreTrainedModel):
1186
+ def __init__(self, config):
1187
+ super().__init__(config)
1188
+ self.num_labels = config.num_labels
1189
+ self.model = MistralModel(config)
1190
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1191
+
1192
+ # Initialize weights and apply final processing
1193
+ self.post_init()
1194
+
1195
+ def get_input_embeddings(self):
1196
+ return self.model.embed_tokens
1197
+
1198
+ def set_input_embeddings(self, value):
1199
+ self.model.embed_tokens = value
1200
+
1201
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1202
+ def forward(
1203
+ self,
1204
+ input_ids: torch.LongTensor = None,
1205
+ attention_mask: Optional[torch.Tensor] = None,
1206
+ position_ids: Optional[torch.LongTensor] = None,
1207
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1208
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1209
+ labels: Optional[torch.LongTensor] = None,
1210
+ use_cache: Optional[bool] = None,
1211
+ output_attentions: Optional[bool] = None,
1212
+ output_hidden_states: Optional[bool] = None,
1213
+ return_dict: Optional[bool] = None,
1214
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1215
+ r"""
1216
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1217
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1218
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1219
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1220
+ """
1221
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1222
+
1223
+ transformer_outputs = self.model(
1224
+ input_ids,
1225
+ attention_mask=attention_mask,
1226
+ position_ids=position_ids,
1227
+ past_key_values=past_key_values,
1228
+ inputs_embeds=inputs_embeds,
1229
+ use_cache=use_cache,
1230
+ output_attentions=output_attentions,
1231
+ output_hidden_states=output_hidden_states,
1232
+ return_dict=return_dict,
1233
+ )
1234
+ hidden_states = transformer_outputs[0]
1235
+ logits = self.score(hidden_states)
1236
+
1237
+ if input_ids is not None:
1238
+ batch_size = input_ids.shape[0]
1239
+ else:
1240
+ batch_size = inputs_embeds.shape[0]
1241
+
1242
+ if self.config.pad_token_id is None and batch_size != 1:
1243
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1244
+ if self.config.pad_token_id is None:
1245
+ sequence_lengths = -1
1246
+ else:
1247
+ if input_ids is not None:
1248
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
1249
+ logits.device
1250
+ )
1251
+ else:
1252
+ sequence_lengths = -1
1253
+
1254
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1255
+
1256
+ loss = None
1257
+ if labels is not None:
1258
+ labels = labels.to(logits.device)
1259
+ if self.config.problem_type is None:
1260
+ if self.num_labels == 1:
1261
+ self.config.problem_type = "regression"
1262
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1263
+ self.config.problem_type = "single_label_classification"
1264
+ else:
1265
+ self.config.problem_type = "multi_label_classification"
1266
+
1267
+ if self.config.problem_type == "regression":
1268
+ loss_fct = MSELoss()
1269
+ if self.num_labels == 1:
1270
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1271
+ else:
1272
+ loss = loss_fct(pooled_logits, labels)
1273
+ elif self.config.problem_type == "single_label_classification":
1274
+ loss_fct = CrossEntropyLoss()
1275
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1276
+ elif self.config.problem_type == "multi_label_classification":
1277
+ loss_fct = BCEWithLogitsLoss()
1278
+ loss = loss_fct(pooled_logits, labels)
1279
+ if not return_dict:
1280
+ output = (pooled_logits,) + transformer_outputs[1:]
1281
+ return ((loss,) + output) if loss is not None else output
1282
+
1283
+ return SequenceClassifierOutputWithPast(
1284
+ loss=loss,
1285
+ logits=pooled_logits,
1286
+ past_key_values=transformer_outputs.past_key_values,
1287
+ hidden_states=transformer_outputs.hidden_states,
1288
+ attentions=transformer_outputs.attentions,
1289
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:086062d4ccaa8b508b0ac3cf541f031251262f6d3c1a836d593fbfea098a0f45
3
+ size 306109337