Upload 13 files
Browse files- README.md +91 -0
- config.json +37 -0
- generation_config.json +9 -0
- model-00000-of-00005.safetensors +3 -0
- model-00001-of-00005.safetensors +3 -0
- model-00002-of-00005.safetensors +3 -0
- model-00003-of-00005.safetensors +3 -0
- model-00004-of-00005.safetensors +3 -0
- model.safetensors.index.json +290 -0
- modeling_llama.py +1255 -0
- tiktoken_tokenizer.py +160 -0
- tokenizer.tiktoken +0 -0
- tokenizer_config.json +12 -0
README.md
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language:
|
3 |
+
- en
|
4 |
+
- zh
|
5 |
+
library_name: transformers
|
6 |
+
tags:
|
7 |
+
- Long Context
|
8 |
+
- chatglm
|
9 |
+
- llama
|
10 |
+
datasets:
|
11 |
+
- THUDM/LongReward-10k
|
12 |
+
pipeline_tag: text-generation
|
13 |
+
---
|
14 |
+
# LongReward-llama3.1-8b-SFT
|
15 |
+
|
16 |
+
|
17 |
+
<p align="center">
|
18 |
+
🤗 <a href="https://huggingface.co/datasets/THUDM/LongReward-10k" target="_blank">[LongReward Dataset] </a> • 💻 <a href="https://github.com/THUDM/LongReward" target="_blank">[Github Repo]</a> • 📃 <a href="https://arxiv.org/abs/" target="_blank">[LongReward Paper]</a>
|
19 |
+
</p>
|
20 |
+
|
21 |
+
LongReward-llama3.1-8b-SFT is supervisedly fined-tuned from [Meta-Llama-3.1-8B](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B) using the `sft` split of [LongReward-10k](https://huggingface.co/datasets/THUDM/LongReward-45) dataset, and supports a maximum context window of up to 64K tokens.
|
22 |
+
|
23 |
+
Environment: `transforemrs>=4.43.0`.
|
24 |
+
|
25 |
+
A simple demo for deployment of the model:
|
26 |
+
```python
|
27 |
+
import torch
|
28 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
29 |
+
|
30 |
+
model_path = "THUDM/LongReward-llama3.1-8b-SFT"
|
31 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
32 |
+
model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch.bfloat16, trust_remote_code=True, device_map='auto')
|
33 |
+
context = '''
|
34 |
+
W. Russell Todd, 94, United States Army general (b. 1928). February 13. Tim Aymar, 59, heavy metal singer (Pharaoh) (b. 1963). Marshall \"Eddie\" Conway, 76, Black Panther Party leader (b. 1946). Roger Bonk, 78, football player (North Dakota Fighting Sioux, Winnipeg Blue Bombers) (b. 1944). Conrad Dobler, 72, football player (St. Louis Cardinals, New Orleans Saints, Buffalo Bills) (b. 1950). Brian DuBois, 55, baseball player (Detroit Tigers) (b. 1967). Robert Geddes, 99, architect, dean of the Princeton University School of Architecture (1965–1982) (b. 1923). Tom Luddy, 79, film producer (Barfly, The Secret Garden), co-founder of the Telluride Film Festival (b. 1943). David Singmaster, 84, mathematician (b. 1938).
|
35 |
+
'''
|
36 |
+
query = "What was Robert Geddes' profession?"
|
37 |
+
prompt = context + '\n\n' + query
|
38 |
+
response, _ = model.chat(tokenizer, prompt, temprature=1, max_new_tokens=1024)
|
39 |
+
print(response)
|
40 |
+
```
|
41 |
+
|
42 |
+
You can also deploy the model with [vllm](https://github.com/vllm-project/vllm) for faster inference:
|
43 |
+
```python
|
44 |
+
import torch
|
45 |
+
from vllm import LLM, SamplingParams
|
46 |
+
|
47 |
+
model_path = "THUDM/LongReward-llama3.1-8b-SFT"
|
48 |
+
model = LLM(
|
49 |
+
model= model_path,
|
50 |
+
dtype=torch.bfloat16,
|
51 |
+
trust_remote_code=True,
|
52 |
+
tensor_parallel_size=1,
|
53 |
+
max_model_len=65536,
|
54 |
+
gpu_memory_utilization=1,
|
55 |
+
)
|
56 |
+
tokenizer = model.get_tokenizer()
|
57 |
+
context = '''
|
58 |
+
W. Russell Todd, 94, United States Army general (b. 1928). February 13. Tim Aymar, 59, heavy metal singer (Pharaoh) (b. 1963). Marshall \"Eddie\" Conway, 76, Black Panther Party leader (b. 1946). Roger Bonk, 78, football player (North Dakota Fighting Sioux, Winnipeg Blue Bombers) (b. 1944). Conrad Dobler, 72, football player (St. Louis Cardinals, New Orleans Saints, Buffalo Bills) (b. 1950). Brian DuBois, 55, baseball player (Detroit Tigers) (b. 1967). Robert Geddes, 99, architect, dean of the Princeton University School of Architecture (1965–1982) (b. 1923). Tom Luddy, 79, film producer (Barfly, The Secret Garden), co-founder of the Telluride Film Festival (b. 1943). David Singmaster, 84, mathematician (b. 1938).
|
59 |
+
'''
|
60 |
+
query = "What was Robert Geddes' profession?"
|
61 |
+
prompt = context + '\n\n' + query
|
62 |
+
inputs = tokenizer.build_chat_input(prompt, history=[], role='user')
|
63 |
+
eos_token_id = [tokenizer.eos_token_id, tokenizer.get_command("<|user|>"), tokenizer.get_command("<|observation|>")]
|
64 |
+
generation_params = SamplingParams(
|
65 |
+
temperature=0.95,
|
66 |
+
top_p=0.7,
|
67 |
+
max_tokens=1024,
|
68 |
+
stop_token_ids=eos_token_id,
|
69 |
+
)
|
70 |
+
input_ids = inputs.input_ids[0].tolist()
|
71 |
+
outputs = model.generate(sampling_params=generation_params, prompt_token_ids=[input_ids])
|
72 |
+
response = tokenizer.decode(outputs[0].outputs[0].token_ids[:-1])
|
73 |
+
print(response)
|
74 |
+
```
|
75 |
+
|
76 |
+
## License
|
77 |
+
[Llama-3.1 License](https://huggingface.co/meta-llama/Meta-Llama-3.1-8B/blob/main/LICENSE)
|
78 |
+
|
79 |
+
## Citation
|
80 |
+
|
81 |
+
If you find our work useful, please consider citing LongReward:
|
82 |
+
|
83 |
+
```
|
84 |
+
@article{zhang2024longreward,
|
85 |
+
title = {LongReward: Improving Long-context Large Language Models
|
86 |
+
with AI Feedback}
|
87 |
+
author={Jiajie Zhang and Zhongni Hou and Xin Lv and Shulin Cao and Zhenyu Hou and Yilin Niu and Lei Hou and Lei Hou and Yuxiao Dong and Ling Feng and Juanzi Li},
|
88 |
+
journal={arXiv preprint arXiv:},
|
89 |
+
year={2024}
|
90 |
+
}
|
91 |
+
```
|
config.json
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"LlamaForCausalLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM"
|
7 |
+
},
|
8 |
+
"attention_bias": false,
|
9 |
+
"attention_dropout": 0.0,
|
10 |
+
"bos_token_id": 128000,
|
11 |
+
"eos_token_id": 128001,
|
12 |
+
"hidden_act": "silu",
|
13 |
+
"hidden_size": 4096,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 14336,
|
16 |
+
"max_position_embeddings": 65536,
|
17 |
+
"mlp_bias": false,
|
18 |
+
"model_type": "llama",
|
19 |
+
"num_attention_heads": 32,
|
20 |
+
"num_hidden_layers": 32,
|
21 |
+
"num_key_value_heads": 8,
|
22 |
+
"pretraining_tp": 1,
|
23 |
+
"rms_norm_eps": 1e-05,
|
24 |
+
"rope_scaling": {
|
25 |
+
"factor": 8.0,
|
26 |
+
"low_freq_factor": 1.0,
|
27 |
+
"high_freq_factor": 4.0,
|
28 |
+
"original_max_position_embeddings": 8192,
|
29 |
+
"rope_type": "llama3"
|
30 |
+
},
|
31 |
+
"rope_theta": 500000.0,
|
32 |
+
"tie_word_embeddings": false,
|
33 |
+
"torch_dtype": "bfloat16",
|
34 |
+
"transformers_version": "4.43.0.dev0",
|
35 |
+
"use_cache": true,
|
36 |
+
"vocab_size": 128256
|
37 |
+
}
|
generation_config.json
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"do_sample": true,
|
3 |
+
"temperature": 0.6,
|
4 |
+
"top_p": 0.9,
|
5 |
+
"_from_model_config": true,
|
6 |
+
"bos_token_id": 128000,
|
7 |
+
"eos_token_id": 128001,
|
8 |
+
"transformers_version": "4.43.0.dev0"
|
9 |
+
}
|
model-00000-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ff4c8ea839805cc9f7aeb57c4832525fdc04a8f56bb34dff28f7004987fd6de5
|
3 |
+
size 4079226064
|
model-00001-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:c8a0597aa5b9fa44d01c89e31a51f095e144eec1da7cd15ae2392b5a6b4a65f6
|
3 |
+
size 4079226136
|
model-00002-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5f01577fffd10041270665020ac02bd038202cc57a4437ad1e8998c7720b28a4
|
3 |
+
size 4079226136
|
model-00003-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e925cb1224b1c4cd1e70451be4953d741f3007b62ec80843f6135ae115efb295
|
3 |
+
size 4079226136
|
model-00004-of-00005.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d80b9b3c8b19a3605f8991d050a6f1acb4c83d9185fc22dc49339093997c44a6
|
3 |
+
size 2483036544
|
model.safetensors.index.json
ADDED
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 16060522496
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"transformer.encoder.layers.0.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
7 |
+
"transformer.encoder.layers.0.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
8 |
+
"transformer.encoder.layers.0.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
9 |
+
"transformer.encoder.layers.0.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
10 |
+
"transformer.encoder.layers.0.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
11 |
+
"transformer.encoder.layers.0.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
12 |
+
"transformer.encoder.layers.0.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
13 |
+
"transformer.encoder.layers.2.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
14 |
+
"transformer.encoder.layers.2.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
15 |
+
"transformer.encoder.layers.2.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
16 |
+
"transformer.encoder.layers.2.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
17 |
+
"transformer.encoder.layers.2.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
18 |
+
"transformer.encoder.layers.2.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
19 |
+
"transformer.encoder.layers.2.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
20 |
+
"transformer.encoder.layers.10.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
21 |
+
"transformer.encoder.layers.10.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
22 |
+
"transformer.encoder.layers.10.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
23 |
+
"transformer.encoder.layers.10.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
24 |
+
"transformer.encoder.layers.10.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
25 |
+
"transformer.encoder.layers.10.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
26 |
+
"transformer.encoder.layers.10.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors",
|
27 |
+
"transformer.encoder.layers.14.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
28 |
+
"transformer.encoder.layers.14.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
29 |
+
"transformer.encoder.layers.14.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
30 |
+
"transformer.encoder.layers.14.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
31 |
+
"transformer.encoder.layers.14.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
32 |
+
"transformer.encoder.layers.14.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
33 |
+
"transformer.encoder.layers.14.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors",
|
34 |
+
"transformer.encoder.layers.32.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
35 |
+
"transformer.encoder.layers.32.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
36 |
+
"transformer.encoder.layers.32.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
37 |
+
"transformer.encoder.layers.32.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
38 |
+
"transformer.encoder.layers.32.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
39 |
+
"transformer.encoder.layers.32.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
40 |
+
"transformer.encoder.layers.32.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
41 |
+
"transformer.encoder.layers.27.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
42 |
+
"transformer.encoder.layers.27.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
43 |
+
"transformer.encoder.layers.27.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
44 |
+
"transformer.encoder.layers.27.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
45 |
+
"transformer.encoder.layers.27.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
46 |
+
"transformer.encoder.layers.27.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
47 |
+
"transformer.encoder.layers.27.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
48 |
+
"transformer.encoder.layers.25.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
49 |
+
"transformer.encoder.layers.25.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
50 |
+
"transformer.encoder.layers.25.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
51 |
+
"transformer.encoder.layers.25.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
52 |
+
"transformer.encoder.layers.25.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
53 |
+
"transformer.encoder.layers.25.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
54 |
+
"transformer.encoder.layers.25.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
55 |
+
"transformer.encoder.layers.20.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
56 |
+
"transformer.encoder.layers.20.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
57 |
+
"transformer.encoder.layers.20.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
58 |
+
"transformer.encoder.layers.20.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
59 |
+
"transformer.encoder.layers.20.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
60 |
+
"transformer.encoder.layers.20.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
61 |
+
"transformer.encoder.layers.20.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
62 |
+
"transformer.encoder.layers.7.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
63 |
+
"transformer.encoder.layers.7.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
64 |
+
"transformer.encoder.layers.7.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
65 |
+
"transformer.encoder.layers.7.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
66 |
+
"transformer.encoder.layers.7.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
67 |
+
"transformer.encoder.layers.7.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
68 |
+
"transformer.encoder.layers.7.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
69 |
+
"transformer.encoder.layers.36.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
70 |
+
"transformer.encoder.layers.36.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
71 |
+
"transformer.encoder.layers.36.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
72 |
+
"transformer.encoder.layers.36.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
73 |
+
"transformer.encoder.layers.36.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
74 |
+
"transformer.encoder.layers.36.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
75 |
+
"transformer.encoder.layers.36.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
76 |
+
"transformer.encoder.layers.1.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
77 |
+
"transformer.encoder.layers.1.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
78 |
+
"transformer.encoder.layers.1.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
79 |
+
"transformer.encoder.layers.1.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
80 |
+
"transformer.encoder.layers.1.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
81 |
+
"transformer.encoder.layers.1.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
82 |
+
"transformer.encoder.layers.1.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
83 |
+
"transformer.encoder.layers.38.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
84 |
+
"transformer.encoder.layers.38.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
85 |
+
"transformer.encoder.layers.38.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
86 |
+
"transformer.encoder.layers.38.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
87 |
+
"transformer.encoder.layers.38.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
88 |
+
"transformer.encoder.layers.38.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
89 |
+
"transformer.encoder.layers.38.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
90 |
+
"transformer.encoder.layers.28.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
91 |
+
"transformer.encoder.layers.28.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
92 |
+
"transformer.encoder.layers.28.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
93 |
+
"transformer.encoder.layers.28.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
94 |
+
"transformer.encoder.layers.28.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
95 |
+
"transformer.encoder.layers.28.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
96 |
+
"transformer.encoder.layers.28.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
97 |
+
"transformer.encoder.layers.39.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
98 |
+
"transformer.encoder.layers.39.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
99 |
+
"transformer.encoder.layers.39.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
100 |
+
"transformer.encoder.layers.39.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
101 |
+
"transformer.encoder.layers.39.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
102 |
+
"transformer.encoder.layers.39.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
103 |
+
"transformer.encoder.layers.39.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
104 |
+
"transformer.encoder.layers.24.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
105 |
+
"transformer.encoder.layers.24.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
106 |
+
"transformer.encoder.layers.24.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
107 |
+
"transformer.encoder.layers.24.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
108 |
+
"transformer.encoder.layers.24.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
109 |
+
"transformer.encoder.layers.24.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
110 |
+
"transformer.encoder.layers.24.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
111 |
+
"transformer.encoder.layers.9.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
112 |
+
"transformer.encoder.layers.9.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
113 |
+
"transformer.encoder.layers.9.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
114 |
+
"transformer.encoder.layers.9.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
115 |
+
"transformer.encoder.layers.9.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
116 |
+
"transformer.encoder.layers.9.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
117 |
+
"transformer.encoder.layers.9.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
118 |
+
"transformer.encoder.layers.34.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
119 |
+
"transformer.encoder.layers.34.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
120 |
+
"transformer.encoder.layers.34.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
121 |
+
"transformer.encoder.layers.34.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
122 |
+
"transformer.encoder.layers.34.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
123 |
+
"transformer.encoder.layers.34.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
124 |
+
"transformer.encoder.layers.34.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
125 |
+
"transformer.encoder.layers.26.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
126 |
+
"transformer.encoder.layers.26.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
127 |
+
"transformer.encoder.layers.26.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
128 |
+
"transformer.encoder.layers.26.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
129 |
+
"transformer.encoder.layers.26.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
130 |
+
"transformer.encoder.layers.26.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
131 |
+
"transformer.encoder.layers.26.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
132 |
+
"transformer.encoder.layers.18.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
133 |
+
"transformer.encoder.layers.18.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
134 |
+
"transformer.encoder.layers.18.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
135 |
+
"transformer.encoder.layers.18.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
136 |
+
"transformer.encoder.layers.18.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
137 |
+
"transformer.encoder.layers.18.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
138 |
+
"transformer.encoder.layers.18.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors",
|
139 |
+
"transformer.encoder.layers.8.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
140 |
+
"transformer.encoder.layers.8.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
141 |
+
"transformer.encoder.layers.8.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
142 |
+
"transformer.encoder.layers.8.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
143 |
+
"transformer.encoder.layers.8.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
144 |
+
"transformer.encoder.layers.8.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
145 |
+
"transformer.encoder.layers.8.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
146 |
+
"transformer.encoder.layers.37.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
147 |
+
"transformer.encoder.layers.37.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
148 |
+
"transformer.encoder.layers.37.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
149 |
+
"transformer.encoder.layers.37.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
150 |
+
"transformer.encoder.layers.37.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
151 |
+
"transformer.encoder.layers.37.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
152 |
+
"transformer.encoder.layers.37.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
153 |
+
"transformer.encoder.layers.35.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
154 |
+
"transformer.encoder.layers.35.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
155 |
+
"transformer.encoder.layers.35.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
156 |
+
"transformer.encoder.layers.35.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
157 |
+
"transformer.encoder.layers.35.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
158 |
+
"transformer.encoder.layers.35.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
159 |
+
"transformer.encoder.layers.35.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
160 |
+
"transformer.encoder.layers.22.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
161 |
+
"transformer.encoder.layers.22.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
162 |
+
"transformer.encoder.layers.22.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
163 |
+
"transformer.encoder.layers.22.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
164 |
+
"transformer.encoder.layers.22.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
165 |
+
"transformer.encoder.layers.22.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
166 |
+
"transformer.encoder.layers.22.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
167 |
+
"transformer.encoder.layers.4.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
168 |
+
"transformer.encoder.layers.4.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
169 |
+
"transformer.encoder.layers.4.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
170 |
+
"transformer.encoder.layers.4.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
171 |
+
"transformer.encoder.layers.4.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
172 |
+
"transformer.encoder.layers.4.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
173 |
+
"transformer.encoder.layers.4.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
174 |
+
"transformer.embedding.word_embeddings.weight": "model-00004-of-00005.safetensors",
|
175 |
+
"transformer.output_layer.weight": "model-00004-of-00005.safetensors",
|
176 |
+
"transformer.encoder.final_layernorm.weight": "model-00004-of-00005.safetensors",
|
177 |
+
"transformer.encoder.layers.6.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
178 |
+
"transformer.encoder.layers.6.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
179 |
+
"transformer.encoder.layers.6.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
180 |
+
"transformer.encoder.layers.6.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
181 |
+
"transformer.encoder.layers.6.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
182 |
+
"transformer.encoder.layers.6.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
183 |
+
"transformer.encoder.layers.6.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
184 |
+
"transformer.encoder.layers.33.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
185 |
+
"transformer.encoder.layers.33.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
186 |
+
"transformer.encoder.layers.33.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
187 |
+
"transformer.encoder.layers.33.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
188 |
+
"transformer.encoder.layers.33.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
189 |
+
"transformer.encoder.layers.33.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
190 |
+
"transformer.encoder.layers.33.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
191 |
+
"transformer.encoder.layers.31.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
192 |
+
"transformer.encoder.layers.31.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
193 |
+
"transformer.encoder.layers.31.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
194 |
+
"transformer.encoder.layers.31.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
195 |
+
"transformer.encoder.layers.31.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
196 |
+
"transformer.encoder.layers.31.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
197 |
+
"transformer.encoder.layers.31.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
198 |
+
"transformer.encoder.layers.21.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
199 |
+
"transformer.encoder.layers.21.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
200 |
+
"transformer.encoder.layers.21.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
201 |
+
"transformer.encoder.layers.21.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
202 |
+
"transformer.encoder.layers.21.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
203 |
+
"transformer.encoder.layers.21.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
204 |
+
"transformer.encoder.layers.21.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
205 |
+
"transformer.encoder.layers.12.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
206 |
+
"transformer.encoder.layers.12.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
207 |
+
"transformer.encoder.layers.12.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
208 |
+
"transformer.encoder.layers.12.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
209 |
+
"transformer.encoder.layers.12.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
210 |
+
"transformer.encoder.layers.12.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
211 |
+
"transformer.encoder.layers.12.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors",
|
212 |
+
"transformer.encoder.layers.16.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
213 |
+
"transformer.encoder.layers.16.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
214 |
+
"transformer.encoder.layers.16.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
215 |
+
"transformer.encoder.layers.16.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
216 |
+
"transformer.encoder.layers.16.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
217 |
+
"transformer.encoder.layers.16.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
218 |
+
"transformer.encoder.layers.16.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors",
|
219 |
+
"transformer.encoder.layers.17.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
220 |
+
"transformer.encoder.layers.17.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
221 |
+
"transformer.encoder.layers.17.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
222 |
+
"transformer.encoder.layers.17.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
223 |
+
"transformer.encoder.layers.17.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
224 |
+
"transformer.encoder.layers.17.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
225 |
+
"transformer.encoder.layers.17.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors",
|
226 |
+
"transformer.encoder.layers.30.input_layernorm.weight": "model-00003-of-00005.safetensors",
|
227 |
+
"transformer.encoder.layers.30.post_attention_layernorm.weight": "model-00003-of-00005.safetensors",
|
228 |
+
"transformer.encoder.layers.30.self_attention.query_key_value.weight": "model-00003-of-00005.safetensors",
|
229 |
+
"transformer.encoder.layers.30.self_attention.query_key_value.bias": "model-00003-of-00005.safetensors",
|
230 |
+
"transformer.encoder.layers.30.self_attention.dense.weight": "model-00003-of-00005.safetensors",
|
231 |
+
"transformer.encoder.layers.30.mlp.dense_h_to_4h.weight": "model-00003-of-00005.safetensors",
|
232 |
+
"transformer.encoder.layers.30.mlp.dense_4h_to_h.weight": "model-00003-of-00005.safetensors",
|
233 |
+
"transformer.encoder.layers.5.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
234 |
+
"transformer.encoder.layers.5.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
235 |
+
"transformer.encoder.layers.5.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
236 |
+
"transformer.encoder.layers.5.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
237 |
+
"transformer.encoder.layers.5.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
238 |
+
"transformer.encoder.layers.5.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
239 |
+
"transformer.encoder.layers.5.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
240 |
+
"transformer.encoder.layers.11.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
241 |
+
"transformer.encoder.layers.11.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
242 |
+
"transformer.encoder.layers.11.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
243 |
+
"transformer.encoder.layers.11.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
244 |
+
"transformer.encoder.layers.11.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
245 |
+
"transformer.encoder.layers.11.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
246 |
+
"transformer.encoder.layers.11.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors",
|
247 |
+
"transformer.encoder.layers.3.input_layernorm.weight": "model-00000-of-00005.safetensors",
|
248 |
+
"transformer.encoder.layers.3.post_attention_layernorm.weight": "model-00000-of-00005.safetensors",
|
249 |
+
"transformer.encoder.layers.3.self_attention.query_key_value.weight": "model-00000-of-00005.safetensors",
|
250 |
+
"transformer.encoder.layers.3.self_attention.query_key_value.bias": "model-00000-of-00005.safetensors",
|
251 |
+
"transformer.encoder.layers.3.self_attention.dense.weight": "model-00000-of-00005.safetensors",
|
252 |
+
"transformer.encoder.layers.3.mlp.dense_h_to_4h.weight": "model-00000-of-00005.safetensors",
|
253 |
+
"transformer.encoder.layers.3.mlp.dense_4h_to_h.weight": "model-00000-of-00005.safetensors",
|
254 |
+
"transformer.encoder.layers.29.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
255 |
+
"transformer.encoder.layers.29.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
256 |
+
"transformer.encoder.layers.29.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
257 |
+
"transformer.encoder.layers.29.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
258 |
+
"transformer.encoder.layers.29.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
259 |
+
"transformer.encoder.layers.29.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
260 |
+
"transformer.encoder.layers.29.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
261 |
+
"transformer.encoder.layers.23.input_layernorm.weight": "model-00002-of-00005.safetensors",
|
262 |
+
"transformer.encoder.layers.23.post_attention_layernorm.weight": "model-00002-of-00005.safetensors",
|
263 |
+
"transformer.encoder.layers.23.self_attention.query_key_value.weight": "model-00002-of-00005.safetensors",
|
264 |
+
"transformer.encoder.layers.23.self_attention.query_key_value.bias": "model-00002-of-00005.safetensors",
|
265 |
+
"transformer.encoder.layers.23.self_attention.dense.weight": "model-00002-of-00005.safetensors",
|
266 |
+
"transformer.encoder.layers.23.mlp.dense_h_to_4h.weight": "model-00002-of-00005.safetensors",
|
267 |
+
"transformer.encoder.layers.23.mlp.dense_4h_to_h.weight": "model-00002-of-00005.safetensors",
|
268 |
+
"transformer.encoder.layers.13.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
269 |
+
"transformer.encoder.layers.13.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
270 |
+
"transformer.encoder.layers.13.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
271 |
+
"transformer.encoder.layers.13.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
272 |
+
"transformer.encoder.layers.13.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
273 |
+
"transformer.encoder.layers.13.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
274 |
+
"transformer.encoder.layers.13.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors",
|
275 |
+
"transformer.encoder.layers.15.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
276 |
+
"transformer.encoder.layers.15.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
277 |
+
"transformer.encoder.layers.15.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
278 |
+
"transformer.encoder.layers.15.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
279 |
+
"transformer.encoder.layers.15.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
280 |
+
"transformer.encoder.layers.15.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
281 |
+
"transformer.encoder.layers.15.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors",
|
282 |
+
"transformer.encoder.layers.19.input_layernorm.weight": "model-00001-of-00005.safetensors",
|
283 |
+
"transformer.encoder.layers.19.post_attention_layernorm.weight": "model-00001-of-00005.safetensors",
|
284 |
+
"transformer.encoder.layers.19.self_attention.query_key_value.weight": "model-00001-of-00005.safetensors",
|
285 |
+
"transformer.encoder.layers.19.self_attention.query_key_value.bias": "model-00001-of-00005.safetensors",
|
286 |
+
"transformer.encoder.layers.19.self_attention.dense.weight": "model-00001-of-00005.safetensors",
|
287 |
+
"transformer.encoder.layers.19.mlp.dense_h_to_4h.weight": "model-00001-of-00005.safetensors",
|
288 |
+
"transformer.encoder.layers.19.mlp.dense_4h_to_h.weight": "model-00001-of-00005.safetensors"
|
289 |
+
}
|
290 |
+
}
|
modeling_llama.py
ADDED
@@ -0,0 +1,1255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import math
|
21 |
+
from typing import Optional, Tuple, Union, List, Callable, Dict, Any
|
22 |
+
|
23 |
+
import torch
|
24 |
+
import torch.nn.functional as F
|
25 |
+
import torch.utils.checkpoint
|
26 |
+
from torch import nn
|
27 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
28 |
+
|
29 |
+
from transformers.activations import ACT2FN
|
30 |
+
from transformers.cache_utils import Cache, DynamicCache, StaticCache
|
31 |
+
from transformers.modeling_attn_mask_utils import AttentionMaskConverter
|
32 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
33 |
+
from transformers.modeling_outputs import (
|
34 |
+
BaseModelOutputWithPast,
|
35 |
+
CausalLMOutputWithPast,
|
36 |
+
QuestionAnsweringModelOutput,
|
37 |
+
SequenceClassifierOutputWithPast,
|
38 |
+
TokenClassifierOutput,
|
39 |
+
)
|
40 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
|
41 |
+
from transformers.modeling_utils import PreTrainedModel
|
42 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
|
43 |
+
from transformers.utils import (
|
44 |
+
add_start_docstrings,
|
45 |
+
add_start_docstrings_to_model_forward,
|
46 |
+
is_flash_attn_greater_or_equal_2_10,
|
47 |
+
logging,
|
48 |
+
replace_return_docstrings,
|
49 |
+
)
|
50 |
+
from transformers import LlamaConfig
|
51 |
+
|
52 |
+
logger = logging.get_logger(__name__)
|
53 |
+
|
54 |
+
_CONFIG_FOR_DOC = "LlamaConfig"
|
55 |
+
|
56 |
+
|
57 |
+
class LlamaRMSNorm(nn.Module):
|
58 |
+
def __init__(self, hidden_size, eps=1e-6):
|
59 |
+
"""
|
60 |
+
LlamaRMSNorm is equivalent to T5LayerNorm
|
61 |
+
"""
|
62 |
+
super().__init__()
|
63 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
64 |
+
self.variance_epsilon = eps
|
65 |
+
|
66 |
+
def forward(self, hidden_states):
|
67 |
+
input_dtype = hidden_states.dtype
|
68 |
+
hidden_states = hidden_states.to(torch.float32)
|
69 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
70 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
71 |
+
return self.weight * hidden_states.to(input_dtype)
|
72 |
+
|
73 |
+
|
74 |
+
ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
|
75 |
+
|
76 |
+
|
77 |
+
class LlamaRotaryEmbedding(nn.Module):
|
78 |
+
def __init__(
|
79 |
+
self,
|
80 |
+
dim=None,
|
81 |
+
max_position_embeddings=2048,
|
82 |
+
base=10000,
|
83 |
+
device=None,
|
84 |
+
scaling_factor=1.0,
|
85 |
+
rope_type="default",
|
86 |
+
config: Optional[LlamaConfig] = None,
|
87 |
+
):
|
88 |
+
super().__init__()
|
89 |
+
# TODO (joao): remove the `if` below, only used for BC
|
90 |
+
self.rope_kwargs = {}
|
91 |
+
if config is None:
|
92 |
+
logger.warning_once(
|
93 |
+
"`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
|
94 |
+
"`config` argument. All other arguments will be removed in v4.45"
|
95 |
+
)
|
96 |
+
self.rope_kwargs = {
|
97 |
+
"rope_type": rope_type,
|
98 |
+
"factor": scaling_factor,
|
99 |
+
"dim": dim,
|
100 |
+
"base": base,
|
101 |
+
"max_position_embeddings": max_position_embeddings,
|
102 |
+
}
|
103 |
+
self.rope_type = rope_type
|
104 |
+
self.max_seq_len_cached = max_position_embeddings
|
105 |
+
self.original_max_seq_len = max_position_embeddings
|
106 |
+
else:
|
107 |
+
# BC: "rope_type" was originally "type"
|
108 |
+
if config.rope_scaling is not None:
|
109 |
+
self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
|
110 |
+
else:
|
111 |
+
self.rope_type = "default"
|
112 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
113 |
+
self.original_max_seq_len = config.max_position_embeddings
|
114 |
+
|
115 |
+
self.config = config
|
116 |
+
self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
117 |
+
|
118 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
|
119 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
120 |
+
self.original_inv_freq = self.inv_freq
|
121 |
+
|
122 |
+
def _dynamic_frequency_update(self, position_ids, device):
|
123 |
+
"""
|
124 |
+
dynamic RoPE layers should recompute `inv_freq` in the following situations:
|
125 |
+
1 - growing beyond the cached sequence length (allow scaling)
|
126 |
+
2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
|
127 |
+
"""
|
128 |
+
seq_len = torch.max(position_ids) + 1
|
129 |
+
if seq_len > self.max_seq_len_cached: # growth
|
130 |
+
inv_freq, self.attention_scaling = self.rope_init_fn(
|
131 |
+
self.config, device, seq_len=seq_len, **self.rope_kwargs
|
132 |
+
)
|
133 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
|
134 |
+
self.max_seq_len_cached = seq_len
|
135 |
+
|
136 |
+
if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
|
137 |
+
self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
|
138 |
+
self.max_seq_len_cached = self.original_max_seq_len
|
139 |
+
|
140 |
+
@torch.no_grad()
|
141 |
+
def forward(self, x, position_ids):
|
142 |
+
if "dynamic" in self.rope_type:
|
143 |
+
self._dynamic_frequency_update(position_ids, device=x.device)
|
144 |
+
# Core RoPE block
|
145 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
146 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
147 |
+
# Force float32 (see https://github.com/huggingface/transformers/pull/29285)
|
148 |
+
device_type = x.device.type
|
149 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
150 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
151 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
152 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
153 |
+
cos = emb.cos()
|
154 |
+
sin = emb.sin()
|
155 |
+
# Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
|
156 |
+
cos = cos * self.attention_scaling
|
157 |
+
sin = sin * self.attention_scaling
|
158 |
+
|
159 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
160 |
+
|
161 |
+
|
162 |
+
class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
|
163 |
+
"""LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
164 |
+
|
165 |
+
def __init__(self, *args, **kwargs):
|
166 |
+
logger.warning_once(
|
167 |
+
"`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
|
168 |
+
"`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
|
169 |
+
)
|
170 |
+
kwargs["rope_type"] = "linear"
|
171 |
+
super().__init__(*args, **kwargs)
|
172 |
+
|
173 |
+
|
174 |
+
class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
|
175 |
+
"""LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
176 |
+
|
177 |
+
def __init__(self, *args, **kwargs):
|
178 |
+
logger.warning_once(
|
179 |
+
"`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.45. Please use "
|
180 |
+
"`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
|
181 |
+
"__init__)."
|
182 |
+
)
|
183 |
+
kwargs["rope_type"] = "dynamic"
|
184 |
+
super().__init__(*args, **kwargs)
|
185 |
+
|
186 |
+
|
187 |
+
def rotate_half(x):
|
188 |
+
"""Rotates half the hidden dims of the input."""
|
189 |
+
x1 = x[..., : x.shape[-1] // 2]
|
190 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
191 |
+
return torch.cat((-x2, x1), dim=-1)
|
192 |
+
|
193 |
+
|
194 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
195 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
196 |
+
|
197 |
+
Args:
|
198 |
+
q (`torch.Tensor`): The query tensor.
|
199 |
+
k (`torch.Tensor`): The key tensor.
|
200 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
201 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
202 |
+
position_ids (`torch.Tensor`, *optional*):
|
203 |
+
Deprecated and unused.
|
204 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
205 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
206 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
207 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
208 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
209 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
210 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
211 |
+
Returns:
|
212 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
213 |
+
"""
|
214 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
215 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
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=config.mlp_bias)
|
229 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
230 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
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 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
242 |
+
)
|
243 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
244 |
+
|
245 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
246 |
+
down_proj = [
|
247 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
248 |
+
]
|
249 |
+
down_proj = sum(down_proj)
|
250 |
+
else:
|
251 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
252 |
+
|
253 |
+
return down_proj
|
254 |
+
|
255 |
+
|
256 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
257 |
+
"""
|
258 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
259 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
260 |
+
"""
|
261 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
262 |
+
if n_rep == 1:
|
263 |
+
return hidden_states
|
264 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
265 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
266 |
+
|
267 |
+
|
268 |
+
class LlamaAttention(nn.Module):
|
269 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
270 |
+
|
271 |
+
def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
|
272 |
+
super().__init__()
|
273 |
+
self.config = config
|
274 |
+
self.layer_idx = layer_idx
|
275 |
+
if layer_idx is None:
|
276 |
+
logger.warning_once(
|
277 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
278 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
279 |
+
"when creating this class."
|
280 |
+
)
|
281 |
+
|
282 |
+
self.attention_dropout = config.attention_dropout
|
283 |
+
self.hidden_size = config.hidden_size
|
284 |
+
self.num_heads = config.num_attention_heads
|
285 |
+
self.head_dim = self.hidden_size // self.num_heads
|
286 |
+
self.num_key_value_heads = config.num_key_value_heads
|
287 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
288 |
+
self.max_position_embeddings = config.max_position_embeddings
|
289 |
+
self.rope_theta = config.rope_theta
|
290 |
+
self.is_causal = True
|
291 |
+
|
292 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
293 |
+
raise ValueError(
|
294 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
295 |
+
f" and `num_heads`: {self.num_heads})."
|
296 |
+
)
|
297 |
+
|
298 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
299 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
300 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
301 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
|
302 |
+
|
303 |
+
# TODO (joao): remove in v4.45 (RoPE is computed in the model, not in the decoder layers)
|
304 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
|
305 |
+
|
306 |
+
def forward(
|
307 |
+
self,
|
308 |
+
hidden_states: torch.Tensor,
|
309 |
+
attention_mask: Optional[torch.Tensor] = None,
|
310 |
+
position_ids: Optional[torch.LongTensor] = None,
|
311 |
+
past_key_value: Optional[Cache] = None,
|
312 |
+
output_attentions: bool = False,
|
313 |
+
use_cache: bool = False,
|
314 |
+
cache_position: Optional[torch.LongTensor] = None,
|
315 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
|
316 |
+
**kwargs,
|
317 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
318 |
+
bsz, q_len, _ = hidden_states.size()
|
319 |
+
|
320 |
+
if self.config.pretraining_tp > 1:
|
321 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
322 |
+
query_slices = self.q_proj.weight.split(
|
323 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
324 |
+
)
|
325 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
326 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
327 |
+
|
328 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
329 |
+
query_states = torch.cat(query_states, dim=-1)
|
330 |
+
|
331 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
332 |
+
key_states = torch.cat(key_states, dim=-1)
|
333 |
+
|
334 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
335 |
+
value_states = torch.cat(value_states, dim=-1)
|
336 |
+
|
337 |
+
else:
|
338 |
+
query_states = self.q_proj(hidden_states)
|
339 |
+
key_states = self.k_proj(hidden_states)
|
340 |
+
value_states = self.v_proj(hidden_states)
|
341 |
+
|
342 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
343 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
344 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
345 |
+
|
346 |
+
if position_embeddings is None:
|
347 |
+
logger.warning_once(
|
348 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
349 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
350 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
|
351 |
+
"removed and `position_embeddings` will be mandatory."
|
352 |
+
)
|
353 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
354 |
+
else:
|
355 |
+
cos, sin = position_embeddings
|
356 |
+
|
357 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
358 |
+
|
359 |
+
if past_key_value is not None:
|
360 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
361 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
362 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
363 |
+
|
364 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
365 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
366 |
+
|
367 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
368 |
+
|
369 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
370 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
371 |
+
attn_weights = attn_weights + causal_mask
|
372 |
+
|
373 |
+
# upcast attention to fp32
|
374 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
375 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
376 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
377 |
+
|
378 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
379 |
+
raise ValueError(
|
380 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
381 |
+
f" {attn_output.size()}"
|
382 |
+
)
|
383 |
+
|
384 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
385 |
+
|
386 |
+
attn_output = attn_output.reshape(bsz, q_len, -1)
|
387 |
+
|
388 |
+
if self.config.pretraining_tp > 1:
|
389 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
390 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
391 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
392 |
+
else:
|
393 |
+
attn_output = self.o_proj(attn_output)
|
394 |
+
|
395 |
+
if not output_attentions:
|
396 |
+
attn_weights = None
|
397 |
+
|
398 |
+
return attn_output, attn_weights, past_key_value
|
399 |
+
|
400 |
+
|
401 |
+
class LlamaFlashAttention2(LlamaAttention):
|
402 |
+
"""
|
403 |
+
Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
|
404 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
405 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
406 |
+
"""
|
407 |
+
|
408 |
+
def __init__(self, *args, **kwargs):
|
409 |
+
super().__init__(*args, **kwargs)
|
410 |
+
|
411 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
412 |
+
# 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.
|
413 |
+
# 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).
|
414 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
415 |
+
|
416 |
+
def forward(
|
417 |
+
self,
|
418 |
+
hidden_states: torch.Tensor,
|
419 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
420 |
+
position_ids: Optional[torch.LongTensor] = None,
|
421 |
+
past_key_value: Optional[Cache] = None,
|
422 |
+
output_attentions: bool = False,
|
423 |
+
use_cache: bool = False,
|
424 |
+
cache_position: Optional[torch.LongTensor] = None,
|
425 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
|
426 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
427 |
+
if isinstance(past_key_value, StaticCache):
|
428 |
+
raise ValueError(
|
429 |
+
"`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
|
430 |
+
"make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
|
431 |
+
)
|
432 |
+
|
433 |
+
output_attentions = False
|
434 |
+
|
435 |
+
bsz, q_len, _ = hidden_states.size()
|
436 |
+
|
437 |
+
query_states = self.q_proj(hidden_states)
|
438 |
+
key_states = self.k_proj(hidden_states)
|
439 |
+
value_states = self.v_proj(hidden_states)
|
440 |
+
|
441 |
+
# Flash attention requires the input to have the shape
|
442 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
443 |
+
# therefore we just need to keep the original shape
|
444 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
445 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
446 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
447 |
+
|
448 |
+
if position_embeddings is None:
|
449 |
+
logger.warning_once(
|
450 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
451 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
452 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
|
453 |
+
"removed and `position_embeddings` will be mandatory."
|
454 |
+
)
|
455 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
456 |
+
else:
|
457 |
+
cos, sin = position_embeddings
|
458 |
+
|
459 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
460 |
+
|
461 |
+
if past_key_value is not None:
|
462 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
463 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
464 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
465 |
+
|
466 |
+
# 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
|
467 |
+
# to be able to avoid many of these transpose/reshape/view.
|
468 |
+
query_states = query_states.transpose(1, 2)
|
469 |
+
key_states = key_states.transpose(1, 2)
|
470 |
+
value_states = value_states.transpose(1, 2)
|
471 |
+
|
472 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
473 |
+
|
474 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
475 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
476 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
477 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
478 |
+
# in fp32. (LlamaRMSNorm handles it correctly)
|
479 |
+
|
480 |
+
input_dtype = query_states.dtype
|
481 |
+
if input_dtype == torch.float32:
|
482 |
+
if torch.is_autocast_enabled():
|
483 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
484 |
+
# Handle the case where the model is quantized
|
485 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
486 |
+
target_dtype = self.config._pre_quantization_dtype
|
487 |
+
else:
|
488 |
+
target_dtype = self.q_proj.weight.dtype
|
489 |
+
|
490 |
+
logger.warning_once(
|
491 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
492 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
493 |
+
f" {target_dtype}."
|
494 |
+
)
|
495 |
+
|
496 |
+
query_states = query_states.to(target_dtype)
|
497 |
+
key_states = key_states.to(target_dtype)
|
498 |
+
value_states = value_states.to(target_dtype)
|
499 |
+
|
500 |
+
attn_output = _flash_attention_forward(
|
501 |
+
query_states,
|
502 |
+
key_states,
|
503 |
+
value_states,
|
504 |
+
attention_mask,
|
505 |
+
q_len,
|
506 |
+
dropout=dropout_rate,
|
507 |
+
sliding_window=getattr(self, "sliding_window", None),
|
508 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
509 |
+
is_causal=self.is_causal,
|
510 |
+
)
|
511 |
+
|
512 |
+
attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
|
513 |
+
attn_output = self.o_proj(attn_output)
|
514 |
+
|
515 |
+
if not output_attentions:
|
516 |
+
attn_weights = None
|
517 |
+
|
518 |
+
return attn_output, attn_weights, past_key_value
|
519 |
+
|
520 |
+
|
521 |
+
class LlamaSdpaAttention(LlamaAttention):
|
522 |
+
"""
|
523 |
+
Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
524 |
+
`LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
525 |
+
SDPA API.
|
526 |
+
"""
|
527 |
+
|
528 |
+
# Adapted from LlamaAttention.forward
|
529 |
+
def forward(
|
530 |
+
self,
|
531 |
+
hidden_states: torch.Tensor,
|
532 |
+
attention_mask: Optional[torch.Tensor] = None,
|
533 |
+
position_ids: Optional[torch.LongTensor] = None,
|
534 |
+
past_key_value: Optional[Cache] = None,
|
535 |
+
output_attentions: bool = False,
|
536 |
+
use_cache: bool = False,
|
537 |
+
cache_position: Optional[torch.LongTensor] = None,
|
538 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
|
539 |
+
**kwargs,
|
540 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
541 |
+
if output_attentions:
|
542 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
543 |
+
logger.warning_once(
|
544 |
+
"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, "
|
545 |
+
'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.'
|
546 |
+
)
|
547 |
+
return super().forward(
|
548 |
+
hidden_states=hidden_states,
|
549 |
+
attention_mask=attention_mask,
|
550 |
+
position_ids=position_ids,
|
551 |
+
past_key_value=past_key_value,
|
552 |
+
output_attentions=output_attentions,
|
553 |
+
use_cache=use_cache,
|
554 |
+
cache_position=cache_position,
|
555 |
+
position_embeddings=position_embeddings,
|
556 |
+
)
|
557 |
+
|
558 |
+
bsz, q_len, _ = hidden_states.size()
|
559 |
+
# print(hidden_states.sum())
|
560 |
+
query_states = self.q_proj(hidden_states)
|
561 |
+
key_states = self.k_proj(hidden_states)
|
562 |
+
value_states = self.v_proj(hidden_states)
|
563 |
+
# print(query_states.sum() + key_states.sum() + value_states.sum())
|
564 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
565 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
566 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
567 |
+
|
568 |
+
if position_embeddings is None:
|
569 |
+
logger.warning_once(
|
570 |
+
"The attention layers in this model are transitioning from computing the RoPE embeddings internally "
|
571 |
+
"through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
|
572 |
+
"`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.45 `position_ids` will be "
|
573 |
+
"removed and `position_embeddings` will be mandatory."
|
574 |
+
)
|
575 |
+
cos, sin = self.rotary_emb(value_states, position_ids)
|
576 |
+
else:
|
577 |
+
cos, sin = position_embeddings
|
578 |
+
|
579 |
+
# print(query_states.size(), key_states.size())
|
580 |
+
# print(query_states.sum(), key_states.sum(), value_states.sum())
|
581 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
582 |
+
# print(query_states.sum(), key_states.sum())
|
583 |
+
# exit()
|
584 |
+
|
585 |
+
if past_key_value is not None:
|
586 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
587 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
588 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
589 |
+
|
590 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
591 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
592 |
+
|
593 |
+
causal_mask = attention_mask
|
594 |
+
if attention_mask is not None:
|
595 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
596 |
+
|
597 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
598 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
599 |
+
if query_states.device.type == "cuda" and causal_mask is not None:
|
600 |
+
query_states = query_states.contiguous()
|
601 |
+
key_states = key_states.contiguous()
|
602 |
+
value_states = value_states.contiguous()
|
603 |
+
|
604 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
605 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
606 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
607 |
+
|
608 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
609 |
+
query_states,
|
610 |
+
key_states,
|
611 |
+
value_states,
|
612 |
+
attn_mask=causal_mask,
|
613 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
614 |
+
is_causal=is_causal,
|
615 |
+
)
|
616 |
+
|
617 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
618 |
+
attn_output = attn_output.view(bsz, q_len, -1)
|
619 |
+
|
620 |
+
attn_output = self.o_proj(attn_output)
|
621 |
+
|
622 |
+
return attn_output, None, past_key_value
|
623 |
+
|
624 |
+
|
625 |
+
LLAMA_ATTENTION_CLASSES = {
|
626 |
+
"eager": LlamaAttention,
|
627 |
+
"flash_attention_2": LlamaFlashAttention2,
|
628 |
+
"sdpa": LlamaSdpaAttention,
|
629 |
+
}
|
630 |
+
|
631 |
+
|
632 |
+
class LlamaDecoderLayer(nn.Module):
|
633 |
+
def __init__(self, config: LlamaConfig, layer_idx: int):
|
634 |
+
super().__init__()
|
635 |
+
self.hidden_size = config.hidden_size
|
636 |
+
|
637 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
638 |
+
self.mlp = LlamaMLP(config)
|
639 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
640 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
641 |
+
|
642 |
+
def forward(
|
643 |
+
self,
|
644 |
+
hidden_states: torch.Tensor,
|
645 |
+
attention_mask: Optional[torch.Tensor] = None,
|
646 |
+
position_ids: Optional[torch.LongTensor] = None,
|
647 |
+
past_key_value: Optional[Cache] = None,
|
648 |
+
output_attentions: Optional[bool] = False,
|
649 |
+
use_cache: Optional[bool] = False,
|
650 |
+
cache_position: Optional[torch.LongTensor] = None,
|
651 |
+
position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.45
|
652 |
+
**kwargs,
|
653 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
654 |
+
"""
|
655 |
+
Args:
|
656 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
657 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
658 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
659 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
660 |
+
output_attentions (`bool`, *optional*):
|
661 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
662 |
+
returned tensors for more detail.
|
663 |
+
use_cache (`bool`, *optional*):
|
664 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
665 |
+
(see `past_key_values`).
|
666 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
667 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
668 |
+
Indices depicting the position of the input sequence tokens in the sequence
|
669 |
+
position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
670 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
671 |
+
with `head_dim` being the embedding dimension of each attention head.
|
672 |
+
kwargs (`dict`, *optional*):
|
673 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
674 |
+
into the model
|
675 |
+
"""
|
676 |
+
residual = hidden_states
|
677 |
+
# print(hidden_states.float().sum())
|
678 |
+
hidden_states = self.input_layernorm(hidden_states)
|
679 |
+
# print(hidden_states.float().sum())
|
680 |
+
|
681 |
+
# Self Attention
|
682 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
683 |
+
hidden_states=hidden_states,
|
684 |
+
attention_mask=attention_mask,
|
685 |
+
position_ids=position_ids,
|
686 |
+
past_key_value=past_key_value,
|
687 |
+
output_attentions=output_attentions,
|
688 |
+
use_cache=use_cache,
|
689 |
+
cache_position=cache_position,
|
690 |
+
position_embeddings=position_embeddings,
|
691 |
+
**kwargs,
|
692 |
+
)
|
693 |
+
hidden_states = residual + hidden_states
|
694 |
+
|
695 |
+
# Fully Connected
|
696 |
+
residual = hidden_states
|
697 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
698 |
+
hidden_states = self.mlp(hidden_states)
|
699 |
+
hidden_states = residual + hidden_states
|
700 |
+
|
701 |
+
outputs = (hidden_states,)
|
702 |
+
|
703 |
+
if output_attentions:
|
704 |
+
outputs += (self_attn_weights,)
|
705 |
+
|
706 |
+
if use_cache:
|
707 |
+
outputs += (present_key_value,)
|
708 |
+
|
709 |
+
return outputs
|
710 |
+
|
711 |
+
|
712 |
+
LLAMA_START_DOCSTRING = r"""
|
713 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
714 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
715 |
+
etc.)
|
716 |
+
|
717 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
718 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
719 |
+
and behavior.
|
720 |
+
|
721 |
+
Parameters:
|
722 |
+
config ([`LlamaConfig`]):
|
723 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
724 |
+
load the weights associated with the model, only the configuration. Check out the
|
725 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
726 |
+
"""
|
727 |
+
|
728 |
+
|
729 |
+
@add_start_docstrings(
|
730 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
731 |
+
LLAMA_START_DOCSTRING,
|
732 |
+
)
|
733 |
+
class LlamaPreTrainedModel(PreTrainedModel):
|
734 |
+
config_class = LlamaConfig
|
735 |
+
base_model_prefix = "model"
|
736 |
+
supports_gradient_checkpointing = True
|
737 |
+
_no_split_modules = ["LlamaDecoderLayer"]
|
738 |
+
_skip_keys_device_placement = ["past_key_values"]
|
739 |
+
_supports_flash_attn_2 = True
|
740 |
+
_supports_sdpa = True
|
741 |
+
_supports_cache_class = True
|
742 |
+
_supports_quantized_cache = True
|
743 |
+
_supports_static_cache = True
|
744 |
+
|
745 |
+
def _init_weights(self, module):
|
746 |
+
std = self.config.initializer_range
|
747 |
+
if isinstance(module, nn.Linear):
|
748 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
749 |
+
if module.bias is not None:
|
750 |
+
module.bias.data.zero_()
|
751 |
+
elif isinstance(module, nn.Embedding):
|
752 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
753 |
+
if module.padding_idx is not None:
|
754 |
+
module.weight.data[module.padding_idx].zero_()
|
755 |
+
|
756 |
+
|
757 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
758 |
+
Args:
|
759 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
760 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
761 |
+
it.
|
762 |
+
|
763 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
764 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
765 |
+
|
766 |
+
[What are input IDs?](../glossary#input-ids)
|
767 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
768 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
769 |
+
|
770 |
+
- 1 for tokens that are **not masked**,
|
771 |
+
- 0 for tokens that are **masked**.
|
772 |
+
|
773 |
+
[What are attention masks?](../glossary#attention-mask)
|
774 |
+
|
775 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
776 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
777 |
+
|
778 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
779 |
+
`past_key_values`).
|
780 |
+
|
781 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
782 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
783 |
+
information on the default strategy.
|
784 |
+
|
785 |
+
- 1 indicates the head is **not masked**,
|
786 |
+
- 0 indicates the head is **masked**.
|
787 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
788 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
789 |
+
config.n_positions - 1]`.
|
790 |
+
|
791 |
+
[What are position IDs?](../glossary#position-ids)
|
792 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
793 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
794 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
795 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
796 |
+
|
797 |
+
Two formats are allowed:
|
798 |
+
- a [`~cache_utils.Cache`] instance;
|
799 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
800 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
801 |
+
cache format.
|
802 |
+
|
803 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
804 |
+
legacy cache format will be returned.
|
805 |
+
|
806 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
807 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
808 |
+
of shape `(batch_size, sequence_length)`.
|
809 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
810 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
811 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
812 |
+
model's internal embedding lookup matrix.
|
813 |
+
use_cache (`bool`, *optional*):
|
814 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
815 |
+
`past_key_values`).
|
816 |
+
output_attentions (`bool`, *optional*):
|
817 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
818 |
+
tensors for more detail.
|
819 |
+
output_hidden_states (`bool`, *optional*):
|
820 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
821 |
+
more detail.
|
822 |
+
return_dict (`bool`, *optional*):
|
823 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
824 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
825 |
+
Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
|
826 |
+
this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
|
827 |
+
the complete sequence length.
|
828 |
+
"""
|
829 |
+
|
830 |
+
|
831 |
+
@add_start_docstrings(
|
832 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
833 |
+
LLAMA_START_DOCSTRING,
|
834 |
+
)
|
835 |
+
class LlamaModel(LlamaPreTrainedModel):
|
836 |
+
"""
|
837 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
|
838 |
+
|
839 |
+
Args:
|
840 |
+
config: LlamaConfig
|
841 |
+
"""
|
842 |
+
|
843 |
+
def __init__(self, config: LlamaConfig):
|
844 |
+
super().__init__(config)
|
845 |
+
self.padding_idx = config.pad_token_id
|
846 |
+
self.vocab_size = config.vocab_size
|
847 |
+
|
848 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
849 |
+
self.layers = nn.ModuleList(
|
850 |
+
[LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
851 |
+
)
|
852 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
853 |
+
self.rotary_emb = LlamaRotaryEmbedding(config=config)
|
854 |
+
self.gradient_checkpointing = False
|
855 |
+
|
856 |
+
# Initialize weights and apply final processing
|
857 |
+
self.post_init()
|
858 |
+
|
859 |
+
def get_input_embeddings(self):
|
860 |
+
return self.embed_tokens
|
861 |
+
|
862 |
+
def set_input_embeddings(self, value):
|
863 |
+
self.embed_tokens = value
|
864 |
+
|
865 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
866 |
+
def forward(
|
867 |
+
self,
|
868 |
+
input_ids: torch.LongTensor = None,
|
869 |
+
attention_mask: Optional[torch.Tensor] = None,
|
870 |
+
position_ids: Optional[torch.LongTensor] = None,
|
871 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
872 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
873 |
+
use_cache: Optional[bool] = None,
|
874 |
+
output_attentions: Optional[bool] = None,
|
875 |
+
output_hidden_states: Optional[bool] = None,
|
876 |
+
return_dict: Optional[bool] = None,
|
877 |
+
cache_position: Optional[torch.LongTensor] = None,
|
878 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
879 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
880 |
+
output_hidden_states = (
|
881 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
882 |
+
)
|
883 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
884 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
885 |
+
|
886 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
887 |
+
raise ValueError(
|
888 |
+
"You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
|
889 |
+
)
|
890 |
+
|
891 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
892 |
+
logger.warning_once(
|
893 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
894 |
+
)
|
895 |
+
use_cache = False
|
896 |
+
|
897 |
+
if inputs_embeds is None:
|
898 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
899 |
+
|
900 |
+
return_legacy_cache = False
|
901 |
+
if (
|
902 |
+
use_cache and not isinstance(past_key_values, Cache) and not self.training
|
903 |
+
): # kept for BC (non `Cache` `past_key_values` inputs)
|
904 |
+
return_legacy_cache = True
|
905 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
906 |
+
logger.warning_once(
|
907 |
+
"We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
|
908 |
+
"Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
|
909 |
+
)
|
910 |
+
|
911 |
+
if cache_position is None:
|
912 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
913 |
+
cache_position = torch.arange(
|
914 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
915 |
+
)
|
916 |
+
if position_ids is None:
|
917 |
+
position_ids = cache_position.unsqueeze(0)
|
918 |
+
|
919 |
+
causal_mask = self._update_causal_mask(
|
920 |
+
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
|
921 |
+
)
|
922 |
+
hidden_states = inputs_embeds
|
923 |
+
|
924 |
+
# create position embeddings to be shared across the decoder layers
|
925 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
926 |
+
|
927 |
+
# decoder layers
|
928 |
+
all_hidden_states = () if output_hidden_states else None
|
929 |
+
all_self_attns = () if output_attentions else None
|
930 |
+
next_decoder_cache = None
|
931 |
+
|
932 |
+
for decoder_layer in self.layers:
|
933 |
+
if output_hidden_states:
|
934 |
+
all_hidden_states += (hidden_states,)
|
935 |
+
|
936 |
+
if self.gradient_checkpointing and self.training:
|
937 |
+
layer_outputs = self._gradient_checkpointing_func(
|
938 |
+
decoder_layer.__call__,
|
939 |
+
hidden_states,
|
940 |
+
causal_mask,
|
941 |
+
position_ids,
|
942 |
+
past_key_values,
|
943 |
+
output_attentions,
|
944 |
+
use_cache,
|
945 |
+
cache_position,
|
946 |
+
position_embeddings,
|
947 |
+
)
|
948 |
+
else:
|
949 |
+
layer_outputs = decoder_layer(
|
950 |
+
hidden_states,
|
951 |
+
attention_mask=causal_mask,
|
952 |
+
position_ids=position_ids,
|
953 |
+
past_key_value=past_key_values,
|
954 |
+
output_attentions=output_attentions,
|
955 |
+
use_cache=use_cache,
|
956 |
+
cache_position=cache_position,
|
957 |
+
position_embeddings=position_embeddings,
|
958 |
+
)
|
959 |
+
|
960 |
+
hidden_states = layer_outputs[0]
|
961 |
+
|
962 |
+
if use_cache:
|
963 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
964 |
+
|
965 |
+
if output_attentions:
|
966 |
+
all_self_attns += (layer_outputs[1],)
|
967 |
+
|
968 |
+
hidden_states = self.norm(hidden_states)
|
969 |
+
|
970 |
+
# add hidden states from the last decoder layer
|
971 |
+
if output_hidden_states:
|
972 |
+
all_hidden_states += (hidden_states,)
|
973 |
+
|
974 |
+
next_cache = next_decoder_cache if use_cache else None
|
975 |
+
if return_legacy_cache:
|
976 |
+
next_cache = next_cache.to_legacy_cache()
|
977 |
+
|
978 |
+
if not return_dict:
|
979 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
980 |
+
return BaseModelOutputWithPast(
|
981 |
+
last_hidden_state=hidden_states,
|
982 |
+
past_key_values=next_cache,
|
983 |
+
hidden_states=all_hidden_states,
|
984 |
+
attentions=all_self_attns,
|
985 |
+
)
|
986 |
+
|
987 |
+
def _update_causal_mask(
|
988 |
+
self,
|
989 |
+
attention_mask: torch.Tensor,
|
990 |
+
input_tensor: torch.Tensor,
|
991 |
+
cache_position: torch.Tensor,
|
992 |
+
past_key_values: Cache,
|
993 |
+
output_attentions: bool,
|
994 |
+
):
|
995 |
+
# TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
|
996 |
+
# KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
|
997 |
+
# (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
|
998 |
+
# `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
|
999 |
+
|
1000 |
+
if self.config._attn_implementation == "flash_attention_2":
|
1001 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
1002 |
+
return attention_mask
|
1003 |
+
return None
|
1004 |
+
|
1005 |
+
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
|
1006 |
+
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
|
1007 |
+
# to infer the attention mask.
|
1008 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
1009 |
+
using_static_cache = isinstance(past_key_values, StaticCache)
|
1010 |
+
|
1011 |
+
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
|
1012 |
+
if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
|
1013 |
+
if AttentionMaskConverter._ignore_causal_mask_sdpa(
|
1014 |
+
attention_mask,
|
1015 |
+
inputs_embeds=input_tensor,
|
1016 |
+
past_key_values_length=past_seen_tokens,
|
1017 |
+
is_training=self.training,
|
1018 |
+
):
|
1019 |
+
return None
|
1020 |
+
|
1021 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
1022 |
+
min_dtype = torch.finfo(dtype).min
|
1023 |
+
sequence_length = input_tensor.shape[1]
|
1024 |
+
if using_static_cache:
|
1025 |
+
target_length = past_key_values.get_max_length()
|
1026 |
+
else:
|
1027 |
+
target_length = (
|
1028 |
+
attention_mask.shape[-1]
|
1029 |
+
if isinstance(attention_mask, torch.Tensor)
|
1030 |
+
else past_seen_tokens + sequence_length + 1
|
1031 |
+
)
|
1032 |
+
|
1033 |
+
if attention_mask is not None and attention_mask.dim() == 4:
|
1034 |
+
# in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
|
1035 |
+
if attention_mask.max() != 0:
|
1036 |
+
raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
|
1037 |
+
causal_mask = attention_mask
|
1038 |
+
else:
|
1039 |
+
causal_mask = torch.full(
|
1040 |
+
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
|
1041 |
+
)
|
1042 |
+
if sequence_length != 1:
|
1043 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
1044 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
1045 |
+
causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
|
1046 |
+
if attention_mask is not None:
|
1047 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
1048 |
+
mask_length = attention_mask.shape[-1]
|
1049 |
+
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
|
1050 |
+
padding_mask = padding_mask == 0
|
1051 |
+
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
|
1052 |
+
padding_mask, min_dtype
|
1053 |
+
)
|
1054 |
+
if (
|
1055 |
+
self.config._attn_implementation == "sdpa"
|
1056 |
+
and attention_mask is not None
|
1057 |
+
and attention_mask.device.type == "cuda"
|
1058 |
+
and not output_attentions
|
1059 |
+
):
|
1060 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
1061 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
1062 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
1063 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
1064 |
+
|
1065 |
+
return causal_mask
|
1066 |
+
|
1067 |
+
|
1068 |
+
class LlamaForCausalLM(LlamaPreTrainedModel):
|
1069 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1070 |
+
|
1071 |
+
def __init__(self, config):
|
1072 |
+
super().__init__(config)
|
1073 |
+
self.model = LlamaModel(config)
|
1074 |
+
self.vocab_size = config.vocab_size
|
1075 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1076 |
+
|
1077 |
+
# Initialize weights and apply final processing
|
1078 |
+
self.post_init()
|
1079 |
+
|
1080 |
+
def get_input_embeddings(self):
|
1081 |
+
return self.model.embed_tokens
|
1082 |
+
|
1083 |
+
def set_input_embeddings(self, value):
|
1084 |
+
self.model.embed_tokens = value
|
1085 |
+
|
1086 |
+
def get_output_embeddings(self):
|
1087 |
+
return self.lm_head
|
1088 |
+
|
1089 |
+
def set_output_embeddings(self, new_embeddings):
|
1090 |
+
self.lm_head = new_embeddings
|
1091 |
+
|
1092 |
+
def set_decoder(self, decoder):
|
1093 |
+
self.model = decoder
|
1094 |
+
|
1095 |
+
def get_decoder(self):
|
1096 |
+
return self.model
|
1097 |
+
|
1098 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1099 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1100 |
+
def forward(
|
1101 |
+
self,
|
1102 |
+
input_ids: torch.LongTensor = None,
|
1103 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1104 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1105 |
+
past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
|
1106 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1107 |
+
labels: Optional[torch.LongTensor] = None,
|
1108 |
+
use_cache: Optional[bool] = None,
|
1109 |
+
output_attentions: Optional[bool] = None,
|
1110 |
+
output_hidden_states: Optional[bool] = None,
|
1111 |
+
return_dict: Optional[bool] = None,
|
1112 |
+
cache_position: Optional[torch.LongTensor] = None,
|
1113 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1114 |
+
r"""
|
1115 |
+
Args:
|
1116 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1117 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1118 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1119 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1120 |
+
|
1121 |
+
Returns:
|
1122 |
+
|
1123 |
+
Example:
|
1124 |
+
|
1125 |
+
```python
|
1126 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
1127 |
+
|
1128 |
+
>>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
|
1129 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
|
1130 |
+
|
1131 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1132 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1133 |
+
|
1134 |
+
>>> # Generate
|
1135 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1136 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1137 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1138 |
+
```"""
|
1139 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1140 |
+
output_hidden_states = (
|
1141 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1142 |
+
)
|
1143 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1144 |
+
|
1145 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1146 |
+
outputs = self.model(
|
1147 |
+
input_ids=input_ids,
|
1148 |
+
attention_mask=attention_mask,
|
1149 |
+
position_ids=position_ids,
|
1150 |
+
past_key_values=past_key_values,
|
1151 |
+
inputs_embeds=inputs_embeds,
|
1152 |
+
use_cache=use_cache,
|
1153 |
+
output_attentions=output_attentions,
|
1154 |
+
output_hidden_states=output_hidden_states,
|
1155 |
+
return_dict=return_dict,
|
1156 |
+
cache_position=cache_position,
|
1157 |
+
)
|
1158 |
+
|
1159 |
+
hidden_states = outputs[0]
|
1160 |
+
if self.config.pretraining_tp > 1:
|
1161 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
1162 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
1163 |
+
logits = torch.cat(logits, dim=-1)
|
1164 |
+
else:
|
1165 |
+
logits = self.lm_head(hidden_states)
|
1166 |
+
logits = logits.float()
|
1167 |
+
|
1168 |
+
loss = None
|
1169 |
+
if labels is not None:
|
1170 |
+
# Shift so that tokens < n predict n
|
1171 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1172 |
+
shift_labels = labels[..., 1:].contiguous()
|
1173 |
+
# Flatten the tokens
|
1174 |
+
loss_fct = CrossEntropyLoss()
|
1175 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1176 |
+
shift_labels = shift_labels.view(-1)
|
1177 |
+
# Enable model parallelism
|
1178 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1179 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1180 |
+
|
1181 |
+
if not return_dict:
|
1182 |
+
output = (logits,) + outputs[1:]
|
1183 |
+
return (loss,) + output if loss is not None else output
|
1184 |
+
|
1185 |
+
return CausalLMOutputWithPast(
|
1186 |
+
loss=loss,
|
1187 |
+
logits=logits,
|
1188 |
+
past_key_values=outputs.past_key_values,
|
1189 |
+
hidden_states=outputs.hidden_states,
|
1190 |
+
attentions=outputs.attentions,
|
1191 |
+
)
|
1192 |
+
|
1193 |
+
def prepare_inputs_for_generation(
|
1194 |
+
self,
|
1195 |
+
input_ids,
|
1196 |
+
past_key_values=None,
|
1197 |
+
attention_mask=None,
|
1198 |
+
inputs_embeds=None,
|
1199 |
+
cache_position=None,
|
1200 |
+
position_ids=None,
|
1201 |
+
use_cache=True,
|
1202 |
+
**kwargs,
|
1203 |
+
):
|
1204 |
+
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
|
1205 |
+
# Exception 1: when passing input_embeds, input_ids may be missing entries
|
1206 |
+
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
|
1207 |
+
if past_key_values is not None:
|
1208 |
+
if inputs_embeds is not None: # Exception 1
|
1209 |
+
input_ids = input_ids[:, -cache_position.shape[0] :]
|
1210 |
+
elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
|
1211 |
+
input_ids = input_ids[:, cache_position]
|
1212 |
+
|
1213 |
+
if attention_mask is not None and position_ids is None:
|
1214 |
+
# create position_ids on the fly for batch generation
|
1215 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1216 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1217 |
+
if past_key_values:
|
1218 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1219 |
+
|
1220 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1221 |
+
if inputs_embeds is not None and cache_position[0] == 0:
|
1222 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1223 |
+
else:
|
1224 |
+
model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
|
1225 |
+
|
1226 |
+
model_inputs.update(
|
1227 |
+
{
|
1228 |
+
"position_ids": position_ids,
|
1229 |
+
"cache_position": cache_position,
|
1230 |
+
"past_key_values": past_key_values,
|
1231 |
+
"use_cache": use_cache,
|
1232 |
+
"attention_mask": attention_mask,
|
1233 |
+
}
|
1234 |
+
)
|
1235 |
+
return model_inputs
|
1236 |
+
|
1237 |
+
@torch.inference_mode()
|
1238 |
+
def chat(self, tokenizer, query: str, history: List[Dict] = None, role: str = "user",
|
1239 |
+
max_length: int = 65536, num_beams=1, do_sample=True, top_p=0.7, temperature=0.95,
|
1240 |
+
**kwargs):
|
1241 |
+
if history is None:
|
1242 |
+
history = []
|
1243 |
+
gen_kwargs = {"max_length": max_length, "num_beams": num_beams, "do_sample": do_sample, "top_p": top_p,
|
1244 |
+
"temperature": temperature, **kwargs}
|
1245 |
+
inputs = tokenizer.build_chat_input(query, history=history, role=role)
|
1246 |
+
del inputs['token_type_ids']
|
1247 |
+
# print(inputs)
|
1248 |
+
inputs = inputs.to(self.device)
|
1249 |
+
eos_token_id = [tokenizer.eos_token_id, tokenizer.get_command("<|user|>"),
|
1250 |
+
tokenizer.get_command("<|observation|>")]
|
1251 |
+
outputs = self.generate(**inputs, **gen_kwargs, eos_token_id=eos_token_id)
|
1252 |
+
outputs = outputs.tolist()[0][len(inputs["input_ids"][0]):-1]
|
1253 |
+
response = tokenizer.decode(outputs).strip()
|
1254 |
+
history.append({"role": role, "content": query})
|
1255 |
+
return response, history
|
tiktoken_tokenizer.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import regex as re
|
2 |
+
import base64
|
3 |
+
import tiktoken
|
4 |
+
import os
|
5 |
+
import json
|
6 |
+
from transformers import PreTrainedTokenizer
|
7 |
+
|
8 |
+
class BaseTokenizer(PreTrainedTokenizer):
|
9 |
+
"""Abstract class for tokenizer."""
|
10 |
+
|
11 |
+
def __init__(self, **kwargs):
|
12 |
+
super().__init__()
|
13 |
+
|
14 |
+
@property
|
15 |
+
def add_prefix_space(self):
|
16 |
+
return False
|
17 |
+
|
18 |
+
@property
|
19 |
+
def vocab_size(self):
|
20 |
+
raise NotImplemented
|
21 |
+
|
22 |
+
def tokenize(self, text):
|
23 |
+
raise NotImplemented
|
24 |
+
|
25 |
+
def detokenize(self, token_ids, ignore_special_tokens=True):
|
26 |
+
raise NotImplemented
|
27 |
+
|
28 |
+
def build_single_message(self, role, metadata, message):
|
29 |
+
assert role in ["system", "user", "assistant", "observation"], role
|
30 |
+
role_tokens = [self.get_command(f"<|{role}|>")] + self.tokenizer.encode(f"{metadata}\n")
|
31 |
+
message_tokens = self.tokenizer.encode(message, disallowed_special=())
|
32 |
+
tokens = role_tokens + message_tokens
|
33 |
+
return tokens
|
34 |
+
|
35 |
+
def build_chat_input(self, query, history=None, role="user", metadata=""):
|
36 |
+
if history is None:
|
37 |
+
history = []
|
38 |
+
input_ids = []
|
39 |
+
for item in history:
|
40 |
+
content = item["content"]
|
41 |
+
if item["role"] == "system" and "tools" in item:
|
42 |
+
content = content + "\n" + json.dumps(item["tools"], indent=4, ensure_ascii=False)
|
43 |
+
input_ids.extend(self.build_single_message(item["role"], item.get("metadata", ""), content))
|
44 |
+
input_ids.extend(self.build_single_message(role, metadata, query))
|
45 |
+
input_ids.extend([self.get_command("<|assistant|>")])
|
46 |
+
return self.batch_encode_plus([input_ids], return_tensors="pt", is_split_into_words=True)
|
47 |
+
|
48 |
+
@property
|
49 |
+
def eos_id(self):
|
50 |
+
raise NotImplemented
|
51 |
+
|
52 |
+
def get_command(self, token):
|
53 |
+
return NotImplemented
|
54 |
+
|
55 |
+
class TikTokenizer(BaseTokenizer):
|
56 |
+
vocab_files_names = {"vocab_file": "tokenizer.tiktoken"}
|
57 |
+
|
58 |
+
def __init__(self, vocab_file, **kwargs):
|
59 |
+
pat_str = "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
|
60 |
+
self.pat_str = re.compile(pat_str)
|
61 |
+
|
62 |
+
self.b64_vocab = {}
|
63 |
+
mergeable_ranks = {}
|
64 |
+
with open(vocab_file) as f:
|
65 |
+
for line in f:
|
66 |
+
token, rank = line.strip().split()
|
67 |
+
rank = int(rank)
|
68 |
+
token = base64.b64decode(token)
|
69 |
+
mergeable_ranks[token] = rank
|
70 |
+
self.b64_vocab['%s' % token] = rank
|
71 |
+
|
72 |
+
self.special_tokens = ["<|endoftext|>", "[MASK]", "[gMASK]", "[sMASK]", "<sop>", "<eop>", "<|system|>",
|
73 |
+
"<|user|>", "<|assistant|>", "<|observation|>"]
|
74 |
+
self.special_tokens = {
|
75 |
+
token: idx for idx, token in enumerate(self.special_tokens, start=len(mergeable_ranks))
|
76 |
+
}
|
77 |
+
self.special_token_ids = {idx: token for token, idx in self.special_tokens.items()}
|
78 |
+
|
79 |
+
self.tokenizer = tiktoken.Encoding(
|
80 |
+
name="my_tokenizer",
|
81 |
+
pat_str=pat_str,
|
82 |
+
mergeable_ranks=mergeable_ranks,
|
83 |
+
special_tokens=self.special_tokens
|
84 |
+
)
|
85 |
+
self.decoder = {rank: token for token, rank in mergeable_ranks.items()}
|
86 |
+
self.n_words = len(self.decoder) + len(self.special_tokens)
|
87 |
+
super().__init__()
|
88 |
+
|
89 |
+
@property
|
90 |
+
def add_prefix_space(self):
|
91 |
+
return False
|
92 |
+
|
93 |
+
def tokenize(self, text, add_special_tokens=True):
|
94 |
+
ids = self.encode(text, add_special_tokens=add_special_tokens)
|
95 |
+
return [self.convert_id_to_token(_id) for _id in ids]
|
96 |
+
|
97 |
+
def detokenize(self, ids, ignore_special_tokens=True):
|
98 |
+
if ignore_special_tokens:
|
99 |
+
ids = [idx for idx in ids if idx not in self.special_token_ids]
|
100 |
+
return self.tokenizer.decode(ids)
|
101 |
+
|
102 |
+
def encode(self, text, add_special_tokens=True):
|
103 |
+
ids = self.tokenizer.encode(text, disallowed_special=(), allowed_special="all")
|
104 |
+
if add_special_tokens:
|
105 |
+
ids = [self.special_tokens["[gMASK]"], self.special_tokens["<sop>"]] + ids
|
106 |
+
return ids
|
107 |
+
|
108 |
+
def decode(self, ids, skip_special_tokens=False, clean_up_tokenization_spaces=False):
|
109 |
+
if type(ids) is int:
|
110 |
+
ids = [ids]
|
111 |
+
return self.detokenize(ids, ignore_special_tokens=skip_special_tokens)
|
112 |
+
|
113 |
+
def encode_pieces(self, text):
|
114 |
+
ids = self.tokenizer.encode(text, disallowed_special=())
|
115 |
+
return list(map(lambda x: self.decoder[x].detokenize('utf-8', errors='replace'), ids))
|
116 |
+
|
117 |
+
@property
|
118 |
+
def vocab_size(self):
|
119 |
+
return self.n_words
|
120 |
+
|
121 |
+
@property
|
122 |
+
def eos_token_id(self):
|
123 |
+
return self.special_tokens["<|endoftext|>"]
|
124 |
+
|
125 |
+
def convert_token_to_id(self, token):
|
126 |
+
""" Converts a token (str) in an id using the vocab. """
|
127 |
+
if token in self.special_tokens:
|
128 |
+
return self.special_tokens[token]
|
129 |
+
# assert type(token) == str, "type of token (%s) is %s" % (token, type(token))
|
130 |
+
# ids = self.tokenizer.encode(token, disallowed_special=())
|
131 |
+
if token in self.b64_vocab:
|
132 |
+
return self.b64_vocab[token]
|
133 |
+
# if len(ids) == 1:
|
134 |
+
# return ids[0]
|
135 |
+
else:
|
136 |
+
raise RuntimeError(f"{token} is not a single token")
|
137 |
+
|
138 |
+
def _convert_token_to_id(self, token):
|
139 |
+
return self.convert_token_to_id(token)
|
140 |
+
|
141 |
+
def convert_id_to_token(self, index):
|
142 |
+
if index in self.special_token_ids:
|
143 |
+
return self.special_token_ids[index]
|
144 |
+
return '%s' % self.decoder[index]
|
145 |
+
# try:
|
146 |
+
# return self.decoder[index].decode('utf-8')
|
147 |
+
# except Exception as e:
|
148 |
+
# print("Exception: %s for (%d)%s" % (e, index, self.decoder[index]))
|
149 |
+
# return ""
|
150 |
+
#return self.decoder[index].detokenize('utf-8', errors='replace')
|
151 |
+
|
152 |
+
def _convert_id_to_token(self, index):
|
153 |
+
return self.convert_id_to_token(index)
|
154 |
+
|
155 |
+
def get_command(self, token):
|
156 |
+
return self.special_tokens[token]
|
157 |
+
|
158 |
+
def get_vocab(self):
|
159 |
+
vocab = {self._convert_id_to_token(i): i for i in range(self.vocab_size)}
|
160 |
+
return vocab
|
tokenizer.tiktoken
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name_or_path": "THUDM/chatglm4-130b",
|
3 |
+
"remove_space": false,
|
4 |
+
"do_lower_case": false,
|
5 |
+
"tokenizer_class": "TikTokenizer",
|
6 |
+
"auto_map": {
|
7 |
+
"AutoTokenizer": [
|
8 |
+
null,
|
9 |
+
"tiktoken_tokenizer.TikTokenizer"
|
10 |
+
]
|
11 |
+
}
|
12 |
+
}
|