llli commited on
Commit
7016651
1 Parent(s): 54186ce

Upload LeerooDedicatedOOE

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