regisss commited on
Commit
5aaa188
1 Parent(s): 2871a70

Push fused QKV checkpoint and config

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