IEIT-Yuan commited on
Commit
45449d7
1 Parent(s): f29f264

model upload

Browse files
README.md CHANGED
@@ -1,5 +1,97 @@
1
  ---
2
  license: other
3
- license_name: ieisystem
4
- license_link: LICENSE
5
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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('IEITYuan/Yuan2-2B-Februa-hf', add_eos_token=False, add_bos_token=False, eos_token='<eod>')
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('IEITYuan/Yuan2-2B-Februa-hf', 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,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "YuanForCausalLM"
4
+ ],
5
+ "hidden_act": "silu",
6
+ "hidden_size": 2048,
7
+ "initializer_range": 0.02,
8
+ "intermediate_size": 8192,
9
+ "max_position_embeddings": 8192,
10
+ "model_type": "yuan",
11
+ "num_attention_heads": 32,
12
+ "num_hidden_layers": 24,
13
+ "rms_norm_eps": 1e-06,
14
+ "dropout": 0.1,
15
+ "tie_word_embeddings": true,
16
+ "torch_dtype": "bfloat16",
17
+ "transformers_version": "4.30.0.dev0",
18
+ "use_cache": false,
19
+ "causal_mask": true,
20
+ "use_flash_attention": false,
21
+ "reset_attention_mask": true,
22
+ "reset_position_ids": true,
23
+ "use_loss_mask": false,
24
+ "eod_token": 77185,
25
+ "sep_token": 77187,
26
+ "eod_token_id": 77185,
27
+ "sep_token_id": 77185,
28
+ "pad_token_id": 77185,
29
+ "bos_token_id": 77185,
30
+ "eos_token_id": 77185,
31
+ "mask_token_id": 77185,
32
+ "vocab_size": 135040
33
+ }
config_cpu.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": false,
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.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"framework":"其他","task":"multimodal-dialogue"}
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.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ae869c7db1eedee394ed033d4a5e0374ccf8e525bbfabcf5abed388375d1183
3
+ size 4730693774
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,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "sep_token": "<sep>",
5
+ "eod_token": "<eod>",
6
+ "chat_template": "{% for message in messages %}{% if message['role'] == 'system' %}{{ message['content'].strip() + '\\n' }}{% elif message['role'] == 'user' %}{{ message['content'].strip() + (sep_token if loop.last else '<n>') }}{% elif message['role'] == 'assistant' %}{{ message['content'].strip() + (sep_token if loop.last else '<n>') }}{% endif %}{% endfor %}",
7
+ "bos_token": {
8
+ "__type": "AddedToken",
9
+ "content": "<s>",
10
+ "lstrip": false,
11
+ "normalized": true,
12
+ "rstrip": false,
13
+ "single_word": false
14
+ },
15
+ "clean_up_tokenization_spaces": false,
16
+ "eos_token": {
17
+ "__type": "AddedToken",
18
+ "content": "</s>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "model_max_length": 1000000000000000019884624838656,
25
+ "pad_token": null,
26
+ "sp_model_kwargs": {},
27
+ "tokenizer_class": "LlamaTokenizer",
28
+ "unk_token": {
29
+ "__type": "AddedToken",
30
+ "content": "<unk>",
31
+ "lstrip": false,
32
+ "normalized": true,
33
+ "rstrip": false,
34
+ "single_word": false
35
+ }
36
+ }
yuan_hf_model.py ADDED
@@ -0,0 +1,1189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.activations import ACT2FN
29
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
30
+ from transformers.modeling_utils import PreTrainedModel
31
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
32
+ from .configuration_yuan import YuanConfig
33
+ from einops import rearrange
34
+ #from flash_attn import flash_attn_varlen_func as flash_attn_unpadded_func
35
+ #from flash_attn import flash_attn_func
36
+
37
+ import copy
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CONFIG_FOR_DOC = "YuanConfig"
42
+
43
+
44
+ class LocalizedFiltering(torch.nn.Module):
45
+ """
46
+ Mega's Exponential Moving Average layer, largely left unmodified from the original repo with the exception of
47
+ variable names and moving away from the stateful representation of incremental decoding state. See
48
+ "https://arxiv.org/abs/2209.10655" for more details.
49
+ """
50
+
51
+ def __init__(self, hidden_size):
52
+ super().__init__()
53
+
54
+ self.embed_dim = hidden_size
55
+ self.lf_conv2d_group = 1
56
+ self.lf_conv2d_num_pad = 1
57
+
58
+ 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)
59
+ 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)
60
+ self.output_layernorm = YuanRMSNorm(self.embed_dim)
61
+
62
+ def _train_forward(self, inputs):
63
+ inputs = inputs.transpose(0,1)
64
+ seq_len, bsz, embed_dim = inputs.size()
65
+ if embed_dim != self.embed_dim:
66
+ raise ValueError(
67
+ f"Unexpected embedding dimension received: input is {embed_dim}, model expects {self.embed_dim}"
68
+ )
69
+ residual = inputs
70
+
71
+ inputs = inputs.view(seq_len, 1, bsz, embed_dim).permute(2, 3, 0, 1)
72
+ output1 = self.conv1(inputs)
73
+ output1 = output1[:, :, :seq_len, :]
74
+
75
+ output2 = self.conv2(output1)
76
+ output2 = output2[:, :, :seq_len, :].permute(2, 3, 0, 1).contiguous()
77
+ output2 = output2.view(seq_len, bsz, embed_dim)
78
+ assert output2.shape == residual.shape
79
+
80
+ lf_output = self.output_layernorm(output2 + residual)
81
+ lf_output = lf_output.transpose(0,1)
82
+ return lf_output
83
+
84
+ def _inference_forward(self, inputs, before_hidden_states):
85
+
86
+ if before_hidden_states is None:
87
+ inputs = inputs.transpose(0,1)
88
+ seq_len, bsz, embed_dim = inputs.size()
89
+ if embed_dim != self.embed_dim:
90
+ raise ValueError(
91
+ f"Unexpected embedding dimension received: input is {embed_dim}, model expects {self.embed_dim}"
92
+ )
93
+ residual = inputs
94
+
95
+ inputs = inputs.view(seq_len, 1, bsz, embed_dim).permute(2, 3, 0, 1)
96
+ output1 = self.conv1(inputs)
97
+ output1 = output1[:, :, :seq_len, :]
98
+
99
+ output2 = self.conv2(output1)
100
+ output2 = output2[:, :, :seq_len, :].permute(2, 3, 0, 1).contiguous()
101
+ output2 = output2.view(seq_len, bsz, embed_dim)
102
+ assert output2.shape == residual.shape
103
+
104
+ lf_output = self.output_layernorm(output2 + residual)
105
+ lf_output = lf_output.transpose(0,1)
106
+ return lf_output
107
+ else:
108
+ inputs = inputs.transpose(0,1)
109
+ before_hidden_states = before_hidden_states.transpose(0,1)
110
+ residual = inputs
111
+
112
+ seq_len, bsz, embed_dim = inputs.size()
113
+ seq_len_before, _, _ = before_hidden_states.size()
114
+
115
+ assert seq_len == 1 and seq_len_before == 2
116
+
117
+ inputs = torch.cat((before_hidden_states, inputs), dim=0)
118
+ inputs = inputs.view(3, 1, bsz, embed_dim).permute(2, 3, 0, 1)
119
+
120
+ output1 = self.conv1(inputs)
121
+ output2 = self.conv2(output1[:,:,1:-1,:])
122
+ output2 = output2[:,:,1:-1,:]
123
+ output2 = output2.view(1, bsz, embed_dim)
124
+ assert output2.shape == residual.shape
125
+
126
+ lf_output = self.output_layernorm(output2 + residual)
127
+ lf_output = lf_output.transpose(0,1)
128
+
129
+ return lf_output
130
+
131
+
132
+
133
+ def forward(
134
+ self,
135
+ inputs,
136
+ before_hidden_states
137
+ ) -> torch.Tensor:
138
+ assert self.lf_conv2d_num_pad == 1
139
+ if self.training:
140
+ lf_output = self._train_forward(inputs)
141
+ else:
142
+ lf_output = self._inference_forward(inputs, before_hidden_states)
143
+
144
+ return lf_output
145
+
146
+
147
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
148
+ def _make_causal_mask(
149
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
150
+ ):
151
+ """
152
+ Make causal mask used for bi-directional self-attention.
153
+ """
154
+ bsz, tgt_len = input_ids_shape
155
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
156
+ mask_cond = torch.arange(mask.size(-1), device=device)
157
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
158
+ mask = mask.to(dtype)
159
+
160
+ if past_key_values_length > 0:
161
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
162
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
163
+
164
+
165
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
166
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
167
+ """
168
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
169
+ """
170
+ bsz, src_len = mask.size()
171
+ tgt_len = tgt_len if tgt_len is not None else src_len
172
+
173
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
174
+
175
+ inverted_mask = 1.0 - expanded_mask
176
+
177
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
178
+
179
+
180
+ def rotate_half(x):
181
+ """Rotates half the hidden dims of the input."""
182
+ x1 = x[..., : x.shape[-1] // 2]
183
+ x2 = x[..., x.shape[-1] // 2 :]
184
+ return torch.cat((-x2, x1), dim=-1)
185
+
186
+
187
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
188
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
189
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
190
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
191
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
192
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
193
+ q_embed = (q * cos) + (rotate_half(q) * sin)
194
+ k_embed = (k * cos) + (rotate_half(k) * sin)
195
+ return q_embed, k_embed
196
+
197
+ class YuanRMSNorm(nn.Module):
198
+ def __init__(self, hidden_size, eps=1e-6):
199
+ """
200
+ YuanRMSNorm is equivalent to LlamaRMSNorm
201
+ """
202
+ super().__init__()
203
+ self.weight = nn.Parameter(torch.ones(hidden_size))
204
+ self.variance_epsilon = eps
205
+
206
+ def forward(self, hidden_states):
207
+ input_dtype = hidden_states.dtype
208
+ hidden_states = hidden_states.to(torch.float32)
209
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
210
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
211
+ return self.weight * hidden_states.to(input_dtype)
212
+
213
+ class YuanRotaryEmbedding(torch.nn.Module):
214
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
215
+
216
+ """
217
+ YuanRotaryEmbedding is equivalent to LlamaRotaryEmbedding in transformers v4.36
218
+ """
219
+
220
+ super().__init__()
221
+
222
+ self.dim = dim
223
+ self.max_position_embeddings = max_position_embeddings
224
+ self.base = base
225
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
226
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
227
+
228
+ # Build here to make `torch.jit.trace` work.
229
+ self._set_cos_sin_cache(
230
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
231
+ )
232
+
233
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
234
+ self.max_seq_len_cached = seq_len
235
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
236
+
237
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
238
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
239
+ emb = torch.cat((freqs, freqs), dim=-1)
240
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
241
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
242
+
243
+ def forward(self, x, seq_len=None):
244
+ # x: [bs, num_attention_heads, seq_len, head_size]
245
+ if seq_len > self.max_seq_len_cached:
246
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
247
+
248
+ return (
249
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
250
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
251
+ )
252
+
253
+ class YuanMLP(nn.Module):
254
+ def __init__(
255
+ self,
256
+ hidden_size: int,
257
+ intermediate_size: int,
258
+ hidden_act: str,
259
+ ):
260
+ super().__init__()
261
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
262
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
263
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
264
+ self.act_fn = ACT2FN[hidden_act]
265
+
266
+ def forward(self, x):
267
+ return self.down_proj(self.gate_proj(x) * self.act_fn(self.up_proj(x)))
268
+
269
+ class YuanAttention(nn.Module):
270
+ """Localized Filtering-based Attention 'YUAN 2.0: A Large Language Model with Localized Filtering-based Attention' paper"""
271
+
272
+ def __init__(self, config: YuanConfig):
273
+ super().__init__()
274
+ self.config = config
275
+ self.hidden_size = config.hidden_size
276
+ self.num_heads = config.num_attention_heads
277
+ self.head_dim = self.hidden_size // self.num_heads
278
+ self.max_position_embeddings = config.max_position_embeddings
279
+ self.causal_mask = config.causal_mask
280
+ self.softmax_scale = 1.0 / math.sqrt(self.head_dim)
281
+ self.use_flash_attention = config.use_flash_attention
282
+ try:
283
+ self.use_shareqk = config.use_shareqk
284
+ except Exception as e:
285
+ self.use_shareqk=False
286
+ self.dropout = 0.0
287
+ if (self.head_dim * self.num_heads) != self.hidden_size:
288
+ raise ValueError(
289
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
290
+ f" and `num_heads`: {self.num_heads})."
291
+ )
292
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
293
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
294
+ self.rotary_emb = YuanRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
295
+ if self.use_shareqk:
296
+ self.qk_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
297
+ self.qk_weight = nn.Parameter(torch.Tensor(2, self.hidden_size))
298
+ self.qk_bias = nn.Parameter(torch.Tensor(2, self.hidden_size))
299
+ else:
300
+ self.lf_gate = LocalizedFiltering(self.hidden_size)
301
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
302
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
303
+
304
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
305
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
306
+
307
+ def forward(
308
+ self,
309
+ hidden_states: torch.Tensor,
310
+ attention_mask: Optional[torch.Tensor] = None,
311
+ position_ids: Optional[torch.LongTensor] = None,
312
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
313
+ output_attentions: bool = False,
314
+ use_cache: bool = False,
315
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
316
+ bsz, q_len, _ = hidden_states.size()
317
+ before_hidden_states = None
318
+ is_first_step = False
319
+ if use_cache:
320
+ if past_key_value is None:
321
+ #inference_hidden_states_memory = torch.empty(bsz, 2, hidden_states.shape[2], dtype=hidden_states.dtype ,device=torch.cuda.current_device())
322
+ inference_hidden_states_memory = torch.empty(bsz, 2, hidden_states.shape[2], dtype=hidden_states.dtype)
323
+ is_first_step = True
324
+ else:
325
+ before_hidden_states = past_key_value[2]
326
+
327
+ if use_cache:
328
+ if is_first_step:
329
+ if q_len >= 2:
330
+ inference_hidden_states_memory = hidden_states[ :, -2:, :]
331
+ else:
332
+ inference_hidden_states_memory[:, :, :] = 0
333
+ inference_hidden_states_memory[:, -1:, :] = hidden_states[:, -1:, :]
334
+ else:
335
+ hidden_states_tmp = before_hidden_states[:, -1:, :]
336
+ inference_hidden_states_memory = copy.deepcopy(torch.cat((hidden_states_tmp, hidden_states), dim=1))
337
+
338
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
339
+ if self.use_shareqk:
340
+ qk_states = self.qk_proj(hidden_states).view(bsz, q_len, self.num_heads*self.head_dim)
341
+ query_key = qk_states.unsqueeze(2) * self.qk_weight + self.qk_bias
342
+ query_states, key_states = torch.unbind(query_key, dim=2)
343
+
344
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
345
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
346
+ else:
347
+ hidden_states = self.lf_gate(hidden_states,before_hidden_states)
348
+ query_states = self.q_proj(hidden_states)
349
+ key_states = self.k_proj(hidden_states)
350
+ qk_states = torch.cat([query_states, key_states], dim=-1)
351
+ qk_states = qk_states.view(bsz,q_len,self.num_heads,int(qk_states.shape[-1]//self.num_heads))
352
+ (query_states,key_states) = torch.chunk(qk_states, 2, dim=-1)
353
+ query_states = query_states.transpose(1, 2)
354
+ key_states = key_states.transpose(1, 2)
355
+
356
+
357
+ kv_seq_len = key_states.shape[-2]
358
+ if past_key_value is not None:
359
+ kv_seq_len += past_key_value[0].shape[-2]
360
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
361
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
362
+
363
+ if past_key_value is not None:
364
+ # reuse k, v, self_attention
365
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
366
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
367
+
368
+ past_key_value = (key_states, value_states,inference_hidden_states_memory) if use_cache else None
369
+
370
+ if self.use_flash_attention:
371
+ attn_weights = None
372
+ query_states = query_states.transpose(1, 2)
373
+ key_states = key_states.transpose(1, 2)
374
+ value_states = value_states.transpose(1, 2)
375
+
376
+ batch_size, seqlen_q = query_states.shape[0], query_states.shape[1]
377
+ seqlen_k = key_states.shape[1]
378
+
379
+ q, k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [query_states, key_states, value_states]]
380
+
381
+ cu_seqlens_q = torch.arange(0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int,
382
+ device=q.device)
383
+
384
+ if self.training:
385
+ assert seqlen_k == seqlen_q
386
+ cu_seqlens_k = cu_seqlens_q
387
+ is_causal = self.causal_mask
388
+ else:
389
+ is_causal = seqlen_q == seqlen_k
390
+ cu_seqlens_k = torch.arange(0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int,
391
+ device=q.device)
392
+ self.dropout=0
393
+
394
+ output = flash_attn_unpadded_func(
395
+ q, k, v, cu_seqlens_q, cu_seqlens_k, seqlen_q, seqlen_k, self.dropout, causal=is_causal
396
+ )
397
+
398
+ attn_output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
399
+ else:
400
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
401
+
402
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
403
+ raise ValueError(
404
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
405
+ f" {attn_weights.size()}"
406
+ )
407
+ if attention_mask is not None:
408
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
409
+ raise ValueError(
410
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
411
+ )
412
+ attn_weights = attn_weights + attention_mask
413
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
414
+
415
+ # upcast attention to fp32
416
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
417
+ attn_output = torch.matmul(attn_weights, value_states)
418
+
419
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
420
+ raise ValueError(
421
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
422
+ f" {attn_output.size()}"
423
+ )
424
+
425
+ attn_output = attn_output.transpose(1, 2)
426
+
427
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
428
+
429
+ attn_output = self.o_proj(attn_output)
430
+
431
+ if not output_attentions:
432
+ attn_weights = None
433
+ return attn_output, attn_weights, past_key_value
434
+
435
+
436
+ class YuanDecoderLayer(nn.Module):
437
+ def __init__(self, config: YuanConfig):
438
+ super().__init__()
439
+ self.hidden_size = config.hidden_size
440
+ self.self_attn = YuanAttention(config=config)
441
+ self.mlp = YuanMLP(
442
+ hidden_size=self.hidden_size,
443
+ intermediate_size=config.intermediate_size,
444
+ hidden_act=config.hidden_act,
445
+ )
446
+ self.input_layernorm = YuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
447
+ self.post_attention_layernorm = YuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
448
+
449
+ def forward(
450
+ self,
451
+ hidden_states: torch.Tensor,
452
+ attention_mask: Optional[torch.Tensor] = None,
453
+ position_ids: Optional[torch.LongTensor] = None,
454
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
455
+ output_attentions: Optional[bool] = False,
456
+ use_cache: Optional[bool] = False,
457
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
458
+ """
459
+ Args:
460
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
461
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
462
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
463
+ output_attentions (`bool`, *optional*):
464
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
465
+ returned tensors for more detail.
466
+ use_cache (`bool`, *optional*):
467
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
468
+ (see `past_key_values`).
469
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
470
+ """
471
+
472
+ residual = hidden_states
473
+ hidden_states = self.input_layernorm(hidden_states)
474
+
475
+ # Self Attention
476
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
477
+ hidden_states=hidden_states,
478
+ attention_mask=attention_mask,
479
+ position_ids=position_ids,
480
+ past_key_value=past_key_value,
481
+ output_attentions=output_attentions,
482
+ use_cache=use_cache,
483
+ )
484
+ hidden_states = residual + hidden_states
485
+
486
+ # Fully Connected
487
+ residual = hidden_states
488
+ hidden_states = self.post_attention_layernorm(hidden_states)
489
+ hidden_states = self.mlp(hidden_states)
490
+ hidden_states = residual + hidden_states
491
+
492
+ outputs = (hidden_states,)
493
+
494
+ if output_attentions:
495
+ outputs += (self_attn_weights,)
496
+
497
+ if use_cache:
498
+ outputs += (present_key_value,)
499
+
500
+ return outputs
501
+
502
+
503
+ YUAN_START_DOCSTRING = r"""
504
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
505
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
506
+ etc.)
507
+
508
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
509
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
510
+ and behavior.
511
+
512
+ Parameters:
513
+ config ([`YuanConfig`]):
514
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
515
+ load the weights associated with the model, only the configuration. Check out the
516
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
517
+ """
518
+
519
+
520
+ @add_start_docstrings(
521
+ "The bare Yuan Model outputting raw hidden-states without any specific head on top.",
522
+ YUAN_START_DOCSTRING,
523
+ )
524
+ class YuanPreTrainedModel(PreTrainedModel):
525
+ config_class = YuanConfig
526
+ base_model_prefix = "model"
527
+ supports_gradient_checkpointing = True
528
+ _no_split_modules = ["YuanDecoderLayer"]
529
+ _skip_keys_device_placement = "past_key_values"
530
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
531
+
532
+ def _init_weights(self, module):
533
+ std = self.config.initializer_range
534
+ if isinstance(module, nn.Linear):
535
+ module.weight.data.normal_(mean=0.0, std=std)
536
+ if module.bias is not None:
537
+ module.bias.data.zero_()
538
+ elif isinstance(module, nn.Embedding):
539
+ module.weight.data.normal_(mean=0.0, std=std)
540
+ if module.padding_idx is not None:
541
+ module.weight.data[module.padding_idx].zero_()
542
+
543
+ def _set_gradient_checkpointing(self, module, value=False):
544
+ if isinstance(module, YuanModel):
545
+ module.gradient_checkpointing = value
546
+
547
+
548
+ YUAN_INPUTS_DOCSTRING = r"""
549
+ Args:
550
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
551
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
552
+ it.
553
+
554
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
555
+ [`PreTrainedTokenizer.__call__`] for details.
556
+
557
+ [What are input IDs?](../glossary#input-ids)
558
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
559
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
560
+
561
+ - 1 for tokens that are **not masked**,
562
+ - 0 for tokens that are **masked**.
563
+
564
+ [What are attention masks?](../glossary#attention-mask)
565
+
566
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
567
+ [`PreTrainedTokenizer.__call__`] for details.
568
+
569
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
570
+ `past_key_values`).
571
+
572
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
573
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
574
+ information on the default strategy.
575
+
576
+ - 1 indicates the head is **not masked**,
577
+ - 0 indicates the head is **masked**.
578
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
579
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
580
+ config.n_positions - 1]`.
581
+
582
+ [What are position IDs?](../glossary#position-ids)
583
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
584
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
585
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
586
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
587
+
588
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
589
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
590
+
591
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
592
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
593
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
594
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
595
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
596
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
597
+ model's internal embedding lookup matrix.
598
+ use_cache (`bool`, *optional*):
599
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
600
+ `past_key_values`).
601
+ output_attentions (`bool`, *optional*):
602
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
603
+ tensors for more detail.
604
+ output_hidden_states (`bool`, *optional*):
605
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
606
+ more detail.
607
+ return_dict (`bool`, *optional*):
608
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
609
+ """
610
+
611
+
612
+ @add_start_docstrings(
613
+ "The bare Yuan Model outputting raw hidden-states without any specific head on top.",
614
+ YUAN_START_DOCSTRING,
615
+ )
616
+ class YuanModel(YuanPreTrainedModel):
617
+ """
618
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`YuanDecoderLayer`]
619
+
620
+ Args:
621
+ config: YuanConfig
622
+ """
623
+
624
+ def __init__(self, config: YuanConfig):
625
+ super().__init__(config)
626
+ self.padding_idx = config.pad_token_id
627
+ self.vocab_size = config.vocab_size
628
+
629
+ #TODO: control it by config
630
+ self.eod_token = config.eod_token
631
+ self.reset_attention_mask = config.reset_attention_mask
632
+ self.reset_position_ids = config.reset_position_ids
633
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
634
+ self.layers = nn.ModuleList([YuanDecoderLayer(config) for _ in range(config.num_hidden_layers)])
635
+ self.norm = YuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
636
+ self.gradient_checkpointing = False
637
+ # Initialize weights and apply final processing
638
+ self.post_init()
639
+
640
+ def get_input_embeddings(self):
641
+ return self.embed_tokens
642
+
643
+ def set_input_embeddings(self, value):
644
+ self.embed_tokens = value
645
+
646
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
647
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
648
+ # create causal mask
649
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
650
+ combined_attention_mask = None
651
+ if input_shape[-1] > 1:
652
+ combined_attention_mask = _make_causal_mask(
653
+ input_shape,
654
+ inputs_embeds.dtype,
655
+ device=inputs_embeds.device,
656
+ past_key_values_length=past_key_values_length,
657
+ )
658
+
659
+ if attention_mask is not None:
660
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
661
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
662
+ inputs_embeds.device
663
+ )
664
+ combined_attention_mask = (
665
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
666
+ )
667
+
668
+ return combined_attention_mask
669
+
670
+ def _prepare_decoder_attention_mask_training(self, input_id, inputs_embeds, eod_token, reset_mask_flag ,reset_attention_mask=True, reset_position_ids=True):
671
+
672
+ micro_batch_size, seq_length = input_id.size()
673
+
674
+ attention_mask = torch.tril(torch.ones(
675
+ (micro_batch_size, seq_length, seq_length), device=inputs_embeds.device)).view(
676
+ micro_batch_size, 1, seq_length, seq_length)
677
+
678
+ position_ids = torch.arange(seq_length, dtype=torch.long,
679
+ device=inputs_embeds.device)
680
+ position_ids = position_ids.unsqueeze(0).expand_as(input_id)
681
+
682
+ if reset_position_ids:
683
+ position_ids = position_ids.clone()
684
+
685
+ if reset_position_ids or reset_attention_mask:
686
+ # Loop through the batches:
687
+ for b in range(micro_batch_size):
688
+
689
+ # Find indecies where EOD token is.
690
+ eod_index = position_ids[b, input_id[b] == eod_token]
691
+
692
+ # Detach indecies from positions if going to modify positions.
693
+ if reset_position_ids:
694
+ eod_index = eod_index.clone()
695
+ # Loop through EOD indecies:
696
+ prev_index = 0
697
+ for j in range(eod_index.size()[0]):
698
+ i = eod_index[j]
699
+ # Mask attention loss.
700
+ if reset_attention_mask:
701
+ attention_mask[b, 0, (i + 1):, :(i + 1)] = 0
702
+ # Reset positions.
703
+ if reset_position_ids:
704
+ position_ids[b, (i + 1):] -= (i + 1 - prev_index)
705
+ prev_index = i + 1
706
+
707
+ inverted_mask = 1 - attention_mask
708
+ output_attn_mask = inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min)
709
+ if reset_mask_flag:
710
+ output_attn_mask = output_attn_mask[:,:,-1:,:]
711
+ return output_attn_mask, position_ids
712
+
713
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
714
+ def forward(
715
+ self,
716
+ input_ids: torch.LongTensor = None,
717
+ attention_mask: Optional[torch.Tensor] = None,
718
+ position_ids: Optional[torch.LongTensor] = None,
719
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
720
+ inputs_embeds: Optional[torch.FloatTensor] = None,
721
+ use_cache: Optional[bool] = None,
722
+ output_attentions: Optional[bool] = None,
723
+ output_hidden_states: Optional[bool] = None,
724
+ return_dict: Optional[bool] = None,
725
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
726
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
727
+ output_hidden_states = (
728
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
729
+ )
730
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
731
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
732
+ input_ids1 = copy.deepcopy(input_ids)
733
+ reset_mask_flag = False
734
+ if past_key_values:
735
+ input_ids = input_ids[:, -1:]
736
+ if use_cache:
737
+ reset_mask_flag = True
738
+ # retrieve input_ids and inputs_embeds
739
+ if input_ids is not None and inputs_embeds is not None:
740
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
741
+ elif input_ids is not None:
742
+ batch_size, seq_length = input_ids.shape
743
+ elif inputs_embeds is not None:
744
+ batch_size, seq_length, _ = inputs_embeds.shape
745
+ else:
746
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
747
+
748
+ seq_length_with_past = seq_length
749
+ past_key_values_length = 0
750
+
751
+ if past_key_values is not None:
752
+ past_key_values_length = past_key_values[0][0].shape[2]
753
+ seq_length_with_past = seq_length_with_past + past_key_values_length
754
+
755
+ if position_ids is None:
756
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
757
+ position_ids = torch.arange(
758
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
759
+ )
760
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
761
+ else:
762
+ position_ids = position_ids.view(-1, seq_length).long()
763
+ if inputs_embeds is None:
764
+ inputs_embeds = self.embed_tokens(input_ids)
765
+ if self.training or self.reset_position_ids:
766
+ 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)
767
+
768
+ else:
769
+ if attention_mask is None:
770
+ attention_mask = torch.ones(
771
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
772
+ )
773
+ attention_mask = self._prepare_decoder_attention_mask(
774
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
775
+ )
776
+
777
+ hidden_states = inputs_embeds
778
+
779
+ if self.gradient_checkpointing and self.training:
780
+ if use_cache:
781
+ logger.warning_once(
782
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
783
+ )
784
+ use_cache = False
785
+
786
+ # decoder layers
787
+ all_hidden_states = () if output_hidden_states else None
788
+ all_self_attns = () if output_attentions else None
789
+ next_decoder_cache = () if use_cache else None
790
+
791
+ for idx, decoder_layer in enumerate(self.layers):
792
+ if output_hidden_states:
793
+ all_hidden_states += (hidden_states,)
794
+
795
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
796
+
797
+ if self.gradient_checkpointing and self.training:
798
+
799
+ def create_custom_forward(module):
800
+ def custom_forward(*inputs):
801
+ # None for past_key_value
802
+ return module(*inputs, output_attentions, None)
803
+
804
+ return custom_forward
805
+
806
+ layer_outputs = torch.utils.checkpoint.checkpoint(
807
+ create_custom_forward(decoder_layer),
808
+ hidden_states,
809
+ attention_mask,
810
+ position_ids,
811
+ None,
812
+ )
813
+ else:
814
+ layer_outputs = decoder_layer(
815
+ hidden_states,
816
+ attention_mask=attention_mask,
817
+ position_ids=position_ids,
818
+ past_key_value=past_key_value,
819
+ output_attentions=output_attentions,
820
+ use_cache=use_cache,
821
+ )
822
+
823
+ hidden_states = layer_outputs[0]
824
+
825
+ if use_cache:
826
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
827
+
828
+ if output_attentions:
829
+ all_self_attns += (layer_outputs[1],)
830
+ hidden_states = self.norm(hidden_states)
831
+
832
+ # add hidden states from the last decoder layer
833
+ if output_hidden_states:
834
+ all_hidden_states += (hidden_states,)
835
+ next_cache = next_decoder_cache if use_cache else None
836
+ if not return_dict:
837
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
838
+ return BaseModelOutputWithPast(
839
+ last_hidden_state=hidden_states,
840
+ past_key_values=next_cache,
841
+ hidden_states=all_hidden_states,
842
+ attentions=all_self_attns,
843
+ )
844
+
845
+
846
+ class YuanForCausalLM(YuanPreTrainedModel):
847
+ def __init__(self, config):
848
+ super().__init__(config)
849
+ self.eod_token = config.eod_token
850
+ self.sep_token = config.sep_token
851
+ self.use_loss_mask = config.use_loss_mask
852
+ self.model = YuanModel(config)
853
+
854
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
855
+
856
+ # Initialize weights and apply final processing
857
+ self.post_init()
858
+
859
+ def get_input_embeddings(self):
860
+ return self.model.embed_tokens
861
+
862
+ def set_input_embeddings(self, value):
863
+ self.model.embed_tokens = value
864
+
865
+ def get_output_embeddings(self):
866
+ return self.lm_head
867
+
868
+ def set_output_embeddings(self, new_embeddings):
869
+ self.lm_head = new_embeddings
870
+
871
+ def set_decoder(self, decoder):
872
+ self.model = decoder
873
+
874
+ def get_decoder(self):
875
+ return self.model
876
+
877
+ def get_loss_mask(self, input_ids, labels, eod_token, sep_token):
878
+ micro_batch_size, seq_length = input_ids.size()
879
+ loss_mask = torch.ones(input_ids.size(), dtype=torch.float, device=input_ids.device)
880
+
881
+ position_ids = torch.arange(seq_length, dtype=torch.long,
882
+ device=input_ids.device)
883
+ position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
884
+
885
+
886
+ """modify loss_mask to only calculate the loss of the answer (separated with [SEP])"""
887
+
888
+ for b in range(micro_batch_size):
889
+ eod_indexs = position_ids[b, input_ids[b] == eod_token]
890
+ sep_indexs = position_ids[b, input_ids[b] == sep_token]
891
+
892
+ if len(eod_indexs) == 0 or len(sep_indexs) == 0:
893
+ loss_mask[b] = 1.0
894
+ else:
895
+ if eod_indexs[0] > sep_indexs[0]:
896
+ loss_mask[b, 0:sep_indexs[0]] = 0
897
+
898
+ if len(eod_indexs) == len(sep_indexs):
899
+ for ii, eod_index in enumerate(eod_indexs):
900
+ start_index = eod_index
901
+ if ii == (len(sep_indexs) - 1):
902
+ stop_index = seq_length
903
+ else:
904
+ stop_index = sep_indexs[ii + 1]
905
+ loss_mask[b, start_index:stop_index] = 0.0
906
+ else:
907
+ if len(eod_indexs) > len(sep_indexs):
908
+ loss_mask[b,:] = 1.0
909
+ else:
910
+ for ii, eod_index in enumerate(eod_indexs):
911
+ start_index = eod_index
912
+ stop_index = sep_indexs[ii + 1]
913
+
914
+ loss_mask[b, start_index:stop_index] = 0.0
915
+
916
+ elif eod_indexs[0] < sep_indexs[0]:
917
+
918
+ if len(eod_indexs) == len(sep_indexs):
919
+ for ii, eod_index in enumerate(eod_indexs):
920
+ start_index = eod_index
921
+ stop_index = sep_indexs[ii]
922
+ loss_mask[b, start_index:stop_index] = 0.0
923
+
924
+ else:
925
+ if len(eod_indexs) < len(sep_indexs):
926
+ loss_mask[b,:] = 1.0
927
+ else:
928
+ for ii, eod_index in enumerate(eod_indexs):
929
+ start_index = eod_index
930
+ if ii >= len(sep_indexs):
931
+ stop_index = seq_length
932
+ else:
933
+ stop_index = sep_indexs[ii]
934
+ loss_mask[b, start_index:stop_index] = 0.0
935
+
936
+ loss_mask[input_ids == eod_token] = 1.0
937
+ return loss_mask
938
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
939
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
940
+ def forward(
941
+ self,
942
+ input_ids: torch.LongTensor = None,
943
+ attention_mask: Optional[torch.Tensor] = None,
944
+ position_ids: Optional[torch.LongTensor] = None,
945
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
946
+ inputs_embeds: Optional[torch.FloatTensor] = None,
947
+ labels: Optional[torch.LongTensor] = None,
948
+ use_cache: Optional[bool] = None,
949
+ output_attentions: Optional[bool] = None,
950
+ output_hidden_states: Optional[bool] = None,
951
+ return_dict: Optional[bool] = None,
952
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
953
+ r"""
954
+ Args:
955
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
956
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
957
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
958
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
959
+
960
+ Returns:
961
+
962
+ Example:
963
+
964
+ ```python
965
+ >>> from transformers import AutoTokenizer, YuanForCausalLM
966
+
967
+ >>> model = YuanForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
968
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
969
+
970
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
971
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
972
+
973
+ >>> # Generate
974
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
975
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
976
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
977
+ ```"""
978
+
979
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
980
+ output_hidden_states = (
981
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
982
+ )
983
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
984
+ outputs = self.model(
985
+ input_ids=input_ids,
986
+ attention_mask=attention_mask,
987
+ position_ids=position_ids,
988
+ past_key_values=past_key_values,
989
+ inputs_embeds=inputs_embeds,
990
+ use_cache=use_cache,
991
+ output_attentions=output_attentions,
992
+ output_hidden_states=output_hidden_states,
993
+ return_dict=return_dict,
994
+ )
995
+
996
+ hidden_states = outputs[0]
997
+ logits = self.lm_head(hidden_states)
998
+ loss = None
999
+ if labels is not None:
1000
+ if self.use_loss_mask:
1001
+ loss_mask = self.get_loss_mask(input_ids, labels, self.eod_token, self.sep_token)
1002
+ # Shift so that tokens < n predict n
1003
+ shift_logits = logits[..., :-1, :].contiguous()
1004
+ shift_labels = labels[..., 1:].contiguous()
1005
+ # Flatten the tokens
1006
+ if self.use_loss_mask:
1007
+ loss_fct = CrossEntropyLoss(reduction='none')
1008
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1009
+ shift_labels = shift_labels.view(-1)
1010
+ # Enable model parallelism
1011
+ shift_labels = shift_labels.to(shift_logits.device)
1012
+ loss = loss_fct(shift_logits, shift_labels)
1013
+ loss = torch.sum(loss * loss_mask) / loss_mask.sum()
1014
+ else:
1015
+ loss_fct = CrossEntropyLoss()
1016
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1017
+ shift_labels = shift_labels.view(-1)
1018
+ # Enable model parallelism
1019
+ shift_labels = shift_labels.to(shift_logits.device)
1020
+ loss = loss_fct(shift_logits, shift_labels)
1021
+ if not return_dict:
1022
+ output = (logits,) + outputs[1:]
1023
+ return (loss,) + output if loss is not None else output
1024
+
1025
+ return CausalLMOutputWithPast(
1026
+ loss=loss,
1027
+ logits=logits,
1028
+ past_key_values=outputs.past_key_values,
1029
+ hidden_states=hidden_states,
1030
+ attentions=outputs.attentions,
1031
+ )
1032
+
1033
+ def prepare_inputs_for_generation(
1034
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1035
+ ):
1036
+
1037
+ position_ids = kwargs.get("position_ids", None)
1038
+ if attention_mask is not None and position_ids is None:
1039
+ # create position_ids on the fly for batch generation
1040
+ position_ids = attention_mask.long().cumsum(-1) - 1
1041
+ position_ids.masked_fill_(attention_mask == 0, 1)
1042
+ if past_key_values:
1043
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1044
+
1045
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1046
+ if inputs_embeds is not None and past_key_values is None:
1047
+ model_inputs = {"inputs_embeds": inputs_embeds}
1048
+ else:
1049
+ model_inputs = {"input_ids": input_ids}
1050
+
1051
+ model_inputs.update(
1052
+ {
1053
+ "position_ids": position_ids,
1054
+ "past_key_values": past_key_values,
1055
+ "use_cache": kwargs.get("use_cache"),
1056
+ "attention_mask": attention_mask,
1057
+ }
1058
+ )
1059
+ return model_inputs
1060
+
1061
+ @staticmethod
1062
+ def _reorder_cache(past_key_values, beam_idx):
1063
+ reordered_past = ()
1064
+ for layer_past in past_key_values:
1065
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1066
+ return reordered_past
1067
+
1068
+
1069
+ @add_start_docstrings(
1070
+ """
1071
+ The Yuan Model transformer with a sequence classification head on top (linear layer).
1072
+
1073
+ [`YuanForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1074
+ (e.g. GPT-2) do.
1075
+
1076
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1077
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1078
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1079
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1080
+ each row of the batch).
1081
+ """,
1082
+ YUAN_START_DOCSTRING,
1083
+ )
1084
+ class YuanForSequenceClassification(YuanPreTrainedModel):
1085
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1086
+
1087
+ def __init__(self, config):
1088
+ super().__init__(config)
1089
+ self.num_labels = config.num_labels
1090
+ self.model = YuanModel(config)
1091
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1092
+
1093
+ # Initialize weights and apply final processing
1094
+ self.post_init()
1095
+
1096
+ def get_input_embeddings(self):
1097
+ return self.model.embed_tokens
1098
+
1099
+ def set_input_embeddings(self, value):
1100
+ self.model.embed_tokens = value
1101
+
1102
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
1103
+ def forward(
1104
+ self,
1105
+ input_ids: torch.LongTensor = None,
1106
+ attention_mask: Optional[torch.Tensor] = None,
1107
+ position_ids: Optional[torch.LongTensor] = None,
1108
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1109
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1110
+ labels: Optional[torch.LongTensor] = None,
1111
+ use_cache: Optional[bool] = None,
1112
+ output_attentions: Optional[bool] = None,
1113
+ output_hidden_states: Optional[bool] = None,
1114
+ return_dict: Optional[bool] = None,
1115
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1116
+ r"""
1117
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1118
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1119
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1120
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1121
+ """
1122
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1123
+ transformer_outputs = self.model(
1124
+ input_ids,
1125
+ attention_mask=attention_mask,
1126
+ position_ids=position_ids,
1127
+ past_key_values=past_key_values,
1128
+ inputs_embeds=inputs_embeds,
1129
+ use_cache=use_cache,
1130
+ output_attentions=output_attentions,
1131
+ output_hidden_states=output_hidden_states,
1132
+ return_dict=return_dict,
1133
+ )
1134
+ hidden_states = transformer_outputs[0]
1135
+ logits = self.score(hidden_states)
1136
+
1137
+ if input_ids is not None:
1138
+ batch_size = input_ids.shape[0]
1139
+ else:
1140
+ batch_size = inputs_embeds.shape[0]
1141
+
1142
+ if self.config.pad_token_id is None and batch_size != 1:
1143
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1144
+ if self.config.pad_token_id is None:
1145
+ sequence_lengths = -1
1146
+ else:
1147
+ if input_ids is not None:
1148
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1149
+ else:
1150
+ sequence_lengths = -1
1151
+
1152
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1153
+
1154
+ loss = None
1155
+ if labels is not None:
1156
+ labels = labels.to(logits.device)
1157
+ if self.config.problem_type is None:
1158
+ if self.num_labels == 1:
1159
+ self.config.problem_type = "regression"
1160
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1161
+ self.config.problem_type = "single_label_classification"
1162
+ else:
1163
+ self.config.problem_type = "multi_label_classification"
1164
+
1165
+ if self.config.problem_type == "regression":
1166
+ loss_fct = MSELoss()
1167
+ if self.num_labels == 1:
1168
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1169
+ else:
1170
+ loss = loss_fct(pooled_logits, labels)
1171
+ elif self.config.problem_type == "single_label_classification":
1172
+ loss_fct = CrossEntropyLoss()
1173
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1174
+ elif self.config.problem_type == "multi_label_classification":
1175
+ loss_fct = BCEWithLogitsLoss()
1176
+ loss = loss_fct(pooled_logits, labels)
1177
+ if not return_dict:
1178
+ output = (pooled_logits,) + transformer_outputs[1:]
1179
+ return ((loss,) + output) if loss is not None else output
1180
+
1181
+ return SequenceClassifierOutputWithPast(
1182
+ loss=loss,
1183
+ logits=pooled_logits,
1184
+ past_key_values=transformer_outputs.past_key_values,
1185
+ hidden_states=transformer_outputs.hidden_states,
1186
+ attentions=transformer_outputs.attentions,
1187
+ )
1188
+
1189
+
yuan_hf_model_cpu.py ADDED
@@ -0,0 +1,1189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.activations import ACT2FN
29
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
30
+ from transformers.modeling_utils import PreTrainedModel
31
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
32
+ from .configuration_yuan import YuanConfig
33
+ from einops import rearrange
34
+ #from flash_attn import flash_attn_varlen_func as flash_attn_unpadded_func
35
+ #from flash_attn import flash_attn_func
36
+
37
+ import copy
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ _CONFIG_FOR_DOC = "YuanConfig"
42
+
43
+
44
+ class LocalizedFiltering(torch.nn.Module):
45
+ """
46
+ Mega's Exponential Moving Average layer, largely left unmodified from the original repo with the exception of
47
+ variable names and moving away from the stateful representation of incremental decoding state. See
48
+ "https://arxiv.org/abs/2209.10655" for more details.
49
+ """
50
+
51
+ def __init__(self, hidden_size):
52
+ super().__init__()
53
+
54
+ self.embed_dim = hidden_size
55
+ self.lf_conv2d_group = 1
56
+ self.lf_conv2d_num_pad = 1
57
+
58
+ 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)
59
+ 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)
60
+ self.output_layernorm = YuanRMSNorm(self.embed_dim)
61
+
62
+ def _train_forward(self, inputs):
63
+ inputs = inputs.transpose(0,1)
64
+ seq_len, bsz, embed_dim = inputs.size()
65
+ if embed_dim != self.embed_dim:
66
+ raise ValueError(
67
+ f"Unexpected embedding dimension received: input is {embed_dim}, model expects {self.embed_dim}"
68
+ )
69
+ residual = inputs
70
+
71
+ inputs = inputs.view(seq_len, 1, bsz, embed_dim).permute(2, 3, 0, 1)
72
+ output1 = self.conv1(inputs)
73
+ output1 = output1[:, :, :seq_len, :]
74
+
75
+ output2 = self.conv2(output1)
76
+ output2 = output2[:, :, :seq_len, :].permute(2, 3, 0, 1).contiguous()
77
+ output2 = output2.view(seq_len, bsz, embed_dim)
78
+ assert output2.shape == residual.shape
79
+
80
+ lf_output = self.output_layernorm(output2 + residual)
81
+ lf_output = lf_output.transpose(0,1)
82
+ return lf_output
83
+
84
+ def _inference_forward(self, inputs, before_hidden_states):
85
+
86
+ if before_hidden_states is None:
87
+ inputs = inputs.transpose(0,1)
88
+ seq_len, bsz, embed_dim = inputs.size()
89
+ if embed_dim != self.embed_dim:
90
+ raise ValueError(
91
+ f"Unexpected embedding dimension received: input is {embed_dim}, model expects {self.embed_dim}"
92
+ )
93
+ residual = inputs
94
+
95
+ inputs = inputs.view(seq_len, 1, bsz, embed_dim).permute(2, 3, 0, 1)
96
+ output1 = self.conv1(inputs)
97
+ output1 = output1[:, :, :seq_len, :]
98
+
99
+ output2 = self.conv2(output1)
100
+ output2 = output2[:, :, :seq_len, :].permute(2, 3, 0, 1).contiguous()
101
+ output2 = output2.view(seq_len, bsz, embed_dim)
102
+ assert output2.shape == residual.shape
103
+
104
+ lf_output = self.output_layernorm(output2 + residual)
105
+ lf_output = lf_output.transpose(0,1)
106
+ return lf_output
107
+ else:
108
+ inputs = inputs.transpose(0,1)
109
+ before_hidden_states = before_hidden_states.transpose(0,1)
110
+ residual = inputs
111
+
112
+ seq_len, bsz, embed_dim = inputs.size()
113
+ seq_len_before, _, _ = before_hidden_states.size()
114
+
115
+ assert seq_len == 1 and seq_len_before == 2
116
+
117
+ inputs = torch.cat((before_hidden_states, inputs), dim=0)
118
+ inputs = inputs.view(3, 1, bsz, embed_dim).permute(2, 3, 0, 1)
119
+
120
+ output1 = self.conv1(inputs)
121
+ output2 = self.conv2(output1[:,:,1:-1,:])
122
+ output2 = output2[:,:,1:-1,:]
123
+ output2 = output2.view(1, bsz, embed_dim)
124
+ assert output2.shape == residual.shape
125
+
126
+ lf_output = self.output_layernorm(output2 + residual)
127
+ lf_output = lf_output.transpose(0,1)
128
+
129
+ return lf_output
130
+
131
+
132
+
133
+ def forward(
134
+ self,
135
+ inputs,
136
+ before_hidden_states
137
+ ) -> torch.Tensor:
138
+ assert self.lf_conv2d_num_pad == 1
139
+ if self.training:
140
+ lf_output = self._train_forward(inputs)
141
+ else:
142
+ lf_output = self._inference_forward(inputs, before_hidden_states)
143
+
144
+ return lf_output
145
+
146
+
147
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
148
+ def _make_causal_mask(
149
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
150
+ ):
151
+ """
152
+ Make causal mask used for bi-directional self-attention.
153
+ """
154
+ bsz, tgt_len = input_ids_shape
155
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
156
+ mask_cond = torch.arange(mask.size(-1), device=device)
157
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
158
+ mask = mask.to(dtype)
159
+
160
+ if past_key_values_length > 0:
161
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
162
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
163
+
164
+
165
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
166
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
167
+ """
168
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
169
+ """
170
+ bsz, src_len = mask.size()
171
+ tgt_len = tgt_len if tgt_len is not None else src_len
172
+
173
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
174
+
175
+ inverted_mask = 1.0 - expanded_mask
176
+
177
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
178
+
179
+
180
+ def rotate_half(x):
181
+ """Rotates half the hidden dims of the input."""
182
+ x1 = x[..., : x.shape[-1] // 2]
183
+ x2 = x[..., x.shape[-1] // 2 :]
184
+ return torch.cat((-x2, x1), dim=-1)
185
+
186
+
187
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
188
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
189
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
190
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
191
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
192
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
193
+ q_embed = (q * cos) + (rotate_half(q) * sin)
194
+ k_embed = (k * cos) + (rotate_half(k) * sin)
195
+ return q_embed, k_embed
196
+
197
+ class YuanRMSNorm(nn.Module):
198
+ def __init__(self, hidden_size, eps=1e-6):
199
+ """
200
+ YuanRMSNorm is equivalent to LlamaRMSNorm
201
+ """
202
+ super().__init__()
203
+ self.weight = nn.Parameter(torch.ones(hidden_size))
204
+ self.variance_epsilon = eps
205
+
206
+ def forward(self, hidden_states):
207
+ input_dtype = hidden_states.dtype
208
+ hidden_states = hidden_states.to(torch.float32)
209
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
210
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
211
+ return self.weight * hidden_states.to(input_dtype)
212
+
213
+ class YuanRotaryEmbedding(torch.nn.Module):
214
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
215
+
216
+ """
217
+ YuanRotaryEmbedding is equivalent to LlamaRotaryEmbedding in transformers v4.36
218
+ """
219
+
220
+ super().__init__()
221
+
222
+ self.dim = dim
223
+ self.max_position_embeddings = max_position_embeddings
224
+ self.base = base
225
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
226
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
227
+
228
+ # Build here to make `torch.jit.trace` work.
229
+ self._set_cos_sin_cache(
230
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
231
+ )
232
+
233
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
234
+ self.max_seq_len_cached = seq_len
235
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
236
+
237
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
238
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
239
+ emb = torch.cat((freqs, freqs), dim=-1)
240
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
241
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
242
+
243
+ def forward(self, x, seq_len=None):
244
+ # x: [bs, num_attention_heads, seq_len, head_size]
245
+ if seq_len > self.max_seq_len_cached:
246
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
247
+
248
+ return (
249
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
250
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
251
+ )
252
+
253
+ class YuanMLP(nn.Module):
254
+ def __init__(
255
+ self,
256
+ hidden_size: int,
257
+ intermediate_size: int,
258
+ hidden_act: str,
259
+ ):
260
+ super().__init__()
261
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
262
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
263
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
264
+ self.act_fn = ACT2FN[hidden_act]
265
+
266
+ def forward(self, x):
267
+ return self.down_proj(self.gate_proj(x) * self.act_fn(self.up_proj(x)))
268
+
269
+ class YuanAttention(nn.Module):
270
+ """Localized Filtering-based Attention 'YUAN 2.0: A Large Language Model with Localized Filtering-based Attention' paper"""
271
+
272
+ def __init__(self, config: YuanConfig):
273
+ super().__init__()
274
+ self.config = config
275
+ self.hidden_size = config.hidden_size
276
+ self.num_heads = config.num_attention_heads
277
+ self.head_dim = self.hidden_size // self.num_heads
278
+ self.max_position_embeddings = config.max_position_embeddings
279
+ self.causal_mask = config.causal_mask
280
+ self.softmax_scale = 1.0 / math.sqrt(self.head_dim)
281
+ self.use_flash_attention = config.use_flash_attention
282
+ try:
283
+ self.use_shareqk = config.use_shareqk
284
+ except Exception as e:
285
+ self.use_shareqk=False
286
+ self.dropout = 0.0
287
+ if (self.head_dim * self.num_heads) != self.hidden_size:
288
+ raise ValueError(
289
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
290
+ f" and `num_heads`: {self.num_heads})."
291
+ )
292
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
293
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
294
+ self.rotary_emb = YuanRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
295
+ if self.use_shareqk:
296
+ self.qk_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
297
+ self.qk_weight = nn.Parameter(torch.Tensor(2, self.hidden_size))
298
+ self.qk_bias = nn.Parameter(torch.Tensor(2, self.hidden_size))
299
+ else:
300
+ self.lf_gate = LocalizedFiltering(self.hidden_size)
301
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
302
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
303
+
304
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
305
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
306
+
307
+ def forward(
308
+ self,
309
+ hidden_states: torch.Tensor,
310
+ attention_mask: Optional[torch.Tensor] = None,
311
+ position_ids: Optional[torch.LongTensor] = None,
312
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
313
+ output_attentions: bool = False,
314
+ use_cache: bool = False,
315
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
316
+ bsz, q_len, _ = hidden_states.size()
317
+ before_hidden_states = None
318
+ is_first_step = False
319
+ if use_cache:
320
+ if past_key_value is None:
321
+ #inference_hidden_states_memory = torch.empty(bsz, 2, hidden_states.shape[2], dtype=hidden_states.dtype ,device=torch.cuda.current_device())
322
+ inference_hidden_states_memory = torch.empty(bsz, 2, hidden_states.shape[2], dtype=hidden_states.dtype)
323
+ is_first_step = True
324
+ else:
325
+ before_hidden_states = past_key_value[2]
326
+
327
+ if use_cache:
328
+ if is_first_step:
329
+ if q_len >= 2:
330
+ inference_hidden_states_memory = hidden_states[ :, -2:, :]
331
+ else:
332
+ inference_hidden_states_memory[:, :, :] = 0
333
+ inference_hidden_states_memory[:, -1:, :] = hidden_states[:, -1:, :]
334
+ else:
335
+ hidden_states_tmp = before_hidden_states[:, -1:, :]
336
+ inference_hidden_states_memory = copy.deepcopy(torch.cat((hidden_states_tmp, hidden_states), dim=1))
337
+
338
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
339
+ if self.use_shareqk:
340
+ qk_states = self.qk_proj(hidden_states).view(bsz, q_len, self.num_heads*self.head_dim)
341
+ query_key = qk_states.unsqueeze(2) * self.qk_weight + self.qk_bias
342
+ query_states, key_states = torch.unbind(query_key, dim=2)
343
+
344
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
345
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
346
+ else:
347
+ hidden_states = self.lf_gate(hidden_states,before_hidden_states)
348
+ query_states = self.q_proj(hidden_states)
349
+ key_states = self.k_proj(hidden_states)
350
+ qk_states = torch.cat([query_states, key_states], dim=-1)
351
+ qk_states = qk_states.view(bsz,q_len,self.num_heads,int(qk_states.shape[-1]//self.num_heads))
352
+ (query_states,key_states) = torch.chunk(qk_states, 2, dim=-1)
353
+ query_states = query_states.transpose(1, 2)
354
+ key_states = key_states.transpose(1, 2)
355
+
356
+
357
+ kv_seq_len = key_states.shape[-2]
358
+ if past_key_value is not None:
359
+ kv_seq_len += past_key_value[0].shape[-2]
360
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
361
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
362
+
363
+ if past_key_value is not None:
364
+ # reuse k, v, self_attention
365
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
366
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
367
+
368
+ past_key_value = (key_states, value_states,inference_hidden_states_memory) if use_cache else None
369
+
370
+ if self.use_flash_attention:
371
+ attn_weights = None
372
+ query_states = query_states.transpose(1, 2)
373
+ key_states = key_states.transpose(1, 2)
374
+ value_states = value_states.transpose(1, 2)
375
+
376
+ batch_size, seqlen_q = query_states.shape[0], query_states.shape[1]
377
+ seqlen_k = key_states.shape[1]
378
+
379
+ q, k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [query_states, key_states, value_states]]
380
+
381
+ cu_seqlens_q = torch.arange(0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int,
382
+ device=q.device)
383
+
384
+ if self.training:
385
+ assert seqlen_k == seqlen_q
386
+ cu_seqlens_k = cu_seqlens_q
387
+ is_causal = self.causal_mask
388
+ else:
389
+ is_causal = seqlen_q == seqlen_k
390
+ cu_seqlens_k = torch.arange(0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int,
391
+ device=q.device)
392
+ self.dropout=0
393
+
394
+ output = flash_attn_unpadded_func(
395
+ q, k, v, cu_seqlens_q, cu_seqlens_k, seqlen_q, seqlen_k, self.dropout, causal=is_causal
396
+ )
397
+
398
+ attn_output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
399
+ else:
400
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
401
+
402
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
403
+ raise ValueError(
404
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
405
+ f" {attn_weights.size()}"
406
+ )
407
+ if attention_mask is not None:
408
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
409
+ raise ValueError(
410
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
411
+ )
412
+ attn_weights = attn_weights + attention_mask
413
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
414
+
415
+ # upcast attention to fp32
416
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
417
+ attn_output = torch.matmul(attn_weights, value_states)
418
+
419
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
420
+ raise ValueError(
421
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
422
+ f" {attn_output.size()}"
423
+ )
424
+
425
+ attn_output = attn_output.transpose(1, 2)
426
+
427
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
428
+
429
+ attn_output = self.o_proj(attn_output)
430
+
431
+ if not output_attentions:
432
+ attn_weights = None
433
+ return attn_output, attn_weights, past_key_value
434
+
435
+
436
+ class YuanDecoderLayer(nn.Module):
437
+ def __init__(self, config: YuanConfig):
438
+ super().__init__()
439
+ self.hidden_size = config.hidden_size
440
+ self.self_attn = YuanAttention(config=config)
441
+ self.mlp = YuanMLP(
442
+ hidden_size=self.hidden_size,
443
+ intermediate_size=config.intermediate_size,
444
+ hidden_act=config.hidden_act,
445
+ )
446
+ self.input_layernorm = YuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
447
+ self.post_attention_layernorm = YuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
448
+
449
+ def forward(
450
+ self,
451
+ hidden_states: torch.Tensor,
452
+ attention_mask: Optional[torch.Tensor] = None,
453
+ position_ids: Optional[torch.LongTensor] = None,
454
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
455
+ output_attentions: Optional[bool] = False,
456
+ use_cache: Optional[bool] = False,
457
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
458
+ """
459
+ Args:
460
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
461
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
462
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
463
+ output_attentions (`bool`, *optional*):
464
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
465
+ returned tensors for more detail.
466
+ use_cache (`bool`, *optional*):
467
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
468
+ (see `past_key_values`).
469
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
470
+ """
471
+
472
+ residual = hidden_states
473
+ hidden_states = self.input_layernorm(hidden_states)
474
+
475
+ # Self Attention
476
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
477
+ hidden_states=hidden_states,
478
+ attention_mask=attention_mask,
479
+ position_ids=position_ids,
480
+ past_key_value=past_key_value,
481
+ output_attentions=output_attentions,
482
+ use_cache=use_cache,
483
+ )
484
+ hidden_states = residual + hidden_states
485
+
486
+ # Fully Connected
487
+ residual = hidden_states
488
+ hidden_states = self.post_attention_layernorm(hidden_states)
489
+ hidden_states = self.mlp(hidden_states)
490
+ hidden_states = residual + hidden_states
491
+
492
+ outputs = (hidden_states,)
493
+
494
+ if output_attentions:
495
+ outputs += (self_attn_weights,)
496
+
497
+ if use_cache:
498
+ outputs += (present_key_value,)
499
+
500
+ return outputs
501
+
502
+
503
+ YUAN_START_DOCSTRING = r"""
504
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
505
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
506
+ etc.)
507
+
508
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
509
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
510
+ and behavior.
511
+
512
+ Parameters:
513
+ config ([`YuanConfig`]):
514
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
515
+ load the weights associated with the model, only the configuration. Check out the
516
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
517
+ """
518
+
519
+
520
+ @add_start_docstrings(
521
+ "The bare Yuan Model outputting raw hidden-states without any specific head on top.",
522
+ YUAN_START_DOCSTRING,
523
+ )
524
+ class YuanPreTrainedModel(PreTrainedModel):
525
+ config_class = YuanConfig
526
+ base_model_prefix = "model"
527
+ supports_gradient_checkpointing = True
528
+ _no_split_modules = ["YuanDecoderLayer"]
529
+ _skip_keys_device_placement = "past_key_values"
530
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
531
+
532
+ def _init_weights(self, module):
533
+ std = self.config.initializer_range
534
+ if isinstance(module, nn.Linear):
535
+ module.weight.data.normal_(mean=0.0, std=std)
536
+ if module.bias is not None:
537
+ module.bias.data.zero_()
538
+ elif isinstance(module, nn.Embedding):
539
+ module.weight.data.normal_(mean=0.0, std=std)
540
+ if module.padding_idx is not None:
541
+ module.weight.data[module.padding_idx].zero_()
542
+
543
+ def _set_gradient_checkpointing(self, module, value=False):
544
+ if isinstance(module, YuanModel):
545
+ module.gradient_checkpointing = value
546
+
547
+
548
+ YUAN_INPUTS_DOCSTRING = r"""
549
+ Args:
550
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
551
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
552
+ it.
553
+
554
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
555
+ [`PreTrainedTokenizer.__call__`] for details.
556
+
557
+ [What are input IDs?](../glossary#input-ids)
558
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
559
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
560
+
561
+ - 1 for tokens that are **not masked**,
562
+ - 0 for tokens that are **masked**.
563
+
564
+ [What are attention masks?](../glossary#attention-mask)
565
+
566
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
567
+ [`PreTrainedTokenizer.__call__`] for details.
568
+
569
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
570
+ `past_key_values`).
571
+
572
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
573
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
574
+ information on the default strategy.
575
+
576
+ - 1 indicates the head is **not masked**,
577
+ - 0 indicates the head is **masked**.
578
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
579
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
580
+ config.n_positions - 1]`.
581
+
582
+ [What are position IDs?](../glossary#position-ids)
583
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
584
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
585
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
586
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
587
+
588
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
589
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
590
+
591
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
592
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
593
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
594
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
595
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
596
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
597
+ model's internal embedding lookup matrix.
598
+ use_cache (`bool`, *optional*):
599
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
600
+ `past_key_values`).
601
+ output_attentions (`bool`, *optional*):
602
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
603
+ tensors for more detail.
604
+ output_hidden_states (`bool`, *optional*):
605
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
606
+ more detail.
607
+ return_dict (`bool`, *optional*):
608
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
609
+ """
610
+
611
+
612
+ @add_start_docstrings(
613
+ "The bare Yuan Model outputting raw hidden-states without any specific head on top.",
614
+ YUAN_START_DOCSTRING,
615
+ )
616
+ class YuanModel(YuanPreTrainedModel):
617
+ """
618
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`YuanDecoderLayer`]
619
+
620
+ Args:
621
+ config: YuanConfig
622
+ """
623
+
624
+ def __init__(self, config: YuanConfig):
625
+ super().__init__(config)
626
+ self.padding_idx = config.pad_token_id
627
+ self.vocab_size = config.vocab_size
628
+
629
+ #TODO: control it by config
630
+ self.eod_token = config.eod_token
631
+ self.reset_attention_mask = config.reset_attention_mask
632
+ self.reset_position_ids = config.reset_position_ids
633
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
634
+ self.layers = nn.ModuleList([YuanDecoderLayer(config) for _ in range(config.num_hidden_layers)])
635
+ self.norm = YuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
636
+ self.gradient_checkpointing = False
637
+ # Initialize weights and apply final processing
638
+ self.post_init()
639
+
640
+ def get_input_embeddings(self):
641
+ return self.embed_tokens
642
+
643
+ def set_input_embeddings(self, value):
644
+ self.embed_tokens = value
645
+
646
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
647
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
648
+ # create causal mask
649
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
650
+ combined_attention_mask = None
651
+ if input_shape[-1] > 1:
652
+ combined_attention_mask = _make_causal_mask(
653
+ input_shape,
654
+ inputs_embeds.dtype,
655
+ device=inputs_embeds.device,
656
+ past_key_values_length=past_key_values_length,
657
+ )
658
+
659
+ if attention_mask is not None:
660
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
661
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
662
+ inputs_embeds.device
663
+ )
664
+ combined_attention_mask = (
665
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
666
+ )
667
+
668
+ return combined_attention_mask
669
+
670
+ def _prepare_decoder_attention_mask_training(self, input_id, inputs_embeds, eod_token, reset_mask_flag ,reset_attention_mask=True, reset_position_ids=True):
671
+
672
+ micro_batch_size, seq_length = input_id.size()
673
+
674
+ attention_mask = torch.tril(torch.ones(
675
+ (micro_batch_size, seq_length, seq_length), device=inputs_embeds.device)).view(
676
+ micro_batch_size, 1, seq_length, seq_length)
677
+
678
+ position_ids = torch.arange(seq_length, dtype=torch.long,
679
+ device=inputs_embeds.device)
680
+ position_ids = position_ids.unsqueeze(0).expand_as(input_id)
681
+
682
+ if reset_position_ids:
683
+ position_ids = position_ids.clone()
684
+
685
+ if reset_position_ids or reset_attention_mask:
686
+ # Loop through the batches:
687
+ for b in range(micro_batch_size):
688
+
689
+ # Find indecies where EOD token is.
690
+ eod_index = position_ids[b, input_id[b] == eod_token]
691
+
692
+ # Detach indecies from positions if going to modify positions.
693
+ if reset_position_ids:
694
+ eod_index = eod_index.clone()
695
+ # Loop through EOD indecies:
696
+ prev_index = 0
697
+ for j in range(eod_index.size()[0]):
698
+ i = eod_index[j]
699
+ # Mask attention loss.
700
+ if reset_attention_mask:
701
+ attention_mask[b, 0, (i + 1):, :(i + 1)] = 0
702
+ # Reset positions.
703
+ if reset_position_ids:
704
+ position_ids[b, (i + 1):] -= (i + 1 - prev_index)
705
+ prev_index = i + 1
706
+
707
+ inverted_mask = 1 - attention_mask
708
+ output_attn_mask = inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min)
709
+ if reset_mask_flag:
710
+ output_attn_mask = output_attn_mask[:,:,-1:,:]
711
+ return output_attn_mask, position_ids
712
+
713
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
714
+ def forward(
715
+ self,
716
+ input_ids: torch.LongTensor = None,
717
+ attention_mask: Optional[torch.Tensor] = None,
718
+ position_ids: Optional[torch.LongTensor] = None,
719
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
720
+ inputs_embeds: Optional[torch.FloatTensor] = None,
721
+ use_cache: Optional[bool] = None,
722
+ output_attentions: Optional[bool] = None,
723
+ output_hidden_states: Optional[bool] = None,
724
+ return_dict: Optional[bool] = None,
725
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
726
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
727
+ output_hidden_states = (
728
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
729
+ )
730
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
731
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
732
+ input_ids1 = copy.deepcopy(input_ids)
733
+ reset_mask_flag = False
734
+ if past_key_values:
735
+ input_ids = input_ids[:, -1:]
736
+ if use_cache:
737
+ reset_mask_flag = True
738
+ # retrieve input_ids and inputs_embeds
739
+ if input_ids is not None and inputs_embeds is not None:
740
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
741
+ elif input_ids is not None:
742
+ batch_size, seq_length = input_ids.shape
743
+ elif inputs_embeds is not None:
744
+ batch_size, seq_length, _ = inputs_embeds.shape
745
+ else:
746
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
747
+
748
+ seq_length_with_past = seq_length
749
+ past_key_values_length = 0
750
+
751
+ if past_key_values is not None:
752
+ past_key_values_length = past_key_values[0][0].shape[2]
753
+ seq_length_with_past = seq_length_with_past + past_key_values_length
754
+
755
+ if position_ids is None:
756
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
757
+ position_ids = torch.arange(
758
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
759
+ )
760
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
761
+ else:
762
+ position_ids = position_ids.view(-1, seq_length).long()
763
+ if inputs_embeds is None:
764
+ inputs_embeds = self.embed_tokens(input_ids)
765
+ if self.training or self.reset_position_ids:
766
+ 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)
767
+
768
+ else:
769
+ if attention_mask is None:
770
+ attention_mask = torch.ones(
771
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
772
+ )
773
+ attention_mask = self._prepare_decoder_attention_mask(
774
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
775
+ )
776
+
777
+ hidden_states = inputs_embeds
778
+
779
+ if self.gradient_checkpointing and self.training:
780
+ if use_cache:
781
+ logger.warning_once(
782
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
783
+ )
784
+ use_cache = False
785
+
786
+ # decoder layers
787
+ all_hidden_states = () if output_hidden_states else None
788
+ all_self_attns = () if output_attentions else None
789
+ next_decoder_cache = () if use_cache else None
790
+
791
+ for idx, decoder_layer in enumerate(self.layers):
792
+ if output_hidden_states:
793
+ all_hidden_states += (hidden_states,)
794
+
795
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
796
+
797
+ if self.gradient_checkpointing and self.training:
798
+
799
+ def create_custom_forward(module):
800
+ def custom_forward(*inputs):
801
+ # None for past_key_value
802
+ return module(*inputs, output_attentions, None)
803
+
804
+ return custom_forward
805
+
806
+ layer_outputs = torch.utils.checkpoint.checkpoint(
807
+ create_custom_forward(decoder_layer),
808
+ hidden_states,
809
+ attention_mask,
810
+ position_ids,
811
+ None,
812
+ )
813
+ else:
814
+ layer_outputs = decoder_layer(
815
+ hidden_states,
816
+ attention_mask=attention_mask,
817
+ position_ids=position_ids,
818
+ past_key_value=past_key_value,
819
+ output_attentions=output_attentions,
820
+ use_cache=use_cache,
821
+ )
822
+
823
+ hidden_states = layer_outputs[0]
824
+
825
+ if use_cache:
826
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
827
+
828
+ if output_attentions:
829
+ all_self_attns += (layer_outputs[1],)
830
+ hidden_states = self.norm(hidden_states)
831
+
832
+ # add hidden states from the last decoder layer
833
+ if output_hidden_states:
834
+ all_hidden_states += (hidden_states,)
835
+ next_cache = next_decoder_cache if use_cache else None
836
+ if not return_dict:
837
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
838
+ return BaseModelOutputWithPast(
839
+ last_hidden_state=hidden_states,
840
+ past_key_values=next_cache,
841
+ hidden_states=all_hidden_states,
842
+ attentions=all_self_attns,
843
+ )
844
+
845
+
846
+ class YuanForCausalLM(YuanPreTrainedModel):
847
+ def __init__(self, config):
848
+ super().__init__(config)
849
+ self.eod_token = config.eod_token
850
+ self.sep_token = config.sep_token
851
+ self.use_loss_mask = config.use_loss_mask
852
+ self.model = YuanModel(config)
853
+
854
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
855
+
856
+ # Initialize weights and apply final processing
857
+ self.post_init()
858
+
859
+ def get_input_embeddings(self):
860
+ return self.model.embed_tokens
861
+
862
+ def set_input_embeddings(self, value):
863
+ self.model.embed_tokens = value
864
+
865
+ def get_output_embeddings(self):
866
+ return self.lm_head
867
+
868
+ def set_output_embeddings(self, new_embeddings):
869
+ self.lm_head = new_embeddings
870
+
871
+ def set_decoder(self, decoder):
872
+ self.model = decoder
873
+
874
+ def get_decoder(self):
875
+ return self.model
876
+
877
+ def get_loss_mask(self, input_ids, labels, eod_token, sep_token):
878
+ micro_batch_size, seq_length = input_ids.size()
879
+ loss_mask = torch.ones(input_ids.size(), dtype=torch.float, device=input_ids.device)
880
+
881
+ position_ids = torch.arange(seq_length, dtype=torch.long,
882
+ device=input_ids.device)
883
+ position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
884
+
885
+
886
+ """modify loss_mask to only calculate the loss of the answer (separated with [SEP])"""
887
+
888
+ for b in range(micro_batch_size):
889
+ eod_indexs = position_ids[b, input_ids[b] == eod_token]
890
+ sep_indexs = position_ids[b, input_ids[b] == sep_token]
891
+
892
+ if len(eod_indexs) == 0 or len(sep_indexs) == 0:
893
+ loss_mask[b] = 1.0
894
+ else:
895
+ if eod_indexs[0] > sep_indexs[0]:
896
+ loss_mask[b, 0:sep_indexs[0]] = 0
897
+
898
+ if len(eod_indexs) == len(sep_indexs):
899
+ for ii, eod_index in enumerate(eod_indexs):
900
+ start_index = eod_index
901
+ if ii == (len(sep_indexs) - 1):
902
+ stop_index = seq_length
903
+ else:
904
+ stop_index = sep_indexs[ii + 1]
905
+ loss_mask[b, start_index:stop_index] = 0.0
906
+ else:
907
+ if len(eod_indexs) > len(sep_indexs):
908
+ loss_mask[b,:] = 1.0
909
+ else:
910
+ for ii, eod_index in enumerate(eod_indexs):
911
+ start_index = eod_index
912
+ stop_index = sep_indexs[ii + 1]
913
+
914
+ loss_mask[b, start_index:stop_index] = 0.0
915
+
916
+ elif eod_indexs[0] < sep_indexs[0]:
917
+
918
+ if len(eod_indexs) == len(sep_indexs):
919
+ for ii, eod_index in enumerate(eod_indexs):
920
+ start_index = eod_index
921
+ stop_index = sep_indexs[ii]
922
+ loss_mask[b, start_index:stop_index] = 0.0
923
+
924
+ else:
925
+ if len(eod_indexs) < len(sep_indexs):
926
+ loss_mask[b,:] = 1.0
927
+ else:
928
+ for ii, eod_index in enumerate(eod_indexs):
929
+ start_index = eod_index
930
+ if ii >= len(sep_indexs):
931
+ stop_index = seq_length
932
+ else:
933
+ stop_index = sep_indexs[ii]
934
+ loss_mask[b, start_index:stop_index] = 0.0
935
+
936
+ loss_mask[input_ids == eod_token] = 1.0
937
+ return loss_mask
938
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
939
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
940
+ def forward(
941
+ self,
942
+ input_ids: torch.LongTensor = None,
943
+ attention_mask: Optional[torch.Tensor] = None,
944
+ position_ids: Optional[torch.LongTensor] = None,
945
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
946
+ inputs_embeds: Optional[torch.FloatTensor] = None,
947
+ labels: Optional[torch.LongTensor] = None,
948
+ use_cache: Optional[bool] = None,
949
+ output_attentions: Optional[bool] = None,
950
+ output_hidden_states: Optional[bool] = None,
951
+ return_dict: Optional[bool] = None,
952
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
953
+ r"""
954
+ Args:
955
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
956
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
957
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
958
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
959
+
960
+ Returns:
961
+
962
+ Example:
963
+
964
+ ```python
965
+ >>> from transformers import AutoTokenizer, YuanForCausalLM
966
+
967
+ >>> model = YuanForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
968
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
969
+
970
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
971
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
972
+
973
+ >>> # Generate
974
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
975
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
976
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
977
+ ```"""
978
+
979
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
980
+ output_hidden_states = (
981
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
982
+ )
983
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
984
+ outputs = self.model(
985
+ input_ids=input_ids,
986
+ attention_mask=attention_mask,
987
+ position_ids=position_ids,
988
+ past_key_values=past_key_values,
989
+ inputs_embeds=inputs_embeds,
990
+ use_cache=use_cache,
991
+ output_attentions=output_attentions,
992
+ output_hidden_states=output_hidden_states,
993
+ return_dict=return_dict,
994
+ )
995
+
996
+ hidden_states = outputs[0]
997
+ logits = self.lm_head(hidden_states)
998
+ loss = None
999
+ if labels is not None:
1000
+ if self.use_loss_mask:
1001
+ loss_mask = self.get_loss_mask(input_ids, labels, self.eod_token, self.sep_token)
1002
+ # Shift so that tokens < n predict n
1003
+ shift_logits = logits[..., :-1, :].contiguous()
1004
+ shift_labels = labels[..., 1:].contiguous()
1005
+ # Flatten the tokens
1006
+ if self.use_loss_mask:
1007
+ loss_fct = CrossEntropyLoss(reduction='none')
1008
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1009
+ shift_labels = shift_labels.view(-1)
1010
+ # Enable model parallelism
1011
+ shift_labels = shift_labels.to(shift_logits.device)
1012
+ loss = loss_fct(shift_logits, shift_labels)
1013
+ loss = torch.sum(loss * loss_mask) / loss_mask.sum()
1014
+ else:
1015
+ loss_fct = CrossEntropyLoss()
1016
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1017
+ shift_labels = shift_labels.view(-1)
1018
+ # Enable model parallelism
1019
+ shift_labels = shift_labels.to(shift_logits.device)
1020
+ loss = loss_fct(shift_logits, shift_labels)
1021
+ if not return_dict:
1022
+ output = (logits,) + outputs[1:]
1023
+ return (loss,) + output if loss is not None else output
1024
+
1025
+ return CausalLMOutputWithPast(
1026
+ loss=loss,
1027
+ logits=logits,
1028
+ past_key_values=outputs.past_key_values,
1029
+ hidden_states=hidden_states,
1030
+ attentions=outputs.attentions,
1031
+ )
1032
+
1033
+ def prepare_inputs_for_generation(
1034
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1035
+ ):
1036
+
1037
+ position_ids = kwargs.get("position_ids", None)
1038
+ if attention_mask is not None and position_ids is None:
1039
+ # create position_ids on the fly for batch generation
1040
+ position_ids = attention_mask.long().cumsum(-1) - 1
1041
+ position_ids.masked_fill_(attention_mask == 0, 1)
1042
+ if past_key_values:
1043
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1044
+
1045
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1046
+ if inputs_embeds is not None and past_key_values is None:
1047
+ model_inputs = {"inputs_embeds": inputs_embeds}
1048
+ else:
1049
+ model_inputs = {"input_ids": input_ids}
1050
+
1051
+ model_inputs.update(
1052
+ {
1053
+ "position_ids": position_ids,
1054
+ "past_key_values": past_key_values,
1055
+ "use_cache": kwargs.get("use_cache"),
1056
+ "attention_mask": attention_mask,
1057
+ }
1058
+ )
1059
+ return model_inputs
1060
+
1061
+ @staticmethod
1062
+ def _reorder_cache(past_key_values, beam_idx):
1063
+ reordered_past = ()
1064
+ for layer_past in past_key_values:
1065
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1066
+ return reordered_past
1067
+
1068
+
1069
+ @add_start_docstrings(
1070
+ """
1071
+ The Yuan Model transformer with a sequence classification head on top (linear layer).
1072
+
1073
+ [`YuanForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1074
+ (e.g. GPT-2) do.
1075
+
1076
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1077
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1078
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1079
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1080
+ each row of the batch).
1081
+ """,
1082
+ YUAN_START_DOCSTRING,
1083
+ )
1084
+ class YuanForSequenceClassification(YuanPreTrainedModel):
1085
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1086
+
1087
+ def __init__(self, config):
1088
+ super().__init__(config)
1089
+ self.num_labels = config.num_labels
1090
+ self.model = YuanModel(config)
1091
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1092
+
1093
+ # Initialize weights and apply final processing
1094
+ self.post_init()
1095
+
1096
+ def get_input_embeddings(self):
1097
+ return self.model.embed_tokens
1098
+
1099
+ def set_input_embeddings(self, value):
1100
+ self.model.embed_tokens = value
1101
+
1102
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
1103
+ def forward(
1104
+ self,
1105
+ input_ids: torch.LongTensor = None,
1106
+ attention_mask: Optional[torch.Tensor] = None,
1107
+ position_ids: Optional[torch.LongTensor] = None,
1108
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1109
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1110
+ labels: Optional[torch.LongTensor] = None,
1111
+ use_cache: Optional[bool] = None,
1112
+ output_attentions: Optional[bool] = None,
1113
+ output_hidden_states: Optional[bool] = None,
1114
+ return_dict: Optional[bool] = None,
1115
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1116
+ r"""
1117
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1118
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1119
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1120
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1121
+ """
1122
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1123
+ transformer_outputs = self.model(
1124
+ input_ids,
1125
+ attention_mask=attention_mask,
1126
+ position_ids=position_ids,
1127
+ past_key_values=past_key_values,
1128
+ inputs_embeds=inputs_embeds,
1129
+ use_cache=use_cache,
1130
+ output_attentions=output_attentions,
1131
+ output_hidden_states=output_hidden_states,
1132
+ return_dict=return_dict,
1133
+ )
1134
+ hidden_states = transformer_outputs[0]
1135
+ logits = self.score(hidden_states)
1136
+
1137
+ if input_ids is not None:
1138
+ batch_size = input_ids.shape[0]
1139
+ else:
1140
+ batch_size = inputs_embeds.shape[0]
1141
+
1142
+ if self.config.pad_token_id is None and batch_size != 1:
1143
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1144
+ if self.config.pad_token_id is None:
1145
+ sequence_lengths = -1
1146
+ else:
1147
+ if input_ids is not None:
1148
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1149
+ else:
1150
+ sequence_lengths = -1
1151
+
1152
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1153
+
1154
+ loss = None
1155
+ if labels is not None:
1156
+ labels = labels.to(logits.device)
1157
+ if self.config.problem_type is None:
1158
+ if self.num_labels == 1:
1159
+ self.config.problem_type = "regression"
1160
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1161
+ self.config.problem_type = "single_label_classification"
1162
+ else:
1163
+ self.config.problem_type = "multi_label_classification"
1164
+
1165
+ if self.config.problem_type == "regression":
1166
+ loss_fct = MSELoss()
1167
+ if self.num_labels == 1:
1168
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1169
+ else:
1170
+ loss = loss_fct(pooled_logits, labels)
1171
+ elif self.config.problem_type == "single_label_classification":
1172
+ loss_fct = CrossEntropyLoss()
1173
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1174
+ elif self.config.problem_type == "multi_label_classification":
1175
+ loss_fct = BCEWithLogitsLoss()
1176
+ loss = loss_fct(pooled_logits, labels)
1177
+ if not return_dict:
1178
+ output = (pooled_logits,) + transformer_outputs[1:]
1179
+ return ((loss,) + output) if loss is not None else output
1180
+
1181
+ return SequenceClassifierOutputWithPast(
1182
+ loss=loss,
1183
+ logits=pooled_logits,
1184
+ past_key_values=transformer_outputs.past_key_values,
1185
+ hidden_states=transformer_outputs.hidden_states,
1186
+ attentions=transformer_outputs.attentions,
1187
+ )
1188
+
1189
+