初始化项目,由ModelHub XC社区提供模型
Model: codefuse-ai/CodeFuse-QWen-14B Source: Original Platform
This commit is contained in:
34
.gitattributes
vendored
Normal file
34
.gitattributes
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
*.7z filter=lfs diff=lfs merge=lfs -text
|
||||
*.arrow filter=lfs diff=lfs merge=lfs -text
|
||||
*.bin filter=lfs diff=lfs merge=lfs -text
|
||||
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
||||
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
||||
*.ftz filter=lfs diff=lfs merge=lfs -text
|
||||
*.gz filter=lfs diff=lfs merge=lfs -text
|
||||
*.h5 filter=lfs diff=lfs merge=lfs -text
|
||||
*.joblib filter=lfs diff=lfs merge=lfs -text
|
||||
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
||||
*.model filter=lfs diff=lfs merge=lfs -text
|
||||
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
||||
*.onnx filter=lfs diff=lfs merge=lfs -text
|
||||
*.ot filter=lfs diff=lfs merge=lfs -text
|
||||
*.parquet filter=lfs diff=lfs merge=lfs -text
|
||||
*.pb filter=lfs diff=lfs merge=lfs -text
|
||||
*.pt filter=lfs diff=lfs merge=lfs -text
|
||||
*.pth filter=lfs diff=lfs merge=lfs -text
|
||||
*.rar filter=lfs diff=lfs merge=lfs -text
|
||||
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
||||
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
||||
*.tflite filter=lfs diff=lfs merge=lfs -text
|
||||
*.tgz filter=lfs diff=lfs merge=lfs -text
|
||||
*.xz filter=lfs diff=lfs merge=lfs -text
|
||||
*.zip filter=lfs diff=lfs merge=lfs -text
|
||||
*.zstandard filter=lfs diff=lfs merge=lfs -text
|
||||
*.tfevents* filter=lfs diff=lfs merge=lfs -text
|
||||
*.db* filter=lfs diff=lfs merge=lfs -text
|
||||
*.ark* filter=lfs diff=lfs merge=lfs -text
|
||||
**/*ckpt*data* filter=lfs diff=lfs merge=lfs -text
|
||||
**/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text
|
||||
**/*ckpt*.index filter=lfs diff=lfs merge=lfs -text
|
||||
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
||||
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
||||
47
MODEL_LICENSE.md
Normal file
47
MODEL_LICENSE.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# CodeFuse COMMUNITY LICENSE AGREEMENT
|
||||
CodeFuse Release Date: September 8, 2023
|
||||
|
||||
By clicking to agree or by using or distributing any portion or element of the Materials, you will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
|
||||
|
||||
1. Definitions.
|
||||
a. This CodeFuse COMMUNITY LICENSE AGREEMENT (this "Agreement") shall mean the terms and conditions for use, reproduction, distribution and modification of the Materials as defined by this Agreement.
|
||||
b. "Ant" or "We" (or "Us") shall mean Ant Group.
|
||||
c. "CodeFuse" shall mean the large language models (including CodeFuse-13B and CodeFuse-CodeLlaMa-34B), and software and algorithms, consisting of trained model weights, parameters (including optimizer states), machine-learning model code, and other elements of the foregoing distributed by Us.
|
||||
d. "Documentation" shall mean the specifications, manuals and documentation accompanying CodeFuse distributed by Us.
|
||||
e. "Materials" shall mean, collectively, Ant's proprietary CodeFuse and Documentation (and any portion thereof) made available under this Agreement.
|
||||
f. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
||||
g. "Source" form shall mean the preferred form for making modifications, including but not limited to model source code, documentation source, and configuration files.
|
||||
h. "Third Parties" (or "Third Party") shall mean individuals or legal entities that are not controlling, controlled by Us or You, or under common control with Us or You.
|
||||
i. "You" (or "Your") shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Materials for any purpose and in any field of use.
|
||||
|
||||
2. Grant of Rights.
|
||||
You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Ant's intellectual property or other rights owned by Ant embodied in the Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the Materials.
|
||||
|
||||
3. Redistribution.
|
||||
You may distribute or make the Materials or derivative works thereof available to a Third Party in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
||||
a. You shall provide a copy of this Agreement to such Third Party;
|
||||
b. if You modify the CodeFuse model, You shall provide a prominent notice, stating how You have modified the CodeFuse model, to such Third Party; and
|
||||
c. You shall retain in all copies of the Materials that You distribute the following attribution notices within a "Notice" text file distributed as a part of such copies: "CodeFuse is licensed under the CodeFuse COMMUNITY LICENSE AGREEMENT, Copyright (c) Ant Group. All Rights Reserved."
|
||||
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such derivative works as a whole, provided Your use, reproduction, and distribution of the work otherwise complies with the terms and conditions of this Agreement.
|
||||
|
||||
4. Rules of Use.
|
||||
You shall comply with applicable laws and regulations (including without limitation export controls or restrictions) in Your use of the Materials.
|
||||
|
||||
5. Intellectual Property.
|
||||
a. Ant retains ownership of all intellectual property rights in and to the Materials and derivatives made by or for Ant. Conditioned upon compliance with the terms and conditions of this Agreement, with respect to any derivative works and modifications of the Materials that are made by You, You are and will be the owner of such derivative works and modifications.
|
||||
b. No trademark license is granted to use the trade names, trademarks, service marks, or product names of Ant, except as required to fulfill notice requirements under this Agreement or as required for reasonable and customary use in describing and redistributing the Materials.
|
||||
c. If You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Ant or any entity alleging that the Materials or any output therefrom, or any part of the foregoing, infringe any intellectual property or other right owned or licensable by You, then all licences granted to You under this Agreement shall terminate as of the date such lawsuit or other proceeding is commenced or brought.
|
||||
|
||||
6. Disclaimer of Warranty and Limitation of Liability.
|
||||
a. Ant is not obligated to support, update, provide training for, or develop any further version of the Materials or to grant any license thereto.
|
||||
b. THE MATERIALS ARE PROVIDED "AS IS" WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, OR FITNESS FOR A PARTICULAR PURPOSE. WE MAKE NO WARRANTY AND ASSUME NO RESPONSIBILITY FOR THE SAFETY OR STABILITY OF THE MATERIALS AND ANY OUTPUT THEREFROM.
|
||||
c. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE MATERIALS AND ANY OUTPUT AND RESULTS. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT OR ARISING FROM YOUR USE OR INABILITY TO USE THE MATERIALS OR ANY OUTPUT OF IT, FOR ANY DIRECT, OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, NO MATTER HOW IT'S CAUSED OR EVEN IF ANT OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
|
||||
d. You will defend, indemnify and hold harmless Ant from and against any claim by any Third Party arising out of or related to Your use or distribution of the Materials.
|
||||
|
||||
7. Survival and Termination.
|
||||
a. The term of this Agreement shall commence upon Your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.
|
||||
b. We may terminate this Agreement if You breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, You must delete and cease use of the Materials. Sections 6 and 8 shall survive the termination of this Agreement.
|
||||
|
||||
8. Governing Law and Jurisdiction.
|
||||
a. This Agreement and any dispute arising out of or relating to it, whether in contract, tort, negligence, products liability, or otherwise, will be governed by the laws of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
|
||||
b. The People's Courts in Hangzhou City shall have exclusive jurisdiction over any dispute arising out of this Agreement.
|
||||
338
README.md
Normal file
338
README.md
Normal file
@@ -0,0 +1,338 @@
|
||||
---
|
||||
frameworks:
|
||||
- Pytorch
|
||||
license: other
|
||||
tasks:
|
||||
- text-generation
|
||||
---
|
||||
# Model Card for CodeFuse-QWen-14B
|
||||
<p align="center">
|
||||
<img src="https://modelscope.cn/api/v1/models/codefuse-ai/CodeFuse-QWen-14B/repo?Revision=master&FilePath=LOGO.jpg&View=true" width="800"/>
|
||||
<p>
|
||||
|
||||
[[中文]](#chinese) [[English]](#english)
|
||||
|
||||
#### Clone with HTTP
|
||||
```bash
|
||||
git clone https://www.modelscope.cn/codefuse-ai/CodeFuse-QWen-14B.git
|
||||
```
|
||||
|
||||
<a id="english"></a>
|
||||
|
||||
## Model Description
|
||||
|
||||
CodeFuse-QWen-14B is a 14B Code-LLM finetuned by QLoRA of multiple code tasks on the base model StarCoder.
|
||||
|
||||
<br>
|
||||
|
||||
## News and Updates
|
||||
🔥🔥 2023-10-20 CodeFuse-QWen-14B technical documentation has been released. For those interested, please refer to the CodeFuse article on our WeChat official account via the provided link.(https://mp.weixin.qq.com/s/PCQPkvbvfxSPzsqjOILCDw)
|
||||
|
||||
🔥🔥 2023-10-16 CodeFuse-QWen-14B has been released, achieving a pass@1 (greedy decoding) score of 48.78% on HumanEval, which is a 16% increase compared to Qwen-14b's 32.3%.
|
||||
|
||||
🔥🔥 2023-09-27 CodeFuse-StarCoder-15B has been released, achieving a pass@1 (greedy decoding) score of 54.9% on HumanEval, which is a 21% increase compared to StarCoder's 33.6%.
|
||||
|
||||
🔥🔥🔥 2023-09-26 We are pleased to announce the release of the [4-bit quantized version](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B-4bits/summary) of [CodeFuse-CodeLlama-34B](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B/summary). Despite the quantization process, the model still achieves a remarkable 73.8% accuracy (greedy decoding) on the HumanEval pass@1 metric.
|
||||
|
||||
🔥🔥🔥 2023-09-11 [CodeFuse-CodeLlama34B](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B/summary) has achived 74.4% of pass@1 (greedy decoding) on HumanEval, which is SOTA results for openspurced LLMs at present.
|
||||
|
||||
<br>
|
||||
|
||||
## Code Community
|
||||
|
||||
**Homepage**: 🏡 https://github.com/codefuse-ai (**Please give us your support with a Star🌟 + Fork🚀 + Watch👀**)
|
||||
|
||||
+ If you wish to fine-tune the model yourself, you can visit ✨[MFTCoder](https://github.com/codefuse-ai/MFTCoder)✨✨
|
||||
|
||||
+ If you wish to deploy the model yourself, you can visit ✨[FasterTransformer4CodeFuse](https://github.com/codefuse-ai/FasterTransformer4CodeFuse)✨✨
|
||||
|
||||
+ If you wish to see a demo of the model, you can visit ✨[CodeFuse Demo](https://github.com/codefuse-ai/codefuse)✨✨
|
||||
|
||||
<br>
|
||||
|
||||
## Performance
|
||||
|
||||
|
||||
| Model | HumanEval(pass@1) | Date |
|
||||
|:----------------------------|:-----------------:|:-------:|
|
||||
| **CodeFuse-CodeLlama-34B** | **74.4%** | 2023.9 |
|
||||
|**CodeFuse-CodeLlama-34B-4bits** | **73.8%** | 2023.9 |
|
||||
| WizardCoder-Python-34B-V1.0 | 73.2% | 2023.8 |
|
||||
| GPT-4(zero-shot) | 67.0% | 2023.3 |
|
||||
| PanGu-Coder2 15B | 61.6% | 2023.8 |
|
||||
| CodeLlama-34b-Python | 53.7% | 2023.8 |
|
||||
| CodeLlama-34b | 48.8% | 2023.8 |
|
||||
| GPT-3.5(zero-shot) | 48.1% | 2022.11 |
|
||||
| OctoCoder | 46.2% | 2023.8 |
|
||||
| StarCoder-15B | 33.6% | 2023.5 |
|
||||
| Qwen-14b | 32.3% | 2023.10 |
|
||||
| **CodeFuse-StarCoder-15B** | **54.9%** | 2023.9 |
|
||||
| **CodeFuse-QWen-14B** | **48.78%** | 2023.10 |
|
||||
|
||||
|
||||
### NLP
|
||||
|
||||
<p align="center">
|
||||
<img src="https://modelscope.cn/api/v1/models/codefuse-ai/CodeFuse-QWen-14B/repo?Revision=master&FilePath=natural_ability.jpg&View=true" width="800"/>
|
||||
<p>
|
||||
|
||||
<br>
|
||||
|
||||
## Requirements
|
||||
|
||||
* python>=3.8
|
||||
* pytorch>=2.0.0
|
||||
* transformers==4.32.0
|
||||
* Sentencepiece
|
||||
* CUDA 11.4
|
||||
<br>
|
||||
|
||||
## Inference String Format
|
||||
|
||||
The inference string is a concatenated string formed by combining conversation data(system, human and bot contents) in the training data format. It is used as input during the inference process.
|
||||
Here is an example format of the concatenated string:
|
||||
|
||||
```python
|
||||
"""
|
||||
<s>system
|
||||
System instruction
|
||||
<s>human
|
||||
Human 1st round input
|
||||
<s>bot
|
||||
Bot 1st round output<|endoftext|>
|
||||
<s>human
|
||||
Human 2nd round input
|
||||
<s>bot
|
||||
Bot 2nd round output<|endoftext|>
|
||||
...
|
||||
...
|
||||
...
|
||||
<s>human
|
||||
Human nth round input
|
||||
<s>bot
|
||||
{Bot output to be genreated}<|endoftext|>
|
||||
"""
|
||||
```
|
||||
|
||||
When applying inference, you always make your input string end with "\<s\>bot" to ask the model generating answers.
|
||||
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
git clone https://www.modelscope.cn/codefuse-ai/CodeFuse-QWen-14B.git
|
||||
```
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
```python
|
||||
import torch
|
||||
from modelscope import (
|
||||
AutoTokenizer,
|
||||
AutoModelForCausalLM,
|
||||
snapshot_download
|
||||
)
|
||||
model_dir = snapshot_download('codefuse-ai/CodeFuse-QWen-14B',revision = 'v1.0.0')
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
|
||||
tokenizer.padding_side = "left"
|
||||
tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
|
||||
tokenizer.eos_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
|
||||
tokenizer.pad_token = "<|endoftext|>"
|
||||
tokenizer.eos_token = "<|endoftext|>"
|
||||
# try 4bit loading if cuda memory not enough
|
||||
model = AutoModelForCausalLM.from_pretrained(model_dir,
|
||||
trust_remote_code=True,
|
||||
load_in_4bit=False,
|
||||
device_map="auto",
|
||||
torch_dtype=torch.bfloat16)
|
||||
model.eval()
|
||||
|
||||
HUMAN_ROLE_START_TAG = "<s>human\n"
|
||||
BOT_ROLE_START_TAG = "<s>bot\n"
|
||||
|
||||
text = f"{HUMAN_ROLE_START_TAG}write a python function of quick sort.\n{BOT_ROLE_START_TAG}"
|
||||
inputs = tokenizer(text, return_tensors='pt', padding=True, add_special_tokens=False).to("cuda")
|
||||
outputs = model.generate(
|
||||
inputs=inputs["input_ids"],
|
||||
attention_mask=inputs["attention_mask"],
|
||||
max_new_tokens=512,
|
||||
top_p=0.95,
|
||||
temperature=0.1,
|
||||
do_sample=True,
|
||||
eos_token_id=tokenizer.eos_token_id,
|
||||
pad_token_id=tokenizer.pad_token_id
|
||||
)
|
||||
gen_text = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
|
||||
print(gen_text)
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<a id="chinese"></a>
|
||||
|
||||
## 模型简介
|
||||
|
||||
CodeFuse-QWen-14B 是一个通过QLoRA对基座模型QWen-14B进行多代码任务微调的代码大模型。
|
||||
<br>
|
||||
|
||||
## 新闻
|
||||
🔥🔥 2023-10-20 公布了CodeFuse-QWen-14B技术文档,感兴趣详见微信公众号CodeFuse文章:https://mp.weixin.qq.com/s/PCQPkvbvfxSPzsqjOILCDw
|
||||
|
||||
🔥🔥 2023-10-16开源了CodeFuse-QWen-14B模型,在HumanEval pass@1(greedy decoding)上可以达到48.78%, 比Qwen-14b提高了16%的代码能力(HumanEval)
|
||||
|
||||
🔥🔥 2023-09-27开源了CodeFuse-StarCoder-15B模型,在HumanEval pass@1(greedy decoding)上可以达到54.9%, 比StarCoder提高了21%的代码能力(HumanEval)
|
||||
|
||||
🔥🔥🔥 2023-09-26 [CodeFuse-CodeLlama-34B 4bits](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B-4bits/summary)量化版本发布,量化后模型在HumanEval pass@1指标为73.8% (贪婪解码)。
|
||||
|
||||
🔥🔥🔥 2023-09-11 [CodeFuse-CodeLlama-34B](https://modelscope.cn/models/codefuse-ai/CodeFuse-CodeLlama-34B/summary)发布,HumanEval pass@1指标达到74.4% (贪婪解码), 为当前开源SOTA。
|
||||
|
||||
<br>
|
||||
|
||||
## 代码社区
|
||||
**大本营**: 🏡 https://github.com/codefuse-ai (**请支持我们的项目Star🌟 + Fork🚀 + Watch👀**)
|
||||
|
||||
+ 如果您想自己微调该模型,可以访问 ✨[MFTCoder](https://github.com/codefuse-ai/MFTCoder)✨✨
|
||||
|
||||
+ 如果您想自己部署该模型,可以访问 ✨[FasterTransformer4CodeFuse](https://github.com/codefuse-ai/FasterTransformer4CodeFuse)✨✨
|
||||
|
||||
+ 如果您想观看该模型示例,可以访问 ✨[CodeFuse Demo](https://github.com/codefuse-ai/codefuse)✨✨
|
||||
|
||||
<br>
|
||||
|
||||
|
||||
## 评测表现
|
||||
|
||||
### 代码
|
||||
|
||||
|
||||
| 模型 | HumanEval(pass@1) | 日期 |
|
||||
|:----------------------------|:-----------------:|:-------:|
|
||||
| **CodeFuse-CodeLlama-34B** | **74.4%** | 2023.9 |
|
||||
|**CodeFuse-CodeLlama-34B-4bits** | **73.8%** | 2023.9 |
|
||||
| WizardCoder-Python-34B-V1.0 | 73.2% | 2023.8 |
|
||||
| GPT-4(zero-shot) | 67.0% | 2023.3 |
|
||||
| PanGu-Coder2 15B | 61.6% | 2023.8 |
|
||||
| CodeLlama-34b-Python | 53.7% | 2023.8 |
|
||||
| CodeLlama-34b | 48.8% | 2023.8 |
|
||||
| GPT-3.5(zero-shot) | 48.1% | 2022.11 |
|
||||
| OctoCoder | 46.2% | 2023.8 |
|
||||
| StarCoder-15B | 33.6% | 2023.5 |
|
||||
| Qwen-14b | 32.3% | 2023.10 |
|
||||
| **CodeFuse-StarCoder-15B** | **54.9%** | 2023.9 |
|
||||
| **CodeFuse-QWen-14B** | **48.78%** | 2023.8 |
|
||||
|
||||
|
||||
### NLP
|
||||
|
||||
<p align="center">
|
||||
<img src="https://modelscope.cn/api/v1/models/codefuse-ai/CodeFuse-QWen-14B/repo?Revision=master&FilePath=natural_ability.jpg&View=true" width="800"/>
|
||||
<p>
|
||||
|
||||
<br>
|
||||
|
||||
## Requirements
|
||||
|
||||
* python>=3.8
|
||||
* pytorch>=2.0.0
|
||||
* transformers==4.32.0
|
||||
* Sentencepiece
|
||||
* CUDA 11.4
|
||||
<br>
|
||||
|
||||
## 推理数据格式
|
||||
|
||||
推理数据为模型在训练数据格式下拼接的字符串形式,它也是推理时输入prompt拼接的方式:
|
||||
|
||||
```python
|
||||
"""
|
||||
<s>system
|
||||
这是System指令
|
||||
<s>human
|
||||
这是第1轮用户输入的问题
|
||||
<s>bot
|
||||
这是第1轮模型生成的内容<|endoftext|>
|
||||
<s>human
|
||||
这是第2轮用户输入的问题
|
||||
<s>bot
|
||||
这是第2轮模型生成的内容<|endoftext|>
|
||||
...
|
||||
...
|
||||
...
|
||||
<s>human
|
||||
这是第n轮用户输入的问题
|
||||
<s>bot
|
||||
{模型现在要生成的内容}<|endoftext|>
|
||||
"""
|
||||
```
|
||||
|
||||
推理时,请确保拼接的prompt字符串以"\<s\>bot\n"结尾,引导模型生成回答。
|
||||
|
||||
## 快速使用
|
||||
|
||||
```bash
|
||||
git clone https://www.modelscope.cn/codefuse-ai/CodeFuse-QWen-14B.git
|
||||
```
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
```python
|
||||
import torch
|
||||
from modelscope import (
|
||||
AutoTokenizer,
|
||||
AutoModelForCausalLM,
|
||||
snapshot_download
|
||||
)
|
||||
model_dir = snapshot_download('codefuse-ai/CodeFuse-QWen-14B',revision = 'v1.0.0')
|
||||
tokenizer = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
|
||||
tokenizer.padding_side = "left"
|
||||
tokenizer.pad_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
|
||||
tokenizer.eos_token_id = tokenizer.convert_tokens_to_ids("<|endoftext|>")
|
||||
tokenizer.pad_token = "<|endoftext|>"
|
||||
tokenizer.eos_token = "<|endoftext|>"
|
||||
# try 4bit loading if cuda memory not enough
|
||||
model = AutoModelForCausalLM.from_pretrained(model_dir,
|
||||
trust_remote_code=True,
|
||||
load_in_4bit=False,
|
||||
device_map="auto",
|
||||
torch_dtype=torch.bfloat16)
|
||||
model.eval()
|
||||
|
||||
HUMAN_ROLE_START_TAG = "<s>human\n"
|
||||
BOT_ROLE_START_TAG = "<s>bot\n"
|
||||
|
||||
text = f"{HUMAN_ROLE_START_TAG}write a python function of quick sort.\n{BOT_ROLE_START_TAG}"
|
||||
inputs = tokenizer(text, return_tensors='pt', padding=True, add_special_tokens=False).to("cuda")
|
||||
outputs = model.generate(
|
||||
inputs=inputs["input_ids"],
|
||||
attention_mask=inputs["attention_mask"],
|
||||
max_new_tokens=512,
|
||||
top_p=0.95,
|
||||
temperature=0.1,
|
||||
do_sample=True,
|
||||
eos_token_id=tokenizer.eos_token_id,
|
||||
pad_token_id=tokenizer.pad_token_id
|
||||
)
|
||||
|
||||
gen_text = tokenizer.batch_decode(outputs[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
|
||||
print(gen_text)
|
||||
```
|
||||
|
||||
|
||||
## 加入我们
|
||||
|
||||
我们是平台技术事业群AI Native团队,负责蚂蚁蚂蚁集团平台工程的智能化,团队成立3年多以来,支持了蚂蚁集团云计算基础设施智能化运维的升级改造。团队的Mission是,通过世界级的技术创新和影响,构建有广泛用户的算法服务和平台,支撑内外部产品和业务落地。团队秉承创新基因,在支撑业务落地的同时,推动技术影响。3年以来在ICLR、NeurIPS、KDD、ACL等顶会发表论文20余篇,创新业务结果获得两次蚂蚁技术最高奖T-Star,1次蚂蚁集团最高奖SuperMA。开源项目CodeFuse获得4K点赞(2024年2月),Huggingface和modelscope上模型累积下载量超过150万次。
|
||||
|
||||
**我们正在寻找行业中的佼佼者加入我们的团队!如果您希望在一个充满活力、创新和卓越文化的环境中发展您的职业生涯,欢迎您查看我们的社招&校招机会,加入我们,一起创造下一个行业里程碑。**
|
||||
|
||||
校招:https://hrrecommend.antgroup.com/guide.html?code=8uoP5mlus5DqQYbE_EnqcE2FD5JZH21MwvMUIb9mb6X3osXPuBraG54SyM8GLn_7
|
||||
|
||||
社招:https://talent.antgroup.com/off-campus-position?positionId=1933830
|
||||
43
config.json
Normal file
43
config.json
Normal file
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"_name_or_path": "/mnt/user/qumu/download_models/Qwen-14B",
|
||||
"architectures": [
|
||||
"QWenLMHeadModel"
|
||||
],
|
||||
"attn_dropout_prob": 0.0,
|
||||
"auto_map": {
|
||||
"AutoConfig": "configuration_qwen.QWenConfig",
|
||||
"AutoModelForCausalLM": "modeling_qwen.QWenLMHeadModel"
|
||||
},
|
||||
"bf16": true,
|
||||
"emb_dropout_prob": 0.0,
|
||||
"eos_token": "<|endoftext|>",
|
||||
"eos_token_id": 151643,
|
||||
"fp16": false,
|
||||
"fp32": false,
|
||||
"hidden_size": 5120,
|
||||
"initializer_range": 0.02,
|
||||
"intermediate_size": 27392,
|
||||
"kv_channels": 128,
|
||||
"layer_norm_epsilon": 1e-06,
|
||||
"max_position_embeddings": 8192,
|
||||
"model_type": "qwen",
|
||||
"no_bias": true,
|
||||
"num_attention_heads": 40,
|
||||
"num_hidden_layers": 40,
|
||||
"onnx_safe": null,
|
||||
"pad_token": "<|extra_1|>",
|
||||
"pad_token_id": 151647,
|
||||
"rotary_emb_base": 10000,
|
||||
"rotary_pct": 1.0,
|
||||
"scale_attn_weights": true,
|
||||
"seq_length": 2048,
|
||||
"tie_word_embeddings": false,
|
||||
"tokenizer_class": "QWenTokenizer",
|
||||
"torch_dtype": "bfloat16",
|
||||
"transformers_version": "4.33.2",
|
||||
"use_cache": true,
|
||||
"use_dynamic_ntk": true,
|
||||
"use_flash_attn": true,
|
||||
"use_logn_attn": true,
|
||||
"vocab_size": 152064
|
||||
}
|
||||
1
configuration.json
Normal file
1
configuration.json
Normal file
@@ -0,0 +1 @@
|
||||
{"framework":"Pytorch","task":"text-generation"}
|
||||
65
configuration_qwen.py
Normal file
65
configuration_qwen.py
Normal file
@@ -0,0 +1,65 @@
|
||||
# Copyright (c) Alibaba Cloud.
|
||||
#
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
|
||||
from transformers import PretrainedConfig
|
||||
|
||||
|
||||
class QWenConfig(PretrainedConfig):
|
||||
model_type = "qwen"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=151936,
|
||||
hidden_size=4096,
|
||||
num_hidden_layers=32,
|
||||
num_attention_heads=32,
|
||||
emb_dropout_prob=0.0,
|
||||
attn_dropout_prob=0.0,
|
||||
layer_norm_epsilon=1e-6,
|
||||
initializer_range=0.02,
|
||||
max_position_embeddings=8192,
|
||||
scale_attn_weights=True,
|
||||
use_cache=True,
|
||||
bf16=False,
|
||||
fp16=False,
|
||||
fp32=False,
|
||||
kv_channels=128,
|
||||
rotary_pct=1.0,
|
||||
rotary_emb_base=10000,
|
||||
use_dynamic_ntk=True,
|
||||
use_logn_attn=True,
|
||||
use_flash_attn="auto",
|
||||
intermediate_size=22016,
|
||||
no_bias=True,
|
||||
tie_word_embeddings=False,
|
||||
**kwargs,
|
||||
):
|
||||
self.vocab_size = vocab_size
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.num_hidden_layers = num_hidden_layers
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.emb_dropout_prob = emb_dropout_prob
|
||||
self.attn_dropout_prob = attn_dropout_prob
|
||||
self.layer_norm_epsilon = layer_norm_epsilon
|
||||
self.initializer_range = initializer_range
|
||||
self.scale_attn_weights = scale_attn_weights
|
||||
self.use_cache = use_cache
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.bf16 = bf16
|
||||
self.fp16 = fp16
|
||||
self.fp32 = fp32
|
||||
self.kv_channels = kv_channels
|
||||
self.rotary_pct = rotary_pct
|
||||
self.rotary_emb_base = rotary_emb_base
|
||||
self.use_dynamic_ntk = use_dynamic_ntk
|
||||
self.use_logn_attn = use_logn_attn
|
||||
self.use_flash_attn = use_flash_attn
|
||||
self.no_bias = no_bias
|
||||
super().__init__(
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
**kwargs
|
||||
)
|
||||
15
generation_config.json
Normal file
15
generation_config.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"chat_format": "raw",
|
||||
"do_sample": true,
|
||||
"eos_token_id": 151643,
|
||||
"max_new_tokens": 512,
|
||||
"pad_token_id": 151643,
|
||||
"stop_words_ids": [
|
||||
[
|
||||
151643
|
||||
]
|
||||
],
|
||||
"top_k": 0,
|
||||
"top_p": 0.8,
|
||||
"transformers_version": "4.33.2"
|
||||
}
|
||||
1293
modeling_qwen.py
Normal file
1293
modeling_qwen.py
Normal file
File diff suppressed because it is too large
Load Diff
BIN
natural_ability.jpg
Normal file
BIN
natural_ability.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.9 MiB |
BIN
natural_ability.png
Normal file
BIN
natural_ability.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.4 MiB |
3
pytorch_model-00001-of-00003.bin
Normal file
3
pytorch_model-00001-of-00003.bin
Normal file
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:e76c3d05c3ddae911c5eac3fd4781f2dfb1388b164e046d6b08e92893490c1c6
|
||||
size 9963537981
|
||||
3
pytorch_model-00002-of-00003.bin
Normal file
3
pytorch_model-00002-of-00003.bin
Normal file
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:dff9b2a95a67381f6986435b5ab5bb3aaf9a4f3629a69ef2fbb32783c984f50d
|
||||
size 9878407559
|
||||
3
pytorch_model-00003-of-00003.bin
Normal file
3
pytorch_model-00003-of-00003.bin
Normal file
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:7655619bde3958f406386898022b24a7540a9659526651fc6309ccf884ac0296
|
||||
size 8492748925
|
||||
3
pytorch_model.bin.index.json
Normal file
3
pytorch_model.bin.index.json
Normal file
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:a1d9456a1980609eff5aad43f07996680bcd83519fc67ea8af70dcbe2d0bc6c0
|
||||
size 24387
|
||||
151643
qwen.tiktoken
Normal file
151643
qwen.tiktoken
Normal file
File diff suppressed because it is too large
Load Diff
416
qwen_generation_utils.py
Normal file
416
qwen_generation_utils.py
Normal file
@@ -0,0 +1,416 @@
|
||||
# Copyright (c) Alibaba Cloud.
|
||||
#
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
|
||||
"""Generation support."""
|
||||
|
||||
from typing import Tuple, List, Union, Iterable
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from transformers import PreTrainedTokenizer
|
||||
from transformers import logging
|
||||
from transformers.generation import LogitsProcessor
|
||||
|
||||
logger = logging.get_logger(__name__)
|
||||
|
||||
# Types.
|
||||
HistoryType = List[Tuple[str, str]]
|
||||
TokensType = List[int]
|
||||
BatchTokensType = List[List[int]]
|
||||
|
||||
|
||||
def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
|
||||
for tokens in batch:
|
||||
context_length = len(tokens)
|
||||
if context_length < seq_length:
|
||||
tokens.extend([pad_id] * (seq_length - context_length))
|
||||
return batch
|
||||
|
||||
|
||||
def get_ltor_masks_and_position_ids(
|
||||
data,
|
||||
eod_token,
|
||||
reset_position_ids,
|
||||
reset_attention_mask,
|
||||
eod_mask_loss,
|
||||
):
|
||||
"""Build masks and position id for left to right model."""
|
||||
|
||||
# Extract batch size and sequence length.
|
||||
micro_batch_size, seq_length = data.size()
|
||||
|
||||
# Attention mask (lower triangular).
|
||||
if reset_attention_mask:
|
||||
att_mask_batch = micro_batch_size
|
||||
else:
|
||||
att_mask_batch = 1
|
||||
attention_mask = torch.tril(
|
||||
torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)
|
||||
).view(att_mask_batch, 1, seq_length, seq_length)
|
||||
|
||||
# Loss mask.
|
||||
loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
|
||||
if eod_mask_loss:
|
||||
loss_mask[data == eod_token] = 0.0
|
||||
|
||||
# Position ids.
|
||||
position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
|
||||
position_ids = position_ids.unsqueeze(0).expand_as(data)
|
||||
# We need to clone as the ids will be modifed based on batch index.
|
||||
if reset_position_ids:
|
||||
position_ids = position_ids.clone()
|
||||
|
||||
if reset_position_ids or reset_attention_mask:
|
||||
# Loop through the batches:
|
||||
for b in range(micro_batch_size):
|
||||
|
||||
# Find indecies where EOD token is.
|
||||
eod_index = position_ids[b, data[b] == eod_token]
|
||||
# Detach indecies from positions if going to modify positions.
|
||||
if reset_position_ids:
|
||||
eod_index = eod_index.clone()
|
||||
|
||||
# Loop through EOD indecies:
|
||||
prev_index = 0
|
||||
for j in range(eod_index.size()[0]):
|
||||
i = eod_index[j]
|
||||
# Mask attention loss.
|
||||
if reset_attention_mask:
|
||||
attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
|
||||
# Reset positions.
|
||||
if reset_position_ids:
|
||||
position_ids[b, (i + 1) :] -= i + 1 - prev_index
|
||||
prev_index = i + 1
|
||||
|
||||
# Convert attention mask to binary:
|
||||
attention_mask = attention_mask < 0.5
|
||||
|
||||
return attention_mask, loss_mask, position_ids
|
||||
|
||||
|
||||
def get_batch(context_tokens: torch.LongTensor, eod_id: int):
|
||||
"""Generate batch from context tokens."""
|
||||
# Move to GPU.
|
||||
tokens = context_tokens.contiguous().to(context_tokens.device)
|
||||
# Get the attention mask and postition ids.
|
||||
attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
|
||||
tokens,
|
||||
eod_id,
|
||||
reset_position_ids=False,
|
||||
reset_attention_mask=False,
|
||||
eod_mask_loss=False,
|
||||
)
|
||||
return tokens, attention_mask, position_ids
|
||||
|
||||
|
||||
def get_stop_words_ids(chat_format, tokenizer):
|
||||
if chat_format == "raw":
|
||||
stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
|
||||
elif chat_format == "chatml":
|
||||
stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
|
||||
else:
|
||||
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
||||
return stop_words_ids
|
||||
|
||||
|
||||
def make_context(
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
query: str,
|
||||
history: List[Tuple[str, str]] = None,
|
||||
system: str = "",
|
||||
max_window_size: int = 6144,
|
||||
chat_format: str = "chatml",
|
||||
):
|
||||
if history is None:
|
||||
history = []
|
||||
|
||||
if chat_format == "chatml":
|
||||
im_start, im_end = "<|im_start|>", "<|im_end|>"
|
||||
im_start_tokens = [tokenizer.im_start_id]
|
||||
im_end_tokens = [tokenizer.im_end_id]
|
||||
nl_tokens = tokenizer.encode("\n")
|
||||
|
||||
def _tokenize_str(role, content):
|
||||
return f"{role}\n{content}", tokenizer.encode(
|
||||
role, allowed_special=set()
|
||||
) + nl_tokens + tokenizer.encode(content, allowed_special=set())
|
||||
|
||||
system_text, system_tokens_part = _tokenize_str("system", system)
|
||||
system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
|
||||
|
||||
raw_text = ""
|
||||
context_tokens = []
|
||||
|
||||
for turn_query, turn_response in reversed(history):
|
||||
query_text, query_tokens_part = _tokenize_str("user", turn_query)
|
||||
query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
|
||||
response_text, response_tokens_part = _tokenize_str(
|
||||
"assistant", turn_response
|
||||
)
|
||||
response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
|
||||
|
||||
next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
|
||||
prev_chat = (
|
||||
f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
|
||||
)
|
||||
|
||||
current_context_size = (
|
||||
len(system_tokens) + len(next_context_tokens) + len(context_tokens)
|
||||
)
|
||||
if current_context_size < max_window_size:
|
||||
context_tokens = next_context_tokens + context_tokens
|
||||
raw_text = prev_chat + raw_text
|
||||
else:
|
||||
break
|
||||
|
||||
context_tokens = system_tokens + context_tokens
|
||||
raw_text = f"{im_start}{system_text}{im_end}" + raw_text
|
||||
context_tokens += (
|
||||
nl_tokens
|
||||
+ im_start_tokens
|
||||
+ _tokenize_str("user", query)[1]
|
||||
+ im_end_tokens
|
||||
+ nl_tokens
|
||||
+ im_start_tokens
|
||||
+ tokenizer.encode("assistant")
|
||||
+ nl_tokens
|
||||
)
|
||||
raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
|
||||
|
||||
elif chat_format == "raw":
|
||||
raw_text = query
|
||||
context_tokens = tokenizer.encode(raw_text)
|
||||
else:
|
||||
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
||||
|
||||
return raw_text, context_tokens
|
||||
|
||||
|
||||
def _decode_default(
|
||||
tokens: List[int],
|
||||
*,
|
||||
stop_words: List[str],
|
||||
eod_words: List[str],
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
raw_text_len: int,
|
||||
verbose: bool = False,
|
||||
return_end_reason: bool = False,
|
||||
errors: str='replace',
|
||||
):
|
||||
trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
|
||||
if verbose:
|
||||
print("\nRaw Generate: ", trim_decode_tokens)
|
||||
|
||||
end_reason = f"Gen length {len(tokens)}"
|
||||
for stop_word in stop_words:
|
||||
trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
|
||||
for eod_word in eod_words:
|
||||
if eod_word in trim_decode_tokens:
|
||||
end_reason = f"Gen {eod_word!r}"
|
||||
trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
|
||||
trim_decode_tokens = trim_decode_tokens.strip()
|
||||
if verbose:
|
||||
print("\nEnd Reason:", end_reason)
|
||||
print("\nGenerate: ", trim_decode_tokens)
|
||||
|
||||
if return_end_reason:
|
||||
return trim_decode_tokens, end_reason
|
||||
else:
|
||||
return trim_decode_tokens
|
||||
|
||||
|
||||
def _decode_chatml(
|
||||
tokens: List[int],
|
||||
*,
|
||||
stop_words: List[str],
|
||||
eod_token_ids: List[int],
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
raw_text_len: int,
|
||||
context_length: int,
|
||||
verbose: bool = False,
|
||||
return_end_reason: bool = False,
|
||||
errors: str='replace'
|
||||
):
|
||||
end_reason = f"Gen length {len(tokens)}"
|
||||
eod_token_idx = context_length
|
||||
for eod_token_idx in range(context_length, len(tokens)):
|
||||
if tokens[eod_token_idx] in eod_token_ids:
|
||||
end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
|
||||
break
|
||||
|
||||
trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
|
||||
if verbose:
|
||||
print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
|
||||
print("\nRaw Generate:", trim_decode_tokens)
|
||||
print("\nEnd Reason:", end_reason)
|
||||
for stop_word in stop_words:
|
||||
trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
|
||||
trim_decode_tokens = trim_decode_tokens.strip()
|
||||
if verbose:
|
||||
print("\nGenerate:", trim_decode_tokens)
|
||||
|
||||
if return_end_reason:
|
||||
return trim_decode_tokens, end_reason
|
||||
else:
|
||||
return trim_decode_tokens
|
||||
|
||||
|
||||
def decode_tokens(
|
||||
tokens: Union[torch.LongTensor, TokensType],
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
raw_text_len: int,
|
||||
context_length: int,
|
||||
chat_format: str,
|
||||
verbose: bool = False,
|
||||
return_end_reason: bool = False,
|
||||
errors: str="replace",
|
||||
) -> str:
|
||||
if torch.is_tensor(tokens):
|
||||
tokens = tokens.cpu().numpy().tolist()
|
||||
|
||||
if chat_format == "chatml":
|
||||
return _decode_chatml(
|
||||
tokens,
|
||||
stop_words=[],
|
||||
eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
|
||||
tokenizer=tokenizer,
|
||||
raw_text_len=raw_text_len,
|
||||
context_length=context_length,
|
||||
verbose=verbose,
|
||||
return_end_reason=return_end_reason,
|
||||
errors=errors,
|
||||
)
|
||||
elif chat_format == "raw":
|
||||
return _decode_default(
|
||||
tokens,
|
||||
stop_words=["<|endoftext|>"],
|
||||
eod_words=["<|endoftext|>"],
|
||||
tokenizer=tokenizer,
|
||||
raw_text_len=raw_text_len,
|
||||
verbose=verbose,
|
||||
return_end_reason=return_end_reason,
|
||||
errors=errors,
|
||||
)
|
||||
else:
|
||||
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
||||
|
||||
|
||||
class StopWordsLogitsProcessor(LogitsProcessor):
|
||||
"""
|
||||
:class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
|
||||
|
||||
Args:
|
||||
stop_words_ids (:obj:`List[List[int]]`):
|
||||
List of list of token ids of stop ids. In order to get the tokens of the words
|
||||
that should not appear in the generated text, use :obj:`tokenizer(bad_word,
|
||||
add_prefix_space=True).input_ids`.
|
||||
eos_token_id (:obj:`int`):
|
||||
The id of the `end-of-sequence` token.
|
||||
"""
|
||||
|
||||
def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
|
||||
|
||||
if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
|
||||
raise ValueError(
|
||||
f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}."
|
||||
)
|
||||
if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
|
||||
raise ValueError(
|
||||
f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}."
|
||||
)
|
||||
if any(
|
||||
any(
|
||||
(not isinstance(token_id, (int, np.integer)) or token_id < 0)
|
||||
for token_id in stop_word_ids
|
||||
)
|
||||
for stop_word_ids in stop_words_ids
|
||||
):
|
||||
raise ValueError(
|
||||
f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}."
|
||||
)
|
||||
|
||||
self.stop_words_ids = list(
|
||||
filter(
|
||||
lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids
|
||||
)
|
||||
)
|
||||
self.eos_token_id = eos_token_id
|
||||
for stop_token_seq in self.stop_words_ids:
|
||||
assert (
|
||||
len(stop_token_seq) > 0
|
||||
), "Stop words token sequences {} cannot have an empty list".format(
|
||||
stop_words_ids
|
||||
)
|
||||
|
||||
def __call__(
|
||||
self, input_ids: torch.LongTensor, scores: torch.FloatTensor
|
||||
) -> torch.FloatTensor:
|
||||
stopped_samples = self._calc_stopped_samples(input_ids)
|
||||
for i, should_stop in enumerate(stopped_samples):
|
||||
if should_stop:
|
||||
scores[i, self.eos_token_id] = float(2**15)
|
||||
return scores
|
||||
|
||||
def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
|
||||
if len(tokens) == 0:
|
||||
# if bad word tokens is just one token always ban it
|
||||
return True
|
||||
elif len(tokens) > len(prev_tokens):
|
||||
# if bad word tokens are longer then prev input_ids they can't be equal
|
||||
return False
|
||||
elif prev_tokens[-len(tokens) :].tolist() == tokens:
|
||||
# if tokens match
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
|
||||
stopped_samples = []
|
||||
for prev_input_ids_slice in prev_input_ids:
|
||||
match = False
|
||||
for stop_token_seq in self.stop_words_ids:
|
||||
if self._tokens_match(prev_input_ids_slice, stop_token_seq):
|
||||
# if tokens do not match continue
|
||||
match = True
|
||||
break
|
||||
stopped_samples.append(match)
|
||||
|
||||
return stopped_samples
|
||||
|
||||
|
||||
def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
|
||||
"""This function has been mostly taken from huggingface conversational
|
||||
ai code at
|
||||
https://medium.com/huggingface/how-to-build-a-state-of-the-art-
|
||||
conversational-ai-with-transfer-learning-2d818ac26313"""
|
||||
|
||||
if top_k > 0:
|
||||
# Remove all tokens with a probability less than the
|
||||
# last token of the top-k
|
||||
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
||||
logits[indices_to_remove] = filter_value
|
||||
|
||||
if top_p > 0.0:
|
||||
# Cconvert to 1D
|
||||
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
|
||||
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
||||
|
||||
# Remove tokens with cumulative probability above the threshold
|
||||
sorted_indices_to_remove = cumulative_probs > top_p
|
||||
# Shift the indices to the right to keep also the first token
|
||||
# above the threshold
|
||||
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
||||
sorted_indices_to_remove[..., 0] = 0
|
||||
for i in range(sorted_indices.size(0)):
|
||||
indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
|
||||
logits[i][indices_to_remove] = filter_value
|
||||
|
||||
return logits
|
||||
|
||||
|
||||
def switch(val1, val2, boolean):
|
||||
boolean = boolean.type_as(val1)
|
||||
return (1 - boolean) * val1 + boolean * val2
|
||||
14
requirements.txt
Normal file
14
requirements.txt
Normal file
@@ -0,0 +1,14 @@
|
||||
numpy
|
||||
pandas
|
||||
einops
|
||||
sentencepiece
|
||||
deepspeed==0.9.3
|
||||
transformers==4.32.0
|
||||
accelerate==0.21.0
|
||||
peft==0.4.0
|
||||
BitsAndBytes==0.40.2
|
||||
xformers==0.0.21
|
||||
ujson
|
||||
jsonlines
|
||||
tiktoken
|
||||
transformers_stream_generator
|
||||
1
special_tokens_map.json
Normal file
1
special_tokens_map.json
Normal file
@@ -0,0 +1 @@
|
||||
{}
|
||||
246
tokenization_qwen.py
Normal file
246
tokenization_qwen.py
Normal file
@@ -0,0 +1,246 @@
|
||||
# Copyright (c) Alibaba Cloud.
|
||||
#
|
||||
# This source code is licensed under the license found in the
|
||||
# LICENSE file in the root directory of this source tree.
|
||||
|
||||
"""Tokenization classes for QWen."""
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import unicodedata
|
||||
from typing import Collection, Dict, List, Set, Tuple, Union
|
||||
|
||||
import tiktoken
|
||||
from transformers import PreTrainedTokenizer, AddedToken
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken"}
|
||||
|
||||
PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
|
||||
ENDOFTEXT = "<|endoftext|>"
|
||||
IMSTART = "<|im_start|>"
|
||||
IMEND = "<|im_end|>"
|
||||
# as the default behavior is changed to allow special tokens in
|
||||
# regular texts, the surface forms of special tokens need to be
|
||||
# as different as possible to minimize the impact
|
||||
EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
|
||||
SPECIAL_TOKENS = (
|
||||
ENDOFTEXT,
|
||||
IMSTART,
|
||||
IMEND,
|
||||
) + EXTRAS
|
||||
|
||||
|
||||
def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
|
||||
with open(tiktoken_bpe_file, "rb") as f:
|
||||
contents = f.read()
|
||||
return {
|
||||
base64.b64decode(token): int(rank)
|
||||
for token, rank in (line.split() for line in contents.splitlines() if line)
|
||||
}
|
||||
|
||||
class QWenTokenizer(PreTrainedTokenizer):
|
||||
"""QWen tokenizer."""
|
||||
|
||||
vocab_files_names = VOCAB_FILES_NAMES
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_file,
|
||||
errors="replace",
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
self.errors = errors # how to handle errors in decoding
|
||||
|
||||
self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: dict[bytes, int]
|
||||
self.special_tokens = {
|
||||
token: index
|
||||
for index, token in enumerate(
|
||||
SPECIAL_TOKENS, start=len(self.mergeable_ranks)
|
||||
)
|
||||
}
|
||||
|
||||
enc = tiktoken.Encoding(
|
||||
"Qwen",
|
||||
pat_str=PAT_STR,
|
||||
mergeable_ranks=self.mergeable_ranks,
|
||||
special_tokens=self.special_tokens,
|
||||
)
|
||||
assert (
|
||||
len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
|
||||
), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
|
||||
|
||||
self.decoder = {
|
||||
v: k for k, v in self.mergeable_ranks.items()
|
||||
} # type: dict[int, bytes|str]
|
||||
self.decoder.update({v: k for k, v in self.special_tokens.items()})
|
||||
|
||||
self.tokenizer = enc # type: tiktoken.Encoding
|
||||
|
||||
self.eod_id = self.tokenizer.eot_token
|
||||
self.im_start_id = self.special_tokens[IMSTART]
|
||||
self.im_end_id = self.special_tokens[IMEND]
|
||||
|
||||
def __getstate__(self):
|
||||
# for pickle lovers
|
||||
state = self.__dict__.copy()
|
||||
del state['tokenizer']
|
||||
return state
|
||||
|
||||
def __setstate__(self, state):
|
||||
# tokenizer is not python native; don't pass it; rebuild it
|
||||
self.__dict__.update(state)
|
||||
enc = tiktoken.Encoding(
|
||||
"Qwen",
|
||||
pat_str=PAT_STR,
|
||||
mergeable_ranks=self.mergeable_ranks,
|
||||
special_tokens=self.special_tokens,
|
||||
)
|
||||
self.tokenizer = enc
|
||||
|
||||
|
||||
def __len__(self) -> int:
|
||||
return self.tokenizer.n_vocab
|
||||
|
||||
def get_vocab(self) -> Dict[bytes, int]:
|
||||
return self.mergeable_ranks
|
||||
|
||||
def convert_tokens_to_ids(
|
||||
self, tokens: Union[bytes, str, List[Union[bytes, str]]]
|
||||
) -> List[int]:
|
||||
ids = []
|
||||
if isinstance(tokens, (str, bytes)):
|
||||
if tokens in self.special_tokens:
|
||||
return self.special_tokens[tokens]
|
||||
else:
|
||||
return self.mergeable_ranks.get(tokens)
|
||||
for token in tokens:
|
||||
if token in self.special_tokens:
|
||||
ids.append(self.special_tokens[token])
|
||||
else:
|
||||
ids.append(self.mergeable_ranks.get(token))
|
||||
return ids
|
||||
|
||||
def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
|
||||
if not special_tokens and new_tokens:
|
||||
raise ValueError('Adding regular tokens is not supported')
|
||||
for token in new_tokens:
|
||||
surface_form = token.content if isinstance(token, AddedToken) else token
|
||||
if surface_form not in SPECIAL_TOKENS:
|
||||
raise ValueError('Adding unknown special tokens is not supported')
|
||||
return 0
|
||||
|
||||
def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
|
||||
"""
|
||||
Save only the vocabulary of the tokenizer (vocabulary).
|
||||
|
||||
Returns:
|
||||
`Tuple(str)`: Paths to the files saved.
|
||||
"""
|
||||
file_path = os.path.join(save_directory, "qwen.tiktoken")
|
||||
with open(file_path, "w", encoding="utf8") as w:
|
||||
for k, v in self.mergeable_ranks.items():
|
||||
line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
|
||||
w.write(line)
|
||||
return (file_path,)
|
||||
|
||||
def tokenize(
|
||||
self,
|
||||
text: str,
|
||||
allowed_special: Union[Set, str] = "all",
|
||||
disallowed_special: Union[Collection, str] = (),
|
||||
**kwargs,
|
||||
) -> List[Union[bytes, str]]:
|
||||
"""
|
||||
Converts a string in a sequence of tokens.
|
||||
|
||||
Args:
|
||||
text (`str`):
|
||||
The sequence to be encoded.
|
||||
allowed_special (`Literal["all"]` or `set`):
|
||||
The surface forms of the tokens to be encoded as special tokens in regular texts.
|
||||
Default to "all".
|
||||
disallowed_special (`Literal["all"]` or `Collection`):
|
||||
The surface forms of the tokens that should not be in regular texts and trigger errors.
|
||||
Default to an empty tuple.
|
||||
|
||||
kwargs (additional keyword arguments, *optional*):
|
||||
Will be passed to the underlying model specific encode method.
|
||||
|
||||
Returns:
|
||||
`List[bytes|str]`: The list of tokens.
|
||||
"""
|
||||
tokens = []
|
||||
text = unicodedata.normalize("NFC", text)
|
||||
|
||||
# this implementation takes a detour: text -> token id -> token surface forms
|
||||
for t in self.tokenizer.encode(
|
||||
text, allowed_special=allowed_special, disallowed_special=disallowed_special
|
||||
):
|
||||
tokens.append(self.decoder[t])
|
||||
return tokens
|
||||
|
||||
def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
|
||||
"""
|
||||
Converts a sequence of tokens in a single string.
|
||||
"""
|
||||
text = ""
|
||||
temp = b""
|
||||
for t in tokens:
|
||||
if isinstance(t, str):
|
||||
if temp:
|
||||
text += temp.decode("utf-8", errors=self.errors)
|
||||
temp = b""
|
||||
text += t
|
||||
elif isinstance(t, bytes):
|
||||
temp += t
|
||||
else:
|
||||
raise TypeError("token should only be of type types or str")
|
||||
if temp:
|
||||
text += temp.decode("utf-8", errors=self.errors)
|
||||
return text
|
||||
|
||||
@property
|
||||
def vocab_size(self):
|
||||
return self.tokenizer.n_vocab
|
||||
|
||||
def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
|
||||
"""Converts an id to a token, special tokens included"""
|
||||
if index in self.decoder:
|
||||
return self.decoder[index]
|
||||
raise ValueError("unknown ids")
|
||||
|
||||
def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
|
||||
"""Converts a token to an id using the vocab, special tokens included"""
|
||||
if token in self.special_tokens:
|
||||
return self.special_tokens[token]
|
||||
if token in self.mergeable_ranks:
|
||||
return self.mergeable_ranks[token]
|
||||
raise ValueError("unknown token")
|
||||
|
||||
def _tokenize(self, text: str, **kwargs):
|
||||
"""
|
||||
Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
|
||||
vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
|
||||
|
||||
Do NOT take care of added tokens.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _decode(
|
||||
self,
|
||||
token_ids: Union[int, List[int]],
|
||||
skip_special_tokens: bool = False,
|
||||
errors: str = None,
|
||||
**kwargs,
|
||||
) -> str:
|
||||
if isinstance(token_ids, int):
|
||||
token_ids = [token_ids]
|
||||
if skip_special_tokens:
|
||||
token_ids = [i for i in token_ids if i < self.eod_id]
|
||||
return self.tokenizer.decode(token_ids, errors=errors or self.errors)
|
||||
12
tokenizer_config.json
Normal file
12
tokenizer_config.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"auto_map": {
|
||||
"AutoTokenizer": [
|
||||
"tokenization_qwen.QWenTokenizer",
|
||||
null
|
||||
]
|
||||
},
|
||||
"clean_up_tokenization_spaces": true,
|
||||
"legacy": false,
|
||||
"model_max_length": 8192,
|
||||
"tokenizer_class": "QWenTokenizer"
|
||||
}
|
||||
Reference in New Issue
Block a user