IEIT-Yuan commited on
Commit
584652c
·
1 Parent(s): c4f5000

update model

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.pt* filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,97 @@
1
  ---
2
- license: apache-2.0
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ license: other
3
+ license_name: license-yuan
4
+ license_link: https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/LICENSE-Yuan
5
  ---
6
+
7
+ <div align="center">
8
+ <h1>
9
+ Yuan 2
10
+ </h1>
11
+ </div>
12
+
13
+ <div align="center">
14
+ <a href="https://github.com/IEIT-Yuan/Yuan-2.0" target="_blank"> 💻GitHub Repo</a> | <a href="http://arxiv.org/pdf/2311.15786.pdf" target="_blank">📃Yuan2.0-paper</a>
15
+ </div>
16
+
17
+ # 目录/Table of Contents
18
+
19
+ - [模型介绍/Introduction](#Introduction)
20
+ - [代码调用/Code Usage](#Usage)
21
+ - [Benchmark评估/Benchmark Evaluation](#Benchmark)
22
+ - [声明与协议/Terms and Conditions](#Terms)
23
+ - [引用/Cite](#Cite)
24
+
25
+
26
+ # <span id="Introduction">模型介绍/Introduction</span>
27
+ 源2.0 是浪潮信息发布的新一代基础语言大模型。我们开源了全部的3个模型源2.0-102B,源2.0-51B和源2.0-2B。并且我们提供了预训练,微调,推理服务的相关脚本,以供研发人员做进一步的开发。源2.0是在源1.0的基础上,利用更多样的高质量预训练数据和指令微调数据集,令模型在语义、数学、推理、代码、知识等不同方面具备更强的理解能力。
28
+
29
+ Yuan2.0 is a new generation Fundamental Large Language Model developed by IEIT System. We have published all three models, Yuan 2.0-102B, Yuan 2.0-51B, and Yuan 2.0-2B. And we provide relevant scripts for pretraining, fine-tuning, and inference services for other developers. Yuan2.0 is based on Yuan1.0, utilizing a wider range of high-quality pre training data and instruction fine-tuning datasets to enhance the model's understanding of semantics, mathematics, reasoning, code, knowledge, and other aspects.
30
+
31
+
32
+ # <span id="Usage">代码调用/Code Usage</span>
33
+ 可以通过如下代码调用 Yuan2-2B 模型来生成文本:
34
+
35
+ You can generate text by invoking the Yuan2-2B model with the following code:
36
+
37
+ ```python
38
+ import torch, transformers
39
+ import sys, os
40
+ sys.path.append(
41
+ os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
42
+ from transformers import AutoModelForCausalLM,AutoTokenizer,LlamaTokenizer
43
+
44
+ print("Creat tokenizer...")
45
+ tokenizer = LlamaTokenizer.from_pretrained('yuan2-2B')
46
+ tokenizer.add_tokens(['<sep>', '<pad>', '<mask>', '<predict>', '<FIM_SUFFIX>', '<FIM_PREFIX>', '<FIM_MIDDLE>','<commit_before>','<commit_msg>','<commit_after>','<jupyter_start>','<jupyter_text>','<jupyter_code>','<jupyter_output>','<empty_output>'], special_tokens=True)
47
+
48
+ print("Creat model...")
49
+ model = AutoModelForCausalLM.from_pretrained('yuan2-2B',device_map='auto',torch_dtype=torch.bfloat16,trust_remote_code=True)
50
+
51
+ inputs = tokenizer("请问目前最先进的机器学习算法有哪些?", return_tensors="pt")["input_ids"].to("cuda:0")
52
+ outputs = model.generate(inputs,do_sample=False,max_length=100)
53
+ print(tokenizer.decode(outputs[0]))
54
+
55
+ ```
56
+
57
+ # <span id="Benchmark">Benchmark评估/Benchmark Evaluation</span>
58
+ 我们提供了[HumanEval](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/docs/eval_humaneval.md),[AGIEval-GK-Math](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/docs/eval_agieval_math.md),[GSM8K](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/docs/eval_gsm8k.md)和[TruthfulQA](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/docs/eval_TruthfulQA.md)的评估脚本。在4个典型任务上,我们用源2.0不同版本模型上进行了性能测试。
59
+
60
+ We have provided evaluation scripts for [HumanEval](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/docs/eval_humaneval.md),[AGIEval-GK-Math](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/docs/eval_agieval_math.md),[GSM8K](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/docs/eval_gsm8k.md) and [TruthfulQA](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/docs/eval_TruthfulQA.md). Performance tests were conducted on different versions of the Yuan2.0 model for four typical tasks.
61
+
62
+
63
+ | Model | GSM8K | AGIEval-GK-Math-QA | AGIEval-GK-Math-Cloze | HumanEval | TurthfulQA |
64
+ | ----------------- | :----: | :------------: | :---------------: | :-------: | ---------- |
65
+ | GPT-4 | 92% | 47.0% | 16.1% | 86.6% | 59% |
66
+ | ChatGPT | 68.6%\* | 36.5% | 7.3% | 66.5%\* | 34%\* |
67
+ | Llama2 | 56.8% | - | - | 29.9% | - |
68
+ | 源2.0-102B | 76.6% | 38.7% | 13.5% | 67.1% | 58% |
69
+ | 源2.0-102B-SC | 86.2% | 45.5% | 15.2% | 77.4% | - |
70
+
71
+ \* 使用与源2.0完全相同的输入数据对ChatGPT进行测试,时间2023年11月
72
+
73
+ \* Testing ChatGPT using the same input data as Yuan2.0, as of November 2023.
74
+
75
+ # <span id="Terms">声明与协议/Terms and Conditions</span>
76
+ 对该模型的原代码仓库使用遵循开源许可协议 Apache 2.0。
77
+
78
+ 源2.0模型支持商用,不需要申请授权,请您了解并遵循[《源2.0模型许可协议》](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/LICENSE-Yuan),勿将开源模型和代码及基于开源项目产生的衍生物用于任何可能给国家和社会带来危害的用途以及用于任何未经过安全评估和备案的服务。
79
+
80
+ 尽管模型在训练时我们已采取措施尽力确保数据的合规性和准确性,但模型参数量巨大且受概率随机性因素影响,我们无法保证输出内容的准确性,且模型易被输入指令所误导,本项目不承担开源模型和代码导致的数据安全、舆情风险或发生任何模型被误导、滥用、传播、不当利用而产生的风险和责任。**您将对通过使用、复制、分发和修改模型等方式利用该开源项目所产生的风险与后果,独自承担全部责任。**
81
+
82
+ The use of the original code repository for this model requires compliance with the open source license agreement Apache 2.0. The Yuan2.0 model supports commercial use and does not require authorization. Please understand and comply with the [《Yuan 2.0 Model License Agreement》](https://github.com/IEIT-Yuan/Yuan-2.0/blob/main/LICENSE-Yuan). Do not use the open source model and code, as well as derivatives generated from open source projects, for any purposes that may cause harm to the country and society, or for any services that have not undergone security assessment and filing. Although we have taken measures to ensure the compliance and accuracy of the data during training, the model has a huge number of parameters and is affected by probability and randomness factors. We cannot guarantee the accuracy of the output content, and the model is easily misled by input instructions. This project does not assume any data security, public opinion risks, or any model misleading, abusing, spreading caused by open-source models and code Risks and responsibilities arising from improper utilization **You will be solely responsible for the risks and consequences arising from the use, copying, distribution, and modification of the model in this open source project.**
83
+
84
+ # <span id="Cite">引用/Cite</span>
85
+ 欢迎阅读我们的技术报告 [YUAN 2.0: A Large Language Model with Localized Filtering-based Attention](http://arxiv.org/pdf/2311.15786.pdf)!
86
+
87
+ Welcome to read our technical report [YUAN 2.0: A Large Language Model with Localized Filtering-based Attention](http://arxiv.org/pdf/2311.15786.pdf)!
88
+
89
+ ```latex
90
+ @article{Wu2023,
91
+ title = {{YUAN 2.0: A Large Language Model with Localized Filtering-based Attention}},
92
+ author = {Wu, Shaohua and Zhao, Xudong and Wang, Shenling and Luo, Jiangang and Li, Lingjun and Chen, Xi and Zhao, Bing and Wang, Wei and Yu, Tong and Zhang, Rongguo and Zhang, Jiahua and Wang, Chao},
93
+ url = {http://arxiv.org/abs/2311.15786},
94
+ year = {2023}
95
+ }
96
+
97
+ ```
config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config":true,
3
+ "architectures": [
4
+ "YuanForCausalLM"
5
+ ],
6
+ "auto_map":{
7
+ "AutoConfig":"configuration_yuan.YuanConfig",
8
+ "AutoModelForCausalLM":"yuan_hf_model.YuanForCausalLM"
9
+ },
10
+ "tokenizer_class":"YuanTokenizer",
11
+ "hidden_act": "silu",
12
+ "hidden_size": 2048,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 8192,
15
+ "max_position_embeddings": 8192,
16
+ "model_type": "yuan",
17
+ "num_attention_heads": 32,
18
+ "num_hidden_layers": 24,
19
+ "rms_norm_eps": 1e-06,
20
+ "dropout": 0.1,
21
+ "tie_word_embeddings": true,
22
+ "torch_dtype": "bfloat16",
23
+ "transformers_version": "4.30.0.dev0",
24
+ "use_cache": true,
25
+ "causal_mask": true,
26
+ "use_flash_attention": true,
27
+ "reset_attention_mask": true,
28
+ "reset_position_ids": true,
29
+ "use_loss_mask": false,
30
+ "eod_token": 77185,
31
+ "sep_token": 77187,
32
+ "eod_token_id": 77185,
33
+ "sep_token_id": 77185,
34
+ "pad_token_id": 77185,
35
+ "bos_token_id": 77185,
36
+ "eos_token_id": 77185,
37
+ "mask_token_id": 77185,
38
+ "vocab_size": 135040
39
+ }
40
+
configuration_yuan.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from transformers.configuration_utils import PretrainedConfig
3
+
4
+
5
+ class YuanConfig(PretrainedConfig):
6
+ model_type = "yuan"
7
+ keys_to_ignore_at_inference = ["past_key_values"]
8
+
9
+ def __init__(
10
+ self,
11
+ vocab_size=135040,
12
+ hidden_size=2048,
13
+ intermediate_size=8192,
14
+ num_hidden_layers=24,
15
+ num_attention_heads=32,
16
+ hidden_act="silu",
17
+ model_max_length=8192,
18
+ initializer_range=0.02,
19
+ rms_norm_eps=1e-6,
20
+ use_cache=True,
21
+ pad_token_id=77185,
22
+ bos_token_id=77185,
23
+ eos_token_id=77185,
24
+ tie_word_embeddings=True,
25
+ **kwargs,
26
+ ):
27
+ self.vocab_size = vocab_size
28
+ self.model_max_length = model_max_length
29
+ self.hidden_size = hidden_size
30
+ self.intermediate_size = intermediate_size
31
+ self.num_hidden_layers = num_hidden_layers
32
+ self.num_attention_heads = num_attention_heads
33
+ self.hidden_act = hidden_act
34
+ self.initializer_range = initializer_range
35
+ self.rms_norm_eps = rms_norm_eps
36
+ self.use_cache = use_cache
37
+ super().__init__(
38
+ pad_token_id=pad_token_id,
39
+ bos_token_id=bos_token_id,
40
+ eos_token_id=eos_token_id,
41
+ tie_word_embeddings=tie_word_embeddings,
42
+ **kwargs,
43
+ )
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 77185,
4
+ "eos_token_id": 77185,
5
+ "pad_token_id": 77185,
6
+ "transformers_version": "4.30.2"
7
+ }
pytorch_model-00001-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2ac795a489f91d381be54c8cd408f5fc4ed76797736419c5cf9fb04c7d1015c2
3
+ size 1996194152
pytorch_model-00002-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07101d671ef92940ddf07f387e3ca665612f84e604824128f7ad766e961eabb5
3
+ size 1996799819
pytorch_model-00003-of-00003.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cacf148769038009d769b13faf75174cb9162b96ef44c500b856cc44f722b407
3
+ size 184587257
pytorch_model.bin.index.json ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 4177452032
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "pytorch_model-00001-of-00003.bin",
7
+ "model.embed_tokens.weight": "pytorch_model-00001-of-00003.bin",
8
+ "model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
9
+ "model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
10
+ "model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
11
+ "model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
12
+ "model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
13
+ "model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
14
+ "model.layers.0.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
15
+ "model.layers.0.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
16
+ "model.layers.0.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
17
+ "model.layers.0.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
18
+ "model.layers.0.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
19
+ "model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
20
+ "model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
21
+ "model.layers.0.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
22
+ "model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
23
+ "model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
24
+ "model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
25
+ "model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
26
+ "model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
27
+ "model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
28
+ "model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
29
+ "model.layers.1.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
30
+ "model.layers.1.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
31
+ "model.layers.1.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
32
+ "model.layers.1.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
33
+ "model.layers.1.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
34
+ "model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
35
+ "model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
36
+ "model.layers.1.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
37
+ "model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
38
+ "model.layers.10.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
39
+ "model.layers.10.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
40
+ "model.layers.10.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
41
+ "model.layers.10.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
42
+ "model.layers.10.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
43
+ "model.layers.10.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
44
+ "model.layers.10.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
45
+ "model.layers.10.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
46
+ "model.layers.10.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
47
+ "model.layers.10.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
48
+ "model.layers.10.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
49
+ "model.layers.10.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
50
+ "model.layers.10.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
51
+ "model.layers.10.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
52
+ "model.layers.10.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
53
+ "model.layers.11.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
54
+ "model.layers.11.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
55
+ "model.layers.11.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
56
+ "model.layers.11.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
57
+ "model.layers.11.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
58
+ "model.layers.11.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
59
+ "model.layers.11.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
60
+ "model.layers.11.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
61
+ "model.layers.11.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
62
+ "model.layers.11.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
63
+ "model.layers.11.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
64
+ "model.layers.11.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
65
+ "model.layers.11.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
66
+ "model.layers.11.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
67
+ "model.layers.11.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
68
+ "model.layers.12.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
69
+ "model.layers.12.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
70
+ "model.layers.12.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
71
+ "model.layers.12.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
72
+ "model.layers.12.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
73
+ "model.layers.12.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
74
+ "model.layers.12.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
75
+ "model.layers.12.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
76
+ "model.layers.12.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
77
+ "model.layers.12.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
78
+ "model.layers.12.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
79
+ "model.layers.12.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
80
+ "model.layers.12.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
81
+ "model.layers.12.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
82
+ "model.layers.12.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
83
+ "model.layers.13.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
84
+ "model.layers.13.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
85
+ "model.layers.13.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
86
+ "model.layers.13.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
87
+ "model.layers.13.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
88
+ "model.layers.13.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
89
+ "model.layers.13.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
90
+ "model.layers.13.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
91
+ "model.layers.13.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
92
+ "model.layers.13.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
93
+ "model.layers.13.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
94
+ "model.layers.13.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
95
+ "model.layers.13.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
96
+ "model.layers.13.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
97
+ "model.layers.13.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
98
+ "model.layers.14.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
99
+ "model.layers.14.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
100
+ "model.layers.14.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
101
+ "model.layers.14.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
102
+ "model.layers.14.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
103
+ "model.layers.14.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
104
+ "model.layers.14.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
105
+ "model.layers.14.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
106
+ "model.layers.14.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
107
+ "model.layers.14.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
108
+ "model.layers.14.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
109
+ "model.layers.14.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
110
+ "model.layers.14.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
111
+ "model.layers.14.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
112
+ "model.layers.14.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
113
+ "model.layers.15.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
114
+ "model.layers.15.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
115
+ "model.layers.15.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
116
+ "model.layers.15.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
117
+ "model.layers.15.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
118
+ "model.layers.15.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
119
+ "model.layers.15.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
120
+ "model.layers.15.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
121
+ "model.layers.15.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
122
+ "model.layers.15.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
123
+ "model.layers.15.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
124
+ "model.layers.15.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
125
+ "model.layers.15.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
126
+ "model.layers.15.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
127
+ "model.layers.15.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
128
+ "model.layers.16.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
129
+ "model.layers.16.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
130
+ "model.layers.16.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
131
+ "model.layers.16.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
132
+ "model.layers.16.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
133
+ "model.layers.16.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
134
+ "model.layers.16.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
135
+ "model.layers.16.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
136
+ "model.layers.16.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
137
+ "model.layers.16.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
138
+ "model.layers.16.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
139
+ "model.layers.16.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
140
+ "model.layers.16.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
141
+ "model.layers.16.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
142
+ "model.layers.16.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
143
+ "model.layers.17.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
144
+ "model.layers.17.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
145
+ "model.layers.17.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
146
+ "model.layers.17.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
147
+ "model.layers.17.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
148
+ "model.layers.17.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
149
+ "model.layers.17.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
150
+ "model.layers.17.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
151
+ "model.layers.17.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
152
+ "model.layers.17.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
153
+ "model.layers.17.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
154
+ "model.layers.17.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
155
+ "model.layers.17.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
156
+ "model.layers.17.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
157
+ "model.layers.17.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
158
+ "model.layers.18.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
159
+ "model.layers.18.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
160
+ "model.layers.18.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
161
+ "model.layers.18.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
162
+ "model.layers.18.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
163
+ "model.layers.18.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
164
+ "model.layers.18.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
165
+ "model.layers.18.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
166
+ "model.layers.18.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
167
+ "model.layers.18.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
168
+ "model.layers.18.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
169
+ "model.layers.18.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
170
+ "model.layers.18.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
171
+ "model.layers.18.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
172
+ "model.layers.18.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
173
+ "model.layers.19.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
174
+ "model.layers.19.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
175
+ "model.layers.19.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
176
+ "model.layers.19.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
177
+ "model.layers.19.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
178
+ "model.layers.19.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
179
+ "model.layers.19.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
180
+ "model.layers.19.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
181
+ "model.layers.19.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
182
+ "model.layers.19.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
183
+ "model.layers.19.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
184
+ "model.layers.19.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
185
+ "model.layers.19.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
186
+ "model.layers.19.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
187
+ "model.layers.19.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
188
+ "model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
189
+ "model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
190
+ "model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
191
+ "model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
192
+ "model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
193
+ "model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
194
+ "model.layers.2.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
195
+ "model.layers.2.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
196
+ "model.layers.2.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
197
+ "model.layers.2.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
198
+ "model.layers.2.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
199
+ "model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
200
+ "model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
201
+ "model.layers.2.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
202
+ "model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
203
+ "model.layers.20.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
204
+ "model.layers.20.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
205
+ "model.layers.20.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
206
+ "model.layers.20.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
207
+ "model.layers.20.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
208
+ "model.layers.20.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
209
+ "model.layers.20.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
210
+ "model.layers.20.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
211
+ "model.layers.20.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
212
+ "model.layers.20.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
213
+ "model.layers.20.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
214
+ "model.layers.20.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
215
+ "model.layers.20.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
216
+ "model.layers.20.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
217
+ "model.layers.20.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
218
+ "model.layers.21.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
219
+ "model.layers.21.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
220
+ "model.layers.21.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
221
+ "model.layers.21.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
222
+ "model.layers.21.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
223
+ "model.layers.21.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
224
+ "model.layers.21.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
225
+ "model.layers.21.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
226
+ "model.layers.21.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
227
+ "model.layers.21.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
228
+ "model.layers.21.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
229
+ "model.layers.21.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
230
+ "model.layers.21.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
231
+ "model.layers.21.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
232
+ "model.layers.21.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
233
+ "model.layers.22.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
234
+ "model.layers.22.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
235
+ "model.layers.22.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
236
+ "model.layers.22.mlp.up_proj.weight": "pytorch_model-00002-of-00003.bin",
237
+ "model.layers.22.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
238
+ "model.layers.22.self_attn.k_proj.weight": "pytorch_model-00002-of-00003.bin",
239
+ "model.layers.22.self_attn.lf_gate.conv1.bias": "pytorch_model-00002-of-00003.bin",
240
+ "model.layers.22.self_attn.lf_gate.conv1.weight": "pytorch_model-00002-of-00003.bin",
241
+ "model.layers.22.self_attn.lf_gate.conv2.bias": "pytorch_model-00002-of-00003.bin",
242
+ "model.layers.22.self_attn.lf_gate.conv2.weight": "pytorch_model-00002-of-00003.bin",
243
+ "model.layers.22.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00002-of-00003.bin",
244
+ "model.layers.22.self_attn.o_proj.weight": "pytorch_model-00002-of-00003.bin",
245
+ "model.layers.22.self_attn.q_proj.weight": "pytorch_model-00002-of-00003.bin",
246
+ "model.layers.22.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00003.bin",
247
+ "model.layers.22.self_attn.v_proj.weight": "pytorch_model-00002-of-00003.bin",
248
+ "model.layers.23.input_layernorm.weight": "pytorch_model-00003-of-00003.bin",
249
+ "model.layers.23.mlp.down_proj.weight": "pytorch_model-00003-of-00003.bin",
250
+ "model.layers.23.mlp.gate_proj.weight": "pytorch_model-00003-of-00003.bin",
251
+ "model.layers.23.mlp.up_proj.weight": "pytorch_model-00003-of-00003.bin",
252
+ "model.layers.23.post_attention_layernorm.weight": "pytorch_model-00003-of-00003.bin",
253
+ "model.layers.23.self_attn.k_proj.weight": "pytorch_model-00003-of-00003.bin",
254
+ "model.layers.23.self_attn.lf_gate.conv1.bias": "pytorch_model-00003-of-00003.bin",
255
+ "model.layers.23.self_attn.lf_gate.conv1.weight": "pytorch_model-00003-of-00003.bin",
256
+ "model.layers.23.self_attn.lf_gate.conv2.bias": "pytorch_model-00003-of-00003.bin",
257
+ "model.layers.23.self_attn.lf_gate.conv2.weight": "pytorch_model-00003-of-00003.bin",
258
+ "model.layers.23.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00003-of-00003.bin",
259
+ "model.layers.23.self_attn.o_proj.weight": "pytorch_model-00003-of-00003.bin",
260
+ "model.layers.23.self_attn.q_proj.weight": "pytorch_model-00003-of-00003.bin",
261
+ "model.layers.23.self_attn.rotary_emb.inv_freq": "pytorch_model-00003-of-00003.bin",
262
+ "model.layers.23.self_attn.v_proj.weight": "pytorch_model-00003-of-00003.bin",
263
+ "model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
264
+ "model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
265
+ "model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
266
+ "model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
267
+ "model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
268
+ "model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
269
+ "model.layers.3.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
270
+ "model.layers.3.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
271
+ "model.layers.3.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
272
+ "model.layers.3.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
273
+ "model.layers.3.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
274
+ "model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
275
+ "model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
276
+ "model.layers.3.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
277
+ "model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
278
+ "model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
279
+ "model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
280
+ "model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
281
+ "model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
282
+ "model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
283
+ "model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
284
+ "model.layers.4.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
285
+ "model.layers.4.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
286
+ "model.layers.4.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
287
+ "model.layers.4.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
288
+ "model.layers.4.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
289
+ "model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
290
+ "model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
291
+ "model.layers.4.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
292
+ "model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
293
+ "model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
294
+ "model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
295
+ "model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
296
+ "model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
297
+ "model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
298
+ "model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
299
+ "model.layers.5.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
300
+ "model.layers.5.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
301
+ "model.layers.5.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
302
+ "model.layers.5.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
303
+ "model.layers.5.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
304
+ "model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
305
+ "model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
306
+ "model.layers.5.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
307
+ "model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
308
+ "model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
309
+ "model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
310
+ "model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
311
+ "model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
312
+ "model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
313
+ "model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
314
+ "model.layers.6.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
315
+ "model.layers.6.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
316
+ "model.layers.6.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
317
+ "model.layers.6.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
318
+ "model.layers.6.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
319
+ "model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
320
+ "model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
321
+ "model.layers.6.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
322
+ "model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
323
+ "model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
324
+ "model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
325
+ "model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
326
+ "model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
327
+ "model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
328
+ "model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
329
+ "model.layers.7.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
330
+ "model.layers.7.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
331
+ "model.layers.7.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
332
+ "model.layers.7.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
333
+ "model.layers.7.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
334
+ "model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
335
+ "model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
336
+ "model.layers.7.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
337
+ "model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
338
+ "model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00003.bin",
339
+ "model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00003.bin",
340
+ "model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00003.bin",
341
+ "model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
342
+ "model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00003.bin",
343
+ "model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
344
+ "model.layers.8.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
345
+ "model.layers.8.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
346
+ "model.layers.8.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
347
+ "model.layers.8.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
348
+ "model.layers.8.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
349
+ "model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
350
+ "model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
351
+ "model.layers.8.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
352
+ "model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
353
+ "model.layers.9.input_layernorm.weight": "pytorch_model-00002-of-00003.bin",
354
+ "model.layers.9.mlp.down_proj.weight": "pytorch_model-00002-of-00003.bin",
355
+ "model.layers.9.mlp.gate_proj.weight": "pytorch_model-00002-of-00003.bin",
356
+ "model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00003.bin",
357
+ "model.layers.9.post_attention_layernorm.weight": "pytorch_model-00002-of-00003.bin",
358
+ "model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00003.bin",
359
+ "model.layers.9.self_attn.lf_gate.conv1.bias": "pytorch_model-00001-of-00003.bin",
360
+ "model.layers.9.self_attn.lf_gate.conv1.weight": "pytorch_model-00001-of-00003.bin",
361
+ "model.layers.9.self_attn.lf_gate.conv2.bias": "pytorch_model-00001-of-00003.bin",
362
+ "model.layers.9.self_attn.lf_gate.conv2.weight": "pytorch_model-00001-of-00003.bin",
363
+ "model.layers.9.self_attn.lf_gate.output_layernorm.weight": "pytorch_model-00001-of-00003.bin",
364
+ "model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00003.bin",
365
+ "model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00003.bin",
366
+ "model.layers.9.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00003.bin",
367
+ "model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00003.bin",
368
+ "model.norm.weight": "pytorch_model-00003-of-00003.bin"
369
+ }
370
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "</s>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "unk_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": true,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ }
23
+ }
tokenizer.model ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36f79e0c70f73cdd2a8dd0fbe7bfe290da158eea746778d289e4ad76c8b383d9
3
+ size 2155861
tokenizer_config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": true,
4
+ "bos_token": {
5
+ "__type": "AddedToken",
6
+ "content": "<s>",
7
+ "lstrip": false,
8
+ "normalized": true,
9
+ "rstrip": false,
10
+ "single_word": false
11
+ },
12
+ "clean_up_tokenization_spaces": false,
13
+ "eos_token": {
14
+ "__type": "AddedToken",
15
+ "content": "</s>",
16
+ "lstrip": false,
17
+ "normalized": true,
18
+ "rstrip": false,
19
+ "single_word": false
20
+ },
21
+ "model_max_length": 1000000000000000019884624838656,
22
+ "pad_token": null,
23
+ "sp_model_kwargs": {},
24
+ "tokenizer_class": "LlamaTokenizer",
25
+ "unk_token": {
26
+ "__type": "AddedToken",
27
+ "content": "<unk>",
28
+ "lstrip": false,
29
+ "normalized": true,
30
+ "rstrip": false,
31
+ "single_word": false
32
+ }
33
+ }
yuan_hf_model.py ADDED
@@ -0,0 +1,1140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch Yuan model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+ import torch.nn.functional as F
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm,LlamaRotaryEmbedding
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
33
+ from .configuration_yuan import YuanConfig
34
+ from einops import rearrange
35
+ from flash_attn import flash_attn_varlen_func as flash_attn_unpadded_func
36
+ from flash_attn import flash_attn_func
37
+
38
+ import copy
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CONFIG_FOR_DOC = "YuanConfig"
43
+
44
+
45
+ class LocalizedFiltering(torch.nn.Module):
46
+ """
47
+ Mega's Exponential Moving Average layer, largely left unmodified from the original repo with the exception of
48
+ variable names and moving away from the stateful representation of incremental decoding state. See
49
+ "https://arxiv.org/abs/2209.10655" for more details.
50
+ """
51
+
52
+ def __init__(self, hidden_size):
53
+ super().__init__()
54
+
55
+ self.embed_dim = hidden_size
56
+ self.lf_conv2d_group = 1
57
+ self.lf_conv2d_num_pad = 1
58
+
59
+ self.conv1 = torch.nn.Conv2d(self.embed_dim, self.embed_dim // 2, (2, 1), stride=(1, 1), padding=(self.lf_conv2d_num_pad, 0), groups=self.lf_conv2d_group)
60
+ self.conv2 = torch.nn.Conv2d(self.embed_dim // 2, self.embed_dim, (2, 1), stride=(1, 1), padding=(self.lf_conv2d_num_pad, 0), groups=self.lf_conv2d_group)
61
+
62
+ #Use the same RMSNorm as llama
63
+ self.output_layernorm = LlamaRMSNorm(self.embed_dim)
64
+
65
+ def _train_forward(self, inputs):
66
+ inputs = inputs.transpose(0,1)
67
+ seq_len, bsz, embed_dim = inputs.size()
68
+ if embed_dim != self.embed_dim:
69
+ raise ValueError(
70
+ f"Unexpected embedding dimension received: input is {embed_dim}, model expects {self.embed_dim}"
71
+ )
72
+ residual = inputs
73
+
74
+ inputs = inputs.view(seq_len, 1, bsz, embed_dim).permute(2, 3, 0, 1)
75
+ output1 = self.conv1(inputs)
76
+ output1 = output1[:, :, :seq_len, :]
77
+
78
+ output2 = self.conv2(output1)
79
+ output2 = output2[:, :, :seq_len, :].permute(2, 3, 0, 1).contiguous()
80
+ output2 = output2.view(seq_len, bsz, embed_dim)
81
+ assert output2.shape == residual.shape
82
+
83
+ lf_output = self.output_layernorm(output2 + residual)
84
+ lf_output = lf_output.transpose(0,1)
85
+ return lf_output
86
+
87
+ def _inference_forward(self, inputs, before_hidden_states):
88
+
89
+ if before_hidden_states is None:
90
+ inputs = inputs.transpose(0,1)
91
+ seq_len, bsz, embed_dim = inputs.size()
92
+ if embed_dim != self.embed_dim:
93
+ raise ValueError(
94
+ f"Unexpected embedding dimension received: input is {embed_dim}, model expects {self.embed_dim}"
95
+ )
96
+ residual = inputs
97
+
98
+ inputs = inputs.view(seq_len, 1, bsz, embed_dim).permute(2, 3, 0, 1)
99
+ output1 = self.conv1(inputs)
100
+ output1 = output1[:, :, :seq_len, :]
101
+
102
+ output2 = self.conv2(output1)
103
+ output2 = output2[:, :, :seq_len, :].permute(2, 3, 0, 1).contiguous()
104
+ output2 = output2.view(seq_len, bsz, embed_dim)
105
+ assert output2.shape == residual.shape
106
+
107
+ lf_output = self.output_layernorm(output2 + residual)
108
+ lf_output = lf_output.transpose(0,1)
109
+ return lf_output
110
+ else:
111
+ inputs = inputs.transpose(0,1)
112
+ before_hidden_states = before_hidden_states.transpose(0,1)
113
+ residual = inputs
114
+
115
+ seq_len, bsz, embed_dim = inputs.size()
116
+ seq_len_before, _, _ = before_hidden_states.size()
117
+
118
+ assert seq_len == 1 and seq_len_before == 2
119
+
120
+ inputs = torch.cat((before_hidden_states, inputs), dim=0)
121
+ inputs = inputs.view(3, 1, bsz, embed_dim).permute(2, 3, 0, 1)
122
+
123
+ output1 = self.conv1(inputs)
124
+ output2 = self.conv2(output1[:,:,1:-1,:])
125
+ output2 = output2[:,:,1:-1,:]
126
+ output2 = output2.view(1, bsz, embed_dim)
127
+ assert output2.shape == residual.shape
128
+
129
+ lf_output = self.output_layernorm(output2 + residual)
130
+ lf_output = lf_output.transpose(0,1)
131
+
132
+ return lf_output
133
+
134
+
135
+
136
+ def forward(
137
+ self,
138
+ inputs,
139
+ before_hidden_states
140
+ ) -> torch.Tensor:
141
+ assert self.lf_conv2d_num_pad == 1
142
+ if self.training:
143
+ lf_output = self._train_forward(inputs)
144
+ else:
145
+ lf_output = self._inference_forward(inputs, before_hidden_states)
146
+
147
+ return lf_output
148
+
149
+
150
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
151
+ def _make_causal_mask(
152
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
153
+ ):
154
+ """
155
+ Make causal mask used for bi-directional self-attention.
156
+ """
157
+ bsz, tgt_len = input_ids_shape
158
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
159
+ mask_cond = torch.arange(mask.size(-1), device=device)
160
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
161
+ mask = mask.to(dtype)
162
+
163
+ if past_key_values_length > 0:
164
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
165
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
166
+
167
+
168
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
169
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
170
+ """
171
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
172
+ """
173
+ bsz, src_len = mask.size()
174
+ tgt_len = tgt_len if tgt_len is not None else src_len
175
+
176
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
177
+
178
+ inverted_mask = 1.0 - expanded_mask
179
+
180
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
181
+
182
+
183
+ def rotate_half(x):
184
+ """Rotates half the hidden dims of the input."""
185
+ x1 = x[..., : x.shape[-1] // 2]
186
+ x2 = x[..., x.shape[-1] // 2 :]
187
+ return torch.cat((-x2, x1), dim=-1)
188
+
189
+
190
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
191
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
192
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
193
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
194
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
195
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
196
+ q_embed = (q * cos) + (rotate_half(q) * sin)
197
+ k_embed = (k * cos) + (rotate_half(k) * sin)
198
+ return q_embed, k_embed
199
+
200
+
201
+
202
+ class YuanMLP(nn.Module):
203
+ def __init__(
204
+ self,
205
+ hidden_size: int,
206
+ intermediate_size: int,
207
+ hidden_act: str,
208
+ ):
209
+ super().__init__()
210
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
211
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
212
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
213
+ self.act_fn = ACT2FN[hidden_act]
214
+
215
+ def forward(self, x):
216
+ return self.down_proj(self.gate_proj(x) * self.act_fn(self.up_proj(x)))
217
+
218
+ class YuanAttention(nn.Module):
219
+ """Localized Filtering-based Attention 'YUAN 2.0: A Large Language Model with Localized Filtering-based Attention' paper"""
220
+
221
+ def __init__(self, config: YuanConfig):
222
+ super().__init__()
223
+ self.config = config
224
+ self.hidden_size = config.hidden_size
225
+ self.num_heads = config.num_attention_heads
226
+ self.head_dim = self.hidden_size // self.num_heads
227
+ self.max_position_embeddings = config.max_position_embeddings
228
+ self.causal_mask = config.causal_mask
229
+ self.softmax_scale = 1.0 / math.sqrt(self.head_dim)
230
+ self.use_flash_attention = config.use_flash_attention
231
+ try:
232
+ self.use_shareqk = config.use_shareqk
233
+ except Exception as e:
234
+ self.use_shareqk=False
235
+ self.dropout = 0.0
236
+ if (self.head_dim * self.num_heads) != self.hidden_size:
237
+ raise ValueError(
238
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
239
+ f" and `num_heads`: {self.num_heads})."
240
+ )
241
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
242
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
243
+ #Use the same RoataryEmbedding as llama
244
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
245
+ if self.use_shareqk:
246
+ self.qk_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
247
+ self.qk_weight = nn.Parameter(torch.Tensor(2, self.hidden_size))
248
+ self.qk_bias = nn.Parameter(torch.Tensor(2, self.hidden_size))
249
+ else:
250
+ self.lf_gate = LocalizedFiltering(self.hidden_size)
251
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
252
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
253
+
254
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
255
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
256
+
257
+ def forward(
258
+ self,
259
+ hidden_states: torch.Tensor,
260
+ attention_mask: Optional[torch.Tensor] = None,
261
+ position_ids: Optional[torch.LongTensor] = None,
262
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
263
+ output_attentions: bool = False,
264
+ use_cache: bool = False,
265
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
266
+ bsz, q_len, _ = hidden_states.size()
267
+ before_hidden_states = None
268
+ is_first_step = False
269
+ if use_cache:
270
+ if past_key_value is None:
271
+ inference_hidden_states_memory = torch.empty(bsz, 2, hidden_states.shape[2], dtype=hidden_states.dtype ,device=torch.cuda.current_device())
272
+ is_first_step = True
273
+ else:
274
+ before_hidden_states = past_key_value[2]
275
+
276
+ if use_cache:
277
+ if is_first_step:
278
+ if q_len >= 2:
279
+ inference_hidden_states_memory = hidden_states[ :, -2:, :]
280
+ else:
281
+ inference_hidden_states_memory[:, :, :] = 0
282
+ inference_hidden_states_memory[:, -1:, :] = hidden_states[:, -1:, :]
283
+ else:
284
+ hidden_states_tmp = before_hidden_states[:, -1:, :]
285
+ inference_hidden_states_memory = copy.deepcopy(torch.cat((hidden_states_tmp, hidden_states), dim=1))
286
+
287
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
288
+ if self.use_shareqk:
289
+ qk_states = self.qk_proj(hidden_states).view(bsz, q_len, self.num_heads*self.head_dim)
290
+ query_key = qk_states.unsqueeze(2) * self.qk_weight + self.qk_bias
291
+ query_states, key_states = torch.unbind(query_key, dim=2)
292
+
293
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
294
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
295
+ else:
296
+ hidden_states = self.lf_gate(hidden_states,before_hidden_states)
297
+ query_states = self.q_proj(hidden_states)
298
+ key_states = self.k_proj(hidden_states)
299
+ qk_states = torch.cat([query_states, key_states], dim=-1)
300
+ qk_states = qk_states.view(bsz,q_len,self.num_heads,int(qk_states.shape[-1]//self.num_heads))
301
+ (query_states,key_states) = torch.chunk(qk_states, 2, dim=-1)
302
+ query_states = query_states.transpose(1, 2)
303
+ key_states = key_states.transpose(1, 2)
304
+
305
+
306
+ kv_seq_len = key_states.shape[-2]
307
+ if past_key_value is not None:
308
+ kv_seq_len += past_key_value[0].shape[-2]
309
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
310
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
311
+
312
+ if past_key_value is not None:
313
+ # reuse k, v, self_attention
314
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
315
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
316
+
317
+ past_key_value = (key_states, value_states,inference_hidden_states_memory) if use_cache else None
318
+
319
+ if self.use_flash_attention:
320
+ attn_weights = None
321
+ query_states = query_states.transpose(1, 2)
322
+ key_states = key_states.transpose(1, 2)
323
+ value_states = value_states.transpose(1, 2)
324
+
325
+ batch_size, seqlen_q = query_states.shape[0], query_states.shape[1]
326
+ seqlen_k = key_states.shape[1]
327
+
328
+ q, k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [query_states, key_states, value_states]]
329
+
330
+ cu_seqlens_q = torch.arange(0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int,
331
+ device=q.device)
332
+
333
+ if self.training:
334
+ assert seqlen_k == seqlen_q
335
+ cu_seqlens_k = cu_seqlens_q
336
+ is_causal = self.causal_mask
337
+ else:
338
+ is_causal = seqlen_q == seqlen_k
339
+ cu_seqlens_k = torch.arange(0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int,
340
+ device=q.device)
341
+ self.dropout=0
342
+
343
+ output = flash_attn_unpadded_func(
344
+ q, k, v, cu_seqlens_q, cu_seqlens_k, seqlen_q, seqlen_k, self.dropout, causal=is_causal
345
+ )
346
+
347
+ attn_output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
348
+ else:
349
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
350
+
351
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
352
+ raise ValueError(
353
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
354
+ f" {attn_weights.size()}"
355
+ )
356
+ if attention_mask is not None:
357
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
358
+ raise ValueError(
359
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
360
+ )
361
+ attn_weights = attn_weights + attention_mask
362
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
363
+
364
+ # upcast attention to fp32
365
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
366
+ attn_output = torch.matmul(attn_weights, value_states)
367
+
368
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
369
+ raise ValueError(
370
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
371
+ f" {attn_output.size()}"
372
+ )
373
+
374
+ attn_output = attn_output.transpose(1, 2)
375
+
376
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
377
+
378
+ attn_output = self.o_proj(attn_output)
379
+
380
+ if not output_attentions:
381
+ attn_weights = None
382
+ return attn_output, attn_weights, past_key_value
383
+
384
+
385
+ class YuanDecoderLayer(nn.Module):
386
+ def __init__(self, config: YuanConfig):
387
+ super().__init__()
388
+ self.hidden_size = config.hidden_size
389
+ self.self_attn = YuanAttention(config=config)
390
+ self.mlp = YuanMLP(
391
+ hidden_size=self.hidden_size,
392
+ intermediate_size=config.intermediate_size,
393
+ hidden_act=config.hidden_act,
394
+ )
395
+ #Use the same RMSNorm as llama
396
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
397
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
398
+
399
+ def forward(
400
+ self,
401
+ hidden_states: torch.Tensor,
402
+ attention_mask: Optional[torch.Tensor] = None,
403
+ position_ids: Optional[torch.LongTensor] = None,
404
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
405
+ output_attentions: Optional[bool] = False,
406
+ use_cache: Optional[bool] = False,
407
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
408
+ """
409
+ Args:
410
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
411
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
412
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
413
+ output_attentions (`bool`, *optional*):
414
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
415
+ returned tensors for more detail.
416
+ use_cache (`bool`, *optional*):
417
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
418
+ (see `past_key_values`).
419
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
420
+ """
421
+
422
+ residual = hidden_states
423
+ hidden_states = self.input_layernorm(hidden_states)
424
+
425
+ # Self Attention
426
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
427
+ hidden_states=hidden_states,
428
+ attention_mask=attention_mask,
429
+ position_ids=position_ids,
430
+ past_key_value=past_key_value,
431
+ output_attentions=output_attentions,
432
+ use_cache=use_cache,
433
+ )
434
+ hidden_states = residual + hidden_states
435
+
436
+ # Fully Connected
437
+ residual = hidden_states
438
+ hidden_states = self.post_attention_layernorm(hidden_states)
439
+ hidden_states = self.mlp(hidden_states)
440
+ hidden_states = residual + hidden_states
441
+
442
+ outputs = (hidden_states,)
443
+
444
+ if output_attentions:
445
+ outputs += (self_attn_weights,)
446
+
447
+ if use_cache:
448
+ outputs += (present_key_value,)
449
+
450
+ return outputs
451
+
452
+
453
+ YUAN_START_DOCSTRING = r"""
454
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
455
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
456
+ etc.)
457
+
458
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
459
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
460
+ and behavior.
461
+
462
+ Parameters:
463
+ config ([`YuanConfig`]):
464
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
465
+ load the weights associated with the model, only the configuration. Check out the
466
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
467
+ """
468
+
469
+
470
+ @add_start_docstrings(
471
+ "The bare Yuan Model outputting raw hidden-states without any specific head on top.",
472
+ YUAN_START_DOCSTRING,
473
+ )
474
+ class YuanPreTrainedModel(PreTrainedModel):
475
+ config_class = YuanConfig
476
+ base_model_prefix = "model"
477
+ supports_gradient_checkpointing = True
478
+ _no_split_modules = ["YuanDecoderLayer"]
479
+ _skip_keys_device_placement = "past_key_values"
480
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
481
+
482
+ def _init_weights(self, module):
483
+ std = self.config.initializer_range
484
+ if isinstance(module, nn.Linear):
485
+ module.weight.data.normal_(mean=0.0, std=std)
486
+ if module.bias is not None:
487
+ module.bias.data.zero_()
488
+ elif isinstance(module, nn.Embedding):
489
+ module.weight.data.normal_(mean=0.0, std=std)
490
+ if module.padding_idx is not None:
491
+ module.weight.data[module.padding_idx].zero_()
492
+
493
+ def _set_gradient_checkpointing(self, module, value=False):
494
+ if isinstance(module, YuanModel):
495
+ module.gradient_checkpointing = value
496
+
497
+
498
+ YUAN_INPUTS_DOCSTRING = r"""
499
+ Args:
500
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
501
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
502
+ it.
503
+
504
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
505
+ [`PreTrainedTokenizer.__call__`] for details.
506
+
507
+ [What are input IDs?](../glossary#input-ids)
508
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
509
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
510
+
511
+ - 1 for tokens that are **not masked**,
512
+ - 0 for tokens that are **masked**.
513
+
514
+ [What are attention masks?](../glossary#attention-mask)
515
+
516
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
517
+ [`PreTrainedTokenizer.__call__`] for details.
518
+
519
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
520
+ `past_key_values`).
521
+
522
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
523
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
524
+ information on the default strategy.
525
+
526
+ - 1 indicates the head is **not masked**,
527
+ - 0 indicates the head is **masked**.
528
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
529
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
530
+ config.n_positions - 1]`.
531
+
532
+ [What are position IDs?](../glossary#position-ids)
533
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
534
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
535
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
536
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
537
+
538
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
539
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
540
+
541
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
542
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
543
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
544
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
545
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
546
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
547
+ model's internal embedding lookup matrix.
548
+ use_cache (`bool`, *optional*):
549
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
550
+ `past_key_values`).
551
+ output_attentions (`bool`, *optional*):
552
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
553
+ tensors for more detail.
554
+ output_hidden_states (`bool`, *optional*):
555
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
556
+ more detail.
557
+ return_dict (`bool`, *optional*):
558
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
559
+ """
560
+
561
+
562
+ @add_start_docstrings(
563
+ "The bare Yuan Model outputting raw hidden-states without any specific head on top.",
564
+ YUAN_START_DOCSTRING,
565
+ )
566
+ class YuanModel(YuanPreTrainedModel):
567
+ """
568
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`YuanDecoderLayer`]
569
+
570
+ Args:
571
+ config: YuanConfig
572
+ """
573
+
574
+ def __init__(self, config: YuanConfig):
575
+ super().__init__(config)
576
+ self.padding_idx = config.pad_token_id
577
+ self.vocab_size = config.vocab_size
578
+
579
+ #TODO: control it by config
580
+ self.eod_token = config.eod_token
581
+ self.reset_attention_mask = config.reset_attention_mask
582
+ self.reset_position_ids = config.reset_position_ids
583
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
584
+ self.layers = nn.ModuleList([YuanDecoderLayer(config) for _ in range(config.num_hidden_layers)])
585
+ #Use the same RMSNorm as llama
586
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
587
+ self.gradient_checkpointing = False
588
+ # Initialize weights and apply final processing
589
+ self.post_init()
590
+
591
+ def get_input_embeddings(self):
592
+ return self.embed_tokens
593
+
594
+ def set_input_embeddings(self, value):
595
+ self.embed_tokens = value
596
+
597
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
598
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
599
+ # create causal mask
600
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
601
+ combined_attention_mask = None
602
+ if input_shape[-1] > 1:
603
+ combined_attention_mask = _make_causal_mask(
604
+ input_shape,
605
+ inputs_embeds.dtype,
606
+ device=inputs_embeds.device,
607
+ past_key_values_length=past_key_values_length,
608
+ )
609
+
610
+ if attention_mask is not None:
611
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
612
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
613
+ inputs_embeds.device
614
+ )
615
+ combined_attention_mask = (
616
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
617
+ )
618
+
619
+ return combined_attention_mask
620
+
621
+ def _prepare_decoder_attention_mask_training(self, input_id, inputs_embeds, eod_token, reset_mask_flag ,reset_attention_mask=True, reset_position_ids=True):
622
+
623
+ micro_batch_size, seq_length = input_id.size()
624
+
625
+ attention_mask = torch.tril(torch.ones(
626
+ (micro_batch_size, seq_length, seq_length), device=inputs_embeds.device)).view(
627
+ micro_batch_size, 1, seq_length, seq_length)
628
+
629
+ position_ids = torch.arange(seq_length, dtype=torch.long,
630
+ device=inputs_embeds.device)
631
+ position_ids = position_ids.unsqueeze(0).expand_as(input_id)
632
+
633
+ if reset_position_ids:
634
+ position_ids = position_ids.clone()
635
+
636
+ if reset_position_ids or reset_attention_mask:
637
+ # Loop through the batches:
638
+ for b in range(micro_batch_size):
639
+
640
+ # Find indecies where EOD token is.
641
+ eod_index = position_ids[b, input_id[b] == eod_token]
642
+
643
+ # Detach indecies from positions if going to modify positions.
644
+ if reset_position_ids:
645
+ eod_index = eod_index.clone()
646
+ # Loop through EOD indecies:
647
+ prev_index = 0
648
+ for j in range(eod_index.size()[0]):
649
+ i = eod_index[j]
650
+ # Mask attention loss.
651
+ if reset_attention_mask:
652
+ attention_mask[b, 0, (i + 1):, :(i + 1)] = 0
653
+ # Reset positions.
654
+ if reset_position_ids:
655
+ position_ids[b, (i + 1):] -= (i + 1 - prev_index)
656
+ prev_index = i + 1
657
+
658
+ inverted_mask = 1 - attention_mask
659
+ output_attn_mask = inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min)
660
+ if reset_mask_flag:
661
+ output_attn_mask = output_attn_mask[:,:,-1:,:]
662
+ return output_attn_mask, position_ids
663
+
664
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
665
+ def forward(
666
+ self,
667
+ input_ids: torch.LongTensor = None,
668
+ attention_mask: Optional[torch.Tensor] = None,
669
+ position_ids: Optional[torch.LongTensor] = None,
670
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
671
+ inputs_embeds: Optional[torch.FloatTensor] = None,
672
+ use_cache: Optional[bool] = None,
673
+ output_attentions: Optional[bool] = None,
674
+ output_hidden_states: Optional[bool] = None,
675
+ return_dict: Optional[bool] = None,
676
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
677
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
678
+ output_hidden_states = (
679
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
680
+ )
681
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
682
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
683
+ input_ids1 = copy.deepcopy(input_ids)
684
+ reset_mask_flag = False
685
+ if past_key_values:
686
+ input_ids = input_ids[:, -1:]
687
+ if use_cache:
688
+ reset_mask_flag = True
689
+ # retrieve input_ids and inputs_embeds
690
+ if input_ids is not None and inputs_embeds is not None:
691
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
692
+ elif input_ids is not None:
693
+ batch_size, seq_length = input_ids.shape
694
+ elif inputs_embeds is not None:
695
+ batch_size, seq_length, _ = inputs_embeds.shape
696
+ else:
697
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
698
+
699
+ seq_length_with_past = seq_length
700
+ past_key_values_length = 0
701
+
702
+ if past_key_values is not None:
703
+ past_key_values_length = past_key_values[0][0].shape[2]
704
+ seq_length_with_past = seq_length_with_past + past_key_values_length
705
+
706
+ if position_ids is None:
707
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
708
+ position_ids = torch.arange(
709
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
710
+ )
711
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
712
+ else:
713
+ position_ids = position_ids.view(-1, seq_length).long()
714
+ if inputs_embeds is None:
715
+ inputs_embeds = self.embed_tokens(input_ids)
716
+ if self.training or self.reset_position_ids:
717
+ attention_mask, _ = self._prepare_decoder_attention_mask_training(input_ids1, inputs_embeds, self.eod_token, reset_mask_flag, self.reset_attention_mask, self.reset_position_ids)
718
+
719
+ else:
720
+ if attention_mask is None:
721
+ attention_mask = torch.ones(
722
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
723
+ )
724
+ attention_mask = self._prepare_decoder_attention_mask(
725
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
726
+ )
727
+
728
+ hidden_states = inputs_embeds
729
+
730
+ if self.gradient_checkpointing and self.training:
731
+ if use_cache:
732
+ logger.warning_once(
733
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
734
+ )
735
+ use_cache = False
736
+
737
+ # decoder layers
738
+ all_hidden_states = () if output_hidden_states else None
739
+ all_self_attns = () if output_attentions else None
740
+ next_decoder_cache = () if use_cache else None
741
+
742
+ for idx, decoder_layer in enumerate(self.layers):
743
+ if output_hidden_states:
744
+ all_hidden_states += (hidden_states,)
745
+
746
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
747
+
748
+ if self.gradient_checkpointing and self.training:
749
+
750
+ def create_custom_forward(module):
751
+ def custom_forward(*inputs):
752
+ # None for past_key_value
753
+ return module(*inputs, output_attentions, None)
754
+
755
+ return custom_forward
756
+
757
+ layer_outputs = torch.utils.checkpoint.checkpoint(
758
+ create_custom_forward(decoder_layer),
759
+ hidden_states,
760
+ attention_mask,
761
+ position_ids,
762
+ None,
763
+ )
764
+ else:
765
+ layer_outputs = decoder_layer(
766
+ hidden_states,
767
+ attention_mask=attention_mask,
768
+ position_ids=position_ids,
769
+ past_key_value=past_key_value,
770
+ output_attentions=output_attentions,
771
+ use_cache=use_cache,
772
+ )
773
+
774
+ hidden_states = layer_outputs[0]
775
+
776
+ if use_cache:
777
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
778
+
779
+ if output_attentions:
780
+ all_self_attns += (layer_outputs[1],)
781
+ hidden_states = self.norm(hidden_states)
782
+
783
+ # add hidden states from the last decoder layer
784
+ if output_hidden_states:
785
+ all_hidden_states += (hidden_states,)
786
+ next_cache = next_decoder_cache if use_cache else None
787
+ if not return_dict:
788
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
789
+ return BaseModelOutputWithPast(
790
+ last_hidden_state=hidden_states,
791
+ past_key_values=next_cache,
792
+ hidden_states=all_hidden_states,
793
+ attentions=all_self_attns,
794
+ )
795
+
796
+
797
+ class YuanForCausalLM(YuanPreTrainedModel):
798
+ def __init__(self, config):
799
+ super().__init__(config)
800
+ self.eod_token = config.eod_token
801
+ self.sep_token = config.sep_token
802
+ self.use_loss_mask = config.use_loss_mask
803
+ self.model = YuanModel(config)
804
+
805
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
806
+
807
+ # Initialize weights and apply final processing
808
+ self.post_init()
809
+
810
+ def get_input_embeddings(self):
811
+ return self.model.embed_tokens
812
+
813
+ def set_input_embeddings(self, value):
814
+ self.model.embed_tokens = value
815
+
816
+ def get_output_embeddings(self):
817
+ return self.lm_head
818
+
819
+ def set_output_embeddings(self, new_embeddings):
820
+ self.lm_head = new_embeddings
821
+
822
+ def set_decoder(self, decoder):
823
+ self.model = decoder
824
+
825
+ def get_decoder(self):
826
+ return self.model
827
+
828
+ def get_loss_mask(self, input_ids, labels, eod_token, sep_token):
829
+ micro_batch_size, seq_length = input_ids.size()
830
+ loss_mask = torch.ones(input_ids.size(), dtype=torch.float, device=input_ids.device)
831
+
832
+ position_ids = torch.arange(seq_length, dtype=torch.long,
833
+ device=input_ids.device)
834
+ position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
835
+
836
+
837
+ """modify loss_mask to only calculate the loss of the answer (separated with [SEP])"""
838
+
839
+ for b in range(micro_batch_size):
840
+ eod_indexs = position_ids[b, input_ids[b] == eod_token]
841
+ sep_indexs = position_ids[b, input_ids[b] == sep_token]
842
+
843
+ if len(eod_indexs) == 0 or len(sep_indexs) == 0:
844
+ loss_mask[b] = 1.0
845
+ else:
846
+ if eod_indexs[0] > sep_indexs[0]:
847
+ loss_mask[b, 0:sep_indexs[0]] = 0
848
+
849
+ if len(eod_indexs) == len(sep_indexs):
850
+ for ii, eod_index in enumerate(eod_indexs):
851
+ start_index = eod_index
852
+ if ii == (len(sep_indexs) - 1):
853
+ stop_index = seq_length
854
+ else:
855
+ stop_index = sep_indexs[ii + 1]
856
+ loss_mask[b, start_index:stop_index] = 0.0
857
+ else:
858
+ if len(eod_indexs) > len(sep_indexs):
859
+ loss_mask[b,:] = 1.0
860
+ else:
861
+ for ii, eod_index in enumerate(eod_indexs):
862
+ start_index = eod_index
863
+ stop_index = sep_indexs[ii + 1]
864
+
865
+ loss_mask[b, start_index:stop_index] = 0.0
866
+
867
+ elif eod_indexs[0] < sep_indexs[0]:
868
+
869
+ if len(eod_indexs) == len(sep_indexs):
870
+ for ii, eod_index in enumerate(eod_indexs):
871
+ start_index = eod_index
872
+ stop_index = sep_indexs[ii]
873
+ loss_mask[b, start_index:stop_index] = 0.0
874
+
875
+ else:
876
+ if len(eod_indexs) < len(sep_indexs):
877
+ loss_mask[b,:] = 1.0
878
+ else:
879
+ for ii, eod_index in enumerate(eod_indexs):
880
+ start_index = eod_index
881
+ if ii >= len(sep_indexs):
882
+ stop_index = seq_length
883
+ else:
884
+ stop_index = sep_indexs[ii]
885
+ loss_mask[b, start_index:stop_index] = 0.0
886
+
887
+ loss_mask[input_ids == eod_token] = 1.0
888
+ return loss_mask
889
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
890
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
891
+ def forward(
892
+ self,
893
+ input_ids: torch.LongTensor = None,
894
+ attention_mask: Optional[torch.Tensor] = None,
895
+ position_ids: Optional[torch.LongTensor] = None,
896
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
897
+ inputs_embeds: Optional[torch.FloatTensor] = None,
898
+ labels: Optional[torch.LongTensor] = None,
899
+ use_cache: Optional[bool] = None,
900
+ output_attentions: Optional[bool] = None,
901
+ output_hidden_states: Optional[bool] = None,
902
+ return_dict: Optional[bool] = None,
903
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
904
+ r"""
905
+ Args:
906
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
907
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
908
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
909
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
910
+
911
+ Returns:
912
+
913
+ Example:
914
+
915
+ ```python
916
+ >>> from transformers import AutoTokenizer, YuanForCausalLM
917
+
918
+ >>> model = YuanForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
919
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
920
+
921
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
922
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
923
+
924
+ >>> # Generate
925
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
926
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
927
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
928
+ ```"""
929
+
930
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
931
+ output_hidden_states = (
932
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
933
+ )
934
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
935
+ outputs = self.model(
936
+ input_ids=input_ids,
937
+ attention_mask=attention_mask,
938
+ position_ids=position_ids,
939
+ past_key_values=past_key_values,
940
+ inputs_embeds=inputs_embeds,
941
+ use_cache=use_cache,
942
+ output_attentions=output_attentions,
943
+ output_hidden_states=output_hidden_states,
944
+ return_dict=return_dict,
945
+ )
946
+
947
+ hidden_states = outputs[0]
948
+ logits = self.lm_head(hidden_states)
949
+ loss = None
950
+ if labels is not None:
951
+ if self.use_loss_mask:
952
+ loss_mask = self.get_loss_mask(input_ids, labels, self.eod_token, self.sep_token)
953
+ # Shift so that tokens < n predict n
954
+ shift_logits = logits[..., :-1, :].contiguous()
955
+ shift_labels = labels[..., 1:].contiguous()
956
+ # Flatten the tokens
957
+ if self.use_loss_mask:
958
+ loss_fct = CrossEntropyLoss(reduction='none')
959
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
960
+ shift_labels = shift_labels.view(-1)
961
+ # Enable model parallelism
962
+ shift_labels = shift_labels.to(shift_logits.device)
963
+ loss = loss_fct(shift_logits, shift_labels)
964
+ loss = torch.sum(loss * loss_mask) / loss_mask.sum()
965
+ else:
966
+ loss_fct = CrossEntropyLoss()
967
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
968
+ shift_labels = shift_labels.view(-1)
969
+ # Enable model parallelism
970
+ shift_labels = shift_labels.to(shift_logits.device)
971
+ loss = loss_fct(shift_logits, shift_labels)
972
+ if not return_dict:
973
+ output = (logits,) + outputs[1:]
974
+ return (loss,) + output if loss is not None else output
975
+
976
+ return CausalLMOutputWithPast(
977
+ loss=loss,
978
+ logits=logits,
979
+ past_key_values=outputs.past_key_values,
980
+ hidden_states=hidden_states,
981
+ attentions=outputs.attentions,
982
+ )
983
+
984
+ def prepare_inputs_for_generation(
985
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
986
+ ):
987
+
988
+ position_ids = kwargs.get("position_ids", None)
989
+ if attention_mask is not None and position_ids is None:
990
+ # create position_ids on the fly for batch generation
991
+ position_ids = attention_mask.long().cumsum(-1) - 1
992
+ position_ids.masked_fill_(attention_mask == 0, 1)
993
+ if past_key_values:
994
+ position_ids = position_ids[:, -1].unsqueeze(-1)
995
+
996
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
997
+ if inputs_embeds is not None and past_key_values is None:
998
+ model_inputs = {"inputs_embeds": inputs_embeds}
999
+ else:
1000
+ model_inputs = {"input_ids": input_ids}
1001
+
1002
+ model_inputs.update(
1003
+ {
1004
+ "position_ids": position_ids,
1005
+ "past_key_values": past_key_values,
1006
+ "use_cache": kwargs.get("use_cache"),
1007
+ "attention_mask": attention_mask,
1008
+ }
1009
+ )
1010
+ return model_inputs
1011
+
1012
+ @staticmethod
1013
+ def _reorder_cache(past_key_values, beam_idx):
1014
+ reordered_past = ()
1015
+ for layer_past in past_key_values:
1016
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1017
+ return reordered_past
1018
+
1019
+
1020
+ @add_start_docstrings(
1021
+ """
1022
+ The Yuan Model transformer with a sequence classification head on top (linear layer).
1023
+
1024
+ [`YuanForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1025
+ (e.g. GPT-2) do.
1026
+
1027
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1028
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1029
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1030
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1031
+ each row of the batch).
1032
+ """,
1033
+ YUAN_START_DOCSTRING,
1034
+ )
1035
+ class YuanForSequenceClassification(YuanPreTrainedModel):
1036
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1037
+
1038
+ def __init__(self, config):
1039
+ super().__init__(config)
1040
+ self.num_labels = config.num_labels
1041
+ self.model = YuanModel(config)
1042
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1043
+
1044
+ # Initialize weights and apply final processing
1045
+ self.post_init()
1046
+
1047
+ def get_input_embeddings(self):
1048
+ return self.model.embed_tokens
1049
+
1050
+ def set_input_embeddings(self, value):
1051
+ self.model.embed_tokens = value
1052
+
1053
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
1054
+ def forward(
1055
+ self,
1056
+ input_ids: torch.LongTensor = None,
1057
+ attention_mask: Optional[torch.Tensor] = None,
1058
+ position_ids: Optional[torch.LongTensor] = None,
1059
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1060
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1061
+ labels: Optional[torch.LongTensor] = None,
1062
+ use_cache: Optional[bool] = None,
1063
+ output_attentions: Optional[bool] = None,
1064
+ output_hidden_states: Optional[bool] = None,
1065
+ return_dict: Optional[bool] = None,
1066
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1067
+ r"""
1068
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1069
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1070
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1071
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1072
+ """
1073
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1074
+ transformer_outputs = self.model(
1075
+ input_ids,
1076
+ attention_mask=attention_mask,
1077
+ position_ids=position_ids,
1078
+ past_key_values=past_key_values,
1079
+ inputs_embeds=inputs_embeds,
1080
+ use_cache=use_cache,
1081
+ output_attentions=output_attentions,
1082
+ output_hidden_states=output_hidden_states,
1083
+ return_dict=return_dict,
1084
+ )
1085
+ hidden_states = transformer_outputs[0]
1086
+ logits = self.score(hidden_states)
1087
+
1088
+ if input_ids is not None:
1089
+ batch_size = input_ids.shape[0]
1090
+ else:
1091
+ batch_size = inputs_embeds.shape[0]
1092
+
1093
+ if self.config.pad_token_id is None and batch_size != 1:
1094
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1095
+ if self.config.pad_token_id is None:
1096
+ sequence_lengths = -1
1097
+ else:
1098
+ if input_ids is not None:
1099
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1100
+ else:
1101
+ sequence_lengths = -1
1102
+
1103
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1104
+
1105
+ loss = None
1106
+ if labels is not None:
1107
+ labels = labels.to(logits.device)
1108
+ if self.config.problem_type is None:
1109
+ if self.num_labels == 1:
1110
+ self.config.problem_type = "regression"
1111
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1112
+ self.config.problem_type = "single_label_classification"
1113
+ else:
1114
+ self.config.problem_type = "multi_label_classification"
1115
+
1116
+ if self.config.problem_type == "regression":
1117
+ loss_fct = MSELoss()
1118
+ if self.num_labels == 1:
1119
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1120
+ else:
1121
+ loss = loss_fct(pooled_logits, labels)
1122
+ elif self.config.problem_type == "single_label_classification":
1123
+ loss_fct = CrossEntropyLoss()
1124
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1125
+ elif self.config.problem_type == "multi_label_classification":
1126
+ loss_fct = BCEWithLogitsLoss()
1127
+ loss = loss_fct(pooled_logits, labels)
1128
+ if not return_dict:
1129
+ output = (pooled_logits,) + transformer_outputs[1:]
1130
+ return ((loss,) + output) if loss is not None else output
1131
+
1132
+ return SequenceClassifierOutputWithPast(
1133
+ loss=loss,
1134
+ logits=pooled_logits,
1135
+ past_key_values=transformer_outputs.past_key_values,
1136
+ hidden_states=transformer_outputs.hidden_states,
1137
+ attentions=transformer_outputs.attentions,
1138
+ )
1139
+
1140
+