robegan21 commited on
Commit
a4dcefe
·
verified ·
1 Parent(s): 1f9304c

Upload GenomeOcean-500M-v1.2: expanded dataset with GTDB r226, INPHARED phage, and Zenodo RNA virus database; [CLS] domain tags and [SEP] genome boundaries

Browse files
LICENSE ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *** License Agreement ***
2
+
3
+ genomeocean: a pretrained microbial genome foundational model (genomeoceanLLM)
4
+ Copyright (c) 2025, The Regents of the University of California, through Lawrence Berkeley
5
+ National Laboratory (subject to receipt of any required approvals from the U.S. Dept. of Energy)
6
+ and Northwestern University. All rights reserved.
7
+
8
+ Redistribution and use in source and binary forms, with or without
9
+ modification, are permitted provided that the following conditions are met:
10
+
11
+ (1) Redistributions of source code must retain the above copyright notice,
12
+ this list of conditions and the following disclaimer.
13
+
14
+ (2) Redistributions in binary form must reproduce the above copyright
15
+ notice, this list of conditions and the following disclaimer in the
16
+ documentation and/or other materials provided with the distribution.
17
+
18
+ (3) Neither the name of the University of California, Lawrence Berkeley
19
+ National Laboratory, U.S. Dept. of Energy, Northwestern University nor
20
+ the names of its contributors may be used to endorse or promote products
21
+ derived from this software without specific prior written permission.
22
+
23
+
24
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27
+ IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
28
+ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29
+ NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
31
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
33
+ OF SUCH DAMAGE.
34
+
35
+ You are under no obligation whatsoever to provide any bug fixes, patches,
36
+ or upgrades to the features, functionality or performance of the source
37
+ code ("Enhancements") to anyone; however, if you choose to make your
38
+ Enhancements available either publicly, or directly to Lawrence Berkeley
39
+ National Laboratory, without imposing a separate written license agreement
40
+ for such Enhancements, then you hereby grant the following license: a
41
+ non-exclusive, royalty-free perpetual license to install, use, modify,
42
+ prepare derivative works, incorporate into other computer software,
43
+ distribute, and sublicense such enhancements or derivative works thereof,
44
+ in binary and source code form.
README.md ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: lbnl-bsd
4
+ license_link: LICENSE
5
+ language:
6
+ - en
7
+ tags:
8
+ - biology
9
+ - genomics
10
+ - metagenomics
11
+ - DNA
12
+ - microbiome
13
+ - phage
14
+ - virus
15
+ - GTDB
16
+ model-index:
17
+ - name: GenomeOcean-500M-v1.2
18
+ results: []
19
+ ---
20
+
21
+ # GenomeOcean-500M-v1.2
22
+
23
+ GenomeOcean-500M-v1.2 is a 500-million-parameter causal language model for microbial
24
+ genomic sequences. It is a continued-training checkpoint of
25
+ [GenomeOcean-500M](https://huggingface.co/DOEJGI/GenomeOcean-500M) (v1.0) trained on
26
+ an expanded dataset that adds GTDB r226 representative genomes, INPHARED phage genomes,
27
+ and the Zenodo RNA virus database to the original metagenomic training corpus.
28
+
29
+ ## What's new in v1.2
30
+
31
+ | Change | Details |
32
+ |--------|---------|
33
+ | **Expanded dataset** | Added GTDB r226 (~85k representative genomes), INPHARED phage (~30k genomes), Zenodo RNA virus database |
34
+ | **`[CLS]` domain tag** | Viral/phage sequences are prefixed with `[CLS]` to signal sequence type to the model |
35
+ | **`[SEP]` genome boundaries** | `[SEP]` token inserted between genome records during training |
36
+ | **IUPAC resolution** | Ambiguity codes (R, Y, S, W, K, M, B, D, H, V) resolved by random sampling |
37
+ | **Chunk overlap** | 150 bp overlap between consecutive chunks of long sequences |
38
+
39
+ ## Model Details
40
+
41
+ - **Architecture:** Mistral (decoder-only transformer)
42
+ - **Parameters:** ~500M
43
+ - **Tokenizer:** BPE, vocabulary size 4096
44
+ - **Context length:** 1024 tokens (~5 kbp)
45
+ - **Training precision:** bfloat16
46
+ - **Training framework:** DeepSpeed ZeRO-1
47
+ - **Effective batch size:** 128 (8 per GPU × 16 gradient accumulation steps)
48
+ - **Continued from:** `DOEJGI/GenomeOcean-500M` (v1.0)
49
+
50
+ ## Quick Start
51
+
52
+ ```python
53
+ import torch
54
+ from transformers import AutoModelForCausalLM, AutoTokenizer
55
+
56
+ tokenizer = AutoTokenizer.from_pretrained(
57
+ "DOEJGI/GenomeOcean-500M-v1.2",
58
+ padding_side="left",
59
+ )
60
+ model = AutoModelForCausalLM.from_pretrained(
61
+ "DOEJGI/GenomeOcean-500M-v1.2",
62
+ torch_dtype=torch.bfloat16,
63
+ ).to("cuda")
64
+
65
+ # Generate a sequence continuation
66
+ sequence = "ATGCGATCGATCGATCGATCG"
67
+ inputs = tokenizer(sequence, return_tensors="pt").to("cuda")
68
+ outputs = model.generate(**inputs, max_new_tokens=100, do_sample=True, temperature=0.8)
69
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
70
+ ```
71
+
72
+ ## Training Data
73
+
74
+ | Dataset | Type | Source |
75
+ |---------|------|--------|
76
+ | Antarctic metagenome | Metagenomic assembly | Internal |
77
+ | GRE metagenome | Metagenomic assembly | Internal |
78
+ | Harvard Forest metagenome | Metagenomic assembly | Internal |
79
+ | Lake Mendota metagenome | Metagenomic assembly | Internal |
80
+ | NEON metagenome | Metagenomic assembly | Internal |
81
+ | Oilcane metagenome | Metagenomic assembly | Internal |
82
+ | Tara Oceans metagenome | Metagenomic assembly | Internal |
83
+ | HMP2 | Human microbiome | Internal |
84
+ | GTDB r226 representative genomes | Bacterial/Archaeal genomic DNA | https://gtdb.ecogenomic.org/ |
85
+ | INPHARED phage genomes (Apr 2025) | Phage/bacteriophage DNA | https://github.com/RyanCook94/inphared |
86
+ | Zenodo RNA virus database | RNA virus genomes | https://zenodo.org/records/10989253 |
87
+
88
+ ## Special Token Usage
89
+
90
+ The v3 tokenizer uses special tokens in a specific way during training:
91
+
92
+ - **`[CLS]`** — prepended to every chunk of viral/phage/RNA sequences to act as a domain tag.
93
+ This allows the model to learn sequence-type-specific representations.
94
+ - **`[SEP]`** — inserted at genome boundaries (between the last chunk of one genome and the
95
+ first chunk of the next) during the packing step. This teaches the model that sequences are
96
+ discrete units.
97
+ - **`[UNK]`** — should never appear in clean data. IUPAC ambiguity codes are resolved before
98
+ tokenization.
99
+
100
+ ## Citation
101
+
102
+ If you use GenomeOcean in your research, please cite:
103
+
104
+ ```bibtex
105
+ @article{genomeocean2025,
106
+ title={GenomeOcean: A Pretrained Microbial Genome Foundational Model},
107
+ author={...},
108
+ journal={...},
109
+ year={2025}
110
+ }
111
+ ```
112
+
113
+ ## License
114
+
115
+ Copyright (c) 2025, The Regents of the University of California, through Lawrence
116
+ Berkeley National Laboratory (subject to receipt of any required approvals from the
117
+ U.S. Dept. of Energy) and Northwestern University. All rights reserved.
118
+
119
+ If you have questions about your rights to use or distribute this software, please
120
+ contact Berkeley Lab's Intellectual Property Office at IPO@lbl.gov.
121
+
122
+ NOTICE. This Software was developed under funding from the U.S. Department of Energy
123
+ and the U.S. Government consequently retains certain rights. As such, the U.S.
124
+ Government has been granted for itself and others acting on its behalf a paid-up,
125
+ nonexclusive, irrevocable, worldwide license in the Software to reproduce, distribute
126
+ copies to the public, prepare derivative works, and perform publicly and display
127
+ publicly, and to permit others to do so.
config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./model/model_mistral_500M",
3
+ "architectures": [
4
+ "MistralForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 1,
8
+ "classifier_dropout": 0.1,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "silu",
11
+ "hidden_size": 1536,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 6144,
14
+ "is_causal": true,
15
+ "max_position_embeddings": 32768,
16
+ "model_type": "mistral",
17
+ "num_attention_heads": 8,
18
+ "num_hidden_layers": 14,
19
+ "num_key_value_heads": 8,
20
+ "output_router_logits": false,
21
+ "pad_token_id": 3,
22
+ "rms_norm_eps": 1e-05,
23
+ "rope_theta": 1000000.0,
24
+ "router_aux_loss_coef": 0.02,
25
+ "sliding_window": null,
26
+ "tie_word_embeddings": false,
27
+ "torch_dtype": "bfloat16",
28
+ "transformers_version": "4.57.6",
29
+ "use_cache": true,
30
+ "vocab_size": 4096
31
+ }
configuration_mistral.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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
+ **kwargs,
125
+ ):
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
+ self.attention_dropout = attention_dropout
145
+
146
+ super().__init__(
147
+ pad_token_id=pad_token_id,
148
+ bos_token_id=bos_token_id,
149
+ eos_token_id=eos_token_id,
150
+ tie_word_embeddings=tie_word_embeddings,
151
+ **kwargs,
152
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 3,
6
+ "transformers_version": "4.38.2"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b6315d77656839e51328d2ba04924fe7585782b7e1edd2fa5649fbbcd31b68cb
3
+ size 1082234168
modeling_mistral.py ADDED
@@ -0,0 +1,1622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from dataclasses import dataclass
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ from torch import nn
31
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
+
33
+ from transformers.activations import ACT2FN
34
+ from transformers.cache_utils import Cache, DynamicCache
35
+ from transformers.modeling_attn_mask_utils import (
36
+ _prepare_4d_causal_attention_mask,
37
+ _prepare_4d_causal_attention_mask_for_sdpa,
38
+ _prepare_4d_attention_mask,
39
+ _prepare_4d_attention_mask_for_sdpa,
40
+ )
41
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast, ModelOutput
42
+ from transformers.modeling_utils import PreTrainedModel
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_2_available,
47
+ is_flash_attn_greater_or_equal_2_10,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from .configuration_mistral import MistralConfig
52
+
53
+
54
+ if is_flash_attn_2_available():
55
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
56
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
57
+
58
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
59
+ print("Using flast_attn 2")
60
+ print(f"flash_attn_func supports window_size: {_flash_supports_window_size}")
61
+
62
+
63
+
64
+ logger = logging.get_logger(__name__)
65
+
66
+ _CONFIG_FOR_DOC = "MistralConfig"
67
+
68
+
69
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
70
+ def _get_unpad_data(attention_mask):
71
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
72
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
73
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
74
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
75
+ return (
76
+ indices,
77
+ cu_seqlens,
78
+ max_seqlen_in_batch,
79
+ )
80
+
81
+
82
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Mistral
83
+ class MistralRMSNorm(nn.Module):
84
+ def __init__(self, hidden_size, eps=1e-6):
85
+ """
86
+ MistralRMSNorm is equivalent to T5LayerNorm
87
+ """
88
+ super().__init__()
89
+ self.weight = nn.Parameter(torch.ones(hidden_size))
90
+ self.variance_epsilon = eps
91
+
92
+ def forward(self, hidden_states):
93
+ input_dtype = hidden_states.dtype
94
+ hidden_states = hidden_states.to(torch.float32)
95
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
96
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
97
+ return self.weight * hidden_states.to(input_dtype)
98
+
99
+
100
+ # copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Mistral
101
+ # TODO @Arthur no longer copied from LLama after static cache
102
+ class MistralRotaryEmbedding(nn.Module):
103
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
104
+ super().__init__()
105
+
106
+ self.dim = dim
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.base = base
109
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
110
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
111
+
112
+ # Build here to make `torch.jit.trace` work.
113
+ self._set_cos_sin_cache(
114
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
115
+ )
116
+
117
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
118
+ self.max_seq_len_cached = seq_len
119
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
120
+
121
+ freqs = torch.outer(t, self.inv_freq)
122
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
123
+ emb = torch.cat((freqs, freqs), dim=-1)
124
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
125
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
126
+
127
+ def forward(self, x, seq_len=None):
128
+ # x: [bs, num_attention_heads, seq_len, head_size]
129
+ if seq_len > self.max_seq_len_cached:
130
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
131
+
132
+ return (
133
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
134
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
135
+ )
136
+
137
+
138
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
139
+ def rotate_half(x):
140
+ """Rotates half the hidden dims of the input."""
141
+ x1 = x[..., : x.shape[-1] // 2]
142
+ x2 = x[..., x.shape[-1] // 2 :]
143
+ return torch.cat((-x2, x1), dim=-1)
144
+
145
+
146
+ # copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
147
+ # TODO @Arthur no longer copied from LLama after static cache
148
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
149
+ """Applies Rotary Position Embedding to the query and key tensors.
150
+
151
+ Args:
152
+ q (`torch.Tensor`): The query tensor.
153
+ k (`torch.Tensor`): The key tensor.
154
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
155
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
156
+ position_ids (`torch.Tensor`):
157
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
158
+ used to pass offsetted position ids when working with a KV-cache.
159
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
160
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
161
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
162
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
163
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
164
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
165
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
166
+ Returns:
167
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
168
+ """
169
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
170
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
171
+ q_embed = (q * cos) + (rotate_half(q) * sin)
172
+ k_embed = (k * cos) + (rotate_half(k) * sin)
173
+ return q_embed, k_embed
174
+
175
+
176
+ class MistralMLP(nn.Module):
177
+ def __init__(self, config):
178
+ super().__init__()
179
+ self.config = config
180
+ self.hidden_size = config.hidden_size
181
+ self.intermediate_size = config.intermediate_size
182
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
183
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
184
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
185
+ self.act_fn = ACT2FN[config.hidden_act]
186
+
187
+ def forward(self, x):
188
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
189
+
190
+
191
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
192
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
193
+ """
194
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
195
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
196
+ """
197
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
198
+ if n_rep == 1:
199
+ return hidden_states
200
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
201
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
202
+
203
+
204
+ class MistralAttention(nn.Module):
205
+ """
206
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
207
+ and "Generating Long Sequences with Sparse Transformers".
208
+ """
209
+
210
+ def __init__(self, config: MistralConfig, layer_idx: Optional[int] = None):
211
+ super().__init__()
212
+ self.config = config
213
+ self.layer_idx = layer_idx
214
+ if layer_idx is None:
215
+ logger.warning_once(
216
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
217
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
218
+ "when creating this class."
219
+ )
220
+
221
+ self.hidden_size = config.hidden_size
222
+ self.num_heads = config.num_attention_heads
223
+ self.head_dim = self.hidden_size // self.num_heads
224
+ self.num_key_value_heads = config.num_key_value_heads
225
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
226
+ self.max_position_embeddings = config.max_position_embeddings
227
+ self.rope_theta = config.rope_theta
228
+ self.is_causal = config.is_causal
229
+ self.attention_dropout = config.attention_dropout
230
+
231
+ if (self.head_dim * self.num_heads) != self.hidden_size:
232
+ raise ValueError(
233
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
234
+ f" and `num_heads`: {self.num_heads})."
235
+ )
236
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
237
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
238
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
239
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
240
+
241
+ self.rotary_emb = MistralRotaryEmbedding(
242
+ self.head_dim,
243
+ max_position_embeddings=self.max_position_embeddings,
244
+ base=self.rope_theta,
245
+ )
246
+
247
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
248
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
249
+
250
+ def forward(
251
+ self,
252
+ hidden_states: torch.Tensor,
253
+ attention_mask: Optional[torch.Tensor] = None,
254
+ position_ids: Optional[torch.LongTensor] = None,
255
+ past_key_value: Optional[Cache] = None,
256
+ output_attentions: bool = False,
257
+ use_cache: bool = False,
258
+ **kwargs,
259
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
260
+ if "padding_mask" in kwargs:
261
+ warnings.warn(
262
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
263
+ )
264
+ bsz, q_len, _ = hidden_states.size()
265
+
266
+ query_states = self.q_proj(hidden_states)
267
+ key_states = self.k_proj(hidden_states)
268
+ value_states = self.v_proj(hidden_states)
269
+
270
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
271
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
272
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
273
+
274
+ kv_seq_len = key_states.shape[-2]
275
+ if past_key_value is not None:
276
+ if self.layer_idx is None:
277
+ raise ValueError(
278
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
279
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
280
+ "with a layer index."
281
+ )
282
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
283
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
284
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
285
+
286
+ if past_key_value is not None:
287
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
288
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
289
+
290
+ # repeat k/v heads if n_kv_heads < n_heads
291
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
292
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
293
+
294
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
295
+
296
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
297
+ raise ValueError(
298
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
299
+ f" {attn_weights.size()}"
300
+ )
301
+
302
+ if attention_mask is not None:
303
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
304
+ raise ValueError(
305
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
306
+ )
307
+
308
+ attn_weights = attn_weights + attention_mask
309
+
310
+ # upcast attention to fp32
311
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
312
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
313
+ attn_output = torch.matmul(attn_weights, value_states)
314
+
315
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
316
+ raise ValueError(
317
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
318
+ f" {attn_output.size()}"
319
+ )
320
+
321
+ attn_output = attn_output.transpose(1, 2).contiguous()
322
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
323
+
324
+ attn_output = self.o_proj(attn_output)
325
+
326
+ if not output_attentions:
327
+ attn_weights = None
328
+
329
+ return attn_output, attn_weights, past_key_value
330
+
331
+
332
+ class MistralFlashAttention2(MistralAttention):
333
+ """
334
+ Mistral flash attention module. This module inherits from `MistralAttention` as the weights of the module stays
335
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
336
+ flash attention and deal with padding tokens in case the input contains any of them.
337
+ """
338
+
339
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
340
+ def __init__(self, *args, **kwargs):
341
+ super().__init__(*args, **kwargs)
342
+
343
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
344
+ # 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.
345
+ # 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).
346
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
347
+
348
+ def forward(
349
+ self,
350
+ hidden_states: torch.Tensor,
351
+ attention_mask: Optional[torch.Tensor] = None,
352
+ position_ids: Optional[torch.LongTensor] = None,
353
+ past_key_value: Optional[Cache] = None,
354
+ output_attentions: bool = False,
355
+ use_cache: bool = False,
356
+ **kwargs,
357
+ ):
358
+ if "padding_mask" in kwargs:
359
+ warnings.warn(
360
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
361
+ )
362
+
363
+ # overwrite attention_mask with padding_mask
364
+ attention_mask = kwargs.pop("padding_mask")
365
+ bsz, q_len, _ = hidden_states.size()
366
+
367
+ query_states = self.q_proj(hidden_states)
368
+ key_states = self.k_proj(hidden_states)
369
+ value_states = self.v_proj(hidden_states)
370
+
371
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
372
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
373
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
374
+
375
+ kv_seq_len = key_states.shape[-2]
376
+ if past_key_value is not None:
377
+ if self.layer_idx is None:
378
+ raise ValueError(
379
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
380
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
381
+ "with a layer index."
382
+ )
383
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
384
+
385
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
386
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
387
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
388
+
389
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
390
+
391
+ use_sliding_windows = (
392
+ _flash_supports_window_size
393
+ and getattr(self.config, "sliding_window", None) is not None
394
+ and kv_seq_len > self.config.sliding_window
395
+ )
396
+
397
+ if not _flash_supports_window_size:
398
+ logger.warning_once(
399
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
400
+ " make sure to upgrade flash-attn library."
401
+ )
402
+
403
+ if past_key_value is not None:
404
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
405
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
406
+ if (
407
+ getattr(self.config, "sliding_window", None) is not None
408
+ and kv_seq_len > self.config.sliding_window
409
+ and cache_has_contents
410
+ ):
411
+ slicing_tokens = 1 - self.config.sliding_window
412
+
413
+ past_key = past_key_value[self.layer_idx][0]
414
+ past_value = past_key_value[self.layer_idx][1]
415
+
416
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
417
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
418
+
419
+ if past_key.shape[-2] != self.config.sliding_window - 1:
420
+ raise ValueError(
421
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
422
+ f" {past_key.shape}"
423
+ )
424
+
425
+ if attention_mask is not None:
426
+ attention_mask = attention_mask[:, slicing_tokens:]
427
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
428
+
429
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
430
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
431
+
432
+ # repeat k/v heads if n_kv_heads < n_heads
433
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
434
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
435
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
436
+
437
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
438
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
439
+ # cast them back in float16 just to be sure everything works as expected.
440
+ input_dtype = query_states.dtype
441
+ if input_dtype == torch.float32:
442
+ if torch.is_autocast_enabled():
443
+ target_dtype = torch.get_autocast_gpu_dtype()
444
+ # Handle the case where the model is quantized
445
+ elif hasattr(self.config, "_pre_quantization_dtype"):
446
+ target_dtype = self.config._pre_quantization_dtype
447
+ else:
448
+ target_dtype = self.q_proj.weight.dtype
449
+
450
+ logger.warning_once(
451
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
452
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
453
+ f" {target_dtype}."
454
+ )
455
+
456
+ query_states = query_states.to(target_dtype)
457
+ key_states = key_states.to(target_dtype)
458
+ value_states = value_states.to(target_dtype)
459
+
460
+ # Reashape to the expected shape for Flash Attention
461
+ query_states = query_states.transpose(1, 2)
462
+ key_states = key_states.transpose(1, 2)
463
+ value_states = value_states.transpose(1, 2)
464
+
465
+ attn_output = self._flash_attention_forward(
466
+ query_states,
467
+ key_states,
468
+ value_states,
469
+ attention_mask,
470
+ q_len,
471
+ dropout=dropout_rate,
472
+ use_sliding_windows=use_sliding_windows,
473
+ )
474
+
475
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
476
+ attn_output = self.o_proj(attn_output)
477
+
478
+ if not output_attentions:
479
+ attn_weights = None
480
+
481
+ return attn_output, attn_weights, past_key_value
482
+
483
+ def _flash_attention_forward(
484
+ self,
485
+ query_states,
486
+ key_states,
487
+ value_states,
488
+ attention_mask,
489
+ query_length,
490
+ dropout=0.0,
491
+ softmax_scale=None,
492
+ use_sliding_windows=False,
493
+ ):
494
+ """
495
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
496
+ first unpad the input, then computes the attention scores and pad the final attention scores.
497
+
498
+ Args:
499
+ query_states (`torch.Tensor`):
500
+ Input query states to be passed to Flash Attention API
501
+ key_states (`torch.Tensor`):
502
+ Input key states to be passed to Flash Attention API
503
+ value_states (`torch.Tensor`):
504
+ Input value states to be passed to Flash Attention API
505
+ attention_mask (`torch.Tensor`):
506
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
507
+ position of padding tokens and 1 for the position of non-padding tokens.
508
+ dropout (`int`, *optional*):
509
+ Attention dropout
510
+ softmax_scale (`float`, *optional*):
511
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
512
+ use_sliding_windows (`bool`, *optional*):
513
+ Whether to activate sliding window attention.
514
+ """
515
+ if not self._flash_attn_uses_top_left_mask:
516
+ causal = self.is_causal
517
+ else:
518
+ # 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__.
519
+ causal = self.is_causal and query_length != 1
520
+
521
+ # Contains at least one padding token in the sequence
522
+ if attention_mask is not None:
523
+ batch_size = query_states.shape[0]
524
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
525
+ query_states, key_states, value_states, attention_mask, query_length
526
+ )
527
+
528
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
529
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
530
+
531
+ if not use_sliding_windows:
532
+ attn_output_unpad = flash_attn_varlen_func(
533
+ query_states,
534
+ key_states,
535
+ value_states,
536
+ cu_seqlens_q=cu_seqlens_q,
537
+ cu_seqlens_k=cu_seqlens_k,
538
+ max_seqlen_q=max_seqlen_in_batch_q,
539
+ max_seqlen_k=max_seqlen_in_batch_k,
540
+ dropout_p=dropout,
541
+ softmax_scale=softmax_scale,
542
+ causal=causal,
543
+ )
544
+ else:
545
+ attn_output_unpad = flash_attn_varlen_func(
546
+ query_states,
547
+ key_states,
548
+ value_states,
549
+ cu_seqlens_q=cu_seqlens_q,
550
+ cu_seqlens_k=cu_seqlens_k,
551
+ max_seqlen_q=max_seqlen_in_batch_q,
552
+ max_seqlen_k=max_seqlen_in_batch_k,
553
+ dropout_p=dropout,
554
+ softmax_scale=softmax_scale,
555
+ causal=causal,
556
+ window_size=(self.config.sliding_window, self.config.sliding_window),
557
+ )
558
+
559
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
560
+ else:
561
+ if not use_sliding_windows:
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
+ )
570
+ else:
571
+ attn_output = flash_attn_func(
572
+ query_states,
573
+ key_states,
574
+ value_states,
575
+ dropout,
576
+ softmax_scale=softmax_scale,
577
+ causal=causal,
578
+ window_size=(self.config.sliding_window, self.config.sliding_window),
579
+ )
580
+
581
+ return attn_output
582
+
583
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
584
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
585
+
586
+ # On the first iteration we need to properly re-create the padding mask
587
+ # by slicing it on the proper place
588
+ if kv_seq_len != attention_mask.shape[-1]:
589
+ attention_mask_num_tokens = attention_mask.shape[-1]
590
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
591
+
592
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
593
+
594
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
595
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
596
+
597
+ if query_length == kv_seq_len:
598
+ query_layer = index_first_axis(
599
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
600
+ )
601
+ cu_seqlens_q = cu_seqlens_k
602
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
603
+ indices_q = indices_k
604
+ elif query_length == 1:
605
+ max_seqlen_in_batch_q = 1
606
+ cu_seqlens_q = torch.arange(
607
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
608
+ ) # There is a memcpy here, that is very bad.
609
+ indices_q = cu_seqlens_q[:-1]
610
+ query_layer = query_layer.squeeze(1)
611
+ else:
612
+ # The -q_len: slice assumes left padding.
613
+ attention_mask = attention_mask[:, -query_length:]
614
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
615
+
616
+ return (
617
+ query_layer,
618
+ key_layer,
619
+ value_layer,
620
+ indices_q,
621
+ (cu_seqlens_q, cu_seqlens_k),
622
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
623
+ )
624
+
625
+
626
+ # copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with Llama->Mistral
627
+ # TODO @Arthur no longer copied from LLama after static cache
628
+ class MistralSdpaAttention(MistralAttention):
629
+ """
630
+ Mistral attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
631
+ `MistralAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
632
+ SDPA API.
633
+ """
634
+
635
+ # Adapted from MistralAttention.forward
636
+ def forward(
637
+ self,
638
+ hidden_states: torch.Tensor,
639
+ attention_mask: Optional[torch.Tensor] = None,
640
+ position_ids: Optional[torch.LongTensor] = None,
641
+ past_key_value: Optional[Cache] = None,
642
+ output_attentions: bool = False,
643
+ use_cache: bool = False,
644
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
645
+ if output_attentions:
646
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
647
+ logger.warning_once(
648
+ "MistralModel is using MistralSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
649
+ '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.'
650
+ )
651
+ return super().forward(
652
+ hidden_states=hidden_states,
653
+ attention_mask=attention_mask,
654
+ position_ids=position_ids,
655
+ past_key_value=past_key_value,
656
+ output_attentions=output_attentions,
657
+ use_cache=use_cache,
658
+ )
659
+
660
+ bsz, q_len, _ = hidden_states.size()
661
+
662
+ query_states = self.q_proj(hidden_states)
663
+ key_states = self.k_proj(hidden_states)
664
+ value_states = self.v_proj(hidden_states)
665
+
666
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
667
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
668
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
669
+
670
+ kv_seq_len = key_states.shape[-2]
671
+ if past_key_value is not None:
672
+ kv_seq_len += past_key_value.get_seq_length(self.layer_idx)
673
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
674
+
675
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
676
+
677
+ if past_key_value is not None:
678
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
679
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
680
+
681
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
682
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
683
+
684
+ if attention_mask is not None:
685
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
686
+ raise ValueError(
687
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
688
+ )
689
+
690
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
691
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
692
+ if query_states.device.type == "cuda" and attention_mask is not None:
693
+ query_states = query_states.contiguous()
694
+ key_states = key_states.contiguous()
695
+ value_states = value_states.contiguous()
696
+
697
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
698
+ query_states,
699
+ key_states,
700
+ value_states,
701
+ attn_mask=attention_mask,
702
+ dropout_p=self.attention_dropout if self.training else 0.0,
703
+ # 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.
704
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
705
+ )
706
+
707
+ attn_output = attn_output.transpose(1, 2).contiguous()
708
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
709
+
710
+ attn_output = self.o_proj(attn_output)
711
+
712
+ return attn_output, None, past_key_value
713
+
714
+
715
+ MISTRAL_ATTENTION_CLASSES = {
716
+ "eager": MistralAttention,
717
+ "flash_attention_2": MistralFlashAttention2,
718
+ "sdpa": MistralSdpaAttention,
719
+ }
720
+
721
+
722
+ class MistralDecoderLayer(nn.Module):
723
+ def __init__(self, config: MistralConfig, layer_idx: int):
724
+ super().__init__()
725
+ self.hidden_size = config.hidden_size
726
+
727
+ self.self_attn = MISTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
728
+
729
+ self.mlp = MistralMLP(config)
730
+ self.input_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
731
+ self.post_attention_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
732
+
733
+ def forward(
734
+ self,
735
+ hidden_states: torch.Tensor,
736
+ attention_mask: Optional[torch.Tensor] = None,
737
+ position_ids: Optional[torch.LongTensor] = None,
738
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
739
+ output_attentions: Optional[bool] = False,
740
+ use_cache: Optional[bool] = False,
741
+ **kwargs,
742
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
743
+ if "padding_mask" in kwargs:
744
+ warnings.warn(
745
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
746
+ )
747
+ """
748
+ Args:
749
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
750
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
751
+ `(batch, sequence_length)` where padding elements are indicated by 0.
752
+ output_attentions (`bool`, *optional*):
753
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
754
+ returned tensors for more detail.
755
+ use_cache (`bool`, *optional*):
756
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
757
+ (see `past_key_values`).
758
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
759
+ """
760
+
761
+ residual = hidden_states
762
+
763
+ hidden_states = self.input_layernorm(hidden_states)
764
+
765
+ # Self Attention
766
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
767
+ hidden_states=hidden_states,
768
+ attention_mask=attention_mask,
769
+ position_ids=position_ids,
770
+ past_key_value=past_key_value,
771
+ output_attentions=output_attentions,
772
+ use_cache=use_cache,
773
+ )
774
+ hidden_states = residual + hidden_states
775
+
776
+ # Fully Connected
777
+ residual = hidden_states
778
+ hidden_states = self.post_attention_layernorm(hidden_states)
779
+ hidden_states = self.mlp(hidden_states)
780
+ hidden_states = residual + hidden_states
781
+
782
+ outputs = (hidden_states,)
783
+
784
+ if output_attentions:
785
+ outputs += (self_attn_weights,)
786
+
787
+ if use_cache:
788
+ outputs += (present_key_value,)
789
+
790
+ return outputs
791
+
792
+
793
+ MISTRAL_START_DOCSTRING = r"""
794
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
795
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
796
+ etc.)
797
+
798
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
799
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
800
+ and behavior.
801
+
802
+ Parameters:
803
+ config ([`MistralConfig`]):
804
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
805
+ load the weights associated with the model, only the configuration. Check out the
806
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
807
+ """
808
+
809
+
810
+ @add_start_docstrings(
811
+ "The bare Mistral Model outputting raw hidden-states without any specific head on top.",
812
+ MISTRAL_START_DOCSTRING,
813
+ )
814
+ class MistralPreTrainedModel(PreTrainedModel):
815
+ config_class = MistralConfig
816
+ base_model_prefix = "model"
817
+ supports_gradient_checkpointing = True
818
+ _no_split_modules = ["MistralDecoderLayer"]
819
+ _skip_keys_device_placement = "past_key_values"
820
+ _supports_flash_attn_2 = True
821
+ _supports_sdpa = True
822
+ _supports_cache_class = True
823
+
824
+ def _init_weights(self, module):
825
+ std = self.config.initializer_range
826
+ if isinstance(module, nn.Linear):
827
+ module.weight.data.normal_(mean=0.0, std=std)
828
+ if module.bias is not None:
829
+ module.bias.data.zero_()
830
+ elif isinstance(module, nn.Embedding):
831
+ module.weight.data.normal_(mean=0.0, std=std)
832
+ if module.padding_idx is not None:
833
+ module.weight.data[module.padding_idx].zero_()
834
+
835
+
836
+ MISTRAL_INPUTS_DOCSTRING = r"""
837
+ Args:
838
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
839
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
840
+ it.
841
+
842
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
843
+ [`PreTrainedTokenizer.__call__`] for details.
844
+
845
+ [What are input IDs?](../glossary#input-ids)
846
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
847
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
848
+
849
+ - 1 for tokens that are **not masked**,
850
+ - 0 for tokens that are **masked**.
851
+
852
+ [What are attention masks?](../glossary#attention-mask)
853
+
854
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
855
+ [`PreTrainedTokenizer.__call__`] for details.
856
+
857
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
858
+ `past_key_values`).
859
+
860
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
861
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
862
+ information on the default strategy.
863
+
864
+ - 1 indicates the head is **not masked**,
865
+ - 0 indicates the head is **masked**.
866
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
867
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
868
+ config.n_positions - 1]`.
869
+
870
+ [What are position IDs?](../glossary#position-ids)
871
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
872
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
873
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
874
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
875
+
876
+ Two formats are allowed:
877
+ - a [`~cache_utils.Cache`] instance;
878
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
879
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
880
+ cache format.
881
+
882
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
883
+ legacy cache format will be returned.
884
+
885
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
886
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
887
+ of shape `(batch_size, sequence_length)`.
888
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
889
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
890
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
891
+ model's internal embedding lookup matrix.
892
+ use_cache (`bool`, *optional*):
893
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
894
+ `past_key_values`).
895
+ output_attentions (`bool`, *optional*):
896
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
897
+ tensors for more detail.
898
+ output_hidden_states (`bool`, *optional*):
899
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
900
+ more detail.
901
+ return_dict (`bool`, *optional*):
902
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
903
+ """
904
+
905
+
906
+ @add_start_docstrings(
907
+ "The bare Mistral Model outputting raw hidden-states without any specific head on top.",
908
+ MISTRAL_START_DOCSTRING,
909
+ )
910
+ class MistralModel(MistralPreTrainedModel):
911
+ """
912
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]
913
+
914
+ Args:
915
+ config: MistralConfig
916
+ """
917
+
918
+ def __init__(self, config: MistralConfig):
919
+ super().__init__(config)
920
+ self.padding_idx = config.pad_token_id
921
+ self.vocab_size = config.vocab_size
922
+ self.is_causal = config.is_causal
923
+
924
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
925
+ self.layers = nn.ModuleList(
926
+ [MistralDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
927
+ )
928
+ self._attn_implementation = config._attn_implementation
929
+ self.norm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
930
+
931
+ self.gradient_checkpointing = False
932
+ # Initialize weights and apply final processing
933
+ self.post_init()
934
+
935
+ def get_input_embeddings(self):
936
+ return self.embed_tokens
937
+
938
+ def set_input_embeddings(self, value):
939
+ self.embed_tokens = value
940
+
941
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
942
+ def forward(
943
+ self,
944
+ input_ids: torch.LongTensor = None,
945
+ attention_mask: Optional[torch.Tensor] = None,
946
+ position_ids: Optional[torch.LongTensor] = None,
947
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
948
+ inputs_embeds: Optional[torch.FloatTensor] = None,
949
+ use_cache: Optional[bool] = None,
950
+ output_attentions: Optional[bool] = None,
951
+ output_hidden_states: Optional[bool] = None,
952
+ return_dict: Optional[bool] = None,
953
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
954
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
955
+ output_hidden_states = (
956
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
957
+ )
958
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
959
+
960
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
961
+
962
+ # retrieve input_ids and inputs_embeds
963
+ if input_ids is not None and inputs_embeds is not None:
964
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
965
+ elif input_ids is not None:
966
+ batch_size, seq_length = input_ids.shape
967
+ elif inputs_embeds is not None:
968
+ batch_size, seq_length, _ = inputs_embeds.shape
969
+ else:
970
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
971
+
972
+ # If position_ids are provided externally (e.g. by generate()), use their length
973
+ # to avoid shape mismatch when generate() pre-trims position_ids but not input_ids
974
+ if position_ids is not None:
975
+ seq_length = position_ids.shape[-1]
976
+
977
+ if self.gradient_checkpointing and self.training:
978
+ if use_cache:
979
+ logger.warning_once(
980
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
981
+ )
982
+ use_cache = False
983
+
984
+ past_key_values_length = 0
985
+
986
+ if use_cache:
987
+ use_legacy_cache = not isinstance(past_key_values, Cache)
988
+ if use_legacy_cache:
989
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
990
+ past_key_values_length = past_key_values.get_seq_length()
991
+
992
+ if position_ids is None:
993
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
994
+ position_ids = torch.arange(
995
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
996
+ )
997
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
998
+ else:
999
+ # Use position_ids' own last dim to avoid shape mismatch during generation
1000
+ # (seq_length reflects original input length, but position_ids may be trimmed)
1001
+ position_ids = position_ids.view(-1, position_ids.shape[-1]).long()
1002
+
1003
+ if inputs_embeds is None:
1004
+ inputs_embeds = self.embed_tokens(input_ids)
1005
+
1006
+ if attention_mask is not None and self._attn_implementation == "flash_attention_2" and use_cache:
1007
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1008
+ if is_padding_right:
1009
+ raise ValueError(
1010
+ "You are attempting to perform batched generation with padding_side='right'"
1011
+ " this may lead to unexpected behaviour for Flash Attention version of Mistral. Make sure to "
1012
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1013
+ )
1014
+
1015
+
1016
+ if self._attn_implementation == "flash_attention_2":
1017
+ # 2d mask is passed through the layers
1018
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1019
+ elif self._attn_implementation == "sdpa" and not output_attentions:
1020
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1021
+ # the manual implementation that requires a 4D causal mask in all cases.
1022
+ if self.is_causal:
1023
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1024
+ attention_mask,
1025
+ (batch_size, seq_length),
1026
+ inputs_embeds,
1027
+ past_key_values_length,
1028
+ )
1029
+ else:
1030
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(
1031
+ attention_mask,
1032
+ dtype=inputs_embeds.dtype,
1033
+ )
1034
+ else:
1035
+ # 4d mask is passed through the layers
1036
+ if self.is_causal:
1037
+ attention_mask = _prepare_4d_causal_attention_mask(
1038
+ attention_mask,
1039
+ (batch_size, seq_length),
1040
+ inputs_embeds,
1041
+ past_key_values_length,
1042
+ sliding_window=self.config.sliding_window,
1043
+ )
1044
+ else:
1045
+ attention_mask = _prepare_4d_attention_mask(
1046
+ attention_mask,
1047
+ dtype=inputs_embeds.dtype,
1048
+ )
1049
+
1050
+ hidden_states = inputs_embeds
1051
+
1052
+ # decoder layers
1053
+ all_hidden_states = () if output_hidden_states else None
1054
+ all_self_attns = () if output_attentions else None
1055
+ next_decoder_cache = None
1056
+
1057
+ for decoder_layer in self.layers:
1058
+ if output_hidden_states:
1059
+ all_hidden_states += (hidden_states,)
1060
+
1061
+ if self.gradient_checkpointing and self.training:
1062
+ layer_outputs = self._gradient_checkpointing_func(
1063
+ decoder_layer.__call__,
1064
+ hidden_states,
1065
+ attention_mask,
1066
+ position_ids,
1067
+ past_key_values,
1068
+ output_attentions,
1069
+ use_cache,
1070
+ )
1071
+ else:
1072
+ layer_outputs = decoder_layer(
1073
+ hidden_states,
1074
+ attention_mask=attention_mask,
1075
+ position_ids=position_ids,
1076
+ past_key_value=past_key_values,
1077
+ output_attentions=output_attentions,
1078
+ use_cache=use_cache,
1079
+ )
1080
+
1081
+ hidden_states = layer_outputs[0]
1082
+
1083
+ if use_cache:
1084
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1085
+
1086
+ if output_attentions:
1087
+ all_self_attns += (layer_outputs[1],)
1088
+
1089
+ hidden_states = self.norm(hidden_states)
1090
+
1091
+ # add hidden states from the last decoder layer
1092
+ if output_hidden_states:
1093
+ all_hidden_states += (hidden_states,)
1094
+
1095
+ next_cache = None
1096
+ if use_cache:
1097
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1098
+
1099
+ if not return_dict:
1100
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1101
+ return BaseModelOutputWithPast(
1102
+ last_hidden_state=hidden_states,
1103
+ past_key_values=next_cache,
1104
+ hidden_states=all_hidden_states,
1105
+ attentions=all_self_attns,
1106
+ )
1107
+
1108
+
1109
+ class MistralForCausalLM(MistralPreTrainedModel):
1110
+ _tied_weights_keys = ["lm_head.weight"]
1111
+
1112
+ def __init__(self, config):
1113
+ super().__init__(config)
1114
+ self.model = MistralModel(config)
1115
+ self.vocab_size = config.vocab_size
1116
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1117
+
1118
+ # Initialize weights and apply final processing
1119
+ self.post_init()
1120
+
1121
+ def get_input_embeddings(self):
1122
+ return self.model.embed_tokens
1123
+
1124
+ def set_input_embeddings(self, value):
1125
+ self.model.embed_tokens = value
1126
+
1127
+ def get_output_embeddings(self):
1128
+ return self.lm_head
1129
+
1130
+ def set_output_embeddings(self, new_embeddings):
1131
+ self.lm_head = new_embeddings
1132
+
1133
+ def set_decoder(self, decoder):
1134
+ self.model = decoder
1135
+
1136
+ def get_decoder(self):
1137
+ return self.model
1138
+
1139
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1140
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1141
+ def forward(
1142
+ self,
1143
+ input_ids: torch.LongTensor = None,
1144
+ attention_mask: Optional[torch.Tensor] = None,
1145
+ position_ids: Optional[torch.LongTensor] = None,
1146
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1147
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1148
+ labels: Optional[torch.LongTensor] = None,
1149
+ use_cache: Optional[bool] = None,
1150
+ output_attentions: Optional[bool] = None,
1151
+ output_hidden_states: Optional[bool] = None,
1152
+ return_dict: Optional[bool] = None,
1153
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1154
+ r"""
1155
+ Args:
1156
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1157
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1158
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1159
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1160
+
1161
+ Returns:
1162
+
1163
+ Example:
1164
+
1165
+ ```python
1166
+ >>> from transformers import AutoTokenizer, MistralForCausalLM
1167
+
1168
+ >>> model = MistralForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
1169
+ >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")
1170
+
1171
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1172
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1173
+
1174
+ >>> # Generate
1175
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1176
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1177
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1178
+ ```"""
1179
+
1180
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1181
+ output_hidden_states = (
1182
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1183
+ )
1184
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1185
+
1186
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1187
+ outputs = self.model(
1188
+ input_ids=input_ids,
1189
+ attention_mask=attention_mask,
1190
+ position_ids=position_ids,
1191
+ past_key_values=past_key_values,
1192
+ inputs_embeds=inputs_embeds,
1193
+ use_cache=use_cache,
1194
+ output_attentions=output_attentions,
1195
+ output_hidden_states=output_hidden_states,
1196
+ return_dict=return_dict,
1197
+ )
1198
+
1199
+ hidden_states = outputs[0]
1200
+ logits = self.lm_head(hidden_states)
1201
+ logits = logits.float()
1202
+
1203
+ loss = None
1204
+ if labels is not None:
1205
+ # Shift so that tokens < n predict n
1206
+ shift_logits = logits[..., :-1, :].contiguous()
1207
+ shift_labels = labels[..., 1:].contiguous()
1208
+ # Flatten the tokens
1209
+ loss_fct = CrossEntropyLoss()
1210
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1211
+ shift_labels = shift_labels.view(-1)
1212
+ # Enable model parallelism
1213
+ shift_labels = shift_labels.to(shift_logits.device)
1214
+ loss = loss_fct(shift_logits, shift_labels)
1215
+
1216
+ if not return_dict:
1217
+ output = (logits,) + outputs[1:]
1218
+ return (loss,) + output if loss is not None else output
1219
+
1220
+ return CausalLMOutputWithPast(
1221
+ loss=loss,
1222
+ logits=logits,
1223
+ past_key_values=outputs.past_key_values,
1224
+ hidden_states=outputs.hidden_states,
1225
+ attentions=outputs.attentions,
1226
+ )
1227
+
1228
+ def prepare_inputs_for_generation(
1229
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1230
+ ):
1231
+ # Omit tokens covered by past_key_values
1232
+ if past_key_values is not None:
1233
+ if isinstance(past_key_values, Cache):
1234
+ cache_length = past_key_values.get_seq_length()
1235
+ past_length = past_key_values.get_seq_length()
1236
+ max_cache_length = past_key_values.get_max_cache_shape()
1237
+ else:
1238
+ cache_length = past_length = past_key_values[0][0].shape[2]
1239
+ max_cache_length = None
1240
+
1241
+ # Keep only the unprocessed tokens:
1242
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1243
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1244
+ # input)
1245
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1246
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1247
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1248
+ # input_ids based on the past_length.
1249
+ elif past_length < input_ids.shape[1]:
1250
+ input_ids = input_ids[:, past_length:]
1251
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1252
+
1253
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1254
+ if (
1255
+ max_cache_length is not None
1256
+ and attention_mask is not None
1257
+ and cache_length + input_ids.shape[1] > max_cache_length
1258
+ ):
1259
+ attention_mask = attention_mask[:, -max_cache_length:]
1260
+
1261
+ position_ids = kwargs.get("position_ids", None)
1262
+ if attention_mask is not None and position_ids is None:
1263
+ # create position_ids on the fly for batch generation
1264
+ position_ids = attention_mask.long().cumsum(-1) - 1
1265
+ position_ids.masked_fill_(attention_mask == 0, 1)
1266
+ if past_key_values:
1267
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1268
+
1269
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1270
+ if inputs_embeds is not None and past_key_values is None:
1271
+ model_inputs = {"inputs_embeds": inputs_embeds}
1272
+ else:
1273
+ model_inputs = {"input_ids": input_ids}
1274
+
1275
+ model_inputs.update(
1276
+ {
1277
+ "position_ids": position_ids,
1278
+ "past_key_values": past_key_values,
1279
+ "use_cache": kwargs.get("use_cache"),
1280
+ "attention_mask": attention_mask,
1281
+ }
1282
+ )
1283
+ return model_inputs
1284
+
1285
+ @staticmethod
1286
+ def _reorder_cache(past_key_values, beam_idx):
1287
+ reordered_past = ()
1288
+ for layer_past in past_key_values:
1289
+ reordered_past += (
1290
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1291
+ )
1292
+ return reordered_past
1293
+
1294
+
1295
+
1296
+
1297
+ @dataclass
1298
+ class MoEMaskedLMOutput(ModelOutput):
1299
+ """
1300
+ Base class for causal language model (or autoregressive) outputs as well as Mixture of Expert's router hidden
1301
+ states terms, to train a MoE model.
1302
+
1303
+ Args:
1304
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
1305
+ Language modeling loss (for next-token prediction).
1306
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1307
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1308
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1309
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
1310
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`)
1311
+
1312
+ Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
1313
+ `past_key_values` input) to speed up sequential decoding.
1314
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1315
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1316
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1317
+
1318
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1319
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
1320
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1321
+ sequence_length)`.
1322
+
1323
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
1324
+ heads.
1325
+ z_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
1326
+ z_loss for the sparse modules.
1327
+ aux_loss (`torch.FloatTensor`, *optional*, returned when `labels` is provided):
1328
+ aux_loss for the sparse modules.
1329
+ router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`):
1330
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
1331
+
1332
+ Router logits of the encoder model, useful to compute the auxiliary loss and the z_loss for the sparse
1333
+ modules.
1334
+ """
1335
+
1336
+ loss: Optional[torch.FloatTensor] = None
1337
+ logits: torch.FloatTensor = None
1338
+ hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
1339
+ attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
1340
+ z_loss: torch.FloatTensor = None
1341
+ aux_loss: torch.FloatTensor = None
1342
+ router_logits: Optional[Tuple[torch.FloatTensor]] = None
1343
+
1344
+
1345
+
1346
+ class MistralPredictionHeadTransform(nn.Module):
1347
+ def __init__(self, config):
1348
+ super().__init__()
1349
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
1350
+ if isinstance(config.hidden_act, str):
1351
+ self.transform_act_fn = ACT2FN[config.hidden_act]
1352
+ else:
1353
+ self.transform_act_fn = config.hidden_act
1354
+ self.norm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1355
+
1356
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
1357
+ hidden_states = self.dense(hidden_states)
1358
+ hidden_states = self.transform_act_fn(hidden_states)
1359
+ hidden_states = self.norm(hidden_states)
1360
+ return hidden_states
1361
+
1362
+
1363
+ class MistralLMPredictionHead(nn.Module):
1364
+ def __init__(self, config):
1365
+ super().__init__()
1366
+ self.transform = MistralPredictionHeadTransform(config)
1367
+
1368
+ # The output weights are the same as the input embeddings, but there is
1369
+ # an output-only bias for each token.
1370
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1371
+
1372
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
1373
+
1374
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
1375
+ self.decoder.bias = self.bias
1376
+
1377
+ def _tie_weights(self):
1378
+ self.decoder.bias = self.bias
1379
+
1380
+ def forward(self, hidden_states):
1381
+ hidden_states = self.transform(hidden_states)
1382
+ hidden_states = self.decoder(hidden_states)
1383
+ return hidden_states
1384
+
1385
+
1386
+ class MistralOnlyMLMHead(nn.Module):
1387
+ def __init__(self, config):
1388
+ super().__init__()
1389
+ self.predictions = MistralLMPredictionHead(config)
1390
+
1391
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
1392
+ prediction_scores = self.predictions(sequence_output)
1393
+ return prediction_scores
1394
+
1395
+
1396
+
1397
+ class MistralForMaskedLM(MistralPreTrainedModel):
1398
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1399
+
1400
+ def __init__(self, config):
1401
+ super().__init__(config)
1402
+
1403
+ if config.is_decoder:
1404
+ logger.warning(
1405
+ "If you want to use `MistralForMaskedLM` make sure `config.is_decoder=False` for "
1406
+ "bi-directional self-attention."
1407
+ )
1408
+
1409
+ self.model = MistralModel(config)
1410
+ self.cls = MistralOnlyMLMHead(config)
1411
+
1412
+ # Initialize weights and apply final processing
1413
+ self.post_init()
1414
+
1415
+ def get_output_embeddings(self):
1416
+ return self.cls.predictions.decoder
1417
+
1418
+ def set_output_embeddings(self, new_embeddings):
1419
+ self.cls.predictions.decoder = new_embeddings
1420
+ self.cls.predictions.bias = new_embeddings.bias
1421
+
1422
+ def forward(
1423
+ self,
1424
+ input_ids: Optional[torch.Tensor] = None,
1425
+ attention_mask: Optional[torch.Tensor] = None,
1426
+ token_type_ids: Optional[torch.Tensor] = None,
1427
+ position_ids: Optional[torch.Tensor] = None,
1428
+ inputs_embeds: Optional[torch.Tensor] = None,
1429
+ labels: Optional[torch.Tensor] = None,
1430
+ output_attentions: Optional[bool] = None,
1431
+ output_hidden_states: Optional[bool] = None,
1432
+ return_dict: Optional[bool] = None,
1433
+ ) -> Union[Tuple[torch.Tensor], MoEMaskedLMOutput]:
1434
+ r"""
1435
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1436
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1437
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1438
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1439
+ """
1440
+
1441
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1442
+
1443
+ outputs = self.model(
1444
+ input_ids,
1445
+ attention_mask=attention_mask,
1446
+ position_ids=position_ids,
1447
+ inputs_embeds=inputs_embeds,
1448
+ output_attentions=output_attentions,
1449
+ output_hidden_states=output_hidden_states,
1450
+ return_dict=return_dict,
1451
+ )
1452
+
1453
+
1454
+ sequence_output = outputs[0]
1455
+ logits = self.cls(sequence_output)
1456
+
1457
+ loss = None
1458
+ if labels is not None:
1459
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1460
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
1461
+
1462
+
1463
+ if not return_dict:
1464
+ output = (logits,) + outputs[2:]
1465
+ return ((loss,) + output) if loss is not None else output
1466
+
1467
+ return MoEMaskedLMOutput(
1468
+ loss=loss,
1469
+ logits=logits,
1470
+ hidden_states=outputs.hidden_states,
1471
+ attentions=outputs.attentions,
1472
+ )
1473
+
1474
+
1475
+
1476
+
1477
+ @add_start_docstrings(
1478
+ """
1479
+ The Mistral Model transformer with a sequence classification head on top (linear layer).
1480
+
1481
+ [`MistralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1482
+ (e.g. GPT-2) do.
1483
+
1484
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1485
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1486
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1487
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1488
+ each row of the batch).
1489
+ """,
1490
+ MISTRAL_START_DOCSTRING,
1491
+ )
1492
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Mistral, LLAMA->MISTRAL
1493
+ class MistralForSequenceClassification(MistralPreTrainedModel):
1494
+ def __init__(self, config):
1495
+ super().__init__(config)
1496
+ self.num_labels = config.num_labels
1497
+ self.model = MistralModel(config)
1498
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1499
+ self.dropout = nn.Dropout(config.classifier_dropout)
1500
+ self.is_causal = config.is_causal
1501
+
1502
+
1503
+ # Initialize weights and apply final processing
1504
+ self.post_init()
1505
+
1506
+ def get_input_embeddings(self):
1507
+ return self.model.embed_tokens
1508
+
1509
+ def set_input_embeddings(self, value):
1510
+ self.model.embed_tokens = value
1511
+
1512
+ @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING)
1513
+ def forward(
1514
+ self,
1515
+ input_ids: torch.LongTensor = None,
1516
+ attention_mask: Optional[torch.Tensor] = None,
1517
+ position_ids: Optional[torch.LongTensor] = None,
1518
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1519
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1520
+ labels: Optional[torch.LongTensor] = None,
1521
+ use_cache: Optional[bool] = None,
1522
+ output_attentions: Optional[bool] = None,
1523
+ output_hidden_states: Optional[bool] = None,
1524
+ return_dict: Optional[bool] = None,
1525
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1526
+ r"""
1527
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1528
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1529
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1530
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1531
+ """
1532
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1533
+
1534
+ transformer_outputs = self.model(
1535
+ input_ids,
1536
+ attention_mask=attention_mask,
1537
+ position_ids=position_ids,
1538
+ past_key_values=past_key_values,
1539
+ inputs_embeds=inputs_embeds,
1540
+ use_cache=use_cache,
1541
+ output_attentions=output_attentions,
1542
+ output_hidden_states=output_hidden_states,
1543
+ return_dict=return_dict,
1544
+ )
1545
+ hidden_states = transformer_outputs[0]
1546
+ hidden_states = self.dropout(hidden_states)
1547
+ logits = self.score(hidden_states)
1548
+
1549
+ if input_ids is not None:
1550
+ batch_size = input_ids.shape[0]
1551
+ else:
1552
+ batch_size = inputs_embeds.shape[0]
1553
+
1554
+ if self.is_causal:
1555
+ if self.config.pad_token_id is None and batch_size != 1:
1556
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1557
+ if self.config.pad_token_id is None:
1558
+ sequence_lengths = -1
1559
+ else:
1560
+ if input_ids is not None:
1561
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1562
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1563
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1564
+ sequence_lengths = sequence_lengths.to(logits.device)
1565
+ else:
1566
+ sequence_lengths = -1
1567
+
1568
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1569
+ else:
1570
+ pooled_logits = logits[:, 0]
1571
+
1572
+ loss = None
1573
+ if labels is not None:
1574
+ labels = labels.to(logits.device)
1575
+ if self.config.problem_type is None:
1576
+ if self.num_labels == 1:
1577
+ self.config.problem_type = "regression"
1578
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1579
+ self.config.problem_type = "single_label_classification"
1580
+ else:
1581
+ self.config.problem_type = "multi_label_classification"
1582
+
1583
+ if self.config.problem_type == "regression":
1584
+ loss_fct = MSELoss()
1585
+ if self.num_labels == 1:
1586
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1587
+ else:
1588
+ loss = loss_fct(pooled_logits, labels)
1589
+ elif self.config.problem_type == "single_label_classification":
1590
+ loss_fct = CrossEntropyLoss()
1591
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1592
+ elif self.config.problem_type == "multi_label_classification":
1593
+ loss_fct = BCEWithLogitsLoss()
1594
+ loss = loss_fct(pooled_logits, labels)
1595
+ if not return_dict:
1596
+ output = (pooled_logits,) + transformer_outputs[1:]
1597
+ return ((loss,) + output) if loss is not None else output
1598
+
1599
+ return SequenceClassifierOutputWithPast(
1600
+ loss=loss,
1601
+ logits=pooled_logits,
1602
+ past_key_values=transformer_outputs.past_key_values,
1603
+ hidden_states=transformer_outputs.hidden_states,
1604
+ attentions=transformer_outputs.attentions,
1605
+ )
1606
+
1607
+ # import torch
1608
+ # from safetensors import safe_open
1609
+ # from safetensors.torch import save_file
1610
+
1611
+ # tensors = {}
1612
+ # with safe_open("/root/MOE_DNA/trained_model/mistral_mlm_alldata_len5k_ep3/model.safetensors", framework="pt", device="cpu") as f:
1613
+ # # print(f.metadata())
1614
+
1615
+ # for key in f.keys():
1616
+ # tensors[key] = f.get_tensor(key)
1617
+
1618
+ # new_model = {}
1619
+ # for key in tensors.keys():
1620
+ # k = key.replace("Mistral", "model")
1621
+ # new_model[k] = tensors[key]
1622
+
special_tokens_map.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": {
3
+ "content": "[CLS]",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "mask_token": {
10
+ "content": "[MASK]",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "[PAD]",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "sep_token": {
24
+ "content": "[SEP]",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "unk_token": {
31
+ "content": "[UNK]",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ }
37
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[UNK]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "[CLS]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "[SEP]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "[PAD]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "4": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "mask_token": "[MASK]",
47
+ "model_max_length": 1000000000000000019884624838656,
48
+ "pad_token": "[PAD]",
49
+ "sep_token": "[SEP]",
50
+ "tokenizer_class": "PreTrainedTokenizerFast",
51
+ "unk_token": "[UNK]"
52
+ }