ahmetustun commited on
Commit
385650b
1 Parent(s): b4bb16a

Upload CohereForCausalLM

Browse files
config.json CHANGED
@@ -1,11 +1,13 @@
1
  {
 
2
  "architectures": [
3
  "CohereForCausalLM"
4
  ],
5
  "attention_bias": false,
6
  "attention_dropout": 0.0,
7
  "auto_map": {
8
- "AutoConfig": "configuration_cohere.CohereConfig"
 
9
  },
10
  "bos_token_id": 5,
11
  "eos_token_id": 6,
 
1
  {
2
+ "_name_or_path": "/home/ahmet_cohere_com/HF_Final_weight_tie",
3
  "architectures": [
4
  "CohereForCausalLM"
5
  ],
6
  "attention_bias": false,
7
  "attention_dropout": 0.0,
8
  "auto_map": {
9
+ "AutoConfig": "configuration_cohere.CohereConfig",
10
+ "AutoModelForCausalLM": "modeling_cohere.CohereForCausalLM"
11
  },
12
  "bos_token_id": 5,
13
  "eos_token_id": 6,
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 5,
4
+ "eos_token_id": 6,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.38.2"
7
+ }
model-00001-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f9653711e802010076b31fa799c01f5449f42b1f5e5f0af59908a30897fbbc4
3
+ size 4731175512
model-00002-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03ed0e8bb0088afc5d02499606197bf15d5f67ae6e8131877fa2d734d871e26d
3
+ size 4932553416
model-00003-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ae289d841b00353af6c57727a2d66ac74377e1f6352e13b1fdf8cb1cef84abb
3
+ size 4932553416
model-00004-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df59fd99598731f7794146af4c463304312c32441db103020155a53ae6c0f426
3
+ size 4932553416
model-00005-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:617da60e62f706b6a86246cbf22d23bc76e3d1e9ac6a55bb042459159d53dc2c
3
+ size 4932553440
model-00006-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:272684ba146817e6995756afe2401b089397568ec7e689f4b15a2dec6587c0ef
3
+ size 4932553440
model-00007-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b213b9319f9d0e1e5d0cb74ce494e87fe677d707342699498f0905f94190d516
3
+ size 4932553440
model-00008-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:da231d688528471785c2738c269e216a92e146b5febc762332c371967e5ebf30
3
+ size 4932553440
model-00009-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6089a5aa6020eae1b198e49e1b76b87f2afa00bf510628e949cfaf693952742
3
+ size 4932553440
model-00010-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:283aa181e197224b9109b9beec81df25131f563f12c70e97bf3d518434472d33
3
+ size 4932553440
model-00011-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:410669f4b3a3a7c480a3ccf1b877dc9d4afa407e497cafebf3664cb19fec324d
3
+ size 4932553440
model-00012-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ec831df4a6195547d432d56777bd61d6f1ebe47c9343cbbf162fc8ccc644f369
3
+ size 4932553440
model-00013-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:461a70d548b64af28f408471f4e50b89467730e5ff6ec650b546f0ce9856e13d
3
+ size 4932553440
model-00014-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25eb62bfca55fbcbff92d5e2a51a15abae192827caa88eecd14921a2806d9b07
3
+ size 4932553440
model-00015-of-00015.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb83c27f9d1c2b81e88a63213f28c6b48839aa4e2ba84ed6f9a528f885d69708
3
+ size 1107329592
model.safetensors.index.json ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 69961662464
4
+ },
5
+ "weight_map": {
6
+ "model.embed_tokens.weight": "model-00001-of-00015.safetensors",
7
+ "model.layers.0.input_layernorm.weight": "model-00002-of-00015.safetensors",
8
+ "model.layers.0.mlp.down_proj.weight": "model-00002-of-00015.safetensors",
9
+ "model.layers.0.mlp.gate_proj.weight": "model-00002-of-00015.safetensors",
10
+ "model.layers.0.mlp.up_proj.weight": "model-00002-of-00015.safetensors",
11
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00015.safetensors",
12
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00015.safetensors",
13
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00015.safetensors",
14
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00015.safetensors",
15
+ "model.layers.1.input_layernorm.weight": "model-00002-of-00015.safetensors",
16
+ "model.layers.1.mlp.down_proj.weight": "model-00002-of-00015.safetensors",
17
+ "model.layers.1.mlp.gate_proj.weight": "model-00002-of-00015.safetensors",
18
+ "model.layers.1.mlp.up_proj.weight": "model-00002-of-00015.safetensors",
19
+ "model.layers.1.self_attn.k_proj.weight": "model-00002-of-00015.safetensors",
20
+ "model.layers.1.self_attn.o_proj.weight": "model-00002-of-00015.safetensors",
21
+ "model.layers.1.self_attn.q_proj.weight": "model-00002-of-00015.safetensors",
22
+ "model.layers.1.self_attn.v_proj.weight": "model-00002-of-00015.safetensors",
23
+ "model.layers.10.input_layernorm.weight": "model-00005-of-00015.safetensors",
24
+ "model.layers.10.mlp.down_proj.weight": "model-00005-of-00015.safetensors",
25
+ "model.layers.10.mlp.gate_proj.weight": "model-00005-of-00015.safetensors",
26
+ "model.layers.10.mlp.up_proj.weight": "model-00005-of-00015.safetensors",
27
+ "model.layers.10.self_attn.k_proj.weight": "model-00005-of-00015.safetensors",
28
+ "model.layers.10.self_attn.o_proj.weight": "model-00005-of-00015.safetensors",
29
+ "model.layers.10.self_attn.q_proj.weight": "model-00005-of-00015.safetensors",
30
+ "model.layers.10.self_attn.v_proj.weight": "model-00005-of-00015.safetensors",
31
+ "model.layers.11.input_layernorm.weight": "model-00005-of-00015.safetensors",
32
+ "model.layers.11.mlp.down_proj.weight": "model-00005-of-00015.safetensors",
33
+ "model.layers.11.mlp.gate_proj.weight": "model-00005-of-00015.safetensors",
34
+ "model.layers.11.mlp.up_proj.weight": "model-00005-of-00015.safetensors",
35
+ "model.layers.11.self_attn.k_proj.weight": "model-00005-of-00015.safetensors",
36
+ "model.layers.11.self_attn.o_proj.weight": "model-00005-of-00015.safetensors",
37
+ "model.layers.11.self_attn.q_proj.weight": "model-00005-of-00015.safetensors",
38
+ "model.layers.11.self_attn.v_proj.weight": "model-00005-of-00015.safetensors",
39
+ "model.layers.12.input_layernorm.weight": "model-00006-of-00015.safetensors",
40
+ "model.layers.12.mlp.down_proj.weight": "model-00006-of-00015.safetensors",
41
+ "model.layers.12.mlp.gate_proj.weight": "model-00006-of-00015.safetensors",
42
+ "model.layers.12.mlp.up_proj.weight": "model-00006-of-00015.safetensors",
43
+ "model.layers.12.self_attn.k_proj.weight": "model-00005-of-00015.safetensors",
44
+ "model.layers.12.self_attn.o_proj.weight": "model-00005-of-00015.safetensors",
45
+ "model.layers.12.self_attn.q_proj.weight": "model-00005-of-00015.safetensors",
46
+ "model.layers.12.self_attn.v_proj.weight": "model-00005-of-00015.safetensors",
47
+ "model.layers.13.input_layernorm.weight": "model-00006-of-00015.safetensors",
48
+ "model.layers.13.mlp.down_proj.weight": "model-00006-of-00015.safetensors",
49
+ "model.layers.13.mlp.gate_proj.weight": "model-00006-of-00015.safetensors",
50
+ "model.layers.13.mlp.up_proj.weight": "model-00006-of-00015.safetensors",
51
+ "model.layers.13.self_attn.k_proj.weight": "model-00006-of-00015.safetensors",
52
+ "model.layers.13.self_attn.o_proj.weight": "model-00006-of-00015.safetensors",
53
+ "model.layers.13.self_attn.q_proj.weight": "model-00006-of-00015.safetensors",
54
+ "model.layers.13.self_attn.v_proj.weight": "model-00006-of-00015.safetensors",
55
+ "model.layers.14.input_layernorm.weight": "model-00006-of-00015.safetensors",
56
+ "model.layers.14.mlp.down_proj.weight": "model-00006-of-00015.safetensors",
57
+ "model.layers.14.mlp.gate_proj.weight": "model-00006-of-00015.safetensors",
58
+ "model.layers.14.mlp.up_proj.weight": "model-00006-of-00015.safetensors",
59
+ "model.layers.14.self_attn.k_proj.weight": "model-00006-of-00015.safetensors",
60
+ "model.layers.14.self_attn.o_proj.weight": "model-00006-of-00015.safetensors",
61
+ "model.layers.14.self_attn.q_proj.weight": "model-00006-of-00015.safetensors",
62
+ "model.layers.14.self_attn.v_proj.weight": "model-00006-of-00015.safetensors",
63
+ "model.layers.15.input_layernorm.weight": "model-00007-of-00015.safetensors",
64
+ "model.layers.15.mlp.down_proj.weight": "model-00007-of-00015.safetensors",
65
+ "model.layers.15.mlp.gate_proj.weight": "model-00007-of-00015.safetensors",
66
+ "model.layers.15.mlp.up_proj.weight": "model-00007-of-00015.safetensors",
67
+ "model.layers.15.self_attn.k_proj.weight": "model-00006-of-00015.safetensors",
68
+ "model.layers.15.self_attn.o_proj.weight": "model-00006-of-00015.safetensors",
69
+ "model.layers.15.self_attn.q_proj.weight": "model-00006-of-00015.safetensors",
70
+ "model.layers.15.self_attn.v_proj.weight": "model-00006-of-00015.safetensors",
71
+ "model.layers.16.input_layernorm.weight": "model-00007-of-00015.safetensors",
72
+ "model.layers.16.mlp.down_proj.weight": "model-00007-of-00015.safetensors",
73
+ "model.layers.16.mlp.gate_proj.weight": "model-00007-of-00015.safetensors",
74
+ "model.layers.16.mlp.up_proj.weight": "model-00007-of-00015.safetensors",
75
+ "model.layers.16.self_attn.k_proj.weight": "model-00007-of-00015.safetensors",
76
+ "model.layers.16.self_attn.o_proj.weight": "model-00007-of-00015.safetensors",
77
+ "model.layers.16.self_attn.q_proj.weight": "model-00007-of-00015.safetensors",
78
+ "model.layers.16.self_attn.v_proj.weight": "model-00007-of-00015.safetensors",
79
+ "model.layers.17.input_layernorm.weight": "model-00007-of-00015.safetensors",
80
+ "model.layers.17.mlp.down_proj.weight": "model-00007-of-00015.safetensors",
81
+ "model.layers.17.mlp.gate_proj.weight": "model-00007-of-00015.safetensors",
82
+ "model.layers.17.mlp.up_proj.weight": "model-00007-of-00015.safetensors",
83
+ "model.layers.17.self_attn.k_proj.weight": "model-00007-of-00015.safetensors",
84
+ "model.layers.17.self_attn.o_proj.weight": "model-00007-of-00015.safetensors",
85
+ "model.layers.17.self_attn.q_proj.weight": "model-00007-of-00015.safetensors",
86
+ "model.layers.17.self_attn.v_proj.weight": "model-00007-of-00015.safetensors",
87
+ "model.layers.18.input_layernorm.weight": "model-00008-of-00015.safetensors",
88
+ "model.layers.18.mlp.down_proj.weight": "model-00008-of-00015.safetensors",
89
+ "model.layers.18.mlp.gate_proj.weight": "model-00008-of-00015.safetensors",
90
+ "model.layers.18.mlp.up_proj.weight": "model-00008-of-00015.safetensors",
91
+ "model.layers.18.self_attn.k_proj.weight": "model-00007-of-00015.safetensors",
92
+ "model.layers.18.self_attn.o_proj.weight": "model-00007-of-00015.safetensors",
93
+ "model.layers.18.self_attn.q_proj.weight": "model-00007-of-00015.safetensors",
94
+ "model.layers.18.self_attn.v_proj.weight": "model-00007-of-00015.safetensors",
95
+ "model.layers.19.input_layernorm.weight": "model-00008-of-00015.safetensors",
96
+ "model.layers.19.mlp.down_proj.weight": "model-00008-of-00015.safetensors",
97
+ "model.layers.19.mlp.gate_proj.weight": "model-00008-of-00015.safetensors",
98
+ "model.layers.19.mlp.up_proj.weight": "model-00008-of-00015.safetensors",
99
+ "model.layers.19.self_attn.k_proj.weight": "model-00008-of-00015.safetensors",
100
+ "model.layers.19.self_attn.o_proj.weight": "model-00008-of-00015.safetensors",
101
+ "model.layers.19.self_attn.q_proj.weight": "model-00008-of-00015.safetensors",
102
+ "model.layers.19.self_attn.v_proj.weight": "model-00008-of-00015.safetensors",
103
+ "model.layers.2.input_layernorm.weight": "model-00002-of-00015.safetensors",
104
+ "model.layers.2.mlp.down_proj.weight": "model-00002-of-00015.safetensors",
105
+ "model.layers.2.mlp.gate_proj.weight": "model-00002-of-00015.safetensors",
106
+ "model.layers.2.mlp.up_proj.weight": "model-00002-of-00015.safetensors",
107
+ "model.layers.2.self_attn.k_proj.weight": "model-00002-of-00015.safetensors",
108
+ "model.layers.2.self_attn.o_proj.weight": "model-00002-of-00015.safetensors",
109
+ "model.layers.2.self_attn.q_proj.weight": "model-00002-of-00015.safetensors",
110
+ "model.layers.2.self_attn.v_proj.weight": "model-00002-of-00015.safetensors",
111
+ "model.layers.20.input_layernorm.weight": "model-00008-of-00015.safetensors",
112
+ "model.layers.20.mlp.down_proj.weight": "model-00008-of-00015.safetensors",
113
+ "model.layers.20.mlp.gate_proj.weight": "model-00008-of-00015.safetensors",
114
+ "model.layers.20.mlp.up_proj.weight": "model-00008-of-00015.safetensors",
115
+ "model.layers.20.self_attn.k_proj.weight": "model-00008-of-00015.safetensors",
116
+ "model.layers.20.self_attn.o_proj.weight": "model-00008-of-00015.safetensors",
117
+ "model.layers.20.self_attn.q_proj.weight": "model-00008-of-00015.safetensors",
118
+ "model.layers.20.self_attn.v_proj.weight": "model-00008-of-00015.safetensors",
119
+ "model.layers.21.input_layernorm.weight": "model-00009-of-00015.safetensors",
120
+ "model.layers.21.mlp.down_proj.weight": "model-00009-of-00015.safetensors",
121
+ "model.layers.21.mlp.gate_proj.weight": "model-00009-of-00015.safetensors",
122
+ "model.layers.21.mlp.up_proj.weight": "model-00009-of-00015.safetensors",
123
+ "model.layers.21.self_attn.k_proj.weight": "model-00008-of-00015.safetensors",
124
+ "model.layers.21.self_attn.o_proj.weight": "model-00008-of-00015.safetensors",
125
+ "model.layers.21.self_attn.q_proj.weight": "model-00008-of-00015.safetensors",
126
+ "model.layers.21.self_attn.v_proj.weight": "model-00008-of-00015.safetensors",
127
+ "model.layers.22.input_layernorm.weight": "model-00009-of-00015.safetensors",
128
+ "model.layers.22.mlp.down_proj.weight": "model-00009-of-00015.safetensors",
129
+ "model.layers.22.mlp.gate_proj.weight": "model-00009-of-00015.safetensors",
130
+ "model.layers.22.mlp.up_proj.weight": "model-00009-of-00015.safetensors",
131
+ "model.layers.22.self_attn.k_proj.weight": "model-00009-of-00015.safetensors",
132
+ "model.layers.22.self_attn.o_proj.weight": "model-00009-of-00015.safetensors",
133
+ "model.layers.22.self_attn.q_proj.weight": "model-00009-of-00015.safetensors",
134
+ "model.layers.22.self_attn.v_proj.weight": "model-00009-of-00015.safetensors",
135
+ "model.layers.23.input_layernorm.weight": "model-00009-of-00015.safetensors",
136
+ "model.layers.23.mlp.down_proj.weight": "model-00009-of-00015.safetensors",
137
+ "model.layers.23.mlp.gate_proj.weight": "model-00009-of-00015.safetensors",
138
+ "model.layers.23.mlp.up_proj.weight": "model-00009-of-00015.safetensors",
139
+ "model.layers.23.self_attn.k_proj.weight": "model-00009-of-00015.safetensors",
140
+ "model.layers.23.self_attn.o_proj.weight": "model-00009-of-00015.safetensors",
141
+ "model.layers.23.self_attn.q_proj.weight": "model-00009-of-00015.safetensors",
142
+ "model.layers.23.self_attn.v_proj.weight": "model-00009-of-00015.safetensors",
143
+ "model.layers.24.input_layernorm.weight": "model-00010-of-00015.safetensors",
144
+ "model.layers.24.mlp.down_proj.weight": "model-00010-of-00015.safetensors",
145
+ "model.layers.24.mlp.gate_proj.weight": "model-00010-of-00015.safetensors",
146
+ "model.layers.24.mlp.up_proj.weight": "model-00010-of-00015.safetensors",
147
+ "model.layers.24.self_attn.k_proj.weight": "model-00009-of-00015.safetensors",
148
+ "model.layers.24.self_attn.o_proj.weight": "model-00009-of-00015.safetensors",
149
+ "model.layers.24.self_attn.q_proj.weight": "model-00009-of-00015.safetensors",
150
+ "model.layers.24.self_attn.v_proj.weight": "model-00009-of-00015.safetensors",
151
+ "model.layers.25.input_layernorm.weight": "model-00010-of-00015.safetensors",
152
+ "model.layers.25.mlp.down_proj.weight": "model-00010-of-00015.safetensors",
153
+ "model.layers.25.mlp.gate_proj.weight": "model-00010-of-00015.safetensors",
154
+ "model.layers.25.mlp.up_proj.weight": "model-00010-of-00015.safetensors",
155
+ "model.layers.25.self_attn.k_proj.weight": "model-00010-of-00015.safetensors",
156
+ "model.layers.25.self_attn.o_proj.weight": "model-00010-of-00015.safetensors",
157
+ "model.layers.25.self_attn.q_proj.weight": "model-00010-of-00015.safetensors",
158
+ "model.layers.25.self_attn.v_proj.weight": "model-00010-of-00015.safetensors",
159
+ "model.layers.26.input_layernorm.weight": "model-00010-of-00015.safetensors",
160
+ "model.layers.26.mlp.down_proj.weight": "model-00010-of-00015.safetensors",
161
+ "model.layers.26.mlp.gate_proj.weight": "model-00010-of-00015.safetensors",
162
+ "model.layers.26.mlp.up_proj.weight": "model-00010-of-00015.safetensors",
163
+ "model.layers.26.self_attn.k_proj.weight": "model-00010-of-00015.safetensors",
164
+ "model.layers.26.self_attn.o_proj.weight": "model-00010-of-00015.safetensors",
165
+ "model.layers.26.self_attn.q_proj.weight": "model-00010-of-00015.safetensors",
166
+ "model.layers.26.self_attn.v_proj.weight": "model-00010-of-00015.safetensors",
167
+ "model.layers.27.input_layernorm.weight": "model-00011-of-00015.safetensors",
168
+ "model.layers.27.mlp.down_proj.weight": "model-00011-of-00015.safetensors",
169
+ "model.layers.27.mlp.gate_proj.weight": "model-00011-of-00015.safetensors",
170
+ "model.layers.27.mlp.up_proj.weight": "model-00011-of-00015.safetensors",
171
+ "model.layers.27.self_attn.k_proj.weight": "model-00010-of-00015.safetensors",
172
+ "model.layers.27.self_attn.o_proj.weight": "model-00010-of-00015.safetensors",
173
+ "model.layers.27.self_attn.q_proj.weight": "model-00010-of-00015.safetensors",
174
+ "model.layers.27.self_attn.v_proj.weight": "model-00010-of-00015.safetensors",
175
+ "model.layers.28.input_layernorm.weight": "model-00011-of-00015.safetensors",
176
+ "model.layers.28.mlp.down_proj.weight": "model-00011-of-00015.safetensors",
177
+ "model.layers.28.mlp.gate_proj.weight": "model-00011-of-00015.safetensors",
178
+ "model.layers.28.mlp.up_proj.weight": "model-00011-of-00015.safetensors",
179
+ "model.layers.28.self_attn.k_proj.weight": "model-00011-of-00015.safetensors",
180
+ "model.layers.28.self_attn.o_proj.weight": "model-00011-of-00015.safetensors",
181
+ "model.layers.28.self_attn.q_proj.weight": "model-00011-of-00015.safetensors",
182
+ "model.layers.28.self_attn.v_proj.weight": "model-00011-of-00015.safetensors",
183
+ "model.layers.29.input_layernorm.weight": "model-00011-of-00015.safetensors",
184
+ "model.layers.29.mlp.down_proj.weight": "model-00011-of-00015.safetensors",
185
+ "model.layers.29.mlp.gate_proj.weight": "model-00011-of-00015.safetensors",
186
+ "model.layers.29.mlp.up_proj.weight": "model-00011-of-00015.safetensors",
187
+ "model.layers.29.self_attn.k_proj.weight": "model-00011-of-00015.safetensors",
188
+ "model.layers.29.self_attn.o_proj.weight": "model-00011-of-00015.safetensors",
189
+ "model.layers.29.self_attn.q_proj.weight": "model-00011-of-00015.safetensors",
190
+ "model.layers.29.self_attn.v_proj.weight": "model-00011-of-00015.safetensors",
191
+ "model.layers.3.input_layernorm.weight": "model-00003-of-00015.safetensors",
192
+ "model.layers.3.mlp.down_proj.weight": "model-00003-of-00015.safetensors",
193
+ "model.layers.3.mlp.gate_proj.weight": "model-00003-of-00015.safetensors",
194
+ "model.layers.3.mlp.up_proj.weight": "model-00003-of-00015.safetensors",
195
+ "model.layers.3.self_attn.k_proj.weight": "model-00002-of-00015.safetensors",
196
+ "model.layers.3.self_attn.o_proj.weight": "model-00002-of-00015.safetensors",
197
+ "model.layers.3.self_attn.q_proj.weight": "model-00002-of-00015.safetensors",
198
+ "model.layers.3.self_attn.v_proj.weight": "model-00002-of-00015.safetensors",
199
+ "model.layers.30.input_layernorm.weight": "model-00012-of-00015.safetensors",
200
+ "model.layers.30.mlp.down_proj.weight": "model-00012-of-00015.safetensors",
201
+ "model.layers.30.mlp.gate_proj.weight": "model-00012-of-00015.safetensors",
202
+ "model.layers.30.mlp.up_proj.weight": "model-00012-of-00015.safetensors",
203
+ "model.layers.30.self_attn.k_proj.weight": "model-00011-of-00015.safetensors",
204
+ "model.layers.30.self_attn.o_proj.weight": "model-00011-of-00015.safetensors",
205
+ "model.layers.30.self_attn.q_proj.weight": "model-00011-of-00015.safetensors",
206
+ "model.layers.30.self_attn.v_proj.weight": "model-00011-of-00015.safetensors",
207
+ "model.layers.31.input_layernorm.weight": "model-00012-of-00015.safetensors",
208
+ "model.layers.31.mlp.down_proj.weight": "model-00012-of-00015.safetensors",
209
+ "model.layers.31.mlp.gate_proj.weight": "model-00012-of-00015.safetensors",
210
+ "model.layers.31.mlp.up_proj.weight": "model-00012-of-00015.safetensors",
211
+ "model.layers.31.self_attn.k_proj.weight": "model-00012-of-00015.safetensors",
212
+ "model.layers.31.self_attn.o_proj.weight": "model-00012-of-00015.safetensors",
213
+ "model.layers.31.self_attn.q_proj.weight": "model-00012-of-00015.safetensors",
214
+ "model.layers.31.self_attn.v_proj.weight": "model-00012-of-00015.safetensors",
215
+ "model.layers.32.input_layernorm.weight": "model-00012-of-00015.safetensors",
216
+ "model.layers.32.mlp.down_proj.weight": "model-00012-of-00015.safetensors",
217
+ "model.layers.32.mlp.gate_proj.weight": "model-00012-of-00015.safetensors",
218
+ "model.layers.32.mlp.up_proj.weight": "model-00012-of-00015.safetensors",
219
+ "model.layers.32.self_attn.k_proj.weight": "model-00012-of-00015.safetensors",
220
+ "model.layers.32.self_attn.o_proj.weight": "model-00012-of-00015.safetensors",
221
+ "model.layers.32.self_attn.q_proj.weight": "model-00012-of-00015.safetensors",
222
+ "model.layers.32.self_attn.v_proj.weight": "model-00012-of-00015.safetensors",
223
+ "model.layers.33.input_layernorm.weight": "model-00013-of-00015.safetensors",
224
+ "model.layers.33.mlp.down_proj.weight": "model-00013-of-00015.safetensors",
225
+ "model.layers.33.mlp.gate_proj.weight": "model-00013-of-00015.safetensors",
226
+ "model.layers.33.mlp.up_proj.weight": "model-00013-of-00015.safetensors",
227
+ "model.layers.33.self_attn.k_proj.weight": "model-00012-of-00015.safetensors",
228
+ "model.layers.33.self_attn.o_proj.weight": "model-00012-of-00015.safetensors",
229
+ "model.layers.33.self_attn.q_proj.weight": "model-00012-of-00015.safetensors",
230
+ "model.layers.33.self_attn.v_proj.weight": "model-00012-of-00015.safetensors",
231
+ "model.layers.34.input_layernorm.weight": "model-00013-of-00015.safetensors",
232
+ "model.layers.34.mlp.down_proj.weight": "model-00013-of-00015.safetensors",
233
+ "model.layers.34.mlp.gate_proj.weight": "model-00013-of-00015.safetensors",
234
+ "model.layers.34.mlp.up_proj.weight": "model-00013-of-00015.safetensors",
235
+ "model.layers.34.self_attn.k_proj.weight": "model-00013-of-00015.safetensors",
236
+ "model.layers.34.self_attn.o_proj.weight": "model-00013-of-00015.safetensors",
237
+ "model.layers.34.self_attn.q_proj.weight": "model-00013-of-00015.safetensors",
238
+ "model.layers.34.self_attn.v_proj.weight": "model-00013-of-00015.safetensors",
239
+ "model.layers.35.input_layernorm.weight": "model-00013-of-00015.safetensors",
240
+ "model.layers.35.mlp.down_proj.weight": "model-00013-of-00015.safetensors",
241
+ "model.layers.35.mlp.gate_proj.weight": "model-00013-of-00015.safetensors",
242
+ "model.layers.35.mlp.up_proj.weight": "model-00013-of-00015.safetensors",
243
+ "model.layers.35.self_attn.k_proj.weight": "model-00013-of-00015.safetensors",
244
+ "model.layers.35.self_attn.o_proj.weight": "model-00013-of-00015.safetensors",
245
+ "model.layers.35.self_attn.q_proj.weight": "model-00013-of-00015.safetensors",
246
+ "model.layers.35.self_attn.v_proj.weight": "model-00013-of-00015.safetensors",
247
+ "model.layers.36.input_layernorm.weight": "model-00014-of-00015.safetensors",
248
+ "model.layers.36.mlp.down_proj.weight": "model-00014-of-00015.safetensors",
249
+ "model.layers.36.mlp.gate_proj.weight": "model-00014-of-00015.safetensors",
250
+ "model.layers.36.mlp.up_proj.weight": "model-00014-of-00015.safetensors",
251
+ "model.layers.36.self_attn.k_proj.weight": "model-00013-of-00015.safetensors",
252
+ "model.layers.36.self_attn.o_proj.weight": "model-00013-of-00015.safetensors",
253
+ "model.layers.36.self_attn.q_proj.weight": "model-00013-of-00015.safetensors",
254
+ "model.layers.36.self_attn.v_proj.weight": "model-00013-of-00015.safetensors",
255
+ "model.layers.37.input_layernorm.weight": "model-00014-of-00015.safetensors",
256
+ "model.layers.37.mlp.down_proj.weight": "model-00014-of-00015.safetensors",
257
+ "model.layers.37.mlp.gate_proj.weight": "model-00014-of-00015.safetensors",
258
+ "model.layers.37.mlp.up_proj.weight": "model-00014-of-00015.safetensors",
259
+ "model.layers.37.self_attn.k_proj.weight": "model-00014-of-00015.safetensors",
260
+ "model.layers.37.self_attn.o_proj.weight": "model-00014-of-00015.safetensors",
261
+ "model.layers.37.self_attn.q_proj.weight": "model-00014-of-00015.safetensors",
262
+ "model.layers.37.self_attn.v_proj.weight": "model-00014-of-00015.safetensors",
263
+ "model.layers.38.input_layernorm.weight": "model-00014-of-00015.safetensors",
264
+ "model.layers.38.mlp.down_proj.weight": "model-00014-of-00015.safetensors",
265
+ "model.layers.38.mlp.gate_proj.weight": "model-00014-of-00015.safetensors",
266
+ "model.layers.38.mlp.up_proj.weight": "model-00014-of-00015.safetensors",
267
+ "model.layers.38.self_attn.k_proj.weight": "model-00014-of-00015.safetensors",
268
+ "model.layers.38.self_attn.o_proj.weight": "model-00014-of-00015.safetensors",
269
+ "model.layers.38.self_attn.q_proj.weight": "model-00014-of-00015.safetensors",
270
+ "model.layers.38.self_attn.v_proj.weight": "model-00014-of-00015.safetensors",
271
+ "model.layers.39.input_layernorm.weight": "model-00015-of-00015.safetensors",
272
+ "model.layers.39.mlp.down_proj.weight": "model-00015-of-00015.safetensors",
273
+ "model.layers.39.mlp.gate_proj.weight": "model-00015-of-00015.safetensors",
274
+ "model.layers.39.mlp.up_proj.weight": "model-00015-of-00015.safetensors",
275
+ "model.layers.39.self_attn.k_proj.weight": "model-00014-of-00015.safetensors",
276
+ "model.layers.39.self_attn.o_proj.weight": "model-00014-of-00015.safetensors",
277
+ "model.layers.39.self_attn.q_proj.weight": "model-00014-of-00015.safetensors",
278
+ "model.layers.39.self_attn.v_proj.weight": "model-00014-of-00015.safetensors",
279
+ "model.layers.4.input_layernorm.weight": "model-00003-of-00015.safetensors",
280
+ "model.layers.4.mlp.down_proj.weight": "model-00003-of-00015.safetensors",
281
+ "model.layers.4.mlp.gate_proj.weight": "model-00003-of-00015.safetensors",
282
+ "model.layers.4.mlp.up_proj.weight": "model-00003-of-00015.safetensors",
283
+ "model.layers.4.self_attn.k_proj.weight": "model-00003-of-00015.safetensors",
284
+ "model.layers.4.self_attn.o_proj.weight": "model-00003-of-00015.safetensors",
285
+ "model.layers.4.self_attn.q_proj.weight": "model-00003-of-00015.safetensors",
286
+ "model.layers.4.self_attn.v_proj.weight": "model-00003-of-00015.safetensors",
287
+ "model.layers.5.input_layernorm.weight": "model-00003-of-00015.safetensors",
288
+ "model.layers.5.mlp.down_proj.weight": "model-00003-of-00015.safetensors",
289
+ "model.layers.5.mlp.gate_proj.weight": "model-00003-of-00015.safetensors",
290
+ "model.layers.5.mlp.up_proj.weight": "model-00003-of-00015.safetensors",
291
+ "model.layers.5.self_attn.k_proj.weight": "model-00003-of-00015.safetensors",
292
+ "model.layers.5.self_attn.o_proj.weight": "model-00003-of-00015.safetensors",
293
+ "model.layers.5.self_attn.q_proj.weight": "model-00003-of-00015.safetensors",
294
+ "model.layers.5.self_attn.v_proj.weight": "model-00003-of-00015.safetensors",
295
+ "model.layers.6.input_layernorm.weight": "model-00004-of-00015.safetensors",
296
+ "model.layers.6.mlp.down_proj.weight": "model-00004-of-00015.safetensors",
297
+ "model.layers.6.mlp.gate_proj.weight": "model-00004-of-00015.safetensors",
298
+ "model.layers.6.mlp.up_proj.weight": "model-00004-of-00015.safetensors",
299
+ "model.layers.6.self_attn.k_proj.weight": "model-00003-of-00015.safetensors",
300
+ "model.layers.6.self_attn.o_proj.weight": "model-00003-of-00015.safetensors",
301
+ "model.layers.6.self_attn.q_proj.weight": "model-00003-of-00015.safetensors",
302
+ "model.layers.6.self_attn.v_proj.weight": "model-00003-of-00015.safetensors",
303
+ "model.layers.7.input_layernorm.weight": "model-00004-of-00015.safetensors",
304
+ "model.layers.7.mlp.down_proj.weight": "model-00004-of-00015.safetensors",
305
+ "model.layers.7.mlp.gate_proj.weight": "model-00004-of-00015.safetensors",
306
+ "model.layers.7.mlp.up_proj.weight": "model-00004-of-00015.safetensors",
307
+ "model.layers.7.self_attn.k_proj.weight": "model-00004-of-00015.safetensors",
308
+ "model.layers.7.self_attn.o_proj.weight": "model-00004-of-00015.safetensors",
309
+ "model.layers.7.self_attn.q_proj.weight": "model-00004-of-00015.safetensors",
310
+ "model.layers.7.self_attn.v_proj.weight": "model-00004-of-00015.safetensors",
311
+ "model.layers.8.input_layernorm.weight": "model-00004-of-00015.safetensors",
312
+ "model.layers.8.mlp.down_proj.weight": "model-00004-of-00015.safetensors",
313
+ "model.layers.8.mlp.gate_proj.weight": "model-00004-of-00015.safetensors",
314
+ "model.layers.8.mlp.up_proj.weight": "model-00004-of-00015.safetensors",
315
+ "model.layers.8.self_attn.k_proj.weight": "model-00004-of-00015.safetensors",
316
+ "model.layers.8.self_attn.o_proj.weight": "model-00004-of-00015.safetensors",
317
+ "model.layers.8.self_attn.q_proj.weight": "model-00004-of-00015.safetensors",
318
+ "model.layers.8.self_attn.v_proj.weight": "model-00004-of-00015.safetensors",
319
+ "model.layers.9.input_layernorm.weight": "model-00005-of-00015.safetensors",
320
+ "model.layers.9.mlp.down_proj.weight": "model-00005-of-00015.safetensors",
321
+ "model.layers.9.mlp.gate_proj.weight": "model-00005-of-00015.safetensors",
322
+ "model.layers.9.mlp.up_proj.weight": "model-00005-of-00015.safetensors",
323
+ "model.layers.9.self_attn.k_proj.weight": "model-00004-of-00015.safetensors",
324
+ "model.layers.9.self_attn.o_proj.weight": "model-00004-of-00015.safetensors",
325
+ "model.layers.9.self_attn.q_proj.weight": "model-00004-of-00015.safetensors",
326
+ "model.layers.9.self_attn.v_proj.weight": "model-00004-of-00015.safetensors",
327
+ "model.norm.weight": "model-00015-of-00015.safetensors"
328
+ }
329
+ }
modeling_cohere.py ADDED
@@ -0,0 +1,1286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Cohere 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
+
21
+ # This file is based on the LLama model definition file in transformers
22
+
23
+ """PyTorch Cohere model."""
24
+
25
+ import math
26
+ import warnings
27
+ from typing import List, Optional, Tuple, Union
28
+
29
+ import torch
30
+ import torch.nn.functional as F
31
+ import torch.utils.checkpoint
32
+ from torch import nn
33
+ from torch.nn import CrossEntropyLoss
34
+
35
+ from transformers import AutoModel, AutoModelForCausalLM
36
+ from transformers.activations import ACT2FN
37
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
38
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
39
+ from transformers.modeling_outputs import (
40
+ BaseModelOutputWithPast,
41
+ CausalLMOutputWithPast,
42
+ )
43
+ from transformers.modeling_utils import PreTrainedModel
44
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
45
+ from transformers.utils import (
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ is_flash_attn_2_available,
49
+ is_flash_attn_greater_or_equal_2_10,
50
+ logging,
51
+ replace_return_docstrings,
52
+ )
53
+ from .configuration_cohere import CohereConfig
54
+
55
+
56
+ if is_flash_attn_2_available():
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CONFIG_FOR_DOC = "CohereConfig"
64
+
65
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
66
+ def _get_unpad_data(attention_mask):
67
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
68
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
69
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
70
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
71
+ return (
72
+ indices,
73
+ cu_seqlens,
74
+ max_seqlen_in_batch,
75
+ )
76
+
77
+
78
+ class LayerNorm(nn.Module):
79
+ def __init__(self, hidden_size, eps=1e-5, bias=False):
80
+ super().__init__()
81
+ self.weight = nn.Parameter(torch.ones(hidden_size))
82
+ self.bias = nn.Parameter(torch.zeros(hidden_size)) if bias else None
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
+ mean = hidden_states.mean(-1, keepdim=True)
89
+ variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True)
90
+ hidden_states = (hidden_states - mean) * torch.rsqrt(variance + self.variance_epsilon)
91
+ hidden_states = self.weight.to(torch.float32) * hidden_states
92
+ if self.bias is not None:
93
+ hidden_states = hidden_states + self.bias.to(torch.float32)
94
+ return hidden_states.to(input_dtype)
95
+
96
+
97
+ ALL_LAYERNORM_LAYERS.append(LayerNorm)
98
+
99
+
100
+ # copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Cohere
101
+ class CohereRotaryEmbedding(nn.Module):
102
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
103
+ super().__init__()
104
+ self.scaling_factor = scaling_factor
105
+ self.dim = dim
106
+ self.max_position_embeddings = max_position_embeddings
107
+ self.base = base
108
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
109
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
110
+ # For BC we register cos and sin cached
111
+ self.max_seq_len_cached = max_position_embeddings
112
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
113
+ t = t / self.scaling_factor
114
+ freqs = torch.outer(t, self.inv_freq)
115
+ emb = torch.repeat_interleave(freqs, 2, dim=-1)
116
+ self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False)
117
+ self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False)
118
+
119
+ @property
120
+ def sin_cached(self):
121
+ logger.warning_once(
122
+ "The sin_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
123
+ "the forward method of RoPE from now on instead. It is not used in the `CohereAttention` class"
124
+ )
125
+ return self._sin_cached
126
+
127
+ @property
128
+ def cos_cached(self):
129
+ logger.warning_once(
130
+ "The cos_cached attribute will be removed in 4.39. Bear in mind that its contents changed in v4.38. Use "
131
+ "the forward method of RoPE from now on instead. It is not used in the `CohereAttention` class"
132
+ )
133
+ return self._cos_cached
134
+
135
+ @torch.no_grad()
136
+ def forward(self, x, position_ids, seq_len=None):
137
+ if seq_len is not None:
138
+ logger.warning_once("The `seq_len` argument is deprecated and unused. It will be removed in v4.39.")
139
+
140
+ # x: [bs, num_attention_heads, seq_len, head_size]
141
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
142
+ position_ids_expanded = position_ids[:, None, :].float()
143
+ # Force float32 since bfloat16 loses precision on long contexts
144
+ # See https://github.com/huggingface/transformers/pull/29285
145
+ device_type = x.device.type
146
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
147
+ with torch.autocast(device_type=device_type, enabled=False):
148
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
149
+ emb = torch.repeat_interleave(freqs, 2, dim=-1)
150
+ cos = emb.cos()
151
+ sin = emb.sin()
152
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
153
+
154
+
155
+ def rotate_half(x):
156
+ # Split and rotate
157
+ x1 = x[..., ::2]
158
+ x2 = x[..., 1::2]
159
+ rot_x = torch.stack([-x2, x1], dim=-1).flatten(-2)
160
+ return rot_x
161
+
162
+
163
+ # copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
164
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
165
+ """Applies Rotary Position Embedding to the query and key tensors.
166
+
167
+ Args:
168
+ q (`torch.Tensor`): The query tensor.
169
+ k (`torch.Tensor`): The key tensor.
170
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
171
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
172
+ position_ids (`torch.Tensor`, *optional*):
173
+ Deprecated and unused.
174
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
175
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
176
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
177
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
178
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
179
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
180
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
181
+ Returns:
182
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
183
+ """
184
+ cos = cos.unsqueeze(unsqueeze_dim)
185
+ sin = sin.unsqueeze(unsqueeze_dim)
186
+ q_embed = (q * cos) + (rotate_half(q) * sin)
187
+ k_embed = (k * cos) + (rotate_half(k) * sin)
188
+ return q_embed, k_embed
189
+
190
+
191
+ # Copied from transformers.models.llama.modeling_llama.LlamaMLP Llama->Cohere
192
+ class CohereMLP(nn.Module):
193
+ def __init__(self, config):
194
+ super().__init__()
195
+ self.config = config
196
+ self.hidden_size = config.hidden_size
197
+ self.intermediate_size = config.intermediate_size
198
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
199
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
200
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
201
+ self.act_fn = ACT2FN[config.hidden_act]
202
+
203
+ def forward(self, x):
204
+ if self.config.pretraining_tp > 1:
205
+ slice = self.intermediate_size // self.config.pretraining_tp
206
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
207
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
208
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
209
+
210
+ gate_proj = torch.cat(
211
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
212
+ )
213
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
214
+
215
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
216
+ down_proj = [
217
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
218
+ ]
219
+ down_proj = sum(down_proj)
220
+ else:
221
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
222
+
223
+ return down_proj
224
+
225
+
226
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
227
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
228
+ """
229
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
230
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
231
+ """
232
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
233
+ if n_rep == 1:
234
+ return hidden_states
235
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
236
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
237
+
238
+
239
+ class Attention(nn.Module):
240
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
241
+
242
+ def __init__(self, config: CohereConfig, layer_idx: Optional[int] = None):
243
+ super().__init__()
244
+ self.config = config
245
+ self.layer_idx = layer_idx
246
+ if layer_idx is None:
247
+ logger.warning_once(
248
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
249
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
250
+ "when creating this class."
251
+ )
252
+
253
+ self.attention_dropout = config.attention_dropout
254
+ self.hidden_size = config.hidden_size
255
+ self.num_heads = config.num_attention_heads
256
+ self.head_dim = self.hidden_size // self.num_heads
257
+ self.num_key_value_heads = config.num_key_value_heads
258
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
259
+ self.max_position_embeddings = config.max_position_embeddings
260
+ self.rope_theta = config.rope_theta
261
+ self.is_causal = True
262
+
263
+ if (self.head_dim * self.num_heads) != self.hidden_size:
264
+ raise ValueError(
265
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
266
+ f" and `num_heads`: {self.num_heads})."
267
+ )
268
+
269
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
270
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
271
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
272
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
273
+ self.rotary_emb = CohereRotaryEmbedding(
274
+ self.head_dim,
275
+ max_position_embeddings=self.max_position_embeddings,
276
+ base=self.rope_theta,
277
+ )
278
+
279
+ def forward(
280
+ self,
281
+ hidden_states: torch.Tensor,
282
+ attention_mask: Optional[torch.Tensor] = None,
283
+ position_ids: Optional[torch.LongTensor] = None,
284
+ past_key_value: Optional[Cache] = None,
285
+ output_attentions: bool = False,
286
+ use_cache: bool = False,
287
+ cache_position: Optional[torch.LongTensor] = None,
288
+ **kwargs,
289
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
290
+ bsz, q_len, _ = hidden_states.size()
291
+
292
+ if self.config.pretraining_tp > 1:
293
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
294
+ query_slices = self.q_proj.weight.split(
295
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
296
+ )
297
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
298
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
299
+
300
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
301
+ query_states = torch.cat(query_states, dim=-1)
302
+
303
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
304
+ key_states = torch.cat(key_states, dim=-1)
305
+
306
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
307
+ value_states = torch.cat(value_states, dim=-1)
308
+
309
+ else:
310
+ query_states = self.q_proj(hidden_states)
311
+ key_states = self.k_proj(hidden_states)
312
+ value_states = self.v_proj(hidden_states)
313
+
314
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
315
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
316
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
317
+
318
+ past_key_value = getattr(self, "past_key_value", past_key_value)
319
+ cos, sin = self.rotary_emb(value_states, position_ids)
320
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
321
+
322
+ if past_key_value is not None:
323
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
324
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
325
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
326
+
327
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
328
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
329
+
330
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
331
+
332
+ if attention_mask is not None: # no matter the length, we just slice it
333
+ causal_mask = attention_mask
334
+ if cache_position is not None:
335
+ causal_mask = attention_mask[:, :, cache_position, : key_states.shape[-2]]
336
+ attn_weights = attn_weights + causal_mask
337
+
338
+ # upcast attention to fp32
339
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
340
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
341
+ attn_output = torch.matmul(attn_weights, value_states)
342
+
343
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
344
+ raise ValueError(
345
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
346
+ f" {attn_output.size()}"
347
+ )
348
+
349
+ attn_output = attn_output.transpose(1, 2).contiguous()
350
+
351
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
352
+
353
+ if self.config.pretraining_tp > 1:
354
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
355
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
356
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
357
+ else:
358
+ attn_output = self.o_proj(attn_output)
359
+
360
+ if not output_attentions:
361
+ attn_weights = None
362
+
363
+ return attn_output, attn_weights, past_key_value
364
+
365
+
366
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 Llama->Cohere
367
+ class CohereFlashAttention2(Attention):
368
+ """
369
+ Cohere flash attention module. This module inherits from `Attention` as the weights of the module stays
370
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
371
+ flash attention and deal with padding tokens in case the input contains any of them.
372
+ """
373
+
374
+ def __init__(self, *args, **kwargs):
375
+ super().__init__(*args, **kwargs)
376
+
377
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
378
+ # 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.
379
+ # 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).
380
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
381
+
382
+ def forward(
383
+ self,
384
+ hidden_states: torch.Tensor,
385
+ attention_mask: Optional[torch.LongTensor] = None,
386
+ position_ids: Optional[torch.LongTensor] = None,
387
+ past_key_value: Optional[Cache] = None,
388
+ output_attentions: bool = False,
389
+ use_cache: bool = False,
390
+ cache_position: Optional[torch.LongTensor] = None,
391
+ **kwargs,
392
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
393
+ output_attentions = False
394
+
395
+ bsz, q_len, _ = hidden_states.size()
396
+
397
+ query_states = self.q_proj(hidden_states)
398
+ key_states = self.k_proj(hidden_states)
399
+ value_states = self.v_proj(hidden_states)
400
+
401
+ # Flash attention requires the input to have the shape
402
+ # batch_size x seq_length x head_dim x hidden_dim
403
+ # therefore we just need to keep the original shape
404
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
405
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
406
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
407
+
408
+ cos, sin = self.rotary_emb(value_states, position_ids)
409
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
410
+
411
+ past_key_value = getattr(self, "past_key_value", past_key_value)
412
+
413
+ if past_key_value is not None:
414
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
415
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
416
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
417
+
418
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
419
+ # to be able to avoid many of these transpose/reshape/view.
420
+ query_states = query_states.transpose(1, 2)
421
+ key_states = key_states.transpose(1, 2)
422
+ value_states = value_states.transpose(1, 2)
423
+
424
+ dropout_rate = self.attention_dropout if self.training else 0.0
425
+
426
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
427
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
428
+ # cast them back in the correct dtype just to be sure everything works as expected.
429
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
430
+ # in fp32.
431
+
432
+ input_dtype = query_states.dtype
433
+ if input_dtype == torch.float32:
434
+ if torch.is_autocast_enabled():
435
+ target_dtype = torch.get_autocast_gpu_dtype()
436
+ # Handle the case where the model is quantized
437
+ elif hasattr(self.config, "_pre_quantization_dtype"):
438
+ target_dtype = self.config._pre_quantization_dtype
439
+ else:
440
+ target_dtype = self.q_proj.weight.dtype
441
+
442
+ logger.warning_once(
443
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
444
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
445
+ f" {target_dtype}."
446
+ )
447
+
448
+ query_states = query_states.to(target_dtype)
449
+ key_states = key_states.to(target_dtype)
450
+ value_states = value_states.to(target_dtype)
451
+
452
+ attn_output = self._flash_attention_forward(
453
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
454
+ )
455
+
456
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
457
+ attn_output = self.o_proj(attn_output)
458
+
459
+ if not output_attentions:
460
+ attn_weights = None
461
+
462
+ return attn_output, attn_weights, past_key_value
463
+
464
+ def _flash_attention_forward(
465
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
466
+ ):
467
+ """
468
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
469
+ first unpad the input, then computes the attention scores and pad the final attention scores.
470
+
471
+ Args:
472
+ query_states (`torch.Tensor`):
473
+ Input query states to be passed to Flash Attention API
474
+ key_states (`torch.Tensor`):
475
+ Input key states to be passed to Flash Attention API
476
+ value_states (`torch.Tensor`):
477
+ Input value states to be passed to Flash Attention API
478
+ attention_mask (`torch.Tensor`):
479
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
480
+ position of padding tokens and 1 for the position of non-padding tokens.
481
+ dropout (`int`, *optional*):
482
+ Attention dropout
483
+ softmax_scale (`float`, *optional*):
484
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
485
+ """
486
+ if not self._flash_attn_uses_top_left_mask:
487
+ causal = self.is_causal
488
+ else:
489
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in CohereFlashAttention2 __init__.
490
+ causal = self.is_causal and query_length != 1
491
+
492
+ # Contains at least one padding token in the sequence
493
+ if attention_mask is not None:
494
+ batch_size = query_states.shape[0]
495
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
496
+ query_states, key_states, value_states, attention_mask, query_length
497
+ )
498
+
499
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
500
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
501
+
502
+ attn_output_unpad = flash_attn_varlen_func(
503
+ query_states,
504
+ key_states,
505
+ value_states,
506
+ cu_seqlens_q=cu_seqlens_q,
507
+ cu_seqlens_k=cu_seqlens_k,
508
+ max_seqlen_q=max_seqlen_in_batch_q,
509
+ max_seqlen_k=max_seqlen_in_batch_k,
510
+ dropout_p=dropout,
511
+ softmax_scale=softmax_scale,
512
+ causal=causal,
513
+ )
514
+
515
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
516
+ else:
517
+ attn_output = flash_attn_func(
518
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
519
+ )
520
+
521
+ return attn_output
522
+
523
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
524
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
525
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
526
+
527
+ key_layer = index_first_axis(
528
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
529
+ )
530
+ value_layer = index_first_axis(
531
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
532
+ )
533
+ if query_length == kv_seq_len:
534
+ query_layer = index_first_axis(
535
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
536
+ )
537
+ cu_seqlens_q = cu_seqlens_k
538
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
539
+ indices_q = indices_k
540
+ elif query_length == 1:
541
+ max_seqlen_in_batch_q = 1
542
+ cu_seqlens_q = torch.arange(
543
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
544
+ ) # There is a memcpy here, that is very bad.
545
+ indices_q = cu_seqlens_q[:-1]
546
+ query_layer = query_layer.squeeze(1)
547
+ else:
548
+ # The -q_len: slice assumes left padding.
549
+ attention_mask = attention_mask[:, -query_length:]
550
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
551
+
552
+ return (
553
+ query_layer,
554
+ key_layer,
555
+ value_layer,
556
+ indices_q,
557
+ (cu_seqlens_q, cu_seqlens_k),
558
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
559
+ )
560
+
561
+
562
+ class SdpaAttention(Attention):
563
+ """
564
+ Attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
565
+ `Attention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
566
+ SDPA API.
567
+ """
568
+
569
+ # Adapted from Attention.forward
570
+ def forward(
571
+ self,
572
+ hidden_states: torch.Tensor,
573
+ attention_mask: Optional[torch.Tensor] = None,
574
+ position_ids: Optional[torch.LongTensor] = None,
575
+ past_key_value: Optional[Cache] = None,
576
+ output_attentions: bool = False,
577
+ use_cache: bool = False,
578
+ cache_position: Optional[torch.LongTensor] = None,
579
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
580
+ if output_attentions:
581
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
582
+ logger.warning_once(
583
+ "CohereModel is using SdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
584
+ '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.'
585
+ )
586
+ return super().forward(
587
+ hidden_states=hidden_states,
588
+ attention_mask=attention_mask,
589
+ position_ids=position_ids,
590
+ past_key_value=past_key_value,
591
+ output_attentions=output_attentions,
592
+ use_cache=use_cache,
593
+ cache_position=cache_position,
594
+ )
595
+
596
+ bsz, q_len, _ = hidden_states.size()
597
+
598
+ query_states = self.q_proj(hidden_states)
599
+ key_states = self.k_proj(hidden_states)
600
+ value_states = self.v_proj(hidden_states)
601
+
602
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
603
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
604
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
605
+
606
+ cos, sin = self.rotary_emb(value_states, position_ids)
607
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
608
+
609
+ # In case static cache is used, it is an instance attribute.
610
+ past_key_value = getattr(self, "past_key_value", past_key_value)
611
+
612
+ if past_key_value is not None:
613
+ # sin and cos are specific to RoPE models; position_ids needed for the static cache
614
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
615
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
616
+
617
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
618
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
619
+
620
+ causal_mask = attention_mask
621
+ if attention_mask is not None and cache_position is not None:
622
+ causal_mask = causal_mask[:, :, cache_position, : key_states.shape[-2]]
623
+
624
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
625
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
626
+ if query_states.device.type == "cuda" and causal_mask is not None:
627
+ query_states = query_states.contiguous()
628
+ key_states = key_states.contiguous()
629
+ value_states = value_states.contiguous()
630
+
631
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
632
+ query_states,
633
+ key_states,
634
+ value_states,
635
+ attn_mask=causal_mask,
636
+ dropout_p=self.attention_dropout if self.training else 0.0,
637
+ )
638
+
639
+ attn_output = attn_output.transpose(1, 2).contiguous()
640
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
641
+
642
+ attn_output = self.o_proj(attn_output)
643
+
644
+ return attn_output, None, past_key_value
645
+
646
+
647
+ COHERE_ATTENTION_CLASSES = {
648
+ "eager": Attention,
649
+ "flash_attention_2": CohereFlashAttention2,
650
+ "sdpa": SdpaAttention,
651
+ }
652
+
653
+
654
+ class CohereDecoderLayer(nn.Module):
655
+ def __init__(self, config: CohereConfig, layer_idx: int):
656
+ super().__init__()
657
+ self.hidden_size = config.hidden_size
658
+
659
+ self.self_attn = COHERE_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
660
+
661
+ self.mlp = CohereMLP(config)
662
+ self.input_layernorm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
663
+
664
+ def forward(
665
+ self,
666
+ hidden_states: torch.Tensor,
667
+ attention_mask: Optional[torch.Tensor] = None,
668
+ position_ids: Optional[torch.LongTensor] = None,
669
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
670
+ output_attentions: Optional[bool] = False,
671
+ use_cache: Optional[bool] = False,
672
+ cache_position: Optional[torch.LongTensor] = None,
673
+ **kwargs,
674
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
675
+ """
676
+ Args:
677
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
678
+ attention_mask (`torch.FloatTensor`, *optional*):
679
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
680
+ query_sequence_length, key_sequence_length)` if default attention is used.
681
+ output_attentions (`bool`, *optional*):
682
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
683
+ returned tensors for more detail.
684
+ use_cache (`bool`, *optional*):
685
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
686
+ (see `past_key_values`).
687
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
688
+ """
689
+ if "padding_mask" in kwargs:
690
+ warnings.warn(
691
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
692
+ )
693
+
694
+ residual = hidden_states
695
+
696
+ hidden_states = self.input_layernorm(hidden_states)
697
+
698
+ # Self Attention
699
+ hidden_states_attention, self_attn_weights, present_key_value = self.self_attn(
700
+ hidden_states=hidden_states,
701
+ attention_mask=attention_mask,
702
+ position_ids=position_ids,
703
+ past_key_value=past_key_value,
704
+ output_attentions=output_attentions,
705
+ use_cache=use_cache,
706
+ cache_position=cache_position,
707
+ **kwargs,
708
+ )
709
+
710
+ # Fully Connected
711
+ hidden_states_mlp = self.mlp(hidden_states)
712
+
713
+ # Add everything together
714
+ hidden_states = residual + hidden_states_attention + hidden_states_mlp
715
+
716
+ outputs = (hidden_states,)
717
+
718
+ if output_attentions:
719
+ outputs += (self_attn_weights,)
720
+
721
+ if use_cache:
722
+ outputs += (present_key_value,)
723
+
724
+ return outputs
725
+
726
+
727
+ COHERE_START_DOCSTRING = r"""
728
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
729
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
730
+ etc.)
731
+
732
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
733
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
734
+ and behavior.
735
+
736
+ Parameters:
737
+ config ([`CohereConfig`]):
738
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
739
+ load the weights associated with the model, only the configuration. Check out the
740
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
741
+ """
742
+
743
+
744
+ @add_start_docstrings(
745
+ "The bare Cohere Model outputting raw hidden-states without any specific head on top.",
746
+ COHERE_START_DOCSTRING,
747
+ )
748
+ class CoherePreTrainedModel(PreTrainedModel):
749
+ config_class = CohereConfig
750
+ base_model_prefix = "model"
751
+ supports_gradient_checkpointing = True
752
+ _no_split_modules = ["CohereDecoderLayer"]
753
+ _skip_keys_device_placement = ["past_key_values", "causal_mask"]
754
+ _supports_flash_attn_2 = True
755
+ _supports_sdpa = True
756
+ _supports_cache_class = True
757
+
758
+ def _init_weights(self, module):
759
+ std = self.config.initializer_range
760
+ if isinstance(module, nn.Linear):
761
+ module.weight.data.normal_(mean=0.0, std=std)
762
+ if module.bias is not None:
763
+ module.bias.data.zero_()
764
+ elif isinstance(module, nn.Embedding):
765
+ module.weight.data.normal_(mean=0.0, std=std)
766
+ if module.padding_idx is not None:
767
+ module.weight.data[module.padding_idx].zero_()
768
+
769
+ def _setup_cache(self, cache_cls, max_batch_size, max_cache_len: Optional[int] = None):
770
+ if self.config._attn_implementation == "flash_attention_2" and cache_cls == StaticCache:
771
+ raise ValueError(
772
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
773
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
774
+ )
775
+
776
+ if max_cache_len > self.model.causal_mask.shape[-1] or self.device != self.model.causal_mask.device:
777
+ causal_mask = torch.full(
778
+ (max_cache_len, max_cache_len), fill_value=True, device=self.device, dtype=torch.bool
779
+ )
780
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
781
+
782
+ for layer in self.model.layers:
783
+ device = layer.input_layernorm.weight.device
784
+ if hasattr(self.config, "_pre_quantization_dtype"):
785
+ dtype = self.config._pre_quantization_dtype
786
+ else:
787
+ dtype = layer.self_attn.o_proj.weight.dtype
788
+ layer.self_attn.past_key_value = cache_cls(
789
+ self.config, max_batch_size, max_cache_len, device=device, dtype=dtype
790
+ )
791
+
792
+ def _reset_cache(self):
793
+ for layer in self.model.layers:
794
+ layer.self_attn.past_key_value = None
795
+
796
+
797
+ COHERE_INPUTS_DOCSTRING = r"""
798
+ Args:
799
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
800
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
801
+ it.
802
+
803
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
804
+ [`PreTrainedTokenizer.__call__`] for details.
805
+
806
+ [What are input IDs?](../glossary#input-ids)
807
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
808
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
809
+
810
+ - 1 for tokens that are **not masked**,
811
+ - 0 for tokens that are **masked**.
812
+
813
+ [What are attention masks?](../glossary#attention-mask)
814
+
815
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
816
+ [`PreTrainedTokenizer.__call__`] for details.
817
+
818
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
819
+ `past_key_values`).
820
+
821
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
822
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
823
+ information on the default strategy.
824
+
825
+ - 1 indicates the head is **not masked**,
826
+ - 0 indicates the head is **masked**.
827
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
828
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
829
+ config.n_positions - 1]`.
830
+
831
+ [What are position IDs?](../glossary#position-ids)
832
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
833
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
834
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
835
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
836
+
837
+ Two formats are allowed:
838
+ - a [`~cache_utils.Cache`] instance;
839
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
840
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
841
+ cache format.
842
+
843
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
844
+ legacy cache format will be returned.
845
+
846
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
847
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
848
+ of shape `(batch_size, sequence_length)`.
849
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
850
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
851
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
852
+ model's internal embedding lookup matrix.
853
+ use_cache (`bool`, *optional*):
854
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
855
+ `past_key_values`).
856
+ output_attentions (`bool`, *optional*):
857
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
858
+ tensors for more detail.
859
+ output_hidden_states (`bool`, *optional*):
860
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
861
+ more detail.
862
+ return_dict (`bool`, *optional*):
863
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
864
+ """
865
+
866
+
867
+ @add_start_docstrings(
868
+ "The bare Cohere Model outputting raw hidden-states without any specific head on top.",
869
+ COHERE_START_DOCSTRING,
870
+ )
871
+ class CohereModel(CoherePreTrainedModel):
872
+ """
873
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`CohereDecoderLayer`]
874
+
875
+ Args:
876
+ config: CohereConfig
877
+ """
878
+
879
+ def __init__(self, config: CohereConfig):
880
+ super().__init__(config)
881
+ self.padding_idx = config.pad_token_id
882
+ self.vocab_size = config.vocab_size
883
+
884
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
885
+ self.layers = nn.ModuleList(
886
+ [CohereDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
887
+ )
888
+ self.norm = LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
889
+ self.gradient_checkpointing = False
890
+
891
+ # Register a causal mask to separate causal and padding mask creation. Merging happens in the attention class.
892
+ # NOTE: This is not friendly with TorchScript, ONNX, ExportedProgram serialization for very large `max_position_embeddings`.
893
+ causal_mask = torch.full(
894
+ (config.max_position_embeddings, config.max_position_embeddings), fill_value=True, dtype=torch.bool
895
+ )
896
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
897
+ # Initialize weights and apply final processing
898
+ self.post_init()
899
+
900
+ def get_input_embeddings(self):
901
+ return self.embed_tokens
902
+
903
+ def set_input_embeddings(self, value):
904
+ self.embed_tokens = value
905
+
906
+ @add_start_docstrings_to_model_forward(COHERE_INPUTS_DOCSTRING)
907
+ def forward(
908
+ self,
909
+ input_ids: torch.LongTensor = None,
910
+ attention_mask: Optional[torch.Tensor] = None,
911
+ position_ids: Optional[torch.LongTensor] = None,
912
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
913
+ inputs_embeds: Optional[torch.FloatTensor] = None,
914
+ use_cache: Optional[bool] = None,
915
+ output_attentions: Optional[bool] = None,
916
+ output_hidden_states: Optional[bool] = None,
917
+ return_dict: Optional[bool] = None,
918
+ cache_position: Optional[torch.LongTensor] = None,
919
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
920
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
921
+ output_hidden_states = (
922
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
923
+ )
924
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
925
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
926
+
927
+ if (input_ids is None) ^ (inputs_embeds is not None):
928
+ raise ValueError(
929
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
930
+ )
931
+
932
+ if self.gradient_checkpointing and self.training and use_cache:
933
+ logger.warning_once(
934
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
935
+ )
936
+ use_cache = False
937
+
938
+ if inputs_embeds is None:
939
+ inputs_embeds = self.embed_tokens(input_ids)
940
+
941
+ past_seen_tokens = 0
942
+ if use_cache: # kept for BC (cache positions)
943
+ if not isinstance(past_key_values, StaticCache):
944
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
945
+ past_seen_tokens = past_key_values.get_seq_length()
946
+
947
+ if cache_position is None:
948
+ if isinstance(past_key_values, StaticCache):
949
+ raise ValueError("cache_position is a required argument when using StaticCache.")
950
+ cache_position = torch.arange(
951
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
952
+ )
953
+
954
+ if position_ids is None:
955
+ position_ids = cache_position.unsqueeze(0)
956
+
957
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds)
958
+
959
+ # embed positions
960
+ hidden_states = inputs_embeds
961
+
962
+ # decoder layers
963
+ all_hidden_states = () if output_hidden_states else None
964
+ all_self_attns = () if output_attentions else None
965
+ next_decoder_cache = None
966
+
967
+ for decoder_layer in self.layers:
968
+ if output_hidden_states:
969
+ all_hidden_states += (hidden_states,)
970
+
971
+ if self.gradient_checkpointing and self.training:
972
+ layer_outputs = self._gradient_checkpointing_func(
973
+ decoder_layer.__call__,
974
+ hidden_states,
975
+ causal_mask,
976
+ position_ids,
977
+ past_key_values,
978
+ output_attentions,
979
+ use_cache,
980
+ cache_position,
981
+ )
982
+ else:
983
+ layer_outputs = decoder_layer(
984
+ hidden_states,
985
+ attention_mask=causal_mask,
986
+ position_ids=position_ids,
987
+ past_key_value=past_key_values,
988
+ output_attentions=output_attentions,
989
+ use_cache=use_cache,
990
+ cache_position=cache_position,
991
+ )
992
+
993
+ hidden_states = layer_outputs[0]
994
+
995
+ if use_cache:
996
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
997
+
998
+ if output_attentions:
999
+ all_self_attns += (layer_outputs[1],)
1000
+
1001
+ hidden_states = self.norm(hidden_states)
1002
+
1003
+ # add hidden states from the last decoder layer
1004
+ if output_hidden_states:
1005
+ all_hidden_states += (hidden_states,)
1006
+
1007
+ next_cache = None
1008
+ if use_cache:
1009
+ next_cache = (
1010
+ next_decoder_cache.to_legacy_cache() if isinstance(next_decoder_cache, Cache) else next_decoder_cache
1011
+ )
1012
+ if not return_dict:
1013
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1014
+ return BaseModelOutputWithPast(
1015
+ last_hidden_state=hidden_states,
1016
+ past_key_values=next_cache,
1017
+ hidden_states=all_hidden_states,
1018
+ attentions=all_self_attns,
1019
+ )
1020
+
1021
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1022
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1023
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1024
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1025
+ def _update_causal_mask(self, attention_mask, input_tensor):
1026
+ if self.config._attn_implementation == "flash_attention_2":
1027
+ if attention_mask is not None and 0.0 in attention_mask:
1028
+ return attention_mask
1029
+ return None
1030
+
1031
+ batch_size, seq_length = input_tensor.shape[:2]
1032
+ dtype = input_tensor.dtype
1033
+ device = input_tensor.device
1034
+
1035
+ # support going beyond cached `max_position_embedding`
1036
+ if seq_length > self.causal_mask.shape[-1]:
1037
+ causal_mask = torch.full((2 * self.causal_mask.shape[-1], 2 * self.causal_mask.shape[-1]), fill_value=1)
1038
+ self.register_buffer("causal_mask", torch.triu(causal_mask, diagonal=1), persistent=False)
1039
+
1040
+ # We use the current dtype to avoid any overflows
1041
+ min_dtype = torch.finfo(dtype).min
1042
+ causal_mask = self.causal_mask[None, None, :, :].to(dtype=dtype, device=device) * min_dtype
1043
+ causal_mask = causal_mask.expand(batch_size, 1, -1, -1)
1044
+ if attention_mask is not None and attention_mask.dim() == 2:
1045
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1046
+ mask_length = attention_mask.shape[-1]
1047
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1048
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1049
+
1050
+ if (
1051
+ self.config._attn_implementation == "sdpa"
1052
+ and attention_mask is not None
1053
+ and attention_mask.device.type == "cuda"
1054
+ ):
1055
+ # TODO: For dynamo, rather use a check on fullgraph=True once this is possible (https://github.com/pytorch/pytorch/pull/120400).
1056
+ is_tracing = (
1057
+ torch.jit.is_tracing()
1058
+ or isinstance(input_tensor, torch.fx.Proxy)
1059
+ or (hasattr(torch, "_dynamo") and torch._dynamo.is_compiling())
1060
+ )
1061
+ if not is_tracing and torch.any(attention_mask != 1):
1062
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1063
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1064
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1065
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1066
+
1067
+ return causal_mask
1068
+
1069
+
1070
+ class CohereForCausalLM(CoherePreTrainedModel):
1071
+ _tied_weights_keys = ["model.embed_tokens.weight", "lm_head.weight"]
1072
+
1073
+ def __init__(self, config):
1074
+ super().__init__(config)
1075
+ self.model = CohereModel(config)
1076
+ self.vocab_size = config.vocab_size
1077
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1078
+ self.logit_scale = config.logit_scale
1079
+ # Initialize weights and apply final processing
1080
+ self.post_init()
1081
+
1082
+ def get_input_embeddings(self):
1083
+ return self.model.embed_tokens
1084
+
1085
+ def set_input_embeddings(self, value):
1086
+ self.model.embed_tokens = value
1087
+
1088
+ def get_output_embeddings(self):
1089
+ return self.lm_head
1090
+
1091
+ def set_output_embeddings(self, new_embeddings):
1092
+ self.lm_head = new_embeddings
1093
+
1094
+ def set_decoder(self, decoder):
1095
+ self.model = decoder
1096
+
1097
+ def get_decoder(self):
1098
+ return self.model
1099
+
1100
+ @add_start_docstrings_to_model_forward(COHERE_INPUTS_DOCSTRING)
1101
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1102
+ def forward(
1103
+ self,
1104
+ input_ids: torch.LongTensor = None,
1105
+ attention_mask: Optional[torch.Tensor] = None,
1106
+ position_ids: Optional[torch.LongTensor] = None,
1107
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1108
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1109
+ labels: Optional[torch.LongTensor] = None,
1110
+ use_cache: Optional[bool] = None,
1111
+ output_attentions: Optional[bool] = None,
1112
+ output_hidden_states: Optional[bool] = None,
1113
+ return_dict: Optional[bool] = None,
1114
+ cache_position: Optional[torch.LongTensor] = None,
1115
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1116
+ r"""
1117
+ Args:
1118
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1119
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1120
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1121
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1122
+
1123
+ Returns:
1124
+
1125
+ Example:
1126
+
1127
+ ```python
1128
+ >>> from transformers import AutoTokenizer, CohereForCausalLM
1129
+
1130
+ #TODO: Model name needs to be updated
1131
+ >>> model = CohereForCausalLM.from_pretrained("CohereForAI/Cohere-model")
1132
+ >>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/Cohere-model")
1133
+
1134
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1135
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1136
+
1137
+ >>> # Generate
1138
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1139
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1140
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1141
+ ```"""
1142
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1143
+ output_hidden_states = (
1144
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1145
+ )
1146
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1147
+
1148
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1149
+ outputs = self.model(
1150
+ input_ids=input_ids,
1151
+ attention_mask=attention_mask,
1152
+ position_ids=position_ids,
1153
+ past_key_values=past_key_values,
1154
+ inputs_embeds=inputs_embeds,
1155
+ use_cache=use_cache,
1156
+ output_attentions=output_attentions,
1157
+ output_hidden_states=output_hidden_states,
1158
+ return_dict=return_dict,
1159
+ cache_position=cache_position,
1160
+ )
1161
+
1162
+ hidden_states = outputs[0]
1163
+ if self.config.pretraining_tp > 1:
1164
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1165
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1166
+ logits = torch.cat(logits, dim=-1)
1167
+ else:
1168
+ logits = self.lm_head(hidden_states)
1169
+ logits = logits * self.logit_scale
1170
+ logits = logits.float()
1171
+
1172
+ loss = None
1173
+ if labels is not None:
1174
+ # Shift so that tokens < n predict n
1175
+ shift_logits = logits[..., :-1, :].contiguous()
1176
+ shift_labels = labels[..., 1:].contiguous()
1177
+ # Flatten the tokens
1178
+ loss_fct = CrossEntropyLoss()
1179
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1180
+ shift_labels = shift_labels.view(-1)
1181
+ # Enable model parallelism
1182
+ shift_labels = shift_labels.to(shift_logits.device)
1183
+ loss = loss_fct(shift_logits, shift_labels)
1184
+
1185
+ if not return_dict:
1186
+ output = (logits,) + outputs[1:]
1187
+ return (loss,) + output if loss is not None else output
1188
+
1189
+ return CausalLMOutputWithPast(
1190
+ loss=loss,
1191
+ logits=logits,
1192
+ past_key_values=outputs.past_key_values,
1193
+ hidden_states=outputs.hidden_states,
1194
+ attentions=outputs.attentions,
1195
+ )
1196
+
1197
+ def prepare_inputs_for_generation(
1198
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1199
+ ):
1200
+ past_length = 0
1201
+ if past_key_values is not None:
1202
+ if isinstance(past_key_values, Cache):
1203
+ cache_length = past_key_values.get_seq_length()
1204
+ past_length = past_key_values.seen_tokens
1205
+ max_cache_length = past_key_values.get_max_length()
1206
+ else:
1207
+ cache_length = past_length = past_key_values[0][0].shape[2]
1208
+ max_cache_length = None
1209
+
1210
+ # Keep only the unprocessed tokens:
1211
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1212
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
1213
+ # input)
1214
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1215
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1216
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1217
+ # input_ids based on the past_length.
1218
+ elif past_length < input_ids.shape[1]:
1219
+ input_ids = input_ids[:, past_length:]
1220
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1221
+
1222
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1223
+ if (
1224
+ max_cache_length is not None
1225
+ and attention_mask is not None
1226
+ and cache_length + input_ids.shape[1] > max_cache_length
1227
+ ):
1228
+ attention_mask = attention_mask[:, -max_cache_length:]
1229
+
1230
+ position_ids = kwargs.get("position_ids", None)
1231
+ if attention_mask is not None and position_ids is None:
1232
+ # create position_ids on the fly for batch generation
1233
+ position_ids = attention_mask.long().cumsum(-1) - 1
1234
+ position_ids.masked_fill_(attention_mask == 0, 1)
1235
+ if past_key_values:
1236
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1237
+
1238
+ if self.generation_config.cache_implementation == "static":
1239
+ # generation with static cache
1240
+ cache_position = kwargs.get("cache_position", None)
1241
+ if cache_position is None:
1242
+ past_length = 0
1243
+ else:
1244
+ past_length = cache_position[-1] + 1
1245
+ input_ids = input_ids[:, past_length:]
1246
+ position_ids = position_ids[:, past_length:]
1247
+
1248
+ # TODO @gante we should only keep a `cache_position` in generate, and do +=1.
1249
+ # same goes for position ids. Could also help with continued generation.
1250
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1251
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1252
+ position_ids = position_ids.contiguous() if position_ids is not None else None
1253
+
1254
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1255
+ if inputs_embeds is not None and past_key_values is None:
1256
+ model_inputs = {"inputs_embeds": inputs_embeds}
1257
+ else:
1258
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1259
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1260
+ # TODO: use `next_tokens` directly instead.
1261
+ model_inputs = {"input_ids": input_ids.contiguous()}
1262
+
1263
+ model_inputs.update(
1264
+ {
1265
+ "position_ids": position_ids,
1266
+ "cache_position": cache_position,
1267
+ "past_key_values": past_key_values,
1268
+ "use_cache": kwargs.get("use_cache"),
1269
+ "attention_mask": attention_mask,
1270
+ }
1271
+ )
1272
+ return model_inputs
1273
+
1274
+ @staticmethod
1275
+ def _reorder_cache(past_key_values, beam_idx):
1276
+ reordered_past = ()
1277
+ for layer_past in past_key_values:
1278
+ reordered_past += (
1279
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1280
+ )
1281
+ return reordered_past
1282
+
1283
+
1284
+ # register models as AutoModel and AutoModelForCausalLM
1285
+ AutoModel.register(CohereConfig, CohereModel)
1286
+ AutoModelForCausalLM.register(CohereConfig, CohereForCausalLM)