996savage commited on
Commit
f0d58d3
·
verified ·
1 Parent(s): e224d27

Upload 5 files

Browse files
Files changed (5) hide show
  1. .gitignore +4 -0
  2. LICENSE-CODE +21 -0
  3. LICENSE-MODEL +91 -0
  4. README.md +442 -14
  5. requirements.txt +8 -1
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ Evaluation/MBPP/eval_instruct.sh
3
+ Evaluation/LeetCode/output/
4
+ .vercel
LICENSE-CODE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
LICENSE-MODEL ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DEEPSEEK LICENSE AGREEMENT
2
+
3
+ Version 1.0, 23 October 2023
4
+
5
+ Copyright (c) 2023 DeepSeek
6
+
7
+ Section I: PREAMBLE
8
+
9
+ Large generative models are being widely adopted and used, and have the potential to transform the way individuals conceive and benefit from AI or ML technologies.
10
+
11
+ Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
12
+
13
+ In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for content generation.
14
+
15
+ Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this agreement aims to strike a balance between both in order to enable responsible open-science in the field of AI.
16
+
17
+ This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
18
+
19
+ NOW THEREFORE, You and DeepSeek agree as follows:
20
+
21
+ 1. Definitions
22
+ "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
23
+ "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
24
+ "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
25
+ "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
26
+ "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
27
+ "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
28
+ "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
29
+ "DeepSeek" (or "we") means Beijing DeepSeek Artificial Intelligence Fundamental Technology Research Co., Ltd., Hangzhou DeepSeek Artificial Intelligence Fundamental Technology Research Co., Ltd. and/or any of their affiliates.
30
+ "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, etc.
31
+ "Third Parties" means individuals or legal entities that are not under common control with DeepSeek or You.
32
+
33
+ Section II: INTELLECTUAL PROPERTY RIGHTS
34
+
35
+ Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
36
+
37
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, DeepSeek hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
38
+
39
+ 3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, DeepSeek hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by DeepSeek that are necessarily infringed by its contribution(s). If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or works shall terminate as of the date such litigation is asserted or filed.
40
+
41
+
42
+ Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
43
+
44
+ 4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
45
+ a. Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
46
+ b. You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
47
+ c. You must cause any modified files to carry prominent notices stating that You changed the files;
48
+ d. You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
49
+ e. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. – for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
50
+
51
+ 5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
52
+
53
+ 6. The Output You Generate. Except as set forth herein, DeepSeek claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
54
+
55
+ Section IV: OTHER PROVISIONS
56
+
57
+ 7. Updates and Runtime Restrictions. To the maximum extent permitted by law, DeepSeek reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License.
58
+
59
+ 8. Trademarks and related. Nothing in this License permits You to make use of DeepSeek’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by DeepSeek.
60
+
61
+ 9. Personal information, IP rights and related. This Model may contain personal information and works with IP rights. You commit to complying with applicable laws and regulations in the handling of personal information and the use of such works. Please note that DeepSeek's license granted to you to use the Model does not imply that you have obtained a legitimate basis for processing the related information or works. As an independent personal information processor and IP rights user, you need to ensure full compliance with relevant legal and regulatory requirements when handling personal information and works with IP rights that may be contained in the Model, and are willing to assume solely any risks and consequences that may arise from that.
62
+
63
+ 10. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, DeepSeek provides the Model and the Complementary Material on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
64
+
65
+ 11. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall DeepSeek be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if DeepSeek has been advised of the possibility of such damages.
66
+
67
+ 12. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of DeepSeek, and only if You agree to indemnify, defend, and hold DeepSeek harmless for any liability incurred by, or claims asserted against, DeepSeek by reason of your accepting any such warranty or additional liability.
68
+
69
+ 13. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
70
+
71
+ 14. Governing Law and Jurisdiction. This agreement will be governed and construed under PRC laws without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this agreement. The courts located in the domicile of Hangzhou DeepSeek Artificial Intelligence Fundamental Technology Research Co., Ltd. shall have exclusive jurisdiction of any dispute arising out of this agreement.
72
+
73
+ END OF TERMS AND CONDITIONS
74
+
75
+ Attachment A
76
+
77
+ Use Restrictions
78
+
79
+ You agree not to use the Model or Derivatives of the Model:
80
+
81
+ - In any way that violates any applicable national or international law or regulation or infringes upon the lawful rights and interests of any third party;
82
+ - For military use in any way;
83
+ - For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
84
+ - To generate or disseminate verifiably false information and/or content with the purpose of harming others;
85
+ - To generate or disseminate inappropriate content subject to applicable regulatory requirements;
86
+ - To generate or disseminate personal identifiable information without due authorization or for unreasonable use;
87
+ - To defame, disparage or otherwise harass others;
88
+ - For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
89
+ - For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
90
+ - To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
91
+ - For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories.
README.md CHANGED
@@ -1,14 +1,442 @@
1
- ---
2
- title: Savage
3
- emoji: 💬
4
- colorFrom: yellow
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 5.0.1
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- short_description: chatbot
12
- ---
13
-
14
- An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align="center">
2
+ <img width="1000px" alt="DeepSeek Coder" src="pictures/logo.png">
3
+ </p>
4
+ <p align="center"><a href="https://www.deepseek.com/">[<img src="pictures/home.png" width="20px"> Homepage]</a> | <a href="https://coder.deepseek.com/">[🤖 Chat with DeepSeek Coder]</a> | <a href="https://huggingface.co/deepseek-ai">[🤗 Models Download]</a> | <a href="https://discord.gg/Tc7c45Zzu5">[Discord]</a> | <a href="https://github.com/guoday/assert/blob/main/QR.png?raw=true">[WeChat (微信)]</a></p>
5
+ <p align="center">
6
+ <a href="https://huggingface.co/papers/2401.14196"><b>Paper Link</b>👁️</a>
7
+ </p>
8
+ <hr>
9
+
10
+
11
+ ### 1. Introduction of DeepSeek Coder
12
+
13
+ DeepSeek Coder is composed of a series of code language models, each trained from scratch on 2T tokens, with a composition of 87% code and 13% natural language in both English and Chinese. We provide various sizes of the code model, ranging from 1B to 33B versions. Each model is pre-trained on project-level code corpus by employing a window size of 16K and an extra fill-in-the-blank task, to support project-level code completion and infilling. For coding capabilities, DeepSeek Coder achieves state-of-the-art performance among open-source code models on multiple programming languages and various benchmarks.
14
+
15
+ <p align="center">
16
+ <img src="pictures/result.png" alt="result" width="70%">
17
+ </p>
18
+
19
+ - **Massive Training Data**: Trained from scratch on 2T tokens, including 87% code and 13% linguistic data in both English and Chinese languages.
20
+
21
+ - **Highly Flexible & Scalable**: Offered in model sizes of 1B, 5.7B, 6.7B and 33B, enabling users to choose the setup most suitable for their requirements.
22
+
23
+ - **Superior Model Performance**: State-of-the-art performance among publicly available code models on HumanEval, MultiPL-E, MBPP, DS-1000, and APPS benchmarks.
24
+
25
+ - **Advanced Code Completion Capabilities**: A window size of 16K and a fill-in-the-blank task, supporting project-level code completion and infilling tasks.
26
+
27
+ #### Supported Programming Languages
28
+ `['ada', 'agda', 'alloy', 'antlr', 'applescript', 'assembly', 'augeas', 'awk', 'batchfile', 'bluespec', 'c', 'c-sharp', 'clojure', 'cmake', 'coffeescript', 'common-lisp', 'cpp', 'css', 'cuda', 'dart', 'dockerfile', 'elixir', 'elm', 'emacs-lisp', 'erlang', 'f-sharp', 'fortran', 'glsl', 'go', 'groovy', 'haskell', 'html', 'idris', 'isabelle', 'java', 'java-server-pages', 'javascript', 'json', 'julia', 'jupyter-notebook', 'kotlin', 'lean', 'literate-agda', 'literate-coffeescript', 'literate-haskell', 'lua', 'makefile', 'maple', 'markdown', 'mathematica', 'matlab', 'ocaml', 'pascal', 'perl', 'php', 'powershell', 'prolog', 'protocol-buffer', 'python', 'r', 'racket', 'restructuredtext', 'rmarkdown', 'ruby', 'rust', 'sas', 'scala', 'scheme', 'shell', 'smalltalk', 'solidity', 'sparql', 'sql', 'stan', 'standard-ml', 'stata', 'systemverilog', 'tcl', 'tcsh', 'tex', 'thrift', 'typescript', 'verilog', 'vhdl', 'visual-basic', 'xslt', 'yacc', 'yaml', 'zig']`
29
+
30
+ ### 2. Evaluation Results
31
+ We evaluate DeepSeek Coder on various coding-related benchmarks.
32
+ Only `pass@1` results on HumanEval (Python and Multilingual), MBPP, and DS-1000 are reported here:
33
+
34
+ <p align="center">
35
+ <img src="pictures/table.png" alt="table" width="70%">
36
+ </p>
37
+
38
+
39
+ The result shows that DeepSeek-Coder-Base-33B significantly outperforms existing open-source code LLMs. Compared with CodeLlama-34B, it leads by 7.9%, 9.3%, 10.8% and 5.9% respectively on HumanEval Python, HumanEval Multilingual, MBPP and DS-1000.
40
+ Surprisingly, our DeepSeek-Coder-Base-7B reaches the performance of CodeLlama-34B.
41
+ The DeepSeek-Coder-Instruct-33B model after instruction tuning outperforms GPT35-turbo on HumanEval and achieves comparable results with GPT35-turbo on MBPP.
42
+
43
+ More evaluation details can be found in the [Detailed Evaluation](#6-detailed-evaluation-results).
44
+
45
+
46
+ ### 3. Procedure of Data Creation and Model Training
47
+
48
+ #### Data Creation
49
+
50
+ - Step 1: Collect code data from GitHub and apply the same filtering rules as [StarCoder Data](https://github.com/bigcode-project/bigcode-dataset) to filter data.
51
+ - Step 2: Parsing the dependencies of files within the same repository to rearrange the file positions based on their dependencies.
52
+ - Step 3: Concatenating dependent files to form a single example and employ repo-level minhash for deduplication.
53
+ - Step 4: Further filtering out low-quality code, such as codes with syntax errors or poor readability.
54
+
55
+ <img src="pictures/data_clean.png" alt="data_creation" width="100%">
56
+
57
+ #### Model Training
58
+
59
+ - Step 1: Initially pre-trained with a dataset consisting of 87% code, 10% code-related language (Github Markdown and StackExchange), and 3% non-code-related Chinese language. Models are pre-trained using 1.8T tokens and a 4K window size in this step.
60
+ - Step 2: Further Pre-training using an extended 16K window size on an additional 200B tokens, resulting in foundational models (**DeepSeek-Coder-Base**).
61
+ - Step 3: Instruction Fine-tuning on 2B tokens of instruction data, resulting in instruction-tuned models (**DeepSeek-Coder-Instruct**).
62
+
63
+ <img src="pictures/model_pretraining.png" alt="model_pretraining" width="100%">
64
+
65
+
66
+ ### 4. How to Use
67
+ Before proceeding, you'll need to install the necessary dependencies. You can do this by running the following command:
68
+ ```
69
+ pip install -r requirements.txt
70
+ ```
71
+ A demo is also available on the [🤗 Hugging Face Space](https://huggingface.co/spaces/deepseek-ai/deepseek-coder-33b-instruct), and you can run the demo locally using `app.py` in the [demo](https://github.com/deepseek-ai/deepseek-coder/tree/main/demo) folder. (Thanks to all the HF team for their support)
72
+
73
+ Here are some examples of how to use our model.
74
+
75
+ #### 1) Code Completion
76
+ ```python
77
+ from transformers import AutoTokenizer, AutoModelForCausalLM
78
+ import torch
79
+ tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True)
80
+ model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
81
+ input_text = "#write a quick sort algorithm"
82
+ inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
83
+ outputs = model.generate(**inputs, max_length=128)
84
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True))
85
+ ```
86
+ This code will output the following result:
87
+ ```
88
+ def quick_sort(arr):
89
+ if len(arr) <= 1:
90
+ return arr
91
+ pivot = arr[0]
92
+ left = []
93
+ right = []
94
+ for i in range(1, len(arr)):
95
+ if arr[i] < pivot:
96
+ left.append(arr[i])
97
+ else:
98
+ right.append(arr[i])
99
+ return quick_sort(left) + [pivot] + quick_sort(right)
100
+ ```
101
+
102
+ #### 2) Code Insertion
103
+ ```python
104
+ from transformers import AutoTokenizer, AutoModelForCausalLM
105
+ import torch
106
+ tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True)
107
+ model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
108
+ input_text = """<|fim▁begin|>def quick_sort(arr):
109
+ if len(arr) <= 1:
110
+ return arr
111
+ pivot = arr[0]
112
+ left = []
113
+ right = []
114
+ <|fim▁hole|>
115
+ if arr[i] < pivot:
116
+ left.append(arr[i])
117
+ else:
118
+ right.append(arr[i])
119
+ return quick_sort(left) + [pivot] + quick_sort(right)<|fim▁end|>"""
120
+ inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
121
+ outputs = model.generate(**inputs, max_length=128)
122
+ print(tokenizer.decode(outputs[0], skip_special_tokens=True)[len(input_text):])
123
+ ```
124
+ This code will output the following result:
125
+ ```
126
+ for i in range(1, len(arr)):
127
+ ```
128
+
129
+ #### 3) Chat Model Inference
130
+ ```python
131
+ from transformers import AutoTokenizer, AutoModelForCausalLM
132
+ import torch
133
+ tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-6.7b-instruct", trust_remote_code=True)
134
+ model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-6.7b-instruct", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
135
+ messages=[
136
+ { 'role': 'user', 'content': "write a quick sort algorithm in python."}
137
+ ]
138
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
139
+ # tokenizer.eos_token_id is the id of <|EOT|> token
140
+ outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
141
+ print(tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True))
142
+ ```
143
+ This code will output the following result:
144
+ ```
145
+ Sure, here is a simple implementation of the Quick Sort algorithm in Python:
146
+
147
+ def quick_sort(arr):
148
+ if len(arr) <= 1:
149
+ return arr
150
+ else:
151
+ pivot = arr[0]
152
+ less_than_pivot = [x for x in arr[1:] if x <= pivot]
153
+ greater_than_pivot = [x for x in arr[1:] if x > pivot]
154
+ return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)
155
+
156
+ # Test the function
157
+ arr = [10, 7, 8, 9, 1, 5]
158
+ print("Original array:", arr)
159
+ print("Sorted array:", quick_sort(arr))
160
+
161
+ This code works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The pivot element is then in its final position. The process is then repeated for the sub-arrays.
162
+ ```
163
+
164
+ If you don't want to use the provided API `apply_chat_template` which loads the template from `tokenizer_config.json`, you can use the following template to chat with our model. Replace the `['content']` with your instructions and the model's previous (if any) responses, then the model will generate the response to the currently given instruction.
165
+ ```
166
+ You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.
167
+ ### Instruction:
168
+ ['content']
169
+ ### Response:
170
+ ['content']
171
+ <|EOT|>
172
+ ### Instruction:
173
+ ['content']
174
+ ### Response:
175
+
176
+ ```
177
+
178
+ #### 4) Repository Level Code Completion
179
+ ```python
180
+ from transformers import AutoTokenizer, AutoModelForCausalLM
181
+ import torch
182
+ tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True)
183
+ model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
184
+
185
+ input_text = """#utils.py
186
+ import torch
187
+ from sklearn import datasets
188
+ from sklearn.model_selection import train_test_split
189
+ from sklearn.preprocessing import StandardScaler
190
+ from sklearn.metrics import accuracy_score
191
+
192
+ def load_data():
193
+ iris = datasets.load_iris()
194
+ X = iris.data
195
+ y = iris.target
196
+
197
+ # Standardize the data
198
+ scaler = StandardScaler()
199
+ X = scaler.fit_transform(X)
200
+
201
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
202
+
203
+ # Convert numpy data to PyTorch tensors
204
+ X_train = torch.tensor(X_train, dtype=torch.float32)
205
+ X_test = torch.tensor(X_test, dtype=torch.float32)
206
+ y_train = torch.tensor(y_train, dtype=torch.int64)
207
+ y_test = torch.tensor(y_test, dtype=torch.int64)
208
+
209
+ return X_train, X_test, y_train, y_test
210
+
211
+ def evaluate_predictions(y_test, y_pred):
212
+ return accuracy_score(y_test, y_pred)
213
+
214
+
215
+ # model.py
216
+ import torch
217
+ import torch.nn as nn
218
+ import torch.optim as optim
219
+ from torch.utils.data import DataLoader, TensorDataset
220
+
221
+ class IrisClassifier(nn.Module):
222
+ def __init__(self):
223
+ super(IrisClassifier, self).__init__()
224
+ self.fc = nn.Sequential(
225
+ nn.Linear(4, 16),
226
+ nn.ReLU(),
227
+ nn.Linear(16, 3)
228
+ )
229
+
230
+ def forward(self, x):
231
+ return self.fc(x)
232
+
233
+ def train_model(self, X_train, y_train, epochs, lr, batch_size):
234
+ criterion = nn.CrossEntropyLoss()
235
+ optimizer = optim.Adam(self.parameters(), lr=lr)
236
+
237
+ # Create DataLoader for batches
238
+ dataset = TensorDataset(X_train, y_train)
239
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
240
+
241
+ for epoch in range(epochs):
242
+ for batch_X, batch_y in dataloader:
243
+ optimizer.zero_grad()
244
+ outputs = self(batch_X)
245
+ loss = criterion(outputs, batch_y)
246
+ loss.backward()
247
+ optimizer.step()
248
+
249
+ def predict(self, X_test):
250
+ with torch.no_grad():
251
+ outputs = self(X_test)
252
+ _, predicted = outputs.max(1)
253
+ return predicted.numpy()
254
+
255
+
256
+ # main.py
257
+ from utils import load_data, evaluate_predictions
258
+ from model import IrisClassifier as Classifier
259
+
260
+ def main():
261
+ # Model training and evaluation
262
+ """
263
+ inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
264
+ outputs = model.generate(**inputs, max_new_tokens=140)
265
+ print(tokenizer.decode(outputs[0]))
266
+ ```
267
+
268
+ ---
269
+ In the following scenario, the DeepSeek-Coder-6.7B model effectively calls a class **IrisClassifier** and its member function from the `model.py` file, and also utilizes functions from the `utils.py` file, to correctly complete the **main** function in the `main.py` file for model training and evaluation.
270
+
271
+ ![Completion GIF](pictures/completion_demo.gif)
272
+
273
+ ### 5. How to Fine-tune DeepSeek-Coder
274
+
275
+ We provide script `finetune/finetune_deepseekcoder.py` for users to finetune our models on downstream tasks.
276
+
277
+ The script supports the training with [DeepSpeed](https://github.com/microsoft/DeepSpeed). You need install required packages by:
278
+
279
+ ```bash
280
+ pip install -r finetune/requirements.txt
281
+ ```
282
+
283
+ Please follow [Sample Dataset Format](https://huggingface.co/datasets/nickrosh/Evol-Instruct-Code-80k-v1) to prepare your training data.
284
+ Each line is a json-serialized string with two required fields `instruction` and `output`.
285
+
286
+ After data preparation, you can use the sample shell script to finetune `deepseek-ai/deepseek-coder-6.7b-instruct`.
287
+ Remember to specify `DATA_PATH`, `OUTPUT_PATH`.
288
+ And please choose appropriate hyper-parameters(e.g., `learning_rate`, `per_device_train_batch_size`) according to your scenario.
289
+
290
+ ```bash
291
+ DATA_PATH="<your_data_path>"
292
+ OUTPUT_PATH="<your_output_path>"
293
+ MODEL="deepseek-ai/deepseek-coder-6.7b-instruct"
294
+
295
+ cd finetune && deepspeed finetune_deepseekcoder.py \
296
+ --model_name_or_path $MODEL_PATH \
297
+ --data_path $DATA_PATH \
298
+ --output_dir $OUTPUT_PATH \
299
+ --num_train_epochs 3 \
300
+ --model_max_length 1024 \
301
+ --per_device_train_batch_size 16 \
302
+ --per_device_eval_batch_size 1 \
303
+ --gradient_accumulation_steps 4 \
304
+ --evaluation_strategy "no" \
305
+ --save_strategy "steps" \
306
+ --save_steps 100 \
307
+ --save_total_limit 100 \
308
+ --learning_rate 2e-5 \
309
+ --warmup_steps 10 \
310
+ --logging_steps 1 \
311
+ --lr_scheduler_type "cosine" \
312
+ --gradient_checkpointing True \
313
+ --report_to "tensorboard" \
314
+ --deepspeed configs/ds_config_zero3.json \
315
+ --bf16 True
316
+ ```
317
+
318
+ ### 6. Detailed Evaluation Results
319
+
320
+ The reproducible code for the following evaluation results can be found in the [Evaluation](https://github.com/deepseek-ai/deepseek-coder/tree/main/Evaluation) directory.
321
+ #### 1) Multilingual HumanEval Benchmark
322
+ ![HumanEval](pictures/HumanEval.png)
323
+
324
+ #### 2) MBPP Benchmark
325
+ <img src="pictures/MBPP.png" alt="MBPP" width="40%">
326
+
327
+ #### 3) DS-1000 Benchmark
328
+ ![DS-1000](pictures/DS-1000.png)
329
+
330
+ #### 4) Program-Aid Math Reasoning Benchmark
331
+ ![Math](pictures/Math.png)
332
+
333
+ ### Inference with vLLM
334
+
335
+ You can also employ [vLLM](https://github.com/vllm-project/vllm) for high-throughput inference.
336
+
337
+ **Text Completion**
338
+
339
+ ```python
340
+ from vllm import LLM, SamplingParams
341
+
342
+ tp_size = 4 # Tensor Parallelism
343
+ sampling_params = SamplingParams(temperature=0.7, top_p=0.9, max_tokens=100)
344
+ model_name = "deepseek-ai/deepseek-coder-6.7b-base"
345
+ llm = LLM(model=model_name, trust_remote_code=True, gpu_memory_utilization=0.9, tensor_parallel_size=tp_size)
346
+
347
+ prompts = [
348
+ "If everyone in a country loves one another,",
349
+ "The research should also focus on the technologies",
350
+ "To determine if the label is correct, we need to"
351
+ ]
352
+ outputs = llm.generate(prompts, sampling_params)
353
+
354
+ generated_text = [output.outputs[0].text for output in outputs]
355
+ print(generated_text)
356
+ ```
357
+
358
+ **Chat Completion**
359
+
360
+ ```python
361
+ from transformers import AutoTokenizer
362
+ from vllm import LLM, SamplingParams
363
+
364
+ tp_size = 4 # Tensor Parallelism
365
+ sampling_params = SamplingParams(temperature=0.7, top_p=0.9, max_tokens=100)
366
+ model_name = "deepseek-ai/deepseek-coder-6.7b-instruct"
367
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
368
+ llm = LLM(model=model_name, trust_remote_code=True, gpu_memory_utilization=0.9, tensor_parallel_size=tp_size)
369
+
370
+ messages_list = [
371
+ [{"role": "user", "content": "Who are you?"}],
372
+ [{"role": "user", "content": "What can you do?"}],
373
+ [{"role": "user", "content": "Explain Transformer briefly."}],
374
+ ]
375
+ prompts = [tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) for messages in messages_list]
376
+
377
+ sampling_params.stop = [tokenizer.eos_token]
378
+ outputs = llm.generate(prompts, sampling_params)
379
+
380
+ generated_text = [output.outputs[0].text for output in outputs]
381
+ print(generated_text)
382
+ ```
383
+
384
+ ### 7. Q&A
385
+
386
+ #### Could You Provide the tokenizer.model File for Model Quantization?
387
+
388
+ DeepSeek Coder utilizes the [HuggingFace Tokenizer](https://huggingface.co/docs/tokenizers/index) to implement the Bytelevel-BPE algorithm, with specially designed pre-tokenizers to ensure optimal performance. Currently, there is no direct way to convert the tokenizer into a SentencePiece tokenizer. We are contributing to the open-source quantization methods facilitate the usage of HuggingFace Tokenizer.
389
+
390
+ ##### GGUF(llama.cpp)
391
+
392
+ We have submitted a [PR](https://github.com/ggerganov/llama.cpp/pull/4070) to the popular quantization repository [llama.cpp](https://github.com/ggerganov/llama.cpp) to fully support all HuggingFace pre-tokenizers, including ours.
393
+
394
+ While waiting for the PR to be merged, you can generate your GGUF model using the following steps:
395
+
396
+ ```bash
397
+ git clone https://github.com/DOGEwbx/llama.cpp.git
398
+ cd llama.cpp
399
+ git checkout regex_gpt2_preprocess
400
+ # set up the environment according to README
401
+ make
402
+ python3 -m pip install -r requirements.txt
403
+ # generate GGUF model
404
+ python convert-hf-to-gguf.py <MODEL_PATH> --outfile <GGUF_PATH> --model-name deepseekcoder
405
+ # use q4_0 quantization as an example
406
+ ./quantize <GGUF_PATH> <OUTPUT_PATH> q4_0
407
+ ./main -m <OUTPUT_PATH> -n 128 -p <PROMPT>
408
+ ```
409
+ ##### GPTQ(exllamav2)
410
+
411
+ `UPDATE:`[exllamav2](https://github.com/turboderp/exllamav2) has been able to support Huggingface Tokenizer. Please pull the latest version and try out.
412
+
413
+ Remember to set RoPE scaling to 4 for correct output, more discussion could be found in this [PR](https://github.com/turboderp/exllamav2/pull/189).
414
+
415
+ #### How to use the deepseek-coder-instruct to complete the code?
416
+
417
+ Although the deepseek-coder-instruct models are not specifically trained for code completion tasks during supervised fine-tuning (SFT), they retain the capability to perform code completion effectively. To enable this functionality, you simply need to adjust the eos_token_id parameter. Set the eos_token_id to 32014, as opposed to its default value of 32021 in the deepseek-coder-instruct configuration. This modification prompts the model to recognize the end of a sequence differently, thereby facilitating code completion tasks.
418
+
419
+
420
+ ### 8. Resources
421
+ [awesome-deepseek-coder](https://github.com/deepseek-ai/awesome-deepseek-coder) is a curated list of open-source projects related to DeepSeek Coder.
422
+
423
+ ### 9. License
424
+ This code repository is licensed under the MIT License. The use of DeepSeek Coder models is subject to the Model License. DeepSeek Coder supports commercial use.
425
+
426
+ See the [LICENSE-CODE](LICENSE-CODE) and [LICENSE-MODEL](LICENSE-MODEL) for more details.
427
+
428
+ ### 10. Citation
429
+ ```
430
+ @misc{deepseek-coder,
431
+ author = {Daya Guo, Qihao Zhu, Dejian Yang, Zhenda Xie, Kai Dong, Wentao Zhang, Guanting Chen, Xiao Bi, Y. Wu, Y.K. Li, Fuli Luo, Yingfei Xiong, Wenfeng Liang},
432
+ title = {DeepSeek-Coder: When the Large Language Model Meets Programming -- The Rise of Code Intelligence},
433
+ journal = {CoRR},
434
+ volume = {abs/2401.14196},
435
+ year = {2024},
436
+ url = {https://arxiv.org/abs/2401.14196},
437
+ }
438
+ ```
439
+
440
+ ### 11. Contact
441
+
442
+ If you have any questions, please raise an issue or contact us at [service@deepseek.com](mailto:service@deepseek.com).
requirements.txt CHANGED
@@ -1 +1,8 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
 
1
+ torch>=2.0
2
+ tokenizers>=0.14.0
3
+ transformers==4.35.0
4
+ accelerate
5
+ sympy==1.12
6
+ pebble
7
+ timeout-decorator
8
+ attrdict