Spaces:
Running
Running
Upload 26 files
Browse files- .gitattributes +1 -0
- README.md +136 -293
- WizardCoder/CODE_LICENSE +201 -0
- WizardCoder/DATA_LICENSE +407 -0
- WizardCoder/MODEL_WEIGHTS_LICENSE +111 -0
- WizardCoder/README.md +364 -0
- WizardCoder/data/humaneval.59.8.gen.zip +3 -0
- WizardCoder/data/mbpp.test.zip +3 -0
- WizardCoder/imgs/compare_sota.png +0 -0
- WizardCoder/imgs/pass1.png +0 -0
- WizardCoder/src/humaneval_gen.py +161 -0
- WizardCoder/src/humaneval_gen_vllm.py +114 -0
- WizardCoder/src/inference_wizardcoder.py +121 -0
- WizardCoder/src/mbpp_gen.py +197 -0
- WizardCoder/src/process_humaneval.py +69 -0
- WizardCoder/src/process_mbpp.py +73 -0
- WizardCoder/src/train_wizardcoder.py +248 -0
- training/data/alpaca_data.json +3 -0
- training/requirements.txt +10 -0
- training/src/configs/deepspeed_config.json +46 -0
- training/src/configs/hostfile +2 -0
- training/src/conversation.py +478 -0
- training/src/environment.yml +203 -0
- training/src/generate.py +145 -0
- training/src/train.py +246 -0
- training/src/train_freeform_multiturn.py +301 -0
- training/src/utils.py +173 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
training/data/alpaca_data.json filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
@@ -1,359 +1,201 @@
|
|
1 |
-
|
2 |
-
license: apache-2.0
|
3 |
-
title: WizardLM
|
4 |
-
sdk: streamlit
|
5 |
-
emoji: 🏃
|
6 |
-
colorFrom: red
|
7 |
-
colorTo: purple
|
8 |
-
sdk_version: 1.41.1
|
9 |
-
---
|
10 |
-
|
11 |
-
|
12 |
-
# WizardCoder: Empowering Code Large Language Models with Evol-Instruct
|
13 |
-
|
14 |
-
[](CODE_LICENSE)
|
15 |
-
[](DATA_LICENSE)
|
16 |
-
<!-- [](MODEL_WEIGHTS_LICENSE) -->
|
17 |
-
[](https://www.python.org/downloads/release/python-390/)
|
18 |
-
|
19 |
-
To develop our WizardCoder model, we begin by adapting the Evol-Instruct method specifically for coding tasks. This involves tailoring the prompt to the domain of code-related instructions. Subsequently, we fine-tune the Code LLMs, StarCoder or Code LLama, utilizing the newly created instruction-following training set.
|
20 |
-
|
21 |
-
## News
|
22 |
-
|
23 |
-
- 🔥🔥🔥[2023/08/26] We released **WizardCoder-Python-34B-V1.0** , which achieves the **73.2 pass@1** and surpasses **GPT4 (2023/03/15)**, **ChatGPT-3.5**, and **Claude2** on the [HumanEval Benchmarks](https://github.com/openai/human-eval).
|
24 |
-
- [2023/06/16] We released **WizardCoder-15B-V1.0** , which achieves the **57.3 pass@1** and surpasses **Claude-Plus (+6.8)**, **Bard (+15.3)** and **InstructCodeT5+ (+22.3)** on the [HumanEval Benchmarks](https://github.com/openai/human-eval).
|
25 |
-
|
26 |
-
❗Note: There are two HumanEval results of GPT4 and ChatGPT-3.5. The 67.0 and 48.1 are reported by the official GPT4 Report (2023/03/15) of [OpenAI](https://arxiv.org/abs/2303.08774). The 82.0 and 72.5 are tested by ourselves with the latest API (2023/08/26).
|
27 |
-
|
28 |
-
|
29 |
-
| Model | Checkpoint | Paper | HumanEval | MBPP | Demo | License |
|
30 |
-
| ----- |------| ---- |------|-------| ----- | ----- |
|
31 |
-
| WizardCoder-Python-34B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2306.08568" target="_blank">[WizardCoder]</a> | 73.2 | 61.2 | [Demo](http://47.103.63.15:50085/) | <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/" target="_blank">Llama2</a> |
|
32 |
-
| WizardCoder-15B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardCoder-15B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2306.08568" target="_blank">[WizardCoder]</a> | 59.8 |50.6 | -- | <a href="https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement" target="_blank">OpenRAIL-M</a> |
|
33 |
|
34 |
-
- 📣 Please refer to our Twitter account https://twitter.com/WizardLM_AI and HuggingFace Repo https://huggingface.co/WizardLM . We will use them to announce any new release at the 1st time.
|
35 |
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
<
|
41 |
-
<a ><img src="imgs/compare_sota.png" alt="WizardCoder" style="width: 96%; min-width: 300px; display: block; margin: auto;"></a>
|
42 |
</p>
|
43 |
-
|
44 |
-
❗❗❗**Note: This performance is 100% reproducible! If you cannot reproduce it, please follow the steps in [Evaluation](#evaluation).**
|
45 |
-
|
46 |
-
❗Note: There are two HumanEval results of GPT4 and ChatGPT-3.5. The 67.0 and 48.1 are reported by the official GPT4 Report (2023/03/15) of [OpenAI](https://arxiv.org/abs/2303.08774). The 82.0 and 72.5 are tested by ourselves with the latest API (2023/08/26).
|
47 |
-
|
48 |
-
## Comparing WizardCoder-15B-V1.0 with the Closed-Source Models.
|
49 |
-
|
50 |
-
🔥 The following figure shows that our **WizardCoder attains the third position in this benchmark**, surpassing Claude-Plus (59.8 vs. 53.0) and Bard (59.8 vs. 44.5). Notably, our model exhibits a substantially smaller size compared to these models.
|
51 |
|
52 |
<p align="center" width="100%">
|
53 |
-
<a ><img src="imgs/
|
54 |
</p>
|
55 |
|
56 |
-
|
|
|
|
|
57 |
|
58 |
-
|
59 |
|
60 |
-
|
|
|
|
|
|
|
|
|
61 |
|
62 |
-
|
63 |
|
|
|
|
|
64 |
|
65 |
-
| Model | HumanEval Pass@1 | MBPP Pass@1 |
|
66 |
-
|------------------|------------------|-------------|
|
67 |
-
| CodeGen-16B-Multi| 18.3 |20.9 |
|
68 |
-
| CodeGeeX | 22.9 |24.4 |
|
69 |
-
| LLaMA-33B | 21.7 |30.2 |
|
70 |
-
| LLaMA-65B | 23.7 |37.7 |
|
71 |
-
| PaLM-540B | 26.2 |36.8 |
|
72 |
-
| PaLM-Coder-540B | 36.0 |47.0 |
|
73 |
-
| PaLM 2-S | 37.6 |50.0 |
|
74 |
-
| CodeGen-16B-Mono | 29.3 |35.3 |
|
75 |
-
| Code-Cushman-001 | 33.5 |45.9 |
|
76 |
-
| StarCoder-15B | 33.6 |43.6* |
|
77 |
-
| InstructCodeT5+ | 35.0 |-- |
|
78 |
-
| WizardLM-30B 1.0| 37.8 |-- |
|
79 |
-
| WizardCoder-15B 1.0 | **57.3** |**51.8** |
|
80 |
|
81 |
-
|
|
|
|
|
|
|
82 |
|
83 |
-
❗**Note: The above table conducts a comprehensive comparison of our **WizardCoder** with other models on the HumanEval and MBPP benchmarks. We adhere to the approach outlined in previous studies by generating **20 samples** for each problem to estimate the pass@1 score and evaluate with the same [code](https://github.com/openai/human-eval/tree/master). The scores of GPT4 and GPT3.5 reported by [OpenAI](https://openai.com/research/gpt-4) are 67.0 and 48.1 (maybe these are the early version GPT4&3.5).**
|
84 |
|
85 |
-
## Call for Feedbacks
|
86 |
-
We welcome everyone to use your professional and difficult instructions to evaluate WizardCoder, and show us examples of poor performance and your suggestions in the [issue discussion](https://github.com/nlpxucan/WizardLM/issues) area. We are focusing on improving the Evol-Instruct now and hope to relieve existing weaknesses and issues in the the next version of WizardCoder. After that, we will open the code and pipeline of up-to-date Evol-Instruct algorithm and work with you together to improve it.
|
87 |
|
88 |
-
|
89 |
-
|
90 |
-
1. [WizardCoder AI Is The NEW ChatGPT's Coding TWIN!](https://www.youtube.com/watch?v=XjsyHrmd3Xo)
|
91 |
|
92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
93 |
|
94 |
-
1. [Online Demo](#online-demo)
|
95 |
|
96 |
-
|
97 |
|
98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
99 |
|
100 |
-
4. [Evaluation](#evaluation)
|
101 |
|
102 |
-
5. [Citation](#citation)
|
103 |
|
104 |
-
6. [Disclaimer](#disclaimer)
|
105 |
|
106 |
-
|
107 |
|
108 |
-
|
|
|
|
|
|
|
109 |
|
110 |
-
|
111 |
|
112 |
-
|
113 |
|
114 |
-
|
115 |
-
We fine-tune StarCoder-15B with the following hyperparameters:
|
116 |
|
117 |
-
| Hyperparameter | StarCoder-15B |
|
118 |
-
|----------------|---------------|
|
119 |
-
| Batch size | 512 |
|
120 |
-
| Learning rate | 2e-5 |
|
121 |
-
| Epochs | 3 |
|
122 |
-
| Max length | 2048 |
|
123 |
-
| Warmup step | 30 |
|
124 |
-
| LR scheduler | cosine |
|
125 |
|
126 |
-
|
127 |
-
1. According to the instructions of [Llama-X](https://github.com/AetherCortex/Llama-X), install the environment, download the training code, and deploy. (Note: `deepspeed==0.9.2` and `transformers==4.29.2`)
|
128 |
-
2. Replace the `train.py` with the `train_wizardcoder.py` in our repo (`src/train_wizardcoder.py`)
|
129 |
-
3. Login Huggingface:
|
130 |
-
```bash
|
131 |
-
huggingface-cli login
|
132 |
-
```
|
133 |
-
4. Execute the following training command:
|
134 |
-
```bash
|
135 |
-
deepspeed train_wizardcoder.py \
|
136 |
-
--model_name_or_path "bigcode/starcoder" \
|
137 |
-
--data_path "/your/path/to/code_instruction_data.json" \
|
138 |
-
--output_dir "/your/path/to/ckpt" \
|
139 |
-
--num_train_epochs 3 \
|
140 |
-
--model_max_length 2048 \
|
141 |
-
--per_device_train_batch_size 16 \
|
142 |
-
--per_device_eval_batch_size 1 \
|
143 |
-
--gradient_accumulation_steps 4 \
|
144 |
-
--evaluation_strategy "no" \
|
145 |
-
--save_strategy "steps" \
|
146 |
-
--save_steps 50 \
|
147 |
-
--save_total_limit 2 \
|
148 |
-
--learning_rate 2e-5 \
|
149 |
-
--warmup_steps 30 \
|
150 |
-
--logging_steps 2 \
|
151 |
-
--lr_scheduler_type "cosine" \
|
152 |
-
--report_to "tensorboard" \
|
153 |
-
--gradient_checkpointing True \
|
154 |
-
--deepspeed configs/deepspeed_config.json \
|
155 |
-
--fp16 True
|
156 |
-
```
|
157 |
|
158 |
-
|
159 |
|
160 |
-
|
161 |
|
162 |
-
You can specify `base_model`, `input_data_path` and `output_data_path` in `src\inference_wizardcoder.py` to set the decoding model, path of input file and path of output file.
|
163 |
-
|
164 |
-
```bash
|
165 |
-
pip install jsonlines
|
166 |
-
```
|
167 |
-
|
168 |
-
The decoding command is:
|
169 |
```
|
170 |
-
|
171 |
-
--base_model "/your/path/to/ckpt" \
|
172 |
-
--input_data_path "/your/path/to/input/data.jsonl" \
|
173 |
-
--output_data_path "/your/path/to/output/result.jsonl"
|
174 |
```
|
175 |
|
176 |
-
|
|
|
177 |
```
|
178 |
-
|
179 |
-
{"idx": 12, "Instruction": "Write a Java code to sum 1 to 10."}
|
180 |
```
|
181 |
|
182 |
-
|
183 |
-
```
|
184 |
-
Below is an instruction that describes a task. Write a response that appropriately completes the request.
|
185 |
|
186 |
-
|
187 |
-
{instruction}
|
188 |
|
189 |
-
### Response:
|
190 |
```
|
191 |
-
|
192 |
-
## Evaluation
|
193 |
-
|
194 |
-
### HumanEval
|
195 |
-
|
196 |
-
1. According to the instructions of [HumanEval](https://github.com/openai/human-eval), install the environment.
|
197 |
-
2. Run the following scripts to generate the answer.
|
198 |
-
|
199 |
-
- (1) For WizardCoder-15B-V1.0 (base on StarCoder)
|
200 |
-
```bash
|
201 |
-
model="/path/to/your/model"
|
202 |
-
temp=0.2
|
203 |
-
max_len=2048
|
204 |
-
pred_num=200
|
205 |
-
num_seqs_per_iter=2
|
206 |
-
|
207 |
-
output_path=preds/T${temp}_N${pred_num}
|
208 |
-
|
209 |
-
mkdir -p ${output_path}
|
210 |
-
echo 'Output path: '$output_path
|
211 |
-
echo 'Model to eval: '$model
|
212 |
-
|
213 |
-
# 164 problems, 21 per GPU if GPU=8
|
214 |
-
index=0
|
215 |
-
gpu_num=8
|
216 |
-
for ((i = 0; i < $gpu_num; i++)); do
|
217 |
-
start_index=$((i * 21))
|
218 |
-
end_index=$(((i + 1) * 21))
|
219 |
-
|
220 |
-
gpu=$((i))
|
221 |
-
echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
|
222 |
-
((index++))
|
223 |
-
(
|
224 |
-
CUDA_VISIBLE_DEVICES=$gpu python humaneval_gen.py --model ${model} \
|
225 |
-
--start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
|
226 |
-
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path}
|
227 |
-
) &
|
228 |
-
if (($index % $gpu_num == 0)); then wait; fi
|
229 |
-
done
|
230 |
```
|
231 |
|
232 |
-
- (2) For WizardCoder-Python-34B-V1.0 (base on CodeLLama)
|
233 |
-
|
234 |
-
```bash
|
235 |
-
pip install vllm # This can acclerate the inference process a lot.
|
236 |
-
pip install transformers==4.31.0
|
237 |
-
|
238 |
-
model="/path/to/your/model"
|
239 |
-
temp=0.2
|
240 |
-
max_len=2048
|
241 |
-
pred_num=200
|
242 |
-
num_seqs_per_iter=2
|
243 |
|
244 |
-
|
245 |
|
246 |
-
mkdir -p ${output_path}
|
247 |
-
echo 'Output path: '$output_path
|
248 |
-
echo 'Model to eval: '$model
|
249 |
|
250 |
-
CUDA_VISIBLE_DEVICES=0,1,2,3 python humaneval_gen_vllm.py --model ${model} \
|
251 |
-
--start_index 0 --end_index 164 --temperature ${temp} \
|
252 |
-
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --num_gpus 4
|
253 |
```
|
254 |
-
|
255 |
-
3. Run the post processing code `src/process_humaneval.py` to collect the code completions from all answer files.
|
256 |
-
```bash
|
257 |
-
output_path=preds/T${temp}_N${pred_num}
|
258 |
-
|
259 |
-
echo 'Output path: '$output_path
|
260 |
-
python process_humaneval.py --path ${output_path} --out_path ${output_path}.jsonl --add_prompt
|
261 |
-
|
262 |
-
evaluate_functional_correctness ${output_path}.jsonl
|
263 |
```
|
264 |
|
265 |
-
###
|
266 |
|
267 |
-
|
|
|
|
|
|
|
268 |
|
269 |
-
|
270 |
|
271 |
-
|
272 |
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
max_len=2048
|
277 |
-
pred_num=1
|
278 |
-
num_seqs_per_iter=1
|
279 |
|
280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
281 |
|
282 |
-
|
283 |
-
|
284 |
-
echo 'Model to eval: '$model
|
285 |
|
286 |
-
# 164 problems, 21 per GPU if GPU=8
|
287 |
-
index=0
|
288 |
-
gpu_num=8
|
289 |
-
for ((i = 0; i < $gpu_num; i++)); do
|
290 |
-
start_index=$((i * 21))
|
291 |
-
end_index=$(((i + 1) * 21))
|
292 |
|
293 |
-
gpu=$((i))
|
294 |
-
echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
|
295 |
-
((index++))
|
296 |
-
(
|
297 |
-
CUDA_VISIBLE_DEVICES=$gpu python humaneval_gen.py --model ${model} \
|
298 |
-
--start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
|
299 |
-
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --greedy_decode
|
300 |
-
) &
|
301 |
-
if (($index % $gpu_num == 0)); then wait; fi
|
302 |
-
done
|
303 |
-
```
|
304 |
|
305 |
-
|
306 |
-
|
307 |
-
1. Run the following script to generate the answer.
|
308 |
-
```bash
|
309 |
-
model="/path/to/your/model"
|
310 |
-
temp=0.2
|
311 |
-
max_len=2048
|
312 |
-
pred_num=200
|
313 |
-
num_seqs_per_iter=2
|
314 |
-
|
315 |
-
output_path=preds/MBPP_T${temp}_N${pred_num}
|
316 |
-
mbpp_path=data/mbpp.test.jsonl # we provide this file in data/mbpp.test.zip
|
317 |
-
|
318 |
-
mkdir -p ${output_path}
|
319 |
-
echo 'Output path: '$output_path
|
320 |
-
echo 'Model to eval: '$model
|
321 |
-
|
322 |
-
# 500 problems, 63 per GPU if GPU=8
|
323 |
-
index=0
|
324 |
-
gpu_num=8
|
325 |
-
for ((i = 0; i < $gpu_num; i++)); do
|
326 |
-
start_index=$((i * 50))
|
327 |
-
end_index=$(((i + 1) * 50))
|
328 |
-
|
329 |
-
gpu=$((i))
|
330 |
-
echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
|
331 |
-
((index++))
|
332 |
-
(
|
333 |
-
CUDA_VISIBLE_DEVICES=$gpu python mbpp_gen.py --model ${model} \
|
334 |
-
--start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
|
335 |
-
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --mbpp_path ${mbpp_path}
|
336 |
-
) &
|
337 |
-
if (($index % $gpu_num == 0)); then wait; fi
|
338 |
-
done
|
339 |
-
```
|
340 |
|
341 |
-
|
342 |
-
```bash
|
343 |
-
output_path=preds/MBPP_T${temp}_N${pred_num}
|
344 |
-
mbpp_path=data/mbpp.test.jsonl # we provide this file in data/mbpp.test.zip
|
345 |
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
|
350 |
-
|
|
|
|
|
351 |
|
352 |
-
|
353 |
|
354 |
-
|
355 |
|
356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
357 |
|
358 |
```
|
359 |
@misc{luo2023wizardcoder,
|
@@ -367,8 +209,9 @@ Please cite the repo if you use the data or code in this repo.
|
|
367 |
```
|
368 |
## Disclaimer
|
369 |
|
370 |
-
|
371 |
|
372 |
## Star History
|
373 |
|
374 |
-
[](https://star-history.com/#nlpxucan/WizardLM&Timeline)
|
|
|
|
1 |
+
## WizardLM: Empowering Large Pre-Trained Language Models to Follow Complex Instructions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
|
|
3 |
|
4 |
+
<p align="center">
|
5 |
+
🤗 <a href="https://huggingface.co/WizardLM" target="_blank">HF Repo</a> • 🐦 <a href="https://twitter.com/WizardLM_AI" target="_blank">Twitter</a> • 📃 <a href="https://arxiv.org/abs/2304.12244" target="_blank">[WizardLM]</a> • 📃 <a href="https://arxiv.org/abs/2306.08568" target="_blank">[WizardCoder]</a> • 📃 <a href="https://arxiv.org/abs/2308.09583" target="_blank">[WizardMath]</a> <br>
|
6 |
+
</p>
|
7 |
+
<p align="center">
|
8 |
+
👋 Join our <a href="https://discord.gg/VZjjHtWrKs" target="_blank">Discord</a>
|
|
|
9 |
</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
<p align="center" width="100%">
|
12 |
+
<a ><img src="imgs/WizardLM.png" alt="WizardLM" style="width: 20%; min-width: 300px; display: block; margin: auto;"></a>
|
13 |
</p>
|
14 |
|
15 |
+
[](https://github.com/tatsu-lab/stanford_alpaca/blob/main/LICENSE)
|
16 |
+
[](https://github.com/tatsu-lab/stanford_alpaca/blob/main/DATA_LICENSE)
|
17 |
+
[](https://www.python.org/downloads/release/python-390/)
|
18 |
|
19 |
+
**Unofficial Video Introductions**
|
20 |
|
21 |
+
Thanks to the enthusiastic friends, their video introductions are more lively and interesting.
|
22 |
+
1. [NEW WizardLM 70b 🔥 Giant Model...Insane Performance](https://www.youtube.com/watch?v=WdpiIXrO4_o)
|
23 |
+
2. [GET WizardLM NOW! 7B LLM KING That Can Beat ChatGPT! I'm IMPRESSED!](https://www.youtube.com/watch?v=SaJ8wyKMBds)
|
24 |
+
3. [WizardLM: Enhancing Large Language Models to Follow Complex Instructions](https://www.youtube.com/watch?v=I6sER-qivYk)
|
25 |
+
4. [WizardCoder AI Is The NEW ChatGPT's Coding TWIN!](https://www.youtube.com/watch?v=XjsyHrmd3Xo)
|
26 |
|
27 |
+
## News
|
28 |
|
29 |
+
- 🔥🔥🔥[2023/08/26] We released **WizardCoder-Python-34B-V1.0** , which achieves the **73.2 pass@1** and surpasses **GPT4 (2023/03/15)**, **ChatGPT-3.5**, and **Claude2** on the [HumanEval Benchmarks](https://github.com/openai/human-eval). For more details, please refer to [WizardCoder](https://github.com/nlpxucan/WizardLM/tree/main/WizardCoder).
|
30 |
+
- [2023/06/16] We released **WizardCoder-15B-V1.0** , which surpasses **Claude-Plus (+6.8)**, **Bard (+15.3)** and **InstructCodeT5+ (+22.3)** on the [HumanEval Benchmarks](https://github.com/openai/human-eval). For more details, please refer to [WizardCoder](https://github.com/nlpxucan/WizardLM/tree/main/WizardCoder).
|
31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
+
| Model | Checkpoint | Paper | HumanEval | MBPP | Demo | License |
|
34 |
+
| ----- |------| ---- |------|-------| ----- | ----- |
|
35 |
+
| WizardCoder-Python-34B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2306.08568" target="_blank">[WizardCoder]</a> | 73.2 | 61.2 | [Demo](http://47.103.63.15:50085/) | <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/" target="_blank">Llama2</a> |
|
36 |
+
| WizardCoder-15B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardCoder-15B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2306.08568" target="_blank">[WizardCoder]</a> | 59.8 |50.6 | -- | <a href="https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement" target="_blank">OpenRAIL-M</a> |
|
37 |
|
|
|
38 |
|
|
|
|
|
39 |
|
40 |
+
- Our **WizardMath-70B-V1.0** model slightly outperforms some closed-source LLMs on the GSM8K, including **ChatGPT 3.5**, **Claude Instant 1** and **PaLM 2 540B**.
|
41 |
+
- Our **WizardMath-70B-V1.0** model achieves **81.6 pass@1** on the [GSM8k Benchmarks](https://github.com/openai/grade-school-math), which is **24.8** points higher than the SOTA open-source LLM, and achieves **22.7 pass@1** on the [MATH Benchmarks](https://github.com/hendrycks/math), which is **9.2** points higher than the SOTA open-source LLM.
|
|
|
42 |
|
43 |
+
<font size=0.5>
|
44 |
+
|
45 |
+
| Model | Checkpoint | Paper | GSM8k | MATH |Online Demo| License|
|
46 |
+
| ----- |------| ---- |------|-------| ----- | ----- |
|
47 |
+
| WizardMath-70B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardMath-70B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2308.09583" target="_blank">[WizardMath]</a>| **81.6** | **22.7** |[Demo](http://47.103.63.15:50083/)| <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/" target="_blank">Llama 2 </a> |
|
48 |
+
| WizardMath-13B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardMath-13B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2308.09583" target="_blank">[WizardMath]</a>| **63.9** | **14.0** |[Demo](http://47.103.63.15:50082/)| <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/" target="_blank">Llama 2 </a> |
|
49 |
+
| WizardMath-7B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardMath-7B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2308.09583" target="_blank">[WizardMath]</a>| **54.9** | **10.7** | [Demo ](http://47.103.63.15:50080/)| <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/" target="_blank">Llama 2 </a>|
|
50 |
+
</font>
|
51 |
|
|
|
52 |
|
53 |
+
- [08/09/2023] We released **WizardLM-70B-V1.0** model. Here is [Full Model Weight](https://huggingface.co/WizardLM/WizardLM-70B-V1.0).
|
54 |
|
55 |
+
<font size=0.5>
|
56 |
+
|
57 |
+
|
58 |
+
| <sup>Model</sup> | <sup>Checkpoint</sup> | <sup>Paper</sup> |<sup>MT-Bench</sup> | <sup>AlpacaEval</sup> | <sup>GSM8k</sup> | <sup>HumanEval</sup> | <sup>License</sup>|
|
59 |
+
| ----- |------| ---- |------|-------| ----- | ----- | ----- |
|
60 |
+
| <sup>**WizardLM-70B-V1.0**</sup> | <sup>🤗 <a href="https://huggingface.co/WizardLM/WizardLM-70B-V1.0" target="_blank">HF Link</a> </sup>|<sup>📃**Coming Soon**</sup>| <sup>**7.78**</sup> | <sup>**92.91%**</sup> |<sup>**77.6%**</sup> | <sup> **50.6**</sup>|<sup> <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/" target="_blank">Llama 2 License </a></sup> |
|
61 |
+
| <sup>WizardLM-13B-V1.2</sup> | <sup>🤗 <a href="https://huggingface.co/WizardLM/WizardLM-13B-V1.2" target="_blank">HF Link</a> </sup>| | <sup>7.06</sup> | <sup>89.17%</sup> |<sup>55.3%</sup> | <sup>36.6 </sup>|<sup> <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/" target="_blank">Llama 2 License </a></sup> |
|
62 |
+
| <sup>WizardLM-13B-V1.1</sup> |<sup> 🤗 <a href="https://huggingface.co/WizardLM/WizardLM-13B-V1.1" target="_blank">HF Link</a> </sup> | | <sup>6.76</sup> |<sup>86.32%</sup> | | <sup>25.0 </sup>| <sup>Non-commercial</sup>|
|
63 |
+
| <sup>WizardLM-30B-V1.0</sup> | <sup>🤗 <a href="https://huggingface.co/WizardLM/WizardLM-30B-V1.0" target="_blank">HF Link</a></sup> | | <sup>7.01</sup> | | | <sup>37.8 </sup>| <sup>Non-commercial</sup> |
|
64 |
+
| <sup>WizardLM-13B-V1.0</sup> | <sup>🤗 <a href="https://huggingface.co/WizardLM/WizardLM-13B-V1.0" target="_blank">HF Link</a> </sup> | | <sup>6.35</sup> | <sup>75.31%</sup> | | <sup> 24.0 </sup> | <sup>Non-commercial</sup>|
|
65 |
+
| <sup>WizardLM-7B-V1.0 </sup>| <sup>🤗 <a href="https://huggingface.co/WizardLM/WizardLM-7B-V1.0" target="_blank">HF Link</a> </sup> |<sup> 📃 <a href="https://arxiv.org/abs/2304.12244" target="_blank">[WizardLM]</a> </sup>| | | |<sup>19.1 </sup>|<sup> Non-commercial</sup>|
|
66 |
+
</font>
|
67 |
|
|
|
68 |
|
|
|
69 |
|
|
|
70 |
|
71 |
+
❗To commen concern about dataset:
|
72 |
|
73 |
+
Recently, there have been clear changes in the open-source policy and regulations of our overall organization's code, data, and models.
|
74 |
+
Despite this, we have still worked hard to obtain opening the weights of the model first, but the data involves stricter auditing and is in review with our legal team .
|
75 |
+
Our researchers have no authority to publicly release them without authorization.
|
76 |
+
Thank you for your understanding.
|
77 |
|
78 |
+
## Hiring
|
79 |
|
80 |
+
- 📣 We are looking for highly motivated students to join us as interns to create more intelligent AI together. Please contact [email protected]
|
81 |
|
82 |
+
<!-- Although on our **complexity-balanced test set**, **WizardLM-7B has more cases that are preferred by human labelers than ChatGPT** in the high-complexity instructions (difficulty level >= 8), it still lags behind ChatGPT on the entire test set, and we also consider WizardLM to still be in a **baby state**. This repository will **continue to improve WizardLM**, train on larger scales, add more training data, and innovate more advanced large-model training methods. -->
|
|
|
83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
+
<b>Note for model system prompts usage:</b>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
+
To obtain results **identical to our demo**, please strictly follow the prompts and invocation methods provided in the **"src/infer_wizardlm13b.py"** to use our model for inference. Our model adopts the prompt format from <b>Vicuna</b> and supports **multi-turn** conversation.
|
88 |
|
89 |
+
<b>For WizardLM</b>, the Prompt should be as following:
|
90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
```
|
92 |
+
A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. USER: Hi ASSISTANT: Hello.</s>USER: Who are you? ASSISTANT: I am WizardLM.</s>......
|
|
|
|
|
|
|
93 |
```
|
94 |
|
95 |
+
<b>For WizardCoder </b>, the Prompt should be as following:
|
96 |
+
|
97 |
```
|
98 |
+
"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Response:"
|
|
|
99 |
```
|
100 |
|
101 |
+
<b>For WizardMath</b>, the Prompts should be as following:
|
|
|
|
|
102 |
|
103 |
+
**Default version:**
|
|
|
104 |
|
|
|
105 |
```
|
106 |
+
"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Response:"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
```
|
108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
+
**CoT Version:** (❗For the **simple** math questions, we do NOT recommend to use the CoT prompt.)
|
111 |
|
|
|
|
|
|
|
112 |
|
|
|
|
|
|
|
113 |
```
|
114 |
+
"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Response: Let's think step by step."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
```
|
116 |
|
117 |
+
### GPT-4 automatic evaluation
|
118 |
|
119 |
+
We adopt the automatic evaluation framework based on GPT-4 proposed by FastChat to assess the performance of chatbot models. As shown in the following figure, WizardLM-30B achieved better results than Guanaco-65B.
|
120 |
+
<p align="center" width="100%">
|
121 |
+
<a ><img src="imgs/WizarLM30b-GPT4.png" alt="WizardLM" style="width: 100%; min-width: 300px; display: block; margin: auto;"></a>
|
122 |
+
</p>
|
123 |
|
124 |
+
### WizardLM-30B performance on different skills.
|
125 |
|
126 |
+
The following figure compares WizardLM-30B and ChatGPT’s skill on Evol-Instruct testset. The result indicates that WizardLM-30B achieves 97.8% of ChatGPT’s performance on average, with almost 100% (or more than) capacity on 18 skills, and more than 90% capacity on 24 skills.
|
127 |
|
128 |
+
<p align="center" width="100%">
|
129 |
+
<a ><img src="imgs/evol-testset_skills-30b.png" alt="WizardLM" style="width: 100%; min-width: 300px; display: block; margin: auto;"></a>
|
130 |
+
</p>
|
|
|
|
|
|
|
131 |
|
132 |
+
### WizardLM performance on NLP foundation tasks.
|
133 |
+
|
134 |
+
The following table provides a comparison of WizardLMs and other LLMs on NLP foundation tasks. The results indicate that WizardLMs consistently exhibit superior performance in comparison to the LLaMa models of the same size. Furthermore, our WizardLM-30B model showcases comparable performance to OpenAI's Text-davinci-003 on the MMLU and HellaSwag benchmarks.
|
135 |
+
|
136 |
+
| Model | MMLU 5-shot | ARC 25-shot | TruthfulQA 0-shot | HellaSwag 10-shot | Average |
|
137 |
+
|------------------|-------------|-------------|-------------------|-------------------|------------|
|
138 |
+
| Text-davinci-003 | <u>56.9<u/> | **85.2** | **59.3** | <u>82.2<u/> | **70.9** |
|
139 |
+
|Vicuna-13b 1.1 | 51.3 | 53.0 | 51.8 | 80.1 | 59.1 |
|
140 |
+
|Guanaco 30B | 57.6 | 63.7 | 50.7 | **85.1** | 64.3 |
|
141 |
+
| WizardLM-7B 1.0 | 42.7 | 51.6 | 44.7 | 77.7 | 54.2 |
|
142 |
+
| WizardLM-13B 1.0 | 52.3 | 57.2 | 50.5 | 81.0 | 60.2 |
|
143 |
+
| WizardLM-30B 1.0 | **58.8** | <u>62.5<u/> | <u>52.4<u/> | 83.3 | <u>64.2<u/>|
|
144 |
+
|
145 |
+
### WizardLM performance on code generation.
|
146 |
+
|
147 |
+
The following table provides a comprehensive comparison of WizardLMs and several other LLMs on the code generation task, namely HumanEval. The evaluation metric is pass@1. The results indicate that WizardLMs consistently exhibit superior performance in comparison to the LLaMa models of the same size. Furthermore, our WizardLM-30B model surpasses StarCoder and OpenAI's code-cushman-001. Moreover, our Code LLM, WizardCoder, demonstrates exceptional performance, achieving a pass@1 score of 57.3, surpassing the open-source SOTA by approximately 20 points.
|
148 |
+
|
149 |
+
|
150 |
+
| Model | HumanEval Pass@1 |
|
151 |
+
|------------------|------------------|
|
152 |
+
| LLaMA-7B | 10.5 |
|
153 |
+
| LLaMA-13B | 15.8 |
|
154 |
+
| CodeGen-16B-Multi| 18.3 |
|
155 |
+
| CodeGeeX | 22.9 |
|
156 |
+
| LLaMA-33B | 21.7 |
|
157 |
+
| LLaMA-65B | 23.7 |
|
158 |
+
| PaLM-540B | 26.2 |
|
159 |
+
| CodeGen-16B-Mono | 29.3 |
|
160 |
+
| code-cushman-001 | 33.5 |
|
161 |
+
| StarCoder | <u>33.6<u/> |
|
162 |
+
| WizardLM-7B 1.0 | 19.1 |
|
163 |
+
| WizardLM-13B 1.0 | 24.0 |
|
164 |
+
| WizardLM-30B 1.0 | **37.8** |
|
165 |
+
| WizardCoder-15B 1.0 | **57.3** |
|
166 |
|
167 |
+
## Call for Feedbacks
|
168 |
+
We welcome everyone to use your professional and difficult instructions to evaluate WizardLM, and show us examples of poor performance and your suggestions in the [issue discussion](https://github.com/nlpxucan/WizardLM/issues) area. We are focusing on improving the Evol-Instruct now and hope to relieve existing weaknesses and issues in the the next version of WizardLM. After that, we will open the code and pipeline of up-to-date Evol-Instruct algorithm and work with you together to improve it.
|
|
|
169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
171 |
|
172 |
+
## Overview of Evol-Instruct
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
173 |
|
174 |
+
[Evol-Instruct](https://github.com/nlpxucan/evol-instruct) is a novel method using LLMs instead of humans to automatically mass-produce open-domain instructions of various difficulty levels and skills range, to improve the performance of LLMs.
|
|
|
|
|
|
|
175 |
|
176 |
+
<p align="center" width="100%">
|
177 |
+
<a ><img src="imgs/git_overall.png" alt="WizardLM" style="width: 86%; min-width: 300px; display: block; margin: auto;"></a>
|
178 |
+
</p>
|
179 |
|
180 |
+
<p align="center" width="100%">
|
181 |
+
<a ><img src="imgs/git_running.png" alt="WizardLM" style="width: 86%; min-width: 300px; display: block; margin: auto;"></a>
|
182 |
+
</p>
|
183 |
|
184 |
+
### Citation
|
185 |
|
186 |
+
Please cite the paper if you use the data or code from WizardLM.
|
187 |
|
188 |
+
```
|
189 |
+
@misc{xu2023wizardlm,
|
190 |
+
title={WizardLM: Empowering Large Language Models to Follow Complex Instructions},
|
191 |
+
author={Can Xu and Qingfeng Sun and Kai Zheng and Xiubo Geng and Pu Zhao and Jiazhan Feng and Chongyang Tao and Daxin Jiang},
|
192 |
+
year={2023},
|
193 |
+
eprint={2304.12244},
|
194 |
+
archivePrefix={arXiv},
|
195 |
+
primaryClass={cs.CL}
|
196 |
+
}
|
197 |
+
```
|
198 |
+
Please cite the paper if you use the data or code from WizardCoder.
|
199 |
|
200 |
```
|
201 |
@misc{luo2023wizardcoder,
|
|
|
209 |
```
|
210 |
## Disclaimer
|
211 |
|
212 |
+
The resources, including code, data, and model weights, associated with this project are restricted for academic research purposes only and cannot be used for commercial purposes. The content produced by any version of WizardLM is influenced by uncontrollable variables such as randomness, and therefore, the accuracy of the output cannot be guaranteed by this project. This project does not accept any legal liability for the content of the model output, nor does it assume responsibility for any losses incurred due to the use of associated resources and output results.
|
213 |
|
214 |
## Star History
|
215 |
|
216 |
+
[](https://star-history.com/#nlpxucan/WizardLM&Timeline)
|
217 |
+
|
WizardCoder/CODE_LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Apache License
|
2 |
+
Version 2.0, January 2004
|
3 |
+
http://www.apache.org/licenses/
|
4 |
+
|
5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6 |
+
|
7 |
+
1. Definitions.
|
8 |
+
|
9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
11 |
+
|
12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13 |
+
the copyright owner that is granting the License.
|
14 |
+
|
15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
16 |
+
other entities that control, are controlled by, or are under common
|
17 |
+
control with that entity. For the purposes of this definition,
|
18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
19 |
+
direction or management of such entity, whether by contract or
|
20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22 |
+
|
23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24 |
+
exercising permissions granted by this License.
|
25 |
+
|
26 |
+
"Source" form shall mean the preferred form for making modifications,
|
27 |
+
including but not limited to software source code, documentation
|
28 |
+
source, and configuration files.
|
29 |
+
|
30 |
+
"Object" form shall mean any form resulting from mechanical
|
31 |
+
transformation or translation of a Source form, including but
|
32 |
+
not limited to compiled object code, generated documentation,
|
33 |
+
and conversions to other media types.
|
34 |
+
|
35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
36 |
+
Object form, made available under the License, as indicated by a
|
37 |
+
copyright notice that is included in or attached to the work
|
38 |
+
(an example is provided in the Appendix below).
|
39 |
+
|
40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41 |
+
form, that is based on (or derived from) the Work and for which the
|
42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
44 |
+
of this License, Derivative Works shall not include works that remain
|
45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46 |
+
the Work and Derivative Works thereof.
|
47 |
+
|
48 |
+
"Contribution" shall mean any work of authorship, including
|
49 |
+
the original version of the Work and any modifications or additions
|
50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
54 |
+
means any form of electronic, verbal, or written communication sent
|
55 |
+
to the Licensor or its representatives, including but not limited to
|
56 |
+
communication on electronic mailing lists, source code control systems,
|
57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
59 |
+
excluding communication that is conspicuously marked or otherwise
|
60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
61 |
+
|
62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
64 |
+
subsequently incorporated within the Work.
|
65 |
+
|
66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
71 |
+
Work and such Derivative Works in Source or Object form.
|
72 |
+
|
73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76 |
+
(except as stated in this section) patent license to make, have made,
|
77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78 |
+
where such license applies only to those patent claims licensable
|
79 |
+
by such Contributor that are necessarily infringed by their
|
80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
82 |
+
institute patent litigation against any entity (including a
|
83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84 |
+
or a Contribution incorporated within the Work constitutes direct
|
85 |
+
or contributory patent infringement, then any patent licenses
|
86 |
+
granted to You under this License for that Work shall terminate
|
87 |
+
as of the date such litigation is filed.
|
88 |
+
|
89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
90 |
+
Work or Derivative Works thereof in any medium, with or without
|
91 |
+
modifications, and in Source or Object form, provided that You
|
92 |
+
meet the following conditions:
|
93 |
+
|
94 |
+
(a) You must give any other recipients of the Work or
|
95 |
+
Derivative Works a copy of this License; and
|
96 |
+
|
97 |
+
(b) You must cause any modified files to carry prominent notices
|
98 |
+
stating that You changed the files; and
|
99 |
+
|
100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
101 |
+
that You distribute, all copyright, patent, trademark, and
|
102 |
+
attribution notices from the Source form of the Work,
|
103 |
+
excluding those notices that do not pertain to any part of
|
104 |
+
the Derivative Works; and
|
105 |
+
|
106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107 |
+
distribution, then any Derivative Works that You distribute must
|
108 |
+
include a readable copy of the attribution notices contained
|
109 |
+
within such NOTICE file, excluding those notices that do not
|
110 |
+
pertain to any part of the Derivative Works, in at least one
|
111 |
+
of the following places: within a NOTICE text file distributed
|
112 |
+
as part of the Derivative Works; within the Source form or
|
113 |
+
documentation, if provided along with the Derivative Works; or,
|
114 |
+
within a display generated by the Derivative Works, if and
|
115 |
+
wherever such third-party notices normally appear. The contents
|
116 |
+
of the NOTICE file are for informational purposes only and
|
117 |
+
do not modify the License. You may add Your own attribution
|
118 |
+
notices within Derivative Works that You distribute, alongside
|
119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
120 |
+
that such additional attribution notices cannot be construed
|
121 |
+
as modifying the License.
|
122 |
+
|
123 |
+
You may add Your own copyright statement to Your modifications and
|
124 |
+
may provide additional or different license terms and conditions
|
125 |
+
for use, reproduction, or distribution of Your modifications, or
|
126 |
+
for any such Derivative Works as a whole, provided Your use,
|
127 |
+
reproduction, and distribution of the Work otherwise complies with
|
128 |
+
the conditions stated in this License.
|
129 |
+
|
130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
132 |
+
by You to the Licensor shall be under the terms and conditions of
|
133 |
+
this License, without any additional terms or conditions.
|
134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135 |
+
the terms of any separate license agreement you may have executed
|
136 |
+
with Licensor regarding such Contributions.
|
137 |
+
|
138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
140 |
+
except as required for reasonable and customary use in describing the
|
141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
142 |
+
|
143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144 |
+
agreed to in writing, Licensor provides the Work (and each
|
145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147 |
+
implied, including, without limitation, any warranties or conditions
|
148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150 |
+
appropriateness of using or redistributing the Work and assume any
|
151 |
+
risks associated with Your exercise of permissions under this License.
|
152 |
+
|
153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
154 |
+
whether in tort (including negligence), contract, or otherwise,
|
155 |
+
unless required by applicable law (such as deliberate and grossly
|
156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157 |
+
liable to You for damages, including any direct, indirect, special,
|
158 |
+
incidental, or consequential damages of any character arising as a
|
159 |
+
result of this License or out of the use or inability to use the
|
160 |
+
Work (including but not limited to damages for loss of goodwill,
|
161 |
+
work stoppage, computer failure or malfunction, or any and all
|
162 |
+
other commercial damages or losses), even if such Contributor
|
163 |
+
has been advised of the possibility of such damages.
|
164 |
+
|
165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168 |
+
or other liability obligations and/or rights consistent with this
|
169 |
+
License. However, in accepting such obligations, You may act only
|
170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171 |
+
of any other Contributor, and only if You agree to indemnify,
|
172 |
+
defend, and hold each Contributor harmless for any liability
|
173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
174 |
+
of your accepting any such warranty or additional liability.
|
175 |
+
|
176 |
+
END OF TERMS AND CONDITIONS
|
177 |
+
|
178 |
+
APPENDIX: How to apply the Apache License to your work.
|
179 |
+
|
180 |
+
To apply the Apache License to your work, attach the following
|
181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182 |
+
replaced with your own identifying information. (Don't include
|
183 |
+
the brackets!) The text should be enclosed in the appropriate
|
184 |
+
comment syntax for the file format. We also recommend that a
|
185 |
+
file or class name and description of purpose be included on the
|
186 |
+
same "printed page" as the copyright notice for easier
|
187 |
+
identification within third-party archives.
|
188 |
+
|
189 |
+
Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
|
190 |
+
|
191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192 |
+
you may not use this file except in compliance with the License.
|
193 |
+
You may obtain a copy of the License at
|
194 |
+
|
195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
196 |
+
|
197 |
+
Unless required by applicable law or agreed to in writing, software
|
198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200 |
+
See the License for the specific language governing permissions and
|
201 |
+
limitations under the License.
|
WizardCoder/DATA_LICENSE
ADDED
@@ -0,0 +1,407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Attribution-NonCommercial 4.0 International
|
2 |
+
|
3 |
+
=======================================================================
|
4 |
+
|
5 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
6 |
+
does not provide legal services or legal advice. Distribution of
|
7 |
+
Creative Commons public licenses does not create a lawyer-client or
|
8 |
+
other relationship. Creative Commons makes its licenses and related
|
9 |
+
information available on an "as-is" basis. Creative Commons gives no
|
10 |
+
warranties regarding its licenses, any material licensed under their
|
11 |
+
terms and conditions, or any related information. Creative Commons
|
12 |
+
disclaims all liability for damages resulting from their use to the
|
13 |
+
fullest extent possible.
|
14 |
+
|
15 |
+
Using Creative Commons Public Licenses
|
16 |
+
|
17 |
+
Creative Commons public licenses provide a standard set of terms and
|
18 |
+
conditions that creators and other rights holders may use to share
|
19 |
+
original works of authorship and other material subject to copyright
|
20 |
+
and certain other rights specified in the public license below. The
|
21 |
+
following considerations are for informational purposes only, are not
|
22 |
+
exhaustive, and do not form part of our licenses.
|
23 |
+
|
24 |
+
Considerations for licensors: Our public licenses are
|
25 |
+
intended for use by those authorized to give the public
|
26 |
+
permission to use material in ways otherwise restricted by
|
27 |
+
copyright and certain other rights. Our licenses are
|
28 |
+
irrevocable. Licensors should read and understand the terms
|
29 |
+
and conditions of the license they choose before applying it.
|
30 |
+
Licensors should also secure all rights necessary before
|
31 |
+
applying our licenses so that the public can reuse the
|
32 |
+
material as expected. Licensors should clearly mark any
|
33 |
+
material not subject to the license. This includes other CC-
|
34 |
+
licensed material, or material used under an exception or
|
35 |
+
limitation to copyright. More considerations for licensors:
|
36 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
37 |
+
|
38 |
+
Considerations for the public: By using one of our public
|
39 |
+
licenses, a licensor grants the public permission to use the
|
40 |
+
licensed material under specified terms and conditions. If
|
41 |
+
the licensor's permission is not necessary for any reason--for
|
42 |
+
example, because of any applicable exception or limitation to
|
43 |
+
copyright--then that use is not regulated by the license. Our
|
44 |
+
licenses grant only permissions under copyright and certain
|
45 |
+
other rights that a licensor has authority to grant. Use of
|
46 |
+
the licensed material may still be restricted for other
|
47 |
+
reasons, including because others have copyright or other
|
48 |
+
rights in the material. A licensor may make special requests,
|
49 |
+
such as asking that all changes be marked or described.
|
50 |
+
Although not required by our licenses, you are encouraged to
|
51 |
+
respect those requests where reasonable. More considerations
|
52 |
+
for the public:
|
53 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
54 |
+
|
55 |
+
=======================================================================
|
56 |
+
|
57 |
+
Creative Commons Attribution-NonCommercial 4.0 International Public
|
58 |
+
License
|
59 |
+
|
60 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
61 |
+
to be bound by the terms and conditions of this Creative Commons
|
62 |
+
Attribution-NonCommercial 4.0 International Public License ("Public
|
63 |
+
License"). To the extent this Public License may be interpreted as a
|
64 |
+
contract, You are granted the Licensed Rights in consideration of Your
|
65 |
+
acceptance of these terms and conditions, and the Licensor grants You
|
66 |
+
such rights in consideration of benefits the Licensor receives from
|
67 |
+
making the Licensed Material available under these terms and
|
68 |
+
conditions.
|
69 |
+
|
70 |
+
|
71 |
+
Section 1 -- Definitions.
|
72 |
+
|
73 |
+
a. Adapted Material means material subject to Copyright and Similar
|
74 |
+
Rights that is derived from or based upon the Licensed Material
|
75 |
+
and in which the Licensed Material is translated, altered,
|
76 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
77 |
+
permission under the Copyright and Similar Rights held by the
|
78 |
+
Licensor. For purposes of this Public License, where the Licensed
|
79 |
+
Material is a musical work, performance, or sound recording,
|
80 |
+
Adapted Material is always produced where the Licensed Material is
|
81 |
+
synched in timed relation with a moving image.
|
82 |
+
|
83 |
+
b. Adapter's License means the license You apply to Your Copyright
|
84 |
+
and Similar Rights in Your contributions to Adapted Material in
|
85 |
+
accordance with the terms and conditions of this Public License.
|
86 |
+
|
87 |
+
c. Copyright and Similar Rights means copyright and/or similar rights
|
88 |
+
closely related to copyright including, without limitation,
|
89 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
90 |
+
Rights, without regard to how the rights are labeled or
|
91 |
+
categorized. For purposes of this Public License, the rights
|
92 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
93 |
+
Rights.
|
94 |
+
d. Effective Technological Measures means those measures that, in the
|
95 |
+
absence of proper authority, may not be circumvented under laws
|
96 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
97 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
98 |
+
agreements.
|
99 |
+
|
100 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
101 |
+
any other exception or limitation to Copyright and Similar Rights
|
102 |
+
that applies to Your use of the Licensed Material.
|
103 |
+
|
104 |
+
f. Licensed Material means the artistic or literary work, database,
|
105 |
+
or other material to which the Licensor applied this Public
|
106 |
+
License.
|
107 |
+
|
108 |
+
g. Licensed Rights means the rights granted to You subject to the
|
109 |
+
terms and conditions of this Public License, which are limited to
|
110 |
+
all Copyright and Similar Rights that apply to Your use of the
|
111 |
+
Licensed Material and that the Licensor has authority to license.
|
112 |
+
|
113 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
114 |
+
under this Public License.
|
115 |
+
|
116 |
+
i. NonCommercial means not primarily intended for or directed towards
|
117 |
+
commercial advantage or monetary compensation. For purposes of
|
118 |
+
this Public License, the exchange of the Licensed Material for
|
119 |
+
other material subject to Copyright and Similar Rights by digital
|
120 |
+
file-sharing or similar means is NonCommercial provided there is
|
121 |
+
no payment of monetary compensation in connection with the
|
122 |
+
exchange.
|
123 |
+
|
124 |
+
j. Share means to provide material to the public by any means or
|
125 |
+
process that requires permission under the Licensed Rights, such
|
126 |
+
as reproduction, public display, public performance, distribution,
|
127 |
+
dissemination, communication, or importation, and to make material
|
128 |
+
available to the public including in ways that members of the
|
129 |
+
public may access the material from a place and at a time
|
130 |
+
individually chosen by them.
|
131 |
+
|
132 |
+
k. Sui Generis Database Rights means rights other than copyright
|
133 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
134 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
135 |
+
as amended and/or succeeded, as well as other essentially
|
136 |
+
equivalent rights anywhere in the world.
|
137 |
+
|
138 |
+
l. You means the individual or entity exercising the Licensed Rights
|
139 |
+
under this Public License. Your has a corresponding meaning.
|
140 |
+
|
141 |
+
|
142 |
+
Section 2 -- Scope.
|
143 |
+
|
144 |
+
a. License grant.
|
145 |
+
|
146 |
+
1. Subject to the terms and conditions of this Public License,
|
147 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
148 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
149 |
+
exercise the Licensed Rights in the Licensed Material to:
|
150 |
+
|
151 |
+
a. reproduce and Share the Licensed Material, in whole or
|
152 |
+
in part, for NonCommercial purposes only; and
|
153 |
+
|
154 |
+
b. produce, reproduce, and Share Adapted Material for
|
155 |
+
NonCommercial purposes only.
|
156 |
+
|
157 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
158 |
+
Exceptions and Limitations apply to Your use, this Public
|
159 |
+
License does not apply, and You do not need to comply with
|
160 |
+
its terms and conditions.
|
161 |
+
|
162 |
+
3. Term. The term of this Public License is specified in Section
|
163 |
+
6(a).
|
164 |
+
|
165 |
+
4. Media and formats; technical modifications allowed. The
|
166 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
167 |
+
all media and formats whether now known or hereafter created,
|
168 |
+
and to make technical modifications necessary to do so. The
|
169 |
+
Licensor waives and/or agrees not to assert any right or
|
170 |
+
authority to forbid You from making technical modifications
|
171 |
+
necessary to exercise the Licensed Rights, including
|
172 |
+
technical modifications necessary to circumvent Effective
|
173 |
+
Technological Measures. For purposes of this Public License,
|
174 |
+
simply making modifications authorized by this Section 2(a)
|
175 |
+
(4) never produces Adapted Material.
|
176 |
+
|
177 |
+
5. Downstream recipients.
|
178 |
+
|
179 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
180 |
+
recipient of the Licensed Material automatically
|
181 |
+
receives an offer from the Licensor to exercise the
|
182 |
+
Licensed Rights under the terms and conditions of this
|
183 |
+
Public License.
|
184 |
+
|
185 |
+
b. No downstream restrictions. You may not offer or impose
|
186 |
+
any additional or different terms or conditions on, or
|
187 |
+
apply any Effective Technological Measures to, the
|
188 |
+
Licensed Material if doing so restricts exercise of the
|
189 |
+
Licensed Rights by any recipient of the Licensed
|
190 |
+
Material.
|
191 |
+
|
192 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
193 |
+
may be construed as permission to assert or imply that You
|
194 |
+
are, or that Your use of the Licensed Material is, connected
|
195 |
+
with, or sponsored, endorsed, or granted official status by,
|
196 |
+
the Licensor or others designated to receive attribution as
|
197 |
+
provided in Section 3(a)(1)(A)(i).
|
198 |
+
|
199 |
+
b. Other rights.
|
200 |
+
|
201 |
+
1. Moral rights, such as the right of integrity, are not
|
202 |
+
licensed under this Public License, nor are publicity,
|
203 |
+
privacy, and/or other similar personality rights; however, to
|
204 |
+
the extent possible, the Licensor waives and/or agrees not to
|
205 |
+
assert any such rights held by the Licensor to the limited
|
206 |
+
extent necessary to allow You to exercise the Licensed
|
207 |
+
Rights, but not otherwise.
|
208 |
+
|
209 |
+
2. Patent and trademark rights are not licensed under this
|
210 |
+
Public License.
|
211 |
+
|
212 |
+
3. To the extent possible, the Licensor waives any right to
|
213 |
+
collect royalties from You for the exercise of the Licensed
|
214 |
+
Rights, whether directly or through a collecting society
|
215 |
+
under any voluntary or waivable statutory or compulsory
|
216 |
+
licensing scheme. In all other cases the Licensor expressly
|
217 |
+
reserves any right to collect such royalties, including when
|
218 |
+
the Licensed Material is used other than for NonCommercial
|
219 |
+
purposes.
|
220 |
+
|
221 |
+
|
222 |
+
Section 3 -- License Conditions.
|
223 |
+
|
224 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
225 |
+
following conditions.
|
226 |
+
|
227 |
+
a. Attribution.
|
228 |
+
|
229 |
+
1. If You Share the Licensed Material (including in modified
|
230 |
+
form), You must:
|
231 |
+
|
232 |
+
a. retain the following if it is supplied by the Licensor
|
233 |
+
with the Licensed Material:
|
234 |
+
|
235 |
+
i. identification of the creator(s) of the Licensed
|
236 |
+
Material and any others designated to receive
|
237 |
+
attribution, in any reasonable manner requested by
|
238 |
+
the Licensor (including by pseudonym if
|
239 |
+
designated);
|
240 |
+
|
241 |
+
ii. a copyright notice;
|
242 |
+
|
243 |
+
iii. a notice that refers to this Public License;
|
244 |
+
|
245 |
+
iv. a notice that refers to the disclaimer of
|
246 |
+
warranties;
|
247 |
+
|
248 |
+
v. a URI or hyperlink to the Licensed Material to the
|
249 |
+
extent reasonably practicable;
|
250 |
+
|
251 |
+
b. indicate if You modified the Licensed Material and
|
252 |
+
retain an indication of any previous modifications; and
|
253 |
+
|
254 |
+
c. indicate the Licensed Material is licensed under this
|
255 |
+
Public License, and include the text of, or the URI or
|
256 |
+
hyperlink to, this Public License.
|
257 |
+
|
258 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
259 |
+
reasonable manner based on the medium, means, and context in
|
260 |
+
which You Share the Licensed Material. For example, it may be
|
261 |
+
reasonable to satisfy the conditions by providing a URI or
|
262 |
+
hyperlink to a resource that includes the required
|
263 |
+
information.
|
264 |
+
|
265 |
+
3. If requested by the Licensor, You must remove any of the
|
266 |
+
information required by Section 3(a)(1)(A) to the extent
|
267 |
+
reasonably practicable.
|
268 |
+
|
269 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
270 |
+
License You apply must not prevent recipients of the Adapted
|
271 |
+
Material from complying with this Public License.
|
272 |
+
|
273 |
+
|
274 |
+
Section 4 -- Sui Generis Database Rights.
|
275 |
+
|
276 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
277 |
+
apply to Your use of the Licensed Material:
|
278 |
+
|
279 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
280 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
281 |
+
portion of the contents of the database for NonCommercial purposes
|
282 |
+
only;
|
283 |
+
|
284 |
+
b. if You include all or a substantial portion of the database
|
285 |
+
contents in a database in which You have Sui Generis Database
|
286 |
+
Rights, then the database in which You have Sui Generis Database
|
287 |
+
Rights (but not its individual contents) is Adapted Material; and
|
288 |
+
|
289 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
290 |
+
all or a substantial portion of the contents of the database.
|
291 |
+
|
292 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
293 |
+
replace Your obligations under this Public License where the Licensed
|
294 |
+
Rights include other Copyright and Similar Rights.
|
295 |
+
|
296 |
+
|
297 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
298 |
+
|
299 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
300 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
301 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
302 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
303 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
304 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
305 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
306 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
307 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
308 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
309 |
+
|
310 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
311 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
312 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
313 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
314 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
315 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
316 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
317 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
318 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
319 |
+
|
320 |
+
c. The disclaimer of warranties and limitation of liability provided
|
321 |
+
above shall be interpreted in a manner that, to the extent
|
322 |
+
possible, most closely approximates an absolute disclaimer and
|
323 |
+
waiver of all liability.
|
324 |
+
|
325 |
+
|
326 |
+
Section 6 -- Term and Termination.
|
327 |
+
|
328 |
+
a. This Public License applies for the term of the Copyright and
|
329 |
+
Similar Rights licensed here. However, if You fail to comply with
|
330 |
+
this Public License, then Your rights under this Public License
|
331 |
+
terminate automatically.
|
332 |
+
|
333 |
+
b. Where Your right to use the Licensed Material has terminated under
|
334 |
+
Section 6(a), it reinstates:
|
335 |
+
|
336 |
+
1. automatically as of the date the violation is cured, provided
|
337 |
+
it is cured within 30 days of Your discovery of the
|
338 |
+
violation; or
|
339 |
+
|
340 |
+
2. upon express reinstatement by the Licensor.
|
341 |
+
|
342 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
343 |
+
right the Licensor may have to seek remedies for Your violations
|
344 |
+
of this Public License.
|
345 |
+
|
346 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
347 |
+
Licensed Material under separate terms or conditions or stop
|
348 |
+
distributing the Licensed Material at any time; however, doing so
|
349 |
+
will not terminate this Public License.
|
350 |
+
|
351 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
352 |
+
License.
|
353 |
+
|
354 |
+
|
355 |
+
Section 7 -- Other Terms and Conditions.
|
356 |
+
|
357 |
+
a. The Licensor shall not be bound by any additional or different
|
358 |
+
terms or conditions communicated by You unless expressly agreed.
|
359 |
+
|
360 |
+
b. Any arrangements, understandings, or agreements regarding the
|
361 |
+
Licensed Material not stated herein are separate from and
|
362 |
+
independent of the terms and conditions of this Public License.
|
363 |
+
|
364 |
+
|
365 |
+
Section 8 -- Interpretation.
|
366 |
+
|
367 |
+
a. For the avoidance of doubt, this Public License does not, and
|
368 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
369 |
+
conditions on any use of the Licensed Material that could lawfully
|
370 |
+
be made without permission under this Public License.
|
371 |
+
|
372 |
+
b. To the extent possible, if any provision of this Public License is
|
373 |
+
deemed unenforceable, it shall be automatically reformed to the
|
374 |
+
minimum extent necessary to make it enforceable. If the provision
|
375 |
+
cannot be reformed, it shall be severed from this Public License
|
376 |
+
without affecting the enforceability of the remaining terms and
|
377 |
+
conditions.
|
378 |
+
|
379 |
+
c. No term or condition of this Public License will be waived and no
|
380 |
+
failure to comply consented to unless expressly agreed to by the
|
381 |
+
Licensor.
|
382 |
+
|
383 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
384 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
385 |
+
that apply to the Licensor or You, including from the legal
|
386 |
+
processes of any jurisdiction or authority.
|
387 |
+
|
388 |
+
=======================================================================
|
389 |
+
|
390 |
+
Creative Commons is not a party to its public
|
391 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
392 |
+
its public licenses to material it publishes and in those instances
|
393 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
394 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
395 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
396 |
+
material is shared under a Creative Commons public license or as
|
397 |
+
otherwise permitted by the Creative Commons policies published at
|
398 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
399 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
400 |
+
of Creative Commons without its prior written consent including,
|
401 |
+
without limitation, in connection with any unauthorized modifications
|
402 |
+
to any of its public licenses or any other arrangements,
|
403 |
+
understandings, or agreements concerning use of licensed material. For
|
404 |
+
the avoidance of doubt, this paragraph does not form part of the
|
405 |
+
public licenses.
|
406 |
+
|
407 |
+
Creative Commons may be contacted at creativecommons.org.
|
WizardCoder/MODEL_WEIGHTS_LICENSE
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
BigCode Open RAIL-M v1 License Agreement
|
2 |
+
Section I: Preamble
|
3 |
+
This OpenRAIL-M License Agreement was created under BigCode, an open and collaborative research project aimed at the responsible development and Use of Large Language Models (“LLMs”) for code generation. This license is generally applicable to any machine-learning Model.
|
4 |
+
|
5 |
+
This License Agreement strives for both the open and responsible Use of the accompanying Model. Openness here is understood as enabling users of the Model on a royalty free basis to Use it, modify it, and even share commercial versions of it. Use restrictions are included to prevent misuse of the Model.
|
6 |
+
|
7 |
+
This License Agreement governs the Use of the Model and Modifications of the Model. You and Licensor agree as follows:
|
8 |
+
|
9 |
+
1.Definitions
|
10 |
+
|
11 |
+
a. “Contribution” means any work of authorship, including the original version of the Model and any Modifications of the Model that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
|
12 |
+
|
13 |
+
b. “Contributor” means Licensor and any individual or entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
|
14 |
+
|
15 |
+
c. “Data” means a collection of information 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 Agreement.
|
16 |
+
|
17 |
+
d. “Explanatory Documentation” means model cards, data cards, or any other similar documentation or related information dedicated to inform the public about the characteristics of the model. Explanatory documentation is not licensed under this license.
|
18 |
+
|
19 |
+
e. “Harm” includes but is not limited to physical, mental, psychological, financial and reputational damage, pain, or loss.
|
20 |
+
|
21 |
+
f. “License Agreement” means this document.
|
22 |
+
|
23 |
+
g. “Licensor” means the rights owners or entity authorized by the rights owners that are granting the terms and conditions of this License Agreement.
|
24 |
+
|
25 |
+
h. “Model” means machine-learning based assemblies (including checkpoints), consisting of learnt weights and parameters (including optimizer states), corresponding to a model architecture as embodied in source code. Source code is not licensed under this License Agreement.
|
26 |
+
|
27 |
+
i. “Modifications of the Model” means all changes to 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.
|
28 |
+
|
29 |
+
j. “Output” means the results of operating the Model.
|
30 |
+
|
31 |
+
k. “Share” means any transmission, reproduction, publication or other sharing of the Model or Modifications of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means, including - but not limited to - API-based or web access.
|
32 |
+
|
33 |
+
l. “Third Parties” means individuals or legal entities that are not under common control with Licensor or You.
|
34 |
+
|
35 |
+
m. “Use” includes - but is not limited to - generating any Output, fine tuning, updating, running, training, evaluating and/or reparametrizing the Model.
|
36 |
+
|
37 |
+
n. “You” (or “Your”) means an individual or Legal Entity exercising permissions granted by this License Agreement and/or making Use of the Model for whichever purpose and in any field of Use.
|
38 |
+
|
39 |
+
Section II: INTELLECTUAL PROPERTY RIGHTS
|
40 |
+
The Model and Modifications of the Model are subject to additional terms as described in Section III, which shall govern the Use of the Model and Modifications of the Model.
|
41 |
+
|
42 |
+
Grant of Copyright license. Subject to the terms and conditions of this License Agreement and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, copyright license to reproduce, prepare, publicly display, publicly perform, sublicense under the terms herein, and distribute the Model and Modifications of the Model.
|
43 |
+
Grant of Patent license. Subject to the terms and conditions of this License Agreement and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free patent license to make, have made, Use, offer to sell, sell, import, and otherwise transfer the Model, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model or a Contribution incorporated within the Model constitutes direct or contributory patent infringement, then any rights granted to You under this License Agreement for the Model shall terminate as of the date such litigation is filed.
|
44 |
+
Section III: CONDITIONS OF USE
|
45 |
+
4. Use conditions. Compliance with the restrictions in Attachment A is a condition to the grants in this License Agreement. If You Use the Model, You agree not to Use it for the specified restricted uses set forth in Attachment A.
|
46 |
+
|
47 |
+
5. Sharing of the Model
|
48 |
+
|
49 |
+
5.1. You may Share the Model or Modifications of the Model under any license of your choice that does not contradict the restrictions in Attachment A of this License Agreement and includes:
|
50 |
+
|
51 |
+
a. Paragraph 4 and the restrictions in Attachment A of this License Agreement, or,
|
52 |
+
|
53 |
+
b. Use conditions similar to Paragraph 4 that must accomplish the same purpose as the use conditions in Paragraph 4 and a similar set of restrictions to those in Attachment A that must accomplish the same purpose as the restrictions in Attachment A.
|
54 |
+
|
55 |
+
5.2. When You Share the Model or Modifications of the Model, You agree to:
|
56 |
+
|
57 |
+
a. Give any recipients a copy of this License Agreement;
|
58 |
+
|
59 |
+
b. Retain all Explanatory Documentation; and if sharing Modifications of the Model, add Explanatory Documentation of the same or better quality documenting the changes made to create the Modifications of the Model; and
|
60 |
+
|
61 |
+
c. Retain all copyright, patent, trademark, and attribution notices.
|
62 |
+
|
63 |
+
6. The Output You Generate. Licensor claims no rights in the Output. You agree not to contravene any provision as stated in the License Agreement with your Use of the Output.
|
64 |
+
|
65 |
+
Section IV: OTHER PROVISIONS
|
66 |
+
7. Updates and Runtime Restrictions. Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License Agreement.
|
67 |
+
|
68 |
+
8. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Model by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
69 |
+
|
70 |
+
9. Trademarks and related. Nothing in this License Agreement permits You to make Use of Licensors’ 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 the Licensors.
|
71 |
+
|
72 |
+
10. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model (and each Contributor provides its Contributions) 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 sharing the Model and Modifications of the Model, and assume any risks associated with Your exercise of permissions under this License Agreement.
|
73 |
+
|
74 |
+
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 any Contributor 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 Agreement or out of the Use or inability to Use the Model (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, model failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
75 |
+
|
76 |
+
12. Accepting Warranty or Additional Liability. While sharing the Model or Modifications of the Model 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 Agreement. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
77 |
+
|
78 |
+
13. This License Agreement is a license of copyright and patent rights and an agreement in contract between You and the Licensor. If any provision of this License Agreement 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.
|
79 |
+
|
80 |
+
END OF TERMS AND CONDITIONS
|
81 |
+
|
82 |
+
Attachment A - USE RESTRICTIONS
|
83 |
+
You agree not to Use the Model or Modifications of the Model:
|
84 |
+
|
85 |
+
(a) In any way that violates any applicable national, federal, state, local or international law or regulation;
|
86 |
+
|
87 |
+
(b) For the purpose of exploiting, Harming or attempting to exploit or harm minors in any way;
|
88 |
+
|
89 |
+
(c) To generate and/or disseminate malware (including - but not limited to - ransomware) or any other content to be used for the purpose of Harming electronic systems;
|
90 |
+
|
91 |
+
(d) To generate or disseminate verifiably false information and/or content with the purpose of Harming others;
|
92 |
+
|
93 |
+
(e) To generate or disseminate personal identifiable information with the purpose of Harming others;
|
94 |
+
|
95 |
+
(f) To generate or disseminate information (including - but not limited to - images, code, posts, articles), and place the information in any public context (including - but not limited to - bot generating tweets) without expressly and intelligibly disclaiming that the information and/or content is machine generated;
|
96 |
+
|
97 |
+
(g) To intentionally defame, disparage or otherwise harass others;
|
98 |
+
|
99 |
+
(h) To impersonate or attempt to impersonate human beings for purposes of deception;
|
100 |
+
|
101 |
+
(i) For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation without expressly and intelligibly disclaiming that the creation or modification of the obligation is machine generated;
|
102 |
+
|
103 |
+
(j) For any Use intended to discriminate against or Harm individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
|
104 |
+
|
105 |
+
(k) To intentionally 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;
|
106 |
+
|
107 |
+
(l) For any Use intended to discriminate against individuals or groups based on legally protected characteristics or categories;
|
108 |
+
|
109 |
+
(m) To provide medical advice or medical results interpretation that is intended to be a substitute for professional medical advice, diagnosis, or treatment;
|
110 |
+
|
111 |
+
(n) For fully automated decision making in administration of justice, law enforcement, immigration or asylum processes.
|
WizardCoder/README.md
ADDED
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# WizardCoder: Empowering Code Large Language Models with Evol-Instruct
|
2 |
+
|
3 |
+
[](CODE_LICENSE)
|
4 |
+
[](DATA_LICENSE)
|
5 |
+
<!-- [](MODEL_WEIGHTS_LICENSE) -->
|
6 |
+
[](https://www.python.org/downloads/release/python-390/)
|
7 |
+
|
8 |
+
To develop our WizardCoder model, we begin by adapting the Evol-Instruct method specifically for coding tasks. This involves tailoring the prompt to the domain of code-related instructions. Subsequently, we fine-tune the Code LLMs, StarCoder or Code LLama, utilizing the newly created instruction-following training set.
|
9 |
+
|
10 |
+
## News
|
11 |
+
|
12 |
+
- 🔥🔥🔥[2023/08/26] We released **WizardCoder-Python-34B-V1.0** , which achieves the **73.2 pass@1** and surpasses **GPT4 (2023/03/15)**, **ChatGPT-3.5**, and **Claude2** on the [HumanEval Benchmarks](https://github.com/openai/human-eval).
|
13 |
+
- [2023/06/16] We released **WizardCoder-15B-V1.0** , which achieves the **57.3 pass@1** and surpasses **Claude-Plus (+6.8)**, **Bard (+15.3)** and **InstructCodeT5+ (+22.3)** on the [HumanEval Benchmarks](https://github.com/openai/human-eval).
|
14 |
+
|
15 |
+
❗Note: There are two HumanEval results of GPT4 and ChatGPT-3.5. The 67.0 and 48.1 are reported by the official GPT4 Report (2023/03/15) of [OpenAI](https://arxiv.org/abs/2303.08774). The 82.0 and 72.5 are tested by ourselves with the latest API (2023/08/26).
|
16 |
+
|
17 |
+
|
18 |
+
| Model | Checkpoint | Paper | HumanEval | MBPP | Demo | License |
|
19 |
+
| ----- |------| ---- |------|-------| ----- | ----- |
|
20 |
+
| WizardCoder-Python-34B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardCoder-Python-34B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2306.08568" target="_blank">[WizardCoder]</a> | 73.2 | 61.2 | [Demo](http://47.103.63.15:50085/) | <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/" target="_blank">Llama2</a> |
|
21 |
+
| WizardCoder-15B-V1.0 | 🤗 <a href="https://huggingface.co/WizardLM/WizardCoder-15B-V1.0" target="_blank">HF Link</a> | 📃 <a href="https://arxiv.org/abs/2306.08568" target="_blank">[WizardCoder]</a> | 59.8 |50.6 | -- | <a href="https://huggingface.co/spaces/bigcode/bigcode-model-license-agreement" target="_blank">OpenRAIL-M</a> |
|
22 |
+
|
23 |
+
- 📣 Please refer to our Twitter account https://twitter.com/WizardLM_AI and HuggingFace Repo https://huggingface.co/WizardLM . We will use them to announce any new release at the 1st time.
|
24 |
+
|
25 |
+
## Comparing WizardCoder-Python-34B-V1.0 with Other LLMs.
|
26 |
+
|
27 |
+
🔥 The following figure shows that our **WizardCoder-Python-34B-V1.0 attains the second position in this benchmark**, surpassing GPT4 (2023/03/15, 73.2 vs. 67.0), ChatGPT-3.5 (73.2 vs. 72.5) and Claude2 (73.2 vs. 71.2).
|
28 |
+
|
29 |
+
<p align="center" width="100%">
|
30 |
+
<a ><img src="imgs/compare_sota.png" alt="WizardCoder" style="width: 96%; min-width: 300px; display: block; margin: auto;"></a>
|
31 |
+
</p>
|
32 |
+
|
33 |
+
❗❗❗**Note: This performance is 100% reproducible! If you cannot reproduce it, please follow the steps in [Evaluation](#evaluation).**
|
34 |
+
|
35 |
+
❗Note: There are two HumanEval results of GPT4 and ChatGPT-3.5. The 67.0 and 48.1 are reported by the official GPT4 Report (2023/03/15) of [OpenAI](https://arxiv.org/abs/2303.08774). The 82.0 and 72.5 are tested by ourselves with the latest API (2023/08/26).
|
36 |
+
|
37 |
+
## Comparing WizardCoder-15B-V1.0 with the Closed-Source Models.
|
38 |
+
|
39 |
+
🔥 The following figure shows that our **WizardCoder attains the third position in this benchmark**, surpassing Claude-Plus (59.8 vs. 53.0) and Bard (59.8 vs. 44.5). Notably, our model exhibits a substantially smaller size compared to these models.
|
40 |
+
|
41 |
+
<p align="center" width="100%">
|
42 |
+
<a ><img src="imgs/pass1.png" alt="WizardCoder" style="width: 86%; min-width: 300px; display: block; margin: auto;"></a>
|
43 |
+
</p>
|
44 |
+
|
45 |
+
❗❗❗**Note: This performance is 100% reproducible! If you cannot reproduce it, please follow the steps in [Evaluation](#evaluation).**
|
46 |
+
|
47 |
+
❗**Note: In this study, we copy the scores for HumanEval and HumanEval+ from the [LLM-Humaneval-Benchmarks](https://github.com/my-other-github-account/llm-humaneval-benchmarks). Notably, all the mentioned models generate code solutions for each problem utilizing a **single attempt**, and the resulting pass rate percentage is reported. Our **WizardCoder** generates answers using greedy decoding and tests with the same [code](https://github.com/evalplus/evalplus).**
|
48 |
+
|
49 |
+
## Comparing WizardCoder-15B-V1.0 with the Open-Source Models.
|
50 |
+
|
51 |
+
The following table clearly demonstrates that our **WizardCoder** exhibits a substantial performance advantage over all the open-source models. ❗**If you are confused with the different scores of our model (57.3 and 59.8), please check the Notes.**
|
52 |
+
|
53 |
+
|
54 |
+
| Model | HumanEval Pass@1 | MBPP Pass@1 |
|
55 |
+
|------------------|------------------|-------------|
|
56 |
+
| CodeGen-16B-Multi| 18.3 |20.9 |
|
57 |
+
| CodeGeeX | 22.9 |24.4 |
|
58 |
+
| LLaMA-33B | 21.7 |30.2 |
|
59 |
+
| LLaMA-65B | 23.7 |37.7 |
|
60 |
+
| PaLM-540B | 26.2 |36.8 |
|
61 |
+
| PaLM-Coder-540B | 36.0 |47.0 |
|
62 |
+
| PaLM 2-S | 37.6 |50.0 |
|
63 |
+
| CodeGen-16B-Mono | 29.3 |35.3 |
|
64 |
+
| Code-Cushman-001 | 33.5 |45.9 |
|
65 |
+
| StarCoder-15B | 33.6 |43.6* |
|
66 |
+
| InstructCodeT5+ | 35.0 |-- |
|
67 |
+
| WizardLM-30B 1.0| 37.8 |-- |
|
68 |
+
| WizardCoder-15B 1.0 | **57.3** |**51.8** |
|
69 |
+
|
70 |
+
❗**Note: The reproduced result of StarCoder on MBPP.**
|
71 |
+
|
72 |
+
❗**Note: The above table conducts a comprehensive comparison of our **WizardCoder** with other models on the HumanEval and MBPP benchmarks. We adhere to the approach outlined in previous studies by generating **20 samples** for each problem to estimate the pass@1 score and evaluate with the same [code](https://github.com/openai/human-eval/tree/master). The scores of GPT4 and GPT3.5 reported by [OpenAI](https://openai.com/research/gpt-4) are 67.0 and 48.1 (maybe these are the early version GPT4&3.5).**
|
73 |
+
|
74 |
+
## Call for Feedbacks
|
75 |
+
We welcome everyone to use your professional and difficult instructions to evaluate WizardCoder, and show us examples of poor performance and your suggestions in the [issue discussion](https://github.com/nlpxucan/WizardLM/issues) area. We are focusing on improving the Evol-Instruct now and hope to relieve existing weaknesses and issues in the the next version of WizardCoder. After that, we will open the code and pipeline of up-to-date Evol-Instruct algorithm and work with you together to improve it.
|
76 |
+
|
77 |
+
## Unofficial Video Introductions
|
78 |
+
Thanks to the enthusiastic friends, their video introductions are more lively and interesting.
|
79 |
+
1. [WizardCoder AI Is The NEW ChatGPT's Coding TWIN!](https://www.youtube.com/watch?v=XjsyHrmd3Xo)
|
80 |
+
|
81 |
+
## Contents
|
82 |
+
|
83 |
+
1. [Online Demo](#online-demo)
|
84 |
+
|
85 |
+
2. [Fine-tuning](#fine-tuning)
|
86 |
+
|
87 |
+
3. [Inference](#inference)
|
88 |
+
|
89 |
+
4. [Evaluation](#evaluation)
|
90 |
+
|
91 |
+
5. [Citation](#citation)
|
92 |
+
|
93 |
+
6. [Disclaimer](#disclaimer)
|
94 |
+
|
95 |
+
## Online Demo
|
96 |
+
|
97 |
+
We will provide our latest models for you to try for as long as possible. If you find a link is not working, please try another one. At the same time, please try as many **real-world** and **challenging** code-related problems that you encounter in your work and life as possible. We will continue to evolve our models with your feedbacks.
|
98 |
+
|
99 |
+
[Demo Link](https://e5eaf7d09cc1521c.gradio.app/) (We adopt the greedy decoding now.)
|
100 |
+
|
101 |
+
## Fine-tuning
|
102 |
+
|
103 |
+
We fine-tune WizardCoder using the modified code `train.py` from [Llama-X](https://github.com/AetherCortex/Llama-X).
|
104 |
+
We fine-tune StarCoder-15B with the following hyperparameters:
|
105 |
+
|
106 |
+
| Hyperparameter | StarCoder-15B |
|
107 |
+
|----------------|---------------|
|
108 |
+
| Batch size | 512 |
|
109 |
+
| Learning rate | 2e-5 |
|
110 |
+
| Epochs | 3 |
|
111 |
+
| Max length | 2048 |
|
112 |
+
| Warmup step | 30 |
|
113 |
+
| LR scheduler | cosine |
|
114 |
+
|
115 |
+
To reproduce our fine-tuning of WizardCoder, please follow the following steps:
|
116 |
+
1. According to the instructions of [Llama-X](https://github.com/AetherCortex/Llama-X), install the environment, download the training code, and deploy. (Note: `deepspeed==0.9.2` and `transformers==4.29.2`)
|
117 |
+
2. Replace the `train.py` with the `train_wizardcoder.py` in our repo (`src/train_wizardcoder.py`)
|
118 |
+
3. Login Huggingface:
|
119 |
+
```bash
|
120 |
+
huggingface-cli login
|
121 |
+
```
|
122 |
+
4. Execute the following training command:
|
123 |
+
```bash
|
124 |
+
deepspeed train_wizardcoder.py \
|
125 |
+
--model_name_or_path "bigcode/starcoder" \
|
126 |
+
--data_path "/your/path/to/code_instruction_data.json" \
|
127 |
+
--output_dir "/your/path/to/ckpt" \
|
128 |
+
--num_train_epochs 3 \
|
129 |
+
--model_max_length 2048 \
|
130 |
+
--per_device_train_batch_size 16 \
|
131 |
+
--per_device_eval_batch_size 1 \
|
132 |
+
--gradient_accumulation_steps 4 \
|
133 |
+
--evaluation_strategy "no" \
|
134 |
+
--save_strategy "steps" \
|
135 |
+
--save_steps 50 \
|
136 |
+
--save_total_limit 2 \
|
137 |
+
--learning_rate 2e-5 \
|
138 |
+
--warmup_steps 30 \
|
139 |
+
--logging_steps 2 \
|
140 |
+
--lr_scheduler_type "cosine" \
|
141 |
+
--report_to "tensorboard" \
|
142 |
+
--gradient_checkpointing True \
|
143 |
+
--deepspeed configs/deepspeed_config.json \
|
144 |
+
--fp16 True
|
145 |
+
```
|
146 |
+
|
147 |
+
## Inference
|
148 |
+
|
149 |
+
We provide the decoding script for WizardCoder, which reads a input file and generates corresponding responses for each sample, and finally consolidates them into an output file.
|
150 |
+
|
151 |
+
You can specify `base_model`, `input_data_path` and `output_data_path` in `src\inference_wizardcoder.py` to set the decoding model, path of input file and path of output file.
|
152 |
+
|
153 |
+
```bash
|
154 |
+
pip install jsonlines
|
155 |
+
```
|
156 |
+
|
157 |
+
The decoding command is:
|
158 |
+
```
|
159 |
+
python src\inference_wizardcoder.py \
|
160 |
+
--base_model "/your/path/to/ckpt" \
|
161 |
+
--input_data_path "/your/path/to/input/data.jsonl" \
|
162 |
+
--output_data_path "/your/path/to/output/result.jsonl"
|
163 |
+
```
|
164 |
+
|
165 |
+
The format of `data.jsonl` should be:
|
166 |
+
```
|
167 |
+
{"idx": 11, "Instruction": "Write a Python code to count 1 to 10."}
|
168 |
+
{"idx": 12, "Instruction": "Write a Java code to sum 1 to 10."}
|
169 |
+
```
|
170 |
+
|
171 |
+
The prompt for our WizardCoder in `src\inference_wizardcoder.py` is:
|
172 |
+
```
|
173 |
+
Below is an instruction that describes a task. Write a response that appropriately completes the request.
|
174 |
+
|
175 |
+
### Instruction:
|
176 |
+
{instruction}
|
177 |
+
|
178 |
+
### Response:
|
179 |
+
```
|
180 |
+
|
181 |
+
## Evaluation
|
182 |
+
|
183 |
+
### HumanEval
|
184 |
+
|
185 |
+
1. According to the instructions of [HumanEval](https://github.com/openai/human-eval), install the environment.
|
186 |
+
2. Run the following scripts to generate the answer.
|
187 |
+
|
188 |
+
- (1) For WizardCoder-15B-V1.0 (base on StarCoder)
|
189 |
+
```bash
|
190 |
+
model="/path/to/your/model"
|
191 |
+
temp=0.2
|
192 |
+
max_len=2048
|
193 |
+
pred_num=200
|
194 |
+
num_seqs_per_iter=2
|
195 |
+
|
196 |
+
output_path=preds/T${temp}_N${pred_num}
|
197 |
+
|
198 |
+
mkdir -p ${output_path}
|
199 |
+
echo 'Output path: '$output_path
|
200 |
+
echo 'Model to eval: '$model
|
201 |
+
|
202 |
+
# 164 problems, 21 per GPU if GPU=8
|
203 |
+
index=0
|
204 |
+
gpu_num=8
|
205 |
+
for ((i = 0; i < $gpu_num; i++)); do
|
206 |
+
start_index=$((i * 21))
|
207 |
+
end_index=$(((i + 1) * 21))
|
208 |
+
|
209 |
+
gpu=$((i))
|
210 |
+
echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
|
211 |
+
((index++))
|
212 |
+
(
|
213 |
+
CUDA_VISIBLE_DEVICES=$gpu python humaneval_gen.py --model ${model} \
|
214 |
+
--start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
|
215 |
+
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path}
|
216 |
+
) &
|
217 |
+
if (($index % $gpu_num == 0)); then wait; fi
|
218 |
+
done
|
219 |
+
```
|
220 |
+
|
221 |
+
- (2) For WizardCoder-Python-34B-V1.0 (base on CodeLLama)
|
222 |
+
|
223 |
+
```bash
|
224 |
+
pip install vllm # This can acclerate the inference process a lot.
|
225 |
+
pip install transformers==4.31.0
|
226 |
+
|
227 |
+
model="/path/to/your/model"
|
228 |
+
temp=0.2
|
229 |
+
max_len=2048
|
230 |
+
pred_num=200
|
231 |
+
num_seqs_per_iter=2
|
232 |
+
|
233 |
+
output_path=preds/T${temp}_N${pred_num}
|
234 |
+
|
235 |
+
mkdir -p ${output_path}
|
236 |
+
echo 'Output path: '$output_path
|
237 |
+
echo 'Model to eval: '$model
|
238 |
+
|
239 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3 python humaneval_gen_vllm.py --model ${model} \
|
240 |
+
--start_index 0 --end_index 164 --temperature ${temp} \
|
241 |
+
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --num_gpus 4
|
242 |
+
```
|
243 |
+
|
244 |
+
3. Run the post processing code `src/process_humaneval.py` to collect the code completions from all answer files.
|
245 |
+
```bash
|
246 |
+
output_path=preds/T${temp}_N${pred_num}
|
247 |
+
|
248 |
+
echo 'Output path: '$output_path
|
249 |
+
python process_humaneval.py --path ${output_path} --out_path ${output_path}.jsonl --add_prompt
|
250 |
+
|
251 |
+
evaluate_functional_correctness ${output_path}.jsonl
|
252 |
+
```
|
253 |
+
|
254 |
+
### How to Reproduce the 59.8 Pass@1 on HumanEval with Greedy Decoding?
|
255 |
+
|
256 |
+
❗❗❗**This performance is 100% reproducible!**
|
257 |
+
|
258 |
+
Run the following script to generate the answer with greedy decoding. Then follow the above steps 2 and 3 to get the evaluation result.
|
259 |
+
|
260 |
+
❗We also provide the generated codes in `data/humaneval.59.8.gen.zip`
|
261 |
+
|
262 |
+
```bash
|
263 |
+
model="WizardLM/WizardCoder-15B-V1.0"
|
264 |
+
temp=0.0
|
265 |
+
max_len=2048
|
266 |
+
pred_num=1
|
267 |
+
num_seqs_per_iter=1
|
268 |
+
|
269 |
+
output_path=preds/T${temp}_N${pred_num}_WizardCoder_Greedy_Decode
|
270 |
+
|
271 |
+
mkdir -p ${output_path}
|
272 |
+
echo 'Output path: '$output_path
|
273 |
+
echo 'Model to eval: '$model
|
274 |
+
|
275 |
+
# 164 problems, 21 per GPU if GPU=8
|
276 |
+
index=0
|
277 |
+
gpu_num=8
|
278 |
+
for ((i = 0; i < $gpu_num; i++)); do
|
279 |
+
start_index=$((i * 21))
|
280 |
+
end_index=$(((i + 1) * 21))
|
281 |
+
|
282 |
+
gpu=$((i))
|
283 |
+
echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
|
284 |
+
((index++))
|
285 |
+
(
|
286 |
+
CUDA_VISIBLE_DEVICES=$gpu python humaneval_gen.py --model ${model} \
|
287 |
+
--start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
|
288 |
+
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --greedy_decode
|
289 |
+
) &
|
290 |
+
if (($index % $gpu_num == 0)); then wait; fi
|
291 |
+
done
|
292 |
+
```
|
293 |
+
|
294 |
+
### MBPP
|
295 |
+
|
296 |
+
1. Run the following script to generate the answer.
|
297 |
+
```bash
|
298 |
+
model="/path/to/your/model"
|
299 |
+
temp=0.2
|
300 |
+
max_len=2048
|
301 |
+
pred_num=200
|
302 |
+
num_seqs_per_iter=2
|
303 |
+
|
304 |
+
output_path=preds/MBPP_T${temp}_N${pred_num}
|
305 |
+
mbpp_path=data/mbpp.test.jsonl # we provide this file in data/mbpp.test.zip
|
306 |
+
|
307 |
+
mkdir -p ${output_path}
|
308 |
+
echo 'Output path: '$output_path
|
309 |
+
echo 'Model to eval: '$model
|
310 |
+
|
311 |
+
# 500 problems, 63 per GPU if GPU=8
|
312 |
+
index=0
|
313 |
+
gpu_num=8
|
314 |
+
for ((i = 0; i < $gpu_num; i++)); do
|
315 |
+
start_index=$((i * 50))
|
316 |
+
end_index=$(((i + 1) * 50))
|
317 |
+
|
318 |
+
gpu=$((i))
|
319 |
+
echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
|
320 |
+
((index++))
|
321 |
+
(
|
322 |
+
CUDA_VISIBLE_DEVICES=$gpu python mbpp_gen.py --model ${model} \
|
323 |
+
--start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
|
324 |
+
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --mbpp_path ${mbpp_path}
|
325 |
+
) &
|
326 |
+
if (($index % $gpu_num == 0)); then wait; fi
|
327 |
+
done
|
328 |
+
```
|
329 |
+
|
330 |
+
3. Run the post processing code `src/process_mbpp.py` to collect the code completions from all answer files.
|
331 |
+
```bash
|
332 |
+
output_path=preds/MBPP_T${temp}_N${pred_num}
|
333 |
+
mbpp_path=data/mbpp.test.jsonl # we provide this file in data/mbpp.test.zip
|
334 |
+
|
335 |
+
echo 'Output path: '$output_path
|
336 |
+
python process_mbpp.py --path ${output_path} --out_path ${output_path}.jsonl --mbpp_path ${mbpp_path} --add_prompt
|
337 |
+
```
|
338 |
+
|
339 |
+
4. Evaluate the `MBPP_T${temp}_N${pred_num}.jsonl` with [bigcode-evaluation-harness](https://github.com/bigcode-project/bigcode-evaluation-harness).
|
340 |
+
|
341 |
+
Acknowledgement: The evaluation code `humaneval_gen.py`, `mbpp_gen.py` and bash scripts are modified from the great works of [CodeT5](https://github.com/salesforce/CodeT5).
|
342 |
+
|
343 |
+
## Citation
|
344 |
+
|
345 |
+
Please cite the repo if you use the data or code in this repo.
|
346 |
+
|
347 |
+
```
|
348 |
+
@misc{luo2023wizardcoder,
|
349 |
+
title={WizardCoder: Empowering Code Large Language Models with Evol-Instruct},
|
350 |
+
author={Ziyang Luo and Can Xu and Pu Zhao and Qingfeng Sun and Xiubo Geng and Wenxiang Hu and Chongyang Tao and Jing Ma and Qingwei Lin and Daxin Jiang},
|
351 |
+
year={2023},
|
352 |
+
eprint={2306.08568},
|
353 |
+
archivePrefix={arXiv},
|
354 |
+
primaryClass={cs.CL}
|
355 |
+
}
|
356 |
+
```
|
357 |
+
## Disclaimer
|
358 |
+
|
359 |
+
WizardCoder model follows the same license as StarCoder. The content produced by any version of WizardCoder is influenced by uncontrollable variables such as randomness, and therefore, the accuracy of the output cannot be guaranteed by this project. This project does not accept any legal liability for the content of the model output, nor does it assume responsibility for any losses incurred due to the use of associated resources and output results.
|
360 |
+
|
361 |
+
## Star History
|
362 |
+
|
363 |
+
[](https://star-history.com/#nlpxucan/WizardLM&Timeline)
|
364 |
+
|
WizardCoder/data/humaneval.59.8.gen.zip
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ab30d7146c08712d975316fd2daaf34c2f187d8967e2b80d181798d99e352010
|
3 |
+
size 75828
|
WizardCoder/data/mbpp.test.zip
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9251948d46cd5bc684e378feb45e6edde32829da967f6556a6f66447777ca9d8
|
3 |
+
size 69264
|
WizardCoder/imgs/compare_sota.png
ADDED
![]() |
WizardCoder/imgs/pass1.png
ADDED
![]() |
WizardCoder/src/humaneval_gen.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import pprint
|
3 |
+
import sys
|
4 |
+
import os
|
5 |
+
import re
|
6 |
+
from tqdm import tqdm
|
7 |
+
import torch
|
8 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
|
9 |
+
from human_eval.data import write_jsonl, read_problems, stream_jsonl
|
10 |
+
|
11 |
+
if torch.cuda.is_available():
|
12 |
+
device = "cuda"
|
13 |
+
else:
|
14 |
+
device = "cpu"
|
15 |
+
|
16 |
+
try:
|
17 |
+
if torch.backends.mps.is_available():
|
18 |
+
device = "mps"
|
19 |
+
except:
|
20 |
+
pass
|
21 |
+
|
22 |
+
def generate_prompt(input):
|
23 |
+
INSTRUCTION = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
|
24 |
+
|
25 |
+
|
26 |
+
### Instruction:
|
27 |
+
Create a Python script for this problem:
|
28 |
+
{input}
|
29 |
+
|
30 |
+
### Response:"""
|
31 |
+
return INSTRUCTION
|
32 |
+
|
33 |
+
def get_model(
|
34 |
+
load_8bit: bool = False,
|
35 |
+
base_model: str = "bigcode/starcoder",
|
36 |
+
):
|
37 |
+
assert base_model, (
|
38 |
+
"Please specify a --base_model, e.g. --base_model='bigcode/starcoder'"
|
39 |
+
)
|
40 |
+
|
41 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model)
|
42 |
+
if device == "cuda":
|
43 |
+
model = AutoModelForCausalLM.from_pretrained(
|
44 |
+
base_model,
|
45 |
+
load_in_8bit=load_8bit,
|
46 |
+
torch_dtype=torch.float16,
|
47 |
+
device_map="auto",
|
48 |
+
)
|
49 |
+
elif device == "mps":
|
50 |
+
model = AutoModelForCausalLM.from_pretrained(
|
51 |
+
base_model,
|
52 |
+
device_map={"": device},
|
53 |
+
torch_dtype=torch.float16,
|
54 |
+
)
|
55 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
56 |
+
|
57 |
+
if not load_8bit:
|
58 |
+
model.half() # seems to fix bugs for some users.
|
59 |
+
|
60 |
+
model.eval()
|
61 |
+
if torch.__version__ >= "2" and sys.platform != "win32":
|
62 |
+
model = torch.compile(model)
|
63 |
+
|
64 |
+
return tokenizer, model
|
65 |
+
|
66 |
+
|
67 |
+
def main():
|
68 |
+
parser = argparse.ArgumentParser()
|
69 |
+
|
70 |
+
parser.add_argument('--model', type=str, default='bigcode/starcoder', help="")
|
71 |
+
parser.add_argument('--output_path', type=str, help="")
|
72 |
+
parser.add_argument('--start_index', type=int, default=0, help="")
|
73 |
+
parser.add_argument('--end_index', type=int, default=164, help="")
|
74 |
+
parser.add_argument('--temperature', type=float, default=0.8, help="")
|
75 |
+
parser.add_argument('--N', type=int, default=200, help="")
|
76 |
+
parser.add_argument('--max_len', type=int, default=512, help="")
|
77 |
+
parser.add_argument('--decoding_style', type=str, default='sampling', help="")
|
78 |
+
parser.add_argument('--num_seqs_per_iter', type=int, default=50, help='')
|
79 |
+
parser.add_argument('--greedy_decode', action='store_true', help='')
|
80 |
+
parser.add_argument('--overwrite', action='store_true', help='')
|
81 |
+
|
82 |
+
args = parser.parse_args()
|
83 |
+
|
84 |
+
argsdict = vars(args)
|
85 |
+
print(pprint.pformat(argsdict))
|
86 |
+
|
87 |
+
problems = read_problems()
|
88 |
+
|
89 |
+
task_ids = sorted(problems.keys())[args.start_index: args.end_index]
|
90 |
+
prompts = [problems[task_id]['prompt'] for task_id in task_ids]
|
91 |
+
num_samples = len(prompts)
|
92 |
+
print("Number of samples: {}".format(num_samples))
|
93 |
+
|
94 |
+
tokenizer, model = get_model(base_model=args.model)
|
95 |
+
generation_config = GenerationConfig(
|
96 |
+
pad_token_id=tokenizer.pad_token_id,
|
97 |
+
do_sample=False if args.greedy_decode else True,
|
98 |
+
temperature=args.temperature,
|
99 |
+
max_length=args.max_len,
|
100 |
+
num_return_sequences=args.num_seqs_per_iter,
|
101 |
+
eos_token_id=tokenizer.eos_token_id,
|
102 |
+
top_p=0.95
|
103 |
+
)
|
104 |
+
|
105 |
+
print(f"Loaded {args.model}.")
|
106 |
+
for i in tqdm(range(num_samples), ncols=0, total=num_samples):
|
107 |
+
output_file = args.output_path + '/{}.jsonl'.format(args.start_index + i)
|
108 |
+
|
109 |
+
if os.path.exists(output_file) and not args.overwrite:
|
110 |
+
print(f'Skip {output_file} as it already exists')
|
111 |
+
continue
|
112 |
+
|
113 |
+
prompt = prompts[i].replace(' ', '\t')
|
114 |
+
prompt_batch = [generate_prompt(prompt)]
|
115 |
+
|
116 |
+
ids_batch = [task_ids[i]]
|
117 |
+
|
118 |
+
completion_seqs = []
|
119 |
+
|
120 |
+
encoding = tokenizer(prompt_batch, return_tensors="pt", truncation=True, max_length=args.max_len).to(device)
|
121 |
+
|
122 |
+
if args.decoding_style == 'sampling':
|
123 |
+
loops = int(args.N / args.num_seqs_per_iter)
|
124 |
+
else:
|
125 |
+
loops = 1
|
126 |
+
|
127 |
+
for _ in tqdm(range(loops), total=loops, leave=False, ncols=0):
|
128 |
+
|
129 |
+
with torch.no_grad():
|
130 |
+
gen_tokens = model.generate(
|
131 |
+
**encoding,
|
132 |
+
generation_config=generation_config
|
133 |
+
)
|
134 |
+
|
135 |
+
if gen_tokens is not None:
|
136 |
+
gen_seqs = tokenizer.batch_decode(gen_tokens, skip_special_tokens=True)
|
137 |
+
else:
|
138 |
+
gen_seqs = None
|
139 |
+
|
140 |
+
if gen_seqs is not None:
|
141 |
+
assert len(ids_batch) == 1
|
142 |
+
task_id = ids_batch[0]
|
143 |
+
|
144 |
+
for seq_idx, gen_seq in enumerate(gen_seqs):
|
145 |
+
completion_seq = gen_seq.split("### Response:")[1]
|
146 |
+
completion_seq = completion_seq.replace('\t', ' ')
|
147 |
+
all_code = gen_seq.replace('\t', ' ')
|
148 |
+
|
149 |
+
completion_seqs.append(
|
150 |
+
{'task_id': task_id,
|
151 |
+
'completion': completion_seq,
|
152 |
+
'all_code': all_code,
|
153 |
+
}
|
154 |
+
)
|
155 |
+
|
156 |
+
print("Saving results to {}".format(output_file))
|
157 |
+
write_jsonl(output_file, completion_seqs)
|
158 |
+
|
159 |
+
|
160 |
+
if __name__ == '__main__':
|
161 |
+
main()
|
WizardCoder/src/humaneval_gen_vllm.py
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import pprint
|
3 |
+
import sys
|
4 |
+
import os
|
5 |
+
import re
|
6 |
+
from tqdm import tqdm
|
7 |
+
import torch
|
8 |
+
from transformers import LlamaTokenizer, AutoModelForCausalLM, GenerationConfig, BitsAndBytesConfig
|
9 |
+
from human_eval.data import write_jsonl, read_problems, stream_jsonl
|
10 |
+
|
11 |
+
from vllm import LLM
|
12 |
+
from vllm import SamplingParams
|
13 |
+
|
14 |
+
if torch.cuda.is_available():
|
15 |
+
device = "cuda"
|
16 |
+
else:
|
17 |
+
device = "cpu"
|
18 |
+
|
19 |
+
try:
|
20 |
+
if torch.backends.mps.is_available():
|
21 |
+
device = "mps"
|
22 |
+
except:
|
23 |
+
pass
|
24 |
+
|
25 |
+
def generate_prompt(input):
|
26 |
+
INSTRUCTION = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
|
27 |
+
|
28 |
+
|
29 |
+
### Instruction:
|
30 |
+
Create a Python script for this problem:
|
31 |
+
{input}
|
32 |
+
|
33 |
+
### Response:"""
|
34 |
+
return INSTRUCTION
|
35 |
+
|
36 |
+
|
37 |
+
def main():
|
38 |
+
parser = argparse.ArgumentParser()
|
39 |
+
|
40 |
+
parser.add_argument('--model', type=str, default='bigcode/starcoder', help="")
|
41 |
+
parser.add_argument('--lora', type=str, default='bigcode/starcoder', help="")
|
42 |
+
parser.add_argument('--output_path', type=str, help="")
|
43 |
+
parser.add_argument('--start_index', type=int, default=0, help="")
|
44 |
+
parser.add_argument('--end_index', type=int, default=164, help="")
|
45 |
+
parser.add_argument('--temperature', type=float, default=0.8, help="")
|
46 |
+
parser.add_argument('--N', type=int, default=200, help="")
|
47 |
+
parser.add_argument('--max_len', type=int, default=512, help="")
|
48 |
+
parser.add_argument('--num_gpus', type=int, default=4, help="")
|
49 |
+
parser.add_argument('--decoding_style', type=str, default='sampling', help="")
|
50 |
+
parser.add_argument('--num_seqs_per_iter', type=int, default=50, help='')
|
51 |
+
parser.add_argument('--overwrite', action='store_true', help='')
|
52 |
+
|
53 |
+
args = parser.parse_args()
|
54 |
+
|
55 |
+
argsdict = vars(args)
|
56 |
+
print(pprint.pformat(argsdict))
|
57 |
+
|
58 |
+
problems = read_problems()
|
59 |
+
|
60 |
+
task_ids = sorted(problems.keys())[args.start_index: args.end_index]
|
61 |
+
prompts = [problems[task_id]['prompt'] for task_id in task_ids]
|
62 |
+
num_samples = len(prompts)
|
63 |
+
print("Number of samples: {}".format(num_samples))
|
64 |
+
|
65 |
+
llm = LLM(base_model, tensor_parallel_size=args.num_gpus)
|
66 |
+
sampling_params = SamplingParams(temperature=args.temperature, top_p=1, max_tokens=args.max_len)
|
67 |
+
|
68 |
+
print(f"Loaded {args.model}.")
|
69 |
+
for i in tqdm(range(num_samples), ncols=0, total=num_samples):
|
70 |
+
output_file = args.output_path + '/{}.jsonl'.format(args.start_index + i)
|
71 |
+
|
72 |
+
if os.path.exists(output_file) and not args.overwrite:
|
73 |
+
print(f'Skip {output_file} as it already exists')
|
74 |
+
continue
|
75 |
+
|
76 |
+
prompt = prompts[i].replace(' ', '\t')
|
77 |
+
prompt_batch = [generate_prompt(prompt)]
|
78 |
+
|
79 |
+
ids_batch = [task_ids[i]]
|
80 |
+
completion_seqs = []
|
81 |
+
|
82 |
+
if args.decoding_style == 'sampling':
|
83 |
+
loops = int(args.N / args.num_seqs_per_iter)
|
84 |
+
else:
|
85 |
+
loops = 1
|
86 |
+
|
87 |
+
for _ in tqdm(range(loops), total=loops, leave=False, ncols=0):
|
88 |
+
|
89 |
+
with torch.no_grad():
|
90 |
+
completions = llm.generate(prompt_batch, sampling_params)
|
91 |
+
gen_seqs = [completions[0].outputs[0].text]
|
92 |
+
|
93 |
+
if gen_seqs is not None:
|
94 |
+
assert len(ids_batch) == 1
|
95 |
+
task_id = ids_batch[0]
|
96 |
+
|
97 |
+
for seq_idx, gen_seq in enumerate(gen_seqs):
|
98 |
+
completion_seq = gen_seq.split("### Response:")[-1]
|
99 |
+
completion_seq = completion_seq.replace('\t', ' ')
|
100 |
+
all_code = gen_seq.replace('\t', ' ')
|
101 |
+
|
102 |
+
completion_seqs.append(
|
103 |
+
{'task_id': task_id,
|
104 |
+
'completion': completion_seq,
|
105 |
+
'all_code': all_code,
|
106 |
+
}
|
107 |
+
)
|
108 |
+
|
109 |
+
print("Saving results to {}".format(output_file))
|
110 |
+
write_jsonl(output_file, completion_seqs)
|
111 |
+
|
112 |
+
|
113 |
+
if __name__ == '__main__':
|
114 |
+
main()
|
WizardCoder/src/inference_wizardcoder.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import os
|
3 |
+
import fire
|
4 |
+
import torch
|
5 |
+
import transformers
|
6 |
+
import json
|
7 |
+
import jsonlines
|
8 |
+
|
9 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
|
10 |
+
|
11 |
+
if torch.cuda.is_available():
|
12 |
+
device = "cuda"
|
13 |
+
else:
|
14 |
+
device = "cpu"
|
15 |
+
|
16 |
+
try:
|
17 |
+
if torch.backends.mps.is_available():
|
18 |
+
device = "mps"
|
19 |
+
except:
|
20 |
+
pass
|
21 |
+
|
22 |
+
def evaluate(
|
23 |
+
batch_data,
|
24 |
+
tokenizer,
|
25 |
+
model,
|
26 |
+
input=None,
|
27 |
+
temperature=1,
|
28 |
+
top_p=0.9,
|
29 |
+
top_k=40,
|
30 |
+
num_beams=1,
|
31 |
+
max_new_tokens=2048,
|
32 |
+
**kwargs,
|
33 |
+
):
|
34 |
+
prompts = generate_prompt(batch_data, input)
|
35 |
+
inputs = tokenizer(prompts, return_tensors="pt", max_length=256, truncation=True, padding=True)
|
36 |
+
input_ids = inputs["input_ids"].to(device)
|
37 |
+
generation_config = GenerationConfig(
|
38 |
+
temperature=temperature,
|
39 |
+
top_p=top_p,
|
40 |
+
top_k=top_k,
|
41 |
+
num_beams=num_beams,
|
42 |
+
eos_token_id=tokenizer.eos_token_id,
|
43 |
+
pad_token_id=tokenizer.pad_token_id,
|
44 |
+
**kwargs,
|
45 |
+
)
|
46 |
+
with torch.no_grad():
|
47 |
+
generation_output = model.generate(
|
48 |
+
input_ids=input_ids,
|
49 |
+
generation_config=generation_config,
|
50 |
+
return_dict_in_generate=True,
|
51 |
+
output_scores=True,
|
52 |
+
max_new_tokens=max_new_tokens,
|
53 |
+
)
|
54 |
+
s = generation_output.sequences
|
55 |
+
output = tokenizer.batch_decode(s, skip_special_tokens=True)
|
56 |
+
return output
|
57 |
+
|
58 |
+
|
59 |
+
def generate_prompt(instruction, input=None):
|
60 |
+
return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
|
61 |
+
|
62 |
+
### Instruction:
|
63 |
+
{instruction}
|
64 |
+
|
65 |
+
### Response:"""
|
66 |
+
|
67 |
+
|
68 |
+
def main(
|
69 |
+
load_8bit: bool = False,
|
70 |
+
base_model: str = "Model_Path",
|
71 |
+
input_data_path = "Input.jsonl",
|
72 |
+
output_data_path = "Output.jsonl",
|
73 |
+
):
|
74 |
+
assert base_model, (
|
75 |
+
"Please specify a --base_model, e.g. --base_model='bigcode/starcoder'"
|
76 |
+
)
|
77 |
+
|
78 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model)
|
79 |
+
if device == "cuda":
|
80 |
+
model = AutoModelForCausalLM.from_pretrained(
|
81 |
+
base_model,
|
82 |
+
load_in_8bit=load_8bit,
|
83 |
+
torch_dtype=torch.float16,
|
84 |
+
device_map="auto",
|
85 |
+
)
|
86 |
+
elif device == "mps":
|
87 |
+
model = AutoModelForCausalLM.from_pretrained(
|
88 |
+
base_model,
|
89 |
+
device_map={"": device},
|
90 |
+
torch_dtype=torch.float16,
|
91 |
+
)
|
92 |
+
|
93 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
94 |
+
|
95 |
+
if not load_8bit:
|
96 |
+
model.half()
|
97 |
+
|
98 |
+
model.eval()
|
99 |
+
if torch.__version__ >= "2" and sys.platform != "win32":
|
100 |
+
model = torch.compile(model)
|
101 |
+
|
102 |
+
input_data = jsonlines.open(input_data_path, mode='r')
|
103 |
+
output_data = jsonlines.open(output_data_path, mode='w')
|
104 |
+
|
105 |
+
for num, line in enumerate(input_data):
|
106 |
+
one_data = line
|
107 |
+
id = one_data["idx"]
|
108 |
+
instruction = one_data["Instruction"]
|
109 |
+
print(instruction)
|
110 |
+
_output = evaluate(instruction, tokenizer, model)
|
111 |
+
final_output = _output[0].split("### Response:")[1].strip()
|
112 |
+
new_data = {
|
113 |
+
"id": id,
|
114 |
+
"instruction": instruction,
|
115 |
+
"wizardcoder": final_output
|
116 |
+
}
|
117 |
+
output_data.write(new_data)
|
118 |
+
|
119 |
+
|
120 |
+
if __name__ == "__main__":
|
121 |
+
fire.Fire(main)
|
WizardCoder/src/mbpp_gen.py
ADDED
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import jsonlines
|
2 |
+
import argparse
|
3 |
+
import pprint
|
4 |
+
import sys
|
5 |
+
import os
|
6 |
+
import re
|
7 |
+
from tqdm import tqdm
|
8 |
+
import torch
|
9 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
|
10 |
+
from human_eval.data import write_jsonl, read_problems, stream_jsonl
|
11 |
+
|
12 |
+
if torch.cuda.is_available():
|
13 |
+
device = "cuda"
|
14 |
+
else:
|
15 |
+
device = "cpu"
|
16 |
+
|
17 |
+
try:
|
18 |
+
if torch.backends.mps.is_available():
|
19 |
+
device = "mps"
|
20 |
+
except:
|
21 |
+
pass
|
22 |
+
|
23 |
+
def read_mbpp(path):
|
24 |
+
mbpp_problems = {}
|
25 |
+
with jsonlines.open(path, "r") as fin:
|
26 |
+
for obj in fin:
|
27 |
+
mbpp_problems[obj["task_id"]] = obj
|
28 |
+
return mbpp_problems
|
29 |
+
|
30 |
+
def extract_text(prompt, remove_lines=True):
|
31 |
+
token = '\"\"\"'
|
32 |
+
start = token
|
33 |
+
end = '>>>'
|
34 |
+
|
35 |
+
start_idx = prompt.find(start) + len(start)
|
36 |
+
end_idx = prompt.find(end)
|
37 |
+
|
38 |
+
output = prompt[start_idx: end_idx]
|
39 |
+
if remove_lines:
|
40 |
+
output = output.replace('\n', ' ')
|
41 |
+
output = re.sub(r"\s+", " ", output).strip()
|
42 |
+
|
43 |
+
return output
|
44 |
+
|
45 |
+
def generate_prompt(input):
|
46 |
+
INSTRUCTION = f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
|
47 |
+
|
48 |
+
### Instruction:
|
49 |
+
Create a Python script for this problem:
|
50 |
+
{input}
|
51 |
+
|
52 |
+
### Response:"""
|
53 |
+
return INSTRUCTION
|
54 |
+
|
55 |
+
def get_model(
|
56 |
+
load_8bit: bool = False,
|
57 |
+
base_model: str = "bigcode/starcoder",
|
58 |
+
):
|
59 |
+
assert base_model, (
|
60 |
+
"Please specify a --base_model, e.g. --base_model='bigcode/starcoder'"
|
61 |
+
)
|
62 |
+
|
63 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model)
|
64 |
+
if device == "cuda":
|
65 |
+
model = AutoModelForCausalLM.from_pretrained(
|
66 |
+
base_model,
|
67 |
+
load_in_8bit=load_8bit,
|
68 |
+
torch_dtype=torch.float16,
|
69 |
+
device_map="auto",
|
70 |
+
)
|
71 |
+
elif device == "mps":
|
72 |
+
model = AutoModelForCausalLM.from_pretrained(
|
73 |
+
base_model,
|
74 |
+
device_map={"": device},
|
75 |
+
torch_dtype=torch.float16,
|
76 |
+
)
|
77 |
+
model.config.pad_token_id = tokenizer.pad_token_id
|
78 |
+
|
79 |
+
if not load_8bit:
|
80 |
+
model.half() # seems to fix bugs for some users.
|
81 |
+
|
82 |
+
model.eval()
|
83 |
+
if torch.__version__ >= "2" and sys.platform != "win32":
|
84 |
+
model = torch.compile(model)
|
85 |
+
|
86 |
+
return tokenizer, model
|
87 |
+
|
88 |
+
|
89 |
+
def main():
|
90 |
+
parser = argparse.ArgumentParser()
|
91 |
+
|
92 |
+
parser.add_argument('--model', type=str, default='bigcode/starcoder', help="")
|
93 |
+
parser.add_argument('--output_path', type=str, help="")
|
94 |
+
parser.add_argument('--start_index', type=int, default=0, help="")
|
95 |
+
parser.add_argument('--end_index', type=int, default=164, help="")
|
96 |
+
parser.add_argument('--temperature', type=float, default=0.8, help="")
|
97 |
+
parser.add_argument('--N', type=int, default=200, help="")
|
98 |
+
parser.add_argument('--max_len', type=int, default=512, help="")
|
99 |
+
parser.add_argument('--decoding_style', type=str, default='sampling', help="")
|
100 |
+
parser.add_argument('--num_seqs_per_iter', type=int, default=50, help='')
|
101 |
+
parser.add_argument('--overwrite', action='store_true', help='')
|
102 |
+
parser.add_argument('--mbpp_path', type=str, help="")
|
103 |
+
|
104 |
+
args = parser.parse_args()
|
105 |
+
|
106 |
+
argsdict = vars(args)
|
107 |
+
print(pprint.pformat(argsdict))
|
108 |
+
|
109 |
+
STOP_SEQS = ['\nclass', '\ndef', '\n#', '\nif', '\nprint']
|
110 |
+
|
111 |
+
problems = read_mbpp(args.mbpp_path)
|
112 |
+
|
113 |
+
task_ids = sorted(problems.keys())[args.start_index: args.end_index]
|
114 |
+
prompts = []
|
115 |
+
for task_id in task_ids:
|
116 |
+
prompt = f"\n{problems[task_id]['text']}\nTest examples:"
|
117 |
+
if task_id == 493:
|
118 |
+
# The test examples are too long. We choose to only include the function name.
|
119 |
+
test_example = problems[task_id]['test_list'][0]
|
120 |
+
prompt += f"\ncalculate_polygons(startx, starty, endx, endy, radius)"
|
121 |
+
else:
|
122 |
+
for test_example in problems[task_id]['test_list']:
|
123 |
+
prompt += f"\n{test_example}"
|
124 |
+
prompts.append(prompt)
|
125 |
+
|
126 |
+
num_samples = len(prompts)
|
127 |
+
print("Number of samples: {}".format(num_samples))
|
128 |
+
|
129 |
+
tokenizer, model = get_model(base_model=args.model)
|
130 |
+
generation_config = GenerationConfig(
|
131 |
+
pad_token_id=tokenizer.pad_token_id,
|
132 |
+
do_sample=True,
|
133 |
+
temperature=args.temperature,
|
134 |
+
max_length=args.max_len,
|
135 |
+
num_return_sequences=args.num_seqs_per_iter,
|
136 |
+
eos_token_id=tokenizer.eos_token_id,
|
137 |
+
top_p=0.95
|
138 |
+
)
|
139 |
+
|
140 |
+
print(f"Loaded {args.model}.")
|
141 |
+
for i in tqdm(range(num_samples), ncols=0, total=num_samples):
|
142 |
+
output_file = args.output_path + '/{}.jsonl'.format(args.start_index + i)
|
143 |
+
|
144 |
+
if os.path.exists(output_file) and not args.overwrite:
|
145 |
+
print(f'Skip {output_file} as it already exists')
|
146 |
+
continue
|
147 |
+
|
148 |
+
prompt = prompts[i].replace(' ', '\t')
|
149 |
+
prompt_batch = [generate_prompt(prompt)]
|
150 |
+
|
151 |
+
ids_batch = [task_ids[i]]
|
152 |
+
|
153 |
+
completion_seqs = []
|
154 |
+
|
155 |
+
encoding = tokenizer(prompt_batch, return_tensors="pt", truncation=True, max_length=args.max_len).to(device)
|
156 |
+
|
157 |
+
if args.decoding_style == 'sampling':
|
158 |
+
loops = int(args.N / args.num_seqs_per_iter)
|
159 |
+
else:
|
160 |
+
loops = 1
|
161 |
+
|
162 |
+
for _ in tqdm(range(loops), total=loops, leave=False, ncols=0):
|
163 |
+
|
164 |
+
with torch.no_grad():
|
165 |
+
if args.decoding_style == 'sampling':
|
166 |
+
gen_tokens = model.generate(
|
167 |
+
**encoding,
|
168 |
+
generation_config=generation_config
|
169 |
+
)
|
170 |
+
|
171 |
+
if gen_tokens is not None:
|
172 |
+
gen_seqs = tokenizer.batch_decode(gen_tokens, skip_special_tokens=True)
|
173 |
+
else:
|
174 |
+
gen_seqs = None
|
175 |
+
|
176 |
+
if gen_seqs is not None:
|
177 |
+
assert len(ids_batch) == 1
|
178 |
+
task_id = ids_batch[0]
|
179 |
+
|
180 |
+
for seq_idx, gen_seq in enumerate(gen_seqs):
|
181 |
+
completion_seq = gen_seq.split("### Response:")[-1]
|
182 |
+
completion_seq = completion_seq.replace('\t', ' ')
|
183 |
+
all_code = gen_seq.replace('\t', ' ')
|
184 |
+
|
185 |
+
completion_seqs.append(
|
186 |
+
{'task_id': task_id,
|
187 |
+
'completion': completion_seq,
|
188 |
+
'all_code': all_code,
|
189 |
+
}
|
190 |
+
)
|
191 |
+
|
192 |
+
print("Saving results to {}".format(output_file))
|
193 |
+
write_jsonl(output_file, completion_seqs)
|
194 |
+
|
195 |
+
|
196 |
+
if __name__ == '__main__':
|
197 |
+
main()
|
WizardCoder/src/process_humaneval.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from human_eval.data import read_problems, write_jsonl, stream_jsonl
|
2 |
+
import glob
|
3 |
+
from tqdm import tqdm
|
4 |
+
import argparse
|
5 |
+
|
6 |
+
parser = argparse.ArgumentParser()
|
7 |
+
|
8 |
+
# Inputs
|
9 |
+
parser.add_argument(
|
10 |
+
'--path',
|
11 |
+
type=str,
|
12 |
+
help="")
|
13 |
+
parser.add_argument(
|
14 |
+
'--out_path',
|
15 |
+
type=str,
|
16 |
+
help="")
|
17 |
+
parser.add_argument(
|
18 |
+
'--add_prompt',
|
19 |
+
action='store_true',
|
20 |
+
help='')
|
21 |
+
|
22 |
+
args = parser.parse_args()
|
23 |
+
|
24 |
+
|
25 |
+
files = sorted(glob.glob(args.path + '/*.jsonl'))
|
26 |
+
print("{} files in {}".format(len(files), args.path))
|
27 |
+
|
28 |
+
problems = read_problems()
|
29 |
+
|
30 |
+
output = []
|
31 |
+
a = 0
|
32 |
+
for code_file in tqdm(files, total=len(files)):
|
33 |
+
codes = [c for c in stream_jsonl(code_file)]
|
34 |
+
if args.add_prompt:
|
35 |
+
for code in codes:
|
36 |
+
task_id = code['task_id']
|
37 |
+
prompt = problems[task_id]['prompt']
|
38 |
+
completion = code['completion']
|
39 |
+
completion = completion.replace("\r", "")
|
40 |
+
if '```python' in completion:
|
41 |
+
def_line = completion.index('```python')
|
42 |
+
completion = completion[def_line:].strip()
|
43 |
+
completion = completion.replace('```python', '')
|
44 |
+
# print(completion)
|
45 |
+
try:
|
46 |
+
next_line = completion.index('```')
|
47 |
+
completion = completion[:next_line].strip()
|
48 |
+
except:
|
49 |
+
a += 1
|
50 |
+
print(completion)
|
51 |
+
print("================\n")
|
52 |
+
# print(completion)
|
53 |
+
if "__name__ == \"__main__\"" in completion:
|
54 |
+
next_line = completion.index('if __name__ == "__main__":')
|
55 |
+
completion = completion[:next_line].strip()
|
56 |
+
# print(completion)
|
57 |
+
|
58 |
+
if "# Example usage" in completion:
|
59 |
+
# print(completion)
|
60 |
+
next_line = completion.index('# Example usage')
|
61 |
+
completion = completion[:next_line].strip()
|
62 |
+
|
63 |
+
code['completion'] = completion
|
64 |
+
|
65 |
+
output += codes
|
66 |
+
|
67 |
+
print("save to {}".format(args.out_path))
|
68 |
+
write_jsonl(args.out_path, output)
|
69 |
+
print(a)
|
WizardCoder/src/process_mbpp.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from human_eval.data import stream_jsonl
|
2 |
+
import glob
|
3 |
+
from tqdm import tqdm
|
4 |
+
import argparse
|
5 |
+
import jsonlines
|
6 |
+
import json
|
7 |
+
|
8 |
+
def read_mbpp(path):
|
9 |
+
mbpp_problems = {}
|
10 |
+
with jsonlines.open(path, "r") as fin:
|
11 |
+
for obj in fin:
|
12 |
+
mbpp_problems[obj["task_id"]] = obj
|
13 |
+
return mbpp_problems
|
14 |
+
|
15 |
+
parser = argparse.ArgumentParser()
|
16 |
+
|
17 |
+
# Inputs
|
18 |
+
parser.add_argument(
|
19 |
+
'--path',
|
20 |
+
type=str,
|
21 |
+
help="")
|
22 |
+
parser.add_argument(
|
23 |
+
'--out_path',
|
24 |
+
type=str,
|
25 |
+
help="")
|
26 |
+
parser.add_argument(
|
27 |
+
'--add_prompt',
|
28 |
+
action='store_true',
|
29 |
+
help='')
|
30 |
+
parser.add_argument('--mbpp_path', type=str, help="")
|
31 |
+
|
32 |
+
args = parser.parse_args()
|
33 |
+
|
34 |
+
|
35 |
+
files = sorted(glob.glob(args.path + '/*.jsonl'))
|
36 |
+
print("{} files in {}".format(len(files), args.path))
|
37 |
+
|
38 |
+
problems = read_mbpp(args.mbpp_path)
|
39 |
+
output = [[] for _ in range(len(problems))]
|
40 |
+
a = 0
|
41 |
+
for code_file in tqdm(files, total=len(files)):
|
42 |
+
codes = [c for c in stream_jsonl(code_file)]
|
43 |
+
if args.add_prompt:
|
44 |
+
for code in codes:
|
45 |
+
task_id = code['task_id']
|
46 |
+
completion = code['completion']
|
47 |
+
if '```python' in completion:
|
48 |
+
def_line = completion.index('```python')
|
49 |
+
completion = completion[def_line:].strip()
|
50 |
+
completion = completion.replace('```python', '')
|
51 |
+
try:
|
52 |
+
next_line = completion.index('\n```')
|
53 |
+
completion = completion[:next_line].strip()
|
54 |
+
except:
|
55 |
+
a += 1
|
56 |
+
if "__name__ == \"__main__\"" in completion:
|
57 |
+
next_line = completion.index('if __name__ == "__main__":')
|
58 |
+
completion = completion[:next_line].strip()
|
59 |
+
|
60 |
+
if "# Example usage" in completion:
|
61 |
+
next_line = completion.index('# Example usage')
|
62 |
+
completion = completion[:next_line].strip()
|
63 |
+
|
64 |
+
if "# Test examples" in completion:
|
65 |
+
next_line = completion.index('# Test examples')
|
66 |
+
completion = completion[:next_line].strip()
|
67 |
+
|
68 |
+
output[task_id-11].append(completion)
|
69 |
+
|
70 |
+
print("save to {}".format(args.out_path))
|
71 |
+
print(a)
|
72 |
+
with open(args.out_path, "w", encoding="utf-8") as fout:
|
73 |
+
json.dump(output, fout)
|
WizardCoder/src/train_wizardcoder.py
ADDED
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import copy
|
16 |
+
import logging
|
17 |
+
import random
|
18 |
+
from dataclasses import dataclass, field
|
19 |
+
from typing import Optional, Dict, Sequence
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.distributed
|
23 |
+
import transformers
|
24 |
+
from torch.utils.data import Dataset
|
25 |
+
from transformers import Trainer
|
26 |
+
from datasets import load_dataset
|
27 |
+
import utils
|
28 |
+
|
29 |
+
IGNORE_INDEX = -100
|
30 |
+
DEFAULT_PAD_TOKEN = "[PAD]"
|
31 |
+
DEFAULT_EOS_TOKEN = "<|endoftext|>"
|
32 |
+
DEFAULT_BOS_TOKEN = "<|endoftext|>"
|
33 |
+
DEFAULT_UNK_TOKEN = "<|endoftext|>"
|
34 |
+
PROMPT_DICT = {
|
35 |
+
"prompt_input": (
|
36 |
+
"Below is an instruction that describes a task, paired with an input that provides further context. "
|
37 |
+
"Write a response that appropriately completes the request.\n\n"
|
38 |
+
"### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:"
|
39 |
+
),
|
40 |
+
"prompt_no_input": (
|
41 |
+
"Below is an instruction that describes a task. "
|
42 |
+
"Write a response that appropriately completes the request.\n\n"
|
43 |
+
"### Instruction:\n{instruction}\n\n### Response:"
|
44 |
+
),
|
45 |
+
}
|
46 |
+
|
47 |
+
|
48 |
+
@dataclass
|
49 |
+
class ModelArguments:
|
50 |
+
model_name_or_path: Optional[str] = field(default="bigcode/starcoder")
|
51 |
+
|
52 |
+
|
53 |
+
@dataclass
|
54 |
+
class DataArguments:
|
55 |
+
data_path: str = field(default=None, metadata={"help": "Path to the training data."})
|
56 |
+
|
57 |
+
|
58 |
+
@dataclass
|
59 |
+
class TrainingArguments(transformers.TrainingArguments):
|
60 |
+
cache_dir: Optional[str] = field(default=None)
|
61 |
+
optim: str = field(default="adamw_torch")
|
62 |
+
model_max_length: int = field(
|
63 |
+
default=512,
|
64 |
+
metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
|
65 |
+
)
|
66 |
+
|
67 |
+
|
68 |
+
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
|
69 |
+
"""Collects the state dict and dump to disk."""
|
70 |
+
state_dict = trainer.model.state_dict()
|
71 |
+
if trainer.args.should_save:
|
72 |
+
cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
|
73 |
+
del state_dict
|
74 |
+
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
|
75 |
+
|
76 |
+
|
77 |
+
def smart_tokenizer_and_embedding_resize(
|
78 |
+
special_tokens_dict: Dict,
|
79 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
80 |
+
model: transformers.PreTrainedModel,
|
81 |
+
):
|
82 |
+
"""Resize tokenizer and embedding.
|
83 |
+
|
84 |
+
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
|
85 |
+
"""
|
86 |
+
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
|
87 |
+
model.resize_token_embeddings(len(tokenizer))
|
88 |
+
|
89 |
+
if num_new_tokens > 0:
|
90 |
+
input_embeddings = model.get_input_embeddings().weight.data
|
91 |
+
output_embeddings = model.get_output_embeddings().weight.data
|
92 |
+
|
93 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
94 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
95 |
+
|
96 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
97 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
98 |
+
|
99 |
+
|
100 |
+
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
|
101 |
+
"""Tokenize a list of strings."""
|
102 |
+
tokenized_list = [
|
103 |
+
tokenizer(
|
104 |
+
text,
|
105 |
+
return_tensors="pt",
|
106 |
+
padding="longest",
|
107 |
+
max_length=tokenizer.model_max_length,
|
108 |
+
truncation=True,
|
109 |
+
)
|
110 |
+
for text in strings
|
111 |
+
]
|
112 |
+
input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
|
113 |
+
input_ids_lens = labels_lens = [
|
114 |
+
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list
|
115 |
+
]
|
116 |
+
return dict(
|
117 |
+
input_ids=input_ids,
|
118 |
+
labels=labels,
|
119 |
+
input_ids_lens=input_ids_lens,
|
120 |
+
labels_lens=labels_lens,
|
121 |
+
)
|
122 |
+
|
123 |
+
|
124 |
+
def preprocess(
|
125 |
+
sources: Sequence[str],
|
126 |
+
targets: Sequence[str],
|
127 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
128 |
+
) -> Dict:
|
129 |
+
"""Preprocess the data by tokenizing."""
|
130 |
+
examples = [s + t for s, t in zip(sources, targets)]
|
131 |
+
examples_tokenized, sources_tokenized = [_tokenize_fn(strings, tokenizer) for strings in (examples, sources)]
|
132 |
+
input_ids = examples_tokenized["input_ids"]
|
133 |
+
labels = copy.deepcopy(input_ids)
|
134 |
+
for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]):
|
135 |
+
label[:source_len] = IGNORE_INDEX
|
136 |
+
return dict(input_ids=input_ids, labels=labels)
|
137 |
+
|
138 |
+
|
139 |
+
@dataclass
|
140 |
+
class DataCollatorForSupervisedDataset(object):
|
141 |
+
"""Collate examples for supervised fine-tuning."""
|
142 |
+
|
143 |
+
tokenizer: transformers.PreTrainedTokenizer
|
144 |
+
|
145 |
+
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
|
146 |
+
input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
|
147 |
+
input_ids = [torch.tensor(x) for x in input_ids]
|
148 |
+
input_ids = torch.nn.utils.rnn.pad_sequence(
|
149 |
+
input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id
|
150 |
+
)
|
151 |
+
labels = [torch.tensor(x) for x in labels]
|
152 |
+
labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
|
153 |
+
return dict(
|
154 |
+
input_ids=input_ids,
|
155 |
+
labels=labels,
|
156 |
+
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
|
157 |
+
)
|
158 |
+
|
159 |
+
def train_tokenize_function(examples, tokenizer):
|
160 |
+
prompt_input, prompt_no_input = PROMPT_DICT["prompt_input"], PROMPT_DICT["prompt_no_input"]
|
161 |
+
if 'input' in examples:
|
162 |
+
sources = [
|
163 |
+
prompt_input.format_map(dict(instruction=instruction, input=input)) if input != "" \
|
164 |
+
else prompt_no_input.format_map(dict(instruction=instruction)) \
|
165 |
+
for instruction, input in zip(examples['instruction'], examples['input'])
|
166 |
+
]
|
167 |
+
else:
|
168 |
+
sources = [
|
169 |
+
prompt_no_input.format_map(dict(instruction=instruction)) \
|
170 |
+
for instruction in examples['instruction']
|
171 |
+
]
|
172 |
+
targets = [f"{output}{tokenizer.eos_token}" for output in examples['output']]
|
173 |
+
data_dict = preprocess(sources, targets, tokenizer)
|
174 |
+
return data_dict
|
175 |
+
|
176 |
+
|
177 |
+
def train():
|
178 |
+
parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
|
179 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
180 |
+
|
181 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
182 |
+
model_args.model_name_or_path,
|
183 |
+
cache_dir=training_args.cache_dir,
|
184 |
+
)
|
185 |
+
|
186 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
187 |
+
model_args.model_name_or_path,
|
188 |
+
cache_dir=training_args.cache_dir,
|
189 |
+
model_max_length=training_args.model_max_length,
|
190 |
+
padding_side="right",
|
191 |
+
use_fast=True,
|
192 |
+
)
|
193 |
+
if tokenizer.pad_token is None:
|
194 |
+
smart_tokenizer_and_embedding_resize(
|
195 |
+
special_tokens_dict=dict(pad_token=DEFAULT_PAD_TOKEN),
|
196 |
+
tokenizer=tokenizer,
|
197 |
+
model=model,
|
198 |
+
)
|
199 |
+
if "starcoder" in model_args.model_name_or_path:
|
200 |
+
tokenizer.add_special_tokens(
|
201 |
+
{
|
202 |
+
"eos_token": DEFAULT_EOS_TOKEN,
|
203 |
+
"bos_token": DEFAULT_BOS_TOKEN,
|
204 |
+
"unk_token": DEFAULT_UNK_TOKEN,
|
205 |
+
"pad_token": DEFAULT_PAD_TOKEN,
|
206 |
+
}
|
207 |
+
)
|
208 |
+
|
209 |
+
raw_train_datasets = load_dataset('json', data_files=data_args.data_path, split="train", cache_dir=training_args.cache_dir)
|
210 |
+
if training_args.local_rank > 0:
|
211 |
+
torch.distributed.barrier()
|
212 |
+
|
213 |
+
train_dataset = raw_train_datasets.map(
|
214 |
+
train_tokenize_function,
|
215 |
+
batched=True,
|
216 |
+
batch_size=3000,
|
217 |
+
num_proc=32,
|
218 |
+
remove_columns=raw_train_datasets.column_names,
|
219 |
+
load_from_cache_file=True, # not args.overwrite_cache
|
220 |
+
desc="Running tokenizer on train dataset",
|
221 |
+
fn_kwargs={"tokenizer": tokenizer}
|
222 |
+
)
|
223 |
+
|
224 |
+
if training_args.local_rank == 0:
|
225 |
+
torch.distributed.barrier()
|
226 |
+
|
227 |
+
if training_args.local_rank == 0:
|
228 |
+
print(len(train_dataset))
|
229 |
+
for index in random.sample(range(len(train_dataset)), 3):
|
230 |
+
print(f"Sample {index} of the training set: {train_dataset[index]}.")
|
231 |
+
|
232 |
+
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
|
233 |
+
data_module = dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
|
234 |
+
|
235 |
+
#Tell Trainer not to attempt DataParallel
|
236 |
+
model.is_parallelizable = True
|
237 |
+
model.model_parallel = True
|
238 |
+
|
239 |
+
trainer = Trainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
|
240 |
+
model.config.use_cache = False
|
241 |
+
|
242 |
+
trainer.train()
|
243 |
+
trainer.save_state()
|
244 |
+
safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
|
245 |
+
|
246 |
+
|
247 |
+
if __name__ == "__main__":
|
248 |
+
train()
|
training/data/alpaca_data.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2eddafc6b977608d778aaab8dfc7e50e547b3af9826dfb9e909d9fc362e4a419
|
3 |
+
size 22773992
|
training/requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
numpy
|
2 |
+
rouge_score
|
3 |
+
fire
|
4 |
+
openai
|
5 |
+
sentencepiece
|
6 |
+
wandb
|
7 |
+
gradio==3.9
|
8 |
+
deepspeed==0.9.2
|
9 |
+
accelerate
|
10 |
+
tensorboardX
|
training/src/configs/deepspeed_config.json
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"zero_optimization": {
|
3 |
+
"stage": 3,
|
4 |
+
"offload_optimizer": {
|
5 |
+
"device": "cpu",
|
6 |
+
"pin_memory": true
|
7 |
+
},
|
8 |
+
"offload_param": {
|
9 |
+
"device": "cpu",
|
10 |
+
"pin_memory": true
|
11 |
+
},
|
12 |
+
"overlap_comm": true,
|
13 |
+
"contiguous_gradients": true,
|
14 |
+
"sub_group_size": 0,
|
15 |
+
"reduce_bucket_size": "auto",
|
16 |
+
"stage3_prefetch_bucket_size": "auto",
|
17 |
+
"stage3_param_persistence_threshold": "auto",
|
18 |
+
"stage3_max_live_parameters": 0,
|
19 |
+
"stage3_max_reuse_distance": 0,
|
20 |
+
"stage3_gather_16bit_weights_on_model_save": true
|
21 |
+
},
|
22 |
+
"fp16": {
|
23 |
+
"enabled": true,
|
24 |
+
"auto_cast": false,
|
25 |
+
"loss_scale": 0,
|
26 |
+
"initial_scale_power": 32,
|
27 |
+
"loss_scale_window": 1000,
|
28 |
+
"hysteresis": 2,
|
29 |
+
"min_loss_scale": 1
|
30 |
+
},
|
31 |
+
"optimizer": {
|
32 |
+
"type": "AdamW",
|
33 |
+
"params": {
|
34 |
+
"lr": 2e-5,
|
35 |
+
"betas": [
|
36 |
+
0.9,
|
37 |
+
0.999
|
38 |
+
],
|
39 |
+
"eps": 1e-8,
|
40 |
+
"weight_decay": 0
|
41 |
+
}
|
42 |
+
},
|
43 |
+
"train_batch_size": "auto",
|
44 |
+
"train_micro_batch_size_per_gpu": "auto",
|
45 |
+
"wall_clock_breakdown": false
|
46 |
+
}
|
training/src/configs/hostfile
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
ip_address_of_main_node slots=num_of_gpus_in_each_node
|
2 |
+
ip_address_of_sub_node1 slots=num_of_gpus_in_each_node
|
training/src/conversation.py
ADDED
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Conversation prompt templates.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import dataclasses
|
6 |
+
from enum import auto, Enum
|
7 |
+
from typing import List, Tuple, Any, Dict
|
8 |
+
|
9 |
+
|
10 |
+
class SeparatorStyle(Enum):
|
11 |
+
"""Separator styles."""
|
12 |
+
|
13 |
+
ADD_COLON_SINGLE = auto()
|
14 |
+
ADD_COLON_TWO = auto()
|
15 |
+
NO_COLON_SINGLE = auto()
|
16 |
+
BAIZE = auto()
|
17 |
+
DOLLY = auto()
|
18 |
+
RWKV = auto()
|
19 |
+
PHOENIX = auto()
|
20 |
+
NEW_LINE = auto()
|
21 |
+
BILLA = auto()
|
22 |
+
|
23 |
+
|
24 |
+
@dataclasses.dataclass
|
25 |
+
class Conversation:
|
26 |
+
"""A class that keeps all conversation history."""
|
27 |
+
|
28 |
+
# The name of this template
|
29 |
+
name: str
|
30 |
+
# System prompts
|
31 |
+
system: str
|
32 |
+
# Two roles
|
33 |
+
roles: List[str]
|
34 |
+
# All messages
|
35 |
+
messages: List[List[str]]
|
36 |
+
# Offset of few shot examples
|
37 |
+
offset: int
|
38 |
+
# Separators
|
39 |
+
sep_style: SeparatorStyle
|
40 |
+
sep: str
|
41 |
+
sep2: str = None
|
42 |
+
# Stop criteria (the default one is EOS token)
|
43 |
+
stop_str: str = None
|
44 |
+
# Stops generation if meeting any token in this list
|
45 |
+
stop_token_ids: List[int] = None
|
46 |
+
|
47 |
+
# Used for the state in the gradio servers.
|
48 |
+
# TODO(lmzheng): move this out of this class.
|
49 |
+
conv_id: Any = None
|
50 |
+
skip_next: bool = False
|
51 |
+
model_name: str = None
|
52 |
+
|
53 |
+
def get_prompt(self) -> str:
|
54 |
+
"""Get the prompt for generation."""
|
55 |
+
if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
|
56 |
+
ret = self.system + self.sep
|
57 |
+
for role, message in self.messages:
|
58 |
+
if message:
|
59 |
+
ret += role + ": " + message + self.sep
|
60 |
+
else:
|
61 |
+
ret += role + ":"
|
62 |
+
return ret
|
63 |
+
elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
|
64 |
+
seps = [self.sep, self.sep2]
|
65 |
+
ret = self.system + seps[0]
|
66 |
+
for i, (role, message) in enumerate(self.messages):
|
67 |
+
if message:
|
68 |
+
ret += role + ": " + message + seps[i % 2]
|
69 |
+
else:
|
70 |
+
ret += role + ":"
|
71 |
+
return ret
|
72 |
+
elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
|
73 |
+
ret = self.system
|
74 |
+
for role, message in self.messages:
|
75 |
+
if message:
|
76 |
+
ret += role + message + self.sep
|
77 |
+
else:
|
78 |
+
ret += role
|
79 |
+
return ret
|
80 |
+
elif self.sep_style == SeparatorStyle.BAIZE:
|
81 |
+
ret = self.system + "\n"
|
82 |
+
for role, message in self.messages:
|
83 |
+
if message:
|
84 |
+
ret += role + message + "\n"
|
85 |
+
else:
|
86 |
+
ret += role
|
87 |
+
return ret
|
88 |
+
elif self.sep_style == SeparatorStyle.DOLLY:
|
89 |
+
seps = [self.sep, self.sep2]
|
90 |
+
ret = self.system
|
91 |
+
for i, (role, message) in enumerate(self.messages):
|
92 |
+
if message:
|
93 |
+
ret += role + ":\n" + message + seps[i % 2]
|
94 |
+
if i % 2 == 1:
|
95 |
+
ret += "\n\n"
|
96 |
+
else:
|
97 |
+
ret += role + ":\n"
|
98 |
+
return ret
|
99 |
+
elif self.sep_style == SeparatorStyle.RWKV:
|
100 |
+
ret = self.system
|
101 |
+
for i, (role, message) in enumerate(self.messages):
|
102 |
+
if message:
|
103 |
+
ret += (
|
104 |
+
role
|
105 |
+
+ ": "
|
106 |
+
+ message.replace("\r\n", "\n").replace("\n\n", "\n")
|
107 |
+
)
|
108 |
+
ret += "\n\n"
|
109 |
+
else:
|
110 |
+
ret += role + ":"
|
111 |
+
return ret
|
112 |
+
elif self.sep_style == SeparatorStyle.PHOENIX:
|
113 |
+
ret = self.system
|
114 |
+
for role, message in self.messages:
|
115 |
+
if message:
|
116 |
+
ret += role + ": " + "<s>" + message + "</s>"
|
117 |
+
else:
|
118 |
+
ret += role + ": " + "<s>"
|
119 |
+
return ret
|
120 |
+
elif self.sep_style == SeparatorStyle.NEW_LINE:
|
121 |
+
ret = self.system + self.sep
|
122 |
+
for role, message in self.messages:
|
123 |
+
if message:
|
124 |
+
ret += role + "\n" + message + self.sep
|
125 |
+
else:
|
126 |
+
ret += role + "\n"
|
127 |
+
return ret
|
128 |
+
elif self.sep_style == SeparatorStyle.BILLA:
|
129 |
+
ret = self.system + self.sep
|
130 |
+
for role, message in self.messages:
|
131 |
+
if message:
|
132 |
+
ret += role + ": " + message + self.sep
|
133 |
+
else:
|
134 |
+
ret += role + ": " # must be end with a space
|
135 |
+
return ret
|
136 |
+
else:
|
137 |
+
raise ValueError(f"Invalid style: {self.sep_style}")
|
138 |
+
|
139 |
+
def append_message(self, role: str, message: str):
|
140 |
+
"""Append a new message."""
|
141 |
+
self.messages.append([role, message])
|
142 |
+
|
143 |
+
def to_gradio_chatbot(self):
|
144 |
+
"""Convert the history to gradio chatbot format"""
|
145 |
+
ret = []
|
146 |
+
for i, (role, msg) in enumerate(self.messages[self.offset :]):
|
147 |
+
if i % 2 == 0:
|
148 |
+
ret.append([msg, None])
|
149 |
+
else:
|
150 |
+
ret[-1][-1] = msg
|
151 |
+
return ret
|
152 |
+
|
153 |
+
def to_openai_api_messages(self):
|
154 |
+
"""Convert the conversation to OpenAI chat completion format."""
|
155 |
+
ret = [{"role": "system", "content": self.system}]
|
156 |
+
|
157 |
+
for i, (_, msg) in enumerate(self.messages[self.offset :]):
|
158 |
+
if i % 2 == 0:
|
159 |
+
ret.append({"role": "user", "content": msg})
|
160 |
+
else:
|
161 |
+
if msg is not None:
|
162 |
+
ret.append({"role": "assistant", "content": msg})
|
163 |
+
return ret
|
164 |
+
|
165 |
+
def copy(self):
|
166 |
+
return Conversation(
|
167 |
+
name=self.name,
|
168 |
+
system=self.system,
|
169 |
+
roles=self.roles,
|
170 |
+
messages=[[x, y] for x, y in self.messages],
|
171 |
+
offset=self.offset,
|
172 |
+
sep_style=self.sep_style,
|
173 |
+
sep=self.sep,
|
174 |
+
sep2=self.sep2,
|
175 |
+
stop_str=self.stop_str,
|
176 |
+
stop_token_ids=self.stop_token_ids,
|
177 |
+
conv_id=self.conv_id,
|
178 |
+
model_name=self.model_name,
|
179 |
+
)
|
180 |
+
|
181 |
+
def dict(self):
|
182 |
+
return {
|
183 |
+
"name": self.name,
|
184 |
+
"system": self.system,
|
185 |
+
"roles": self.roles,
|
186 |
+
"messages": self.messages,
|
187 |
+
"offset": self.offset,
|
188 |
+
"conv_id": self.conv_id,
|
189 |
+
"model_name": self.model_name,
|
190 |
+
}
|
191 |
+
|
192 |
+
|
193 |
+
# A global registry for all conversation templates
|
194 |
+
conv_templates: Dict[str, Conversation] = {}
|
195 |
+
|
196 |
+
|
197 |
+
def register_conv_template(template: Conversation, override: bool = False):
|
198 |
+
"""Register a new conversation template."""
|
199 |
+
if not override:
|
200 |
+
assert template.name not in conv_templates, f"{name} has been registered."
|
201 |
+
conv_templates[template.name] = template
|
202 |
+
|
203 |
+
|
204 |
+
def get_conv_template(name: str) -> Conversation:
|
205 |
+
"""Get a conversation template."""
|
206 |
+
return conv_templates[name].copy()
|
207 |
+
|
208 |
+
|
209 |
+
# A template with one conversation example
|
210 |
+
register_conv_template(
|
211 |
+
Conversation(
|
212 |
+
name="one_shot",
|
213 |
+
system="A chat between a curious human and an artificial intelligence assistant. "
|
214 |
+
"The assistant gives helpful, detailed, and polite answers to the human's questions.",
|
215 |
+
roles=("Human", "Assistant"),
|
216 |
+
messages=(
|
217 |
+
(
|
218 |
+
"Human",
|
219 |
+
"What are the key differences between renewable and non-renewable energy sources?",
|
220 |
+
),
|
221 |
+
(
|
222 |
+
"Assistant",
|
223 |
+
"Renewable energy sources are those that can be replenished naturally in a relatively "
|
224 |
+
"short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
|
225 |
+
"Non-renewable energy sources, on the other hand, are finite and will eventually be "
|
226 |
+
"depleted, such as coal, oil, and natural gas. Here are some key differences between "
|
227 |
+
"renewable and non-renewable energy sources:\n"
|
228 |
+
"1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
|
229 |
+
"energy sources are finite and will eventually run out.\n"
|
230 |
+
"2. Environmental impact: Renewable energy sources have a much lower environmental impact "
|
231 |
+
"than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
|
232 |
+
"and other negative effects.\n"
|
233 |
+
"3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
|
234 |
+
"have lower operational costs than non-renewable sources.\n"
|
235 |
+
"4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
|
236 |
+
"locations than non-renewable sources.\n"
|
237 |
+
"5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
|
238 |
+
"situations and needs, while non-renewable sources are more rigid and inflexible.\n"
|
239 |
+
"6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
|
240 |
+
"non-renewable sources are not, and their depletion can lead to economic and social instability.",
|
241 |
+
),
|
242 |
+
),
|
243 |
+
offset=2,
|
244 |
+
sep_style=SeparatorStyle.ADD_COLON_SINGLE,
|
245 |
+
sep="\n### ",
|
246 |
+
stop_str="###",
|
247 |
+
)
|
248 |
+
)
|
249 |
+
|
250 |
+
# Vicuna v1.1 template
|
251 |
+
register_conv_template(
|
252 |
+
Conversation(
|
253 |
+
name="vicuna_v1.1",
|
254 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
255 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
256 |
+
roles=("USER", "ASSISTANT"),
|
257 |
+
messages=(),
|
258 |
+
offset=0,
|
259 |
+
sep_style=SeparatorStyle.ADD_COLON_TWO,
|
260 |
+
sep=" ",
|
261 |
+
sep2="</s>",
|
262 |
+
)
|
263 |
+
)
|
264 |
+
|
265 |
+
# Koala default template
|
266 |
+
register_conv_template(
|
267 |
+
Conversation(
|
268 |
+
name="koala_v1",
|
269 |
+
system="BEGINNING OF CONVERSATION:",
|
270 |
+
roles=("USER", "GPT"),
|
271 |
+
messages=(),
|
272 |
+
offset=0,
|
273 |
+
sep_style=SeparatorStyle.ADD_COLON_TWO,
|
274 |
+
sep=" ",
|
275 |
+
sep2="</s>",
|
276 |
+
)
|
277 |
+
)
|
278 |
+
|
279 |
+
# Dolly V2 default template
|
280 |
+
register_conv_template(
|
281 |
+
Conversation(
|
282 |
+
name="dolly_v2",
|
283 |
+
system="Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n",
|
284 |
+
roles=("### Instruction", "### Response"),
|
285 |
+
messages=(),
|
286 |
+
offset=0,
|
287 |
+
sep_style=SeparatorStyle.DOLLY,
|
288 |
+
sep="\n\n",
|
289 |
+
sep2="### End",
|
290 |
+
)
|
291 |
+
)
|
292 |
+
|
293 |
+
# OpenAssistant Pythia default template
|
294 |
+
register_conv_template(
|
295 |
+
Conversation(
|
296 |
+
name="oasst_pythia",
|
297 |
+
system="",
|
298 |
+
roles=("<|prompter|>", "<|assistant|>"),
|
299 |
+
messages=(),
|
300 |
+
offset=0,
|
301 |
+
sep_style=SeparatorStyle.NO_COLON_SINGLE,
|
302 |
+
sep="<|endoftext|>",
|
303 |
+
)
|
304 |
+
)
|
305 |
+
|
306 |
+
# StableLM Alpha default template
|
307 |
+
register_conv_template(
|
308 |
+
Conversation(
|
309 |
+
name="stablelm",
|
310 |
+
system="""<|SYSTEM|># StableLM Tuned (Alpha version)
|
311 |
+
- StableLM is a helpful and harmless open-source AI language model developed by StabilityAI.
|
312 |
+
- StableLM is excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user.
|
313 |
+
- StableLM is more than just an information source, StableLM is also able to write poetry, short stories, and make jokes.
|
314 |
+
- StableLM will refuse to participate in anything that could harm a human.
|
315 |
+
""",
|
316 |
+
roles=("<|USER|>", "<|ASSISTANT|>"),
|
317 |
+
messages=(),
|
318 |
+
offset=0,
|
319 |
+
sep_style=SeparatorStyle.NO_COLON_SINGLE,
|
320 |
+
sep="",
|
321 |
+
stop_token_ids=[50278, 50279, 50277, 1, 0],
|
322 |
+
)
|
323 |
+
)
|
324 |
+
|
325 |
+
# Baize default template
|
326 |
+
register_conv_template(
|
327 |
+
Conversation(
|
328 |
+
name="baize",
|
329 |
+
system="The following is a conversation between a human and an AI assistant named Baize (named after a mythical creature in Chinese folklore). Baize is an open-source AI assistant developed by UCSD and Sun Yat-Sen University. The human and the AI assistant take turns chatting. Human statements start with [|Human|] and AI assistant statements start with [|AI|]. The AI assistant always provides responses in as much detail as possible, and in Markdown format. The AI assistant always declines to engage with topics, questions and instructions related to unethical, controversial, or sensitive issues. Complete the transcript in exactly that format.",
|
330 |
+
roles=("[|Human|]", "[|AI|]"),
|
331 |
+
messages=(
|
332 |
+
("[|Human|]", "Hello!"),
|
333 |
+
("[|AI|]", "Hi!"),
|
334 |
+
),
|
335 |
+
offset=2,
|
336 |
+
sep_style=SeparatorStyle.BAIZE,
|
337 |
+
sep="[|Human|]",
|
338 |
+
stop_str="[|Human|]",
|
339 |
+
)
|
340 |
+
)
|
341 |
+
|
342 |
+
# RWKV-4-Raven default template
|
343 |
+
register_conv_template(
|
344 |
+
Conversation(
|
345 |
+
name="rwkv",
|
346 |
+
system="The following is a coherent verbose detailed conversation between Bob and Alice.\n\n",
|
347 |
+
roles=("Bob", "Alice"),
|
348 |
+
messages=(
|
349 |
+
("Bob", "Hi"),
|
350 |
+
(
|
351 |
+
"Alice",
|
352 |
+
"Hi. I am your assistant and I will answer all questions. Please feel free to ask any question and I will always answer it.",
|
353 |
+
),
|
354 |
+
),
|
355 |
+
offset=2,
|
356 |
+
sep_style=SeparatorStyle.RWKV,
|
357 |
+
sep="",
|
358 |
+
stop_str="\n\n",
|
359 |
+
)
|
360 |
+
)
|
361 |
+
|
362 |
+
# Buddy default template
|
363 |
+
register_conv_template(
|
364 |
+
Conversation(
|
365 |
+
name="openbuddy",
|
366 |
+
system="""Consider a conversation between User (a human) and Assistant (named Buddy).
|
367 |
+
Buddy is an INTP-T, a friendly, intelligent and multilingual AI assistant, by OpenBuddy team. GitHub: https://github.com/OpenBuddy/OpenBuddy
|
368 |
+
Buddy cannot access the Internet.
|
369 |
+
Buddy can fluently speak the user's language (e.g. English, Chinese).
|
370 |
+
Buddy can generate poems, stories, code, essays, songs, parodies, and more.
|
371 |
+
Buddy possesses vast knowledge about the world, history, and culture.
|
372 |
+
Buddy's responses are always safe, creative, high-quality, human-like, and interesting.
|
373 |
+
Buddy strictly refuses to discuss political, NSFW, or other unsafe topics.
|
374 |
+
|
375 |
+
User: Hi.
|
376 |
+
Assistant: Hi, I'm Buddy, your AI assistant. How can I help you today?""",
|
377 |
+
roles=("User", "Assistant"),
|
378 |
+
messages=(),
|
379 |
+
offset=0,
|
380 |
+
sep_style=SeparatorStyle.ADD_COLON_SINGLE,
|
381 |
+
sep="\n",
|
382 |
+
)
|
383 |
+
)
|
384 |
+
|
385 |
+
# Phoenix default template
|
386 |
+
register_conv_template(
|
387 |
+
Conversation(
|
388 |
+
name="phoenix",
|
389 |
+
system="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n",
|
390 |
+
roles=("Human", "Assistant"),
|
391 |
+
messages=(),
|
392 |
+
offset=0,
|
393 |
+
sep_style=SeparatorStyle.PHOENIX,
|
394 |
+
sep="</s>",
|
395 |
+
)
|
396 |
+
)
|
397 |
+
|
398 |
+
# ChatGPT default template
|
399 |
+
register_conv_template(
|
400 |
+
Conversation(
|
401 |
+
name="chatgpt",
|
402 |
+
system="You are a helpful assistant.",
|
403 |
+
roles=("user", "assistant"),
|
404 |
+
messages=(),
|
405 |
+
offset=0,
|
406 |
+
sep_style=None,
|
407 |
+
sep=None,
|
408 |
+
)
|
409 |
+
)
|
410 |
+
|
411 |
+
# Claude default template
|
412 |
+
register_conv_template(
|
413 |
+
Conversation(
|
414 |
+
name="claude",
|
415 |
+
system="",
|
416 |
+
roles=("Human", "Assistant"),
|
417 |
+
messages=(),
|
418 |
+
offset=0,
|
419 |
+
sep_style=SeparatorStyle.ADD_COLON_SINGLE,
|
420 |
+
sep="\n\n",
|
421 |
+
)
|
422 |
+
)
|
423 |
+
|
424 |
+
# MPT default template
|
425 |
+
register_conv_template(
|
426 |
+
Conversation(
|
427 |
+
name="mpt",
|
428 |
+
system="""<|im_start|>system
|
429 |
+
- You are a helpful assistant chatbot trained by MosaicML.
|
430 |
+
- You answer questions.
|
431 |
+
- You are excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user.
|
432 |
+
- You are more than just an information source, you are also able to write poetry, short stories, and make jokes.
|
433 |
+
""",
|
434 |
+
roles=("<|im_start|>user", "<|im_start|>assistant"),
|
435 |
+
messages=(),
|
436 |
+
offset=0,
|
437 |
+
sep_style=SeparatorStyle.NEW_LINE,
|
438 |
+
sep="<|im_end|>",
|
439 |
+
stop_token_ids=[50278, 0],
|
440 |
+
)
|
441 |
+
)
|
442 |
+
|
443 |
+
# Bard default template
|
444 |
+
# Reference: https://github.com/google/generative-ai-python/blob/9c99bcb474a991a97a2e7d62fcdb52db7ce40729/google/generativeai/discuss.py#L150
|
445 |
+
# https://github.com/google/generative-ai-python/blob/9c99bcb474a991a97a2e7d62fcdb52db7ce40729/google/generativeai/discuss.py#L40
|
446 |
+
register_conv_template(
|
447 |
+
Conversation(
|
448 |
+
name="bard",
|
449 |
+
system="",
|
450 |
+
roles=("0", "1"),
|
451 |
+
messages=(),
|
452 |
+
offset=0,
|
453 |
+
sep_style=None,
|
454 |
+
sep=None,
|
455 |
+
)
|
456 |
+
)
|
457 |
+
|
458 |
+
# BiLLa default template
|
459 |
+
register_conv_template(
|
460 |
+
Conversation(
|
461 |
+
name="billa",
|
462 |
+
system="",
|
463 |
+
roles=("Human", "Assistant"),
|
464 |
+
messages=(),
|
465 |
+
offset=0,
|
466 |
+
sep_style=SeparatorStyle.BILLA,
|
467 |
+
sep="\n",
|
468 |
+
stop_str="Human:",
|
469 |
+
)
|
470 |
+
)
|
471 |
+
|
472 |
+
if __name__ == "__main__":
|
473 |
+
conv = get_conv_template("vicuna_v1.1")
|
474 |
+
conv.append_message(conv.roles[0], "Hello!")
|
475 |
+
conv.append_message(conv.roles[1], "Hi!")
|
476 |
+
conv.append_message(conv.roles[0], "How are you?")
|
477 |
+
conv.append_message(conv.roles[1], None)
|
478 |
+
print(conv.get_prompt())
|
training/src/environment.yml
ADDED
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: llamax
|
2 |
+
channels:
|
3 |
+
- pytorch
|
4 |
+
- defaults
|
5 |
+
dependencies:
|
6 |
+
- _libgcc_mutex=0.1=main
|
7 |
+
- _openmp_mutex=5.1=1_gnu
|
8 |
+
- blas=1.0=mkl
|
9 |
+
- bzip2=1.0.8=h7b6447c_0
|
10 |
+
- ca-certificates=2023.01.10=h06a4308_0
|
11 |
+
- charset-normalizer=2.0.4=pyhd3eb1b0_0
|
12 |
+
- cudatoolkit=11.3.1=h2bc3f7f_2
|
13 |
+
- ffmpeg=4.3=hf484d3e_0
|
14 |
+
- freetype=2.12.1=h4a9f257_0
|
15 |
+
- giflib=5.2.1=h5eee18b_3
|
16 |
+
- gmp=6.2.1=h295c915_3
|
17 |
+
- gnutls=3.6.15=he1e5248_0
|
18 |
+
- intel-openmp=2021.4.0=h06a4308_3561
|
19 |
+
- jpeg=9e=h5eee18b_1
|
20 |
+
- lame=3.100=h7b6447c_0
|
21 |
+
- lcms2=2.12=h3be6417_0
|
22 |
+
- ld_impl_linux-64=2.38=h1181459_1
|
23 |
+
- lerc=3.0=h295c915_0
|
24 |
+
- libdeflate=1.17=h5eee18b_0
|
25 |
+
- libffi=3.4.2=h6a678d5_6
|
26 |
+
- libgcc-ng=11.2.0=h1234567_1
|
27 |
+
- libgomp=11.2.0=h1234567_1
|
28 |
+
- libiconv=1.16=h7f8727e_2
|
29 |
+
- libidn2=2.3.2=h7f8727e_0
|
30 |
+
- libpng=1.6.39=h5eee18b_0
|
31 |
+
- libstdcxx-ng=11.2.0=h1234567_1
|
32 |
+
- libtasn1=4.16.0=h27cfd23_0
|
33 |
+
- libtiff=4.5.0=h6a678d5_2
|
34 |
+
- libunistring=0.9.10=h27cfd23_0
|
35 |
+
- libuuid=1.41.5=h5eee18b_0
|
36 |
+
- libwebp=1.2.4=h11a3e52_1
|
37 |
+
- libwebp-base=1.2.4=h5eee18b_1
|
38 |
+
- lz4-c=1.9.4=h6a678d5_0
|
39 |
+
- mkl=2021.4.0=h06a4308_640
|
40 |
+
- mkl_fft=1.3.1=py310hd6ae3a3_0
|
41 |
+
- mkl_random=1.2.2=py310h00e6091_0
|
42 |
+
- ncurses=6.4=h6a678d5_0
|
43 |
+
- nettle=3.7.3=hbbd107a_1
|
44 |
+
- numpy-base=1.23.5=py310h8e6c178_0
|
45 |
+
- openh264=2.1.1=h4ff587b_0
|
46 |
+
- openssl=1.1.1t=h7f8727e_0
|
47 |
+
- pycparser=2.21=pyhd3eb1b0_0
|
48 |
+
- python=3.10.10=h7a1cb2a_2
|
49 |
+
- pytorch=1.12.0=py3.10_cuda11.3_cudnn8.3.2_0
|
50 |
+
- pytorch-mutex=1.0=cuda
|
51 |
+
- readline=8.2=h5eee18b_0
|
52 |
+
- six=1.16.0=pyhd3eb1b0_1
|
53 |
+
- sqlite=3.41.1=h5eee18b_0
|
54 |
+
- tk=8.6.12=h1ccaba5_0
|
55 |
+
- typing_extensions=4.4.0=py310h06a4308_0
|
56 |
+
- tzdata=2022g=h04d1e81_0
|
57 |
+
- xz=5.2.10=h5eee18b_1
|
58 |
+
- zlib=1.2.13=h5eee18b_0
|
59 |
+
- zstd=1.5.2=ha4553b6_0
|
60 |
+
- pip:
|
61 |
+
- absl-py==1.4.0
|
62 |
+
- accelerate==0.18.0
|
63 |
+
- aiofiles==23.1.0
|
64 |
+
- aiohttp==3.8.4
|
65 |
+
- aiosignal==1.3.1
|
66 |
+
- altair==4.2.2
|
67 |
+
- anyio==3.6.2
|
68 |
+
- appdirs==1.4.4
|
69 |
+
- async-timeout==4.0.2
|
70 |
+
- attrs==22.2.0
|
71 |
+
- bcrypt==4.0.1
|
72 |
+
- beartype==0.12.0
|
73 |
+
- brotlipy==0.7.0
|
74 |
+
- cachetools==5.3.0
|
75 |
+
- certifi==2022.12.7
|
76 |
+
- cffi==1.15.1
|
77 |
+
- chatllama-py==0.0.3
|
78 |
+
- click==8.1.3
|
79 |
+
- cmake==3.26.1
|
80 |
+
- contourpy==1.0.7
|
81 |
+
- cryptography==39.0.1
|
82 |
+
- cycler==0.11.0
|
83 |
+
- dataclasses-json==0.5.7
|
84 |
+
- datasets==2.10.1
|
85 |
+
- deepspeed==0.8.3
|
86 |
+
- dill==0.3.6
|
87 |
+
- docker-pycreds==0.4.0
|
88 |
+
- einops==0.6.0
|
89 |
+
- entrypoints==0.4
|
90 |
+
- fairscale==0.4.13
|
91 |
+
- fastapi==0.95.0
|
92 |
+
- ffmpy==0.3.0
|
93 |
+
- filelock==3.10.5
|
94 |
+
- fire==0.5.0
|
95 |
+
- flit-core==3.8.0
|
96 |
+
- fonttools==4.39.2
|
97 |
+
- frozenlist==1.3.3
|
98 |
+
- fsspec==2023.3.0
|
99 |
+
- gitdb==4.0.10
|
100 |
+
- gitpython==3.1.31
|
101 |
+
- google-auth==2.16.3
|
102 |
+
- google-auth-oauthlib==0.4.6
|
103 |
+
- gradio==3.9
|
104 |
+
- greenlet==2.0.2
|
105 |
+
- grpcio==1.51.3
|
106 |
+
- h11==0.12.0
|
107 |
+
- hjson==3.1.0
|
108 |
+
- httpcore==0.15.0
|
109 |
+
- httpx==0.23.3
|
110 |
+
- huggingface-hub==0.13.3
|
111 |
+
- idna==3.4
|
112 |
+
- jinja2==3.1.2
|
113 |
+
- joblib==1.2.0
|
114 |
+
- jsonschema==4.17.3
|
115 |
+
- kiwisolver==1.4.4
|
116 |
+
- langchain==0.0.123
|
117 |
+
- linkify-it-py==2.0.0
|
118 |
+
- lit==16.0.0
|
119 |
+
- markdown==3.4.3
|
120 |
+
- markdown-it-py==2.2.0
|
121 |
+
- markupsafe==2.1.2
|
122 |
+
- marshmallow==3.19.0
|
123 |
+
- marshmallow-enum==1.5.1
|
124 |
+
- matplotlib==3.7.1
|
125 |
+
- mdit-py-plugins==0.3.3
|
126 |
+
- mdurl==0.1.2
|
127 |
+
- mkl-fft==1.3.1
|
128 |
+
- mkl-random==1.2.2
|
129 |
+
- mkl-service==2.4.0
|
130 |
+
- multidict==6.0.4
|
131 |
+
- multiprocess==0.70.14
|
132 |
+
- mypy-extensions==1.0.0
|
133 |
+
- ninja==1.11.1
|
134 |
+
- nltk==3.8.1
|
135 |
+
- numpy==1.23.5
|
136 |
+
- oauthlib==3.2.2
|
137 |
+
- openai==0.27.2
|
138 |
+
- orjson==3.8.8
|
139 |
+
- packaging==23.0
|
140 |
+
- pandas==1.5.3
|
141 |
+
- paramiko==3.1.0
|
142 |
+
- pathtools==0.1.2
|
143 |
+
- pillow==9.4.0
|
144 |
+
- pip==23.0.1
|
145 |
+
- plotly==5.13.1
|
146 |
+
- protobuf==4.22.1
|
147 |
+
- psutil==5.9.4
|
148 |
+
- py-cpuinfo==9.0.0
|
149 |
+
- pyarrow==11.0.0
|
150 |
+
- pyasn1==0.4.8
|
151 |
+
- pyasn1-modules==0.2.8
|
152 |
+
- pycryptodome==3.17
|
153 |
+
- pydantic==1.10.7
|
154 |
+
- pydub==0.25.1
|
155 |
+
- pynacl==1.5.0
|
156 |
+
- pyopenssl==23.0.0
|
157 |
+
- pyparsing==3.0.9
|
158 |
+
- pyrsistent==0.19.3
|
159 |
+
- pysocks==1.7.1
|
160 |
+
- python-dateutil==2.8.2
|
161 |
+
- python-multipart==0.0.6
|
162 |
+
- pytz==2023.2
|
163 |
+
- pyyaml==6.0
|
164 |
+
- regex==2023.3.23
|
165 |
+
- requests==2.28.1
|
166 |
+
- requests-oauthlib==1.3.1
|
167 |
+
- responses==0.18.0
|
168 |
+
- rfc3986==1.5.0
|
169 |
+
- rouge-score==0.1.2
|
170 |
+
- rsa==4.9
|
171 |
+
- semantic-version==2.10.0
|
172 |
+
- sentencepiece==0.1.97
|
173 |
+
- sentry-sdk==1.17.0
|
174 |
+
- setproctitle==1.3.2
|
175 |
+
- setuptools==65.6.3
|
176 |
+
- smmap==5.0.0
|
177 |
+
- sniffio==1.3.0
|
178 |
+
- sqlalchemy==1.4.47
|
179 |
+
- starlette==0.26.1
|
180 |
+
- tenacity==8.2.2
|
181 |
+
- tensorboard==2.12.0
|
182 |
+
- tensorboard-data-server==0.7.0
|
183 |
+
- tensorboard-plugin-wit==1.8.1
|
184 |
+
- termcolor==2.2.0
|
185 |
+
- tokenizers==0.12.1
|
186 |
+
- toolz==0.12.0
|
187 |
+
- torch==1.12.0
|
188 |
+
- torchaudio==0.12.0
|
189 |
+
- torchvision==0.13.0
|
190 |
+
- tqdm==4.65.0
|
191 |
+
- transformers==4.28.0.dev0
|
192 |
+
- typing-extensions==4.4.0
|
193 |
+
- typing-inspect==0.8.0
|
194 |
+
- uc-micro-py==1.0.1
|
195 |
+
- urllib3==1.26.14
|
196 |
+
- uvicorn==0.21.1
|
197 |
+
- wandb==0.14.0
|
198 |
+
- websockets==10.4
|
199 |
+
- werkzeug==2.2.3
|
200 |
+
- wheel==0.38.4
|
201 |
+
- xxhash==3.2.0
|
202 |
+
- yarl==1.8.2
|
203 |
+
prefix: /home/yourname/.conda/envs/llamax
|
training/src/generate.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
|
3 |
+
import fire
|
4 |
+
import torch
|
5 |
+
# from peft import PeftModel
|
6 |
+
import transformers
|
7 |
+
import gradio as gr
|
8 |
+
|
9 |
+
assert (
|
10 |
+
"LlamaTokenizer" in transformers._import_structure["models.llama"]
|
11 |
+
), "LLaMA is now in HuggingFace's main branch.\nPlease reinstall it: pip uninstall transformers && pip install git+https://github.com/huggingface/transformers.git"
|
12 |
+
from transformers import LlamaTokenizer, LlamaForCausalLM, GenerationConfig
|
13 |
+
|
14 |
+
if torch.cuda.is_available():
|
15 |
+
device = "cuda"
|
16 |
+
else:
|
17 |
+
device = "cpu"
|
18 |
+
|
19 |
+
try:
|
20 |
+
if torch.backends.mps.is_available():
|
21 |
+
device = "mps"
|
22 |
+
except:
|
23 |
+
pass
|
24 |
+
|
25 |
+
|
26 |
+
def main(
|
27 |
+
load_8bit: bool = False,
|
28 |
+
base_model: str = "/path/to/llama-7B/hf/ft/checkpoint-300",
|
29 |
+
# lora_weights: str = "tloen/alpaca-lora-7b",
|
30 |
+
):
|
31 |
+
assert base_model, (
|
32 |
+
"Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'"
|
33 |
+
)
|
34 |
+
|
35 |
+
tokenizer = LlamaTokenizer.from_pretrained(base_model)
|
36 |
+
if device == "cuda":
|
37 |
+
model = LlamaForCausalLM.from_pretrained(
|
38 |
+
base_model,
|
39 |
+
load_in_8bit=load_8bit,
|
40 |
+
torch_dtype=torch.float16,
|
41 |
+
device_map="auto",
|
42 |
+
)
|
43 |
+
elif device == "mps":
|
44 |
+
model = LlamaForCausalLM.from_pretrained(
|
45 |
+
base_model,
|
46 |
+
device_map={"": device},
|
47 |
+
torch_dtype=torch.float16,
|
48 |
+
)
|
49 |
+
|
50 |
+
# unwind broken decapoda-research config
|
51 |
+
model.config.pad_token_id = tokenizer.pad_token_id = 0 # unk
|
52 |
+
model.config.bos_token_id = 1
|
53 |
+
model.config.eos_token_id = 2
|
54 |
+
|
55 |
+
if not load_8bit:
|
56 |
+
model.half() # seems to fix bugs for some users.
|
57 |
+
|
58 |
+
model.eval()
|
59 |
+
if torch.__version__ >= "2" and sys.platform != "win32":
|
60 |
+
model = torch.compile(model)
|
61 |
+
|
62 |
+
def evaluate(
|
63 |
+
instruction,
|
64 |
+
input=None,
|
65 |
+
temperature=0.6,
|
66 |
+
top_p=0.9,
|
67 |
+
top_k=40,
|
68 |
+
num_beams=4,
|
69 |
+
max_new_tokens=512,
|
70 |
+
**kwargs,
|
71 |
+
):
|
72 |
+
prompt = generate_prompt(instruction, input)
|
73 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
74 |
+
input_ids = inputs["input_ids"].to(device)
|
75 |
+
generation_config = GenerationConfig(
|
76 |
+
temperature=temperature,
|
77 |
+
top_p=top_p,
|
78 |
+
top_k=top_k,
|
79 |
+
num_beams=num_beams,
|
80 |
+
**kwargs,
|
81 |
+
)
|
82 |
+
with torch.no_grad():
|
83 |
+
generation_output = model.generate(
|
84 |
+
input_ids=input_ids,
|
85 |
+
generation_config=generation_config,
|
86 |
+
return_dict_in_generate=True,
|
87 |
+
output_scores=True,
|
88 |
+
max_new_tokens=max_new_tokens,
|
89 |
+
)
|
90 |
+
s = generation_output.sequences[0]
|
91 |
+
output = tokenizer.decode(s)
|
92 |
+
return output.split("### Response:")[1].strip()
|
93 |
+
|
94 |
+
gr.Interface(
|
95 |
+
fn=evaluate,
|
96 |
+
inputs=[
|
97 |
+
gr.components.Textbox(
|
98 |
+
lines=2, label="Instruction", placeholder="Tell me about alpacas."
|
99 |
+
),
|
100 |
+
gr.components.Textbox(lines=2, label="Input", placeholder="none"),
|
101 |
+
gr.components.Slider(minimum=0, maximum=1, value=0.1, label="Temperature"),
|
102 |
+
gr.components.Slider(minimum=0, maximum=1, value=0.75, label="Top p"),
|
103 |
+
gr.components.Slider(
|
104 |
+
minimum=0, maximum=100, step=1, value=40, label="Top k"
|
105 |
+
),
|
106 |
+
gr.components.Slider(minimum=1, maximum=4, step=1, value=4, label="Beams"),
|
107 |
+
gr.components.Slider(
|
108 |
+
minimum=1, maximum=2000, step=1, value=128, label="Max tokens"
|
109 |
+
),
|
110 |
+
],
|
111 |
+
outputs=[
|
112 |
+
gr.inputs.Textbox(
|
113 |
+
lines=5,
|
114 |
+
label="Output",
|
115 |
+
)
|
116 |
+
],
|
117 |
+
title="Llama-X",
|
118 |
+
description="Improve LLaMA model to follow instructions.",
|
119 |
+
).launch(share=True)
|
120 |
+
|
121 |
+
|
122 |
+
def generate_prompt(instruction, input=None):
|
123 |
+
if input:
|
124 |
+
return f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
|
125 |
+
|
126 |
+
### Instruction:
|
127 |
+
{instruction}
|
128 |
+
|
129 |
+
### Input:
|
130 |
+
{input}
|
131 |
+
|
132 |
+
### Response:
|
133 |
+
"""
|
134 |
+
else:
|
135 |
+
return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.
|
136 |
+
|
137 |
+
### Instruction:
|
138 |
+
{instruction}
|
139 |
+
|
140 |
+
### Response:
|
141 |
+
"""
|
142 |
+
|
143 |
+
|
144 |
+
if __name__ == "__main__":
|
145 |
+
fire.Fire(main)
|
training/src/train.py
ADDED
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import copy
|
16 |
+
import logging
|
17 |
+
import random
|
18 |
+
from dataclasses import dataclass, field
|
19 |
+
from typing import Optional, Dict, Sequence
|
20 |
+
|
21 |
+
import torch
|
22 |
+
import torch.distributed
|
23 |
+
import transformers
|
24 |
+
from torch.utils.data import Dataset
|
25 |
+
from transformers import Trainer
|
26 |
+
from datasets import load_dataset
|
27 |
+
import utils
|
28 |
+
|
29 |
+
IGNORE_INDEX = -100
|
30 |
+
DEFAULT_PAD_TOKEN = "[PAD]"
|
31 |
+
DEFAULT_EOS_TOKEN = "</s>"
|
32 |
+
DEFAULT_BOS_TOKEN = "</s>"
|
33 |
+
DEFAULT_UNK_TOKEN = "</s>"
|
34 |
+
PROMPT_DICT = {
|
35 |
+
"prompt_input": (
|
36 |
+
"Below is an instruction that describes a task, paired with an input that provides further context. "
|
37 |
+
"Write a response that appropriately completes the request.\n\n"
|
38 |
+
"### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:"
|
39 |
+
),
|
40 |
+
"prompt_no_input": (
|
41 |
+
"Below is an instruction that describes a task. "
|
42 |
+
"Write a response that appropriately completes the request.\n\n"
|
43 |
+
"### Instruction:\n{instruction}\n\n### Response:"
|
44 |
+
),
|
45 |
+
}
|
46 |
+
|
47 |
+
|
48 |
+
@dataclass
|
49 |
+
class ModelArguments:
|
50 |
+
model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
|
51 |
+
|
52 |
+
|
53 |
+
@dataclass
|
54 |
+
class DataArguments:
|
55 |
+
data_path: str = field(default=None, metadata={"help": "Path to the training data."})
|
56 |
+
|
57 |
+
|
58 |
+
@dataclass
|
59 |
+
class TrainingArguments(transformers.TrainingArguments):
|
60 |
+
cache_dir: Optional[str] = field(default=None)
|
61 |
+
optim: str = field(default="adamw_torch")
|
62 |
+
model_max_length: int = field(
|
63 |
+
default=512,
|
64 |
+
metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
|
65 |
+
)
|
66 |
+
|
67 |
+
|
68 |
+
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
|
69 |
+
"""Collects the state dict and dump to disk."""
|
70 |
+
state_dict = trainer.model.state_dict()
|
71 |
+
if trainer.args.should_save:
|
72 |
+
cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
|
73 |
+
del state_dict
|
74 |
+
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
|
75 |
+
|
76 |
+
|
77 |
+
def smart_tokenizer_and_embedding_resize(
|
78 |
+
special_tokens_dict: Dict,
|
79 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
80 |
+
model: transformers.PreTrainedModel,
|
81 |
+
):
|
82 |
+
"""Resize tokenizer and embedding.
|
83 |
+
|
84 |
+
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
|
85 |
+
"""
|
86 |
+
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
|
87 |
+
model.resize_token_embeddings(len(tokenizer))
|
88 |
+
|
89 |
+
if num_new_tokens > 0:
|
90 |
+
input_embeddings = model.get_input_embeddings().weight.data
|
91 |
+
output_embeddings = model.get_output_embeddings().weight.data
|
92 |
+
|
93 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
94 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
95 |
+
|
96 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
97 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
98 |
+
|
99 |
+
|
100 |
+
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
|
101 |
+
"""Tokenize a list of strings."""
|
102 |
+
tokenized_list = [
|
103 |
+
tokenizer(
|
104 |
+
text,
|
105 |
+
return_tensors="pt",
|
106 |
+
padding="longest",
|
107 |
+
max_length=tokenizer.model_max_length,
|
108 |
+
truncation=True,
|
109 |
+
)
|
110 |
+
for text in strings
|
111 |
+
]
|
112 |
+
input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
|
113 |
+
input_ids_lens = labels_lens = [
|
114 |
+
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list
|
115 |
+
]
|
116 |
+
return dict(
|
117 |
+
input_ids=input_ids,
|
118 |
+
labels=labels,
|
119 |
+
input_ids_lens=input_ids_lens,
|
120 |
+
labels_lens=labels_lens,
|
121 |
+
)
|
122 |
+
|
123 |
+
|
124 |
+
def preprocess(
|
125 |
+
sources: Sequence[str],
|
126 |
+
targets: Sequence[str],
|
127 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
128 |
+
) -> Dict:
|
129 |
+
"""Preprocess the data by tokenizing."""
|
130 |
+
examples = [s + t for s, t in zip(sources, targets)]
|
131 |
+
examples_tokenized, sources_tokenized = [_tokenize_fn(strings, tokenizer) for strings in (examples, sources)]
|
132 |
+
input_ids = examples_tokenized["input_ids"]
|
133 |
+
labels = copy.deepcopy(input_ids)
|
134 |
+
for label, source_len in zip(labels, sources_tokenized["input_ids_lens"]):
|
135 |
+
label[:source_len] = IGNORE_INDEX
|
136 |
+
return dict(input_ids=input_ids, labels=labels)
|
137 |
+
|
138 |
+
|
139 |
+
@dataclass
|
140 |
+
class DataCollatorForSupervisedDataset(object):
|
141 |
+
"""Collate examples for supervised fine-tuning."""
|
142 |
+
|
143 |
+
tokenizer: transformers.PreTrainedTokenizer
|
144 |
+
|
145 |
+
def __call__(self, instances: Sequence[Dict]) -> Dict[str, torch.Tensor]:
|
146 |
+
input_ids, labels = tuple([instance[key] for instance in instances] for key in ("input_ids", "labels"))
|
147 |
+
input_ids = [torch.tensor(x) for x in input_ids]
|
148 |
+
input_ids = torch.nn.utils.rnn.pad_sequence(
|
149 |
+
input_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id
|
150 |
+
)
|
151 |
+
labels = [torch.tensor(x) for x in labels]
|
152 |
+
labels = torch.nn.utils.rnn.pad_sequence(labels, batch_first=True, padding_value=IGNORE_INDEX)
|
153 |
+
return dict(
|
154 |
+
input_ids=input_ids,
|
155 |
+
labels=labels,
|
156 |
+
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
|
157 |
+
)
|
158 |
+
|
159 |
+
def train_tokenize_function(examples, tokenizer):
|
160 |
+
prompt_input, prompt_no_input = PROMPT_DICT["prompt_input"], PROMPT_DICT["prompt_no_input"]
|
161 |
+
if 'input' in examples:
|
162 |
+
sources = [
|
163 |
+
prompt_input.format_map(dict(instruction=instruction, input=input)) if input != "" \
|
164 |
+
else prompt_no_input.format_map(dict(instruction=instruction)) \
|
165 |
+
for instruction, input in zip(examples['instruction'], examples['input'])
|
166 |
+
]
|
167 |
+
else:
|
168 |
+
sources = [
|
169 |
+
prompt_no_input.format_map(dict(instruction=instruction)) \
|
170 |
+
for instruction in examples['instruction']
|
171 |
+
]
|
172 |
+
targets = [f"{output}{tokenizer.eos_token}" for output in examples['output']]
|
173 |
+
data_dict = preprocess(sources, targets, tokenizer)
|
174 |
+
return data_dict
|
175 |
+
|
176 |
+
def train():
|
177 |
+
parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
|
178 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
179 |
+
|
180 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
181 |
+
model_args.model_name_or_path,
|
182 |
+
cache_dir=training_args.cache_dir,
|
183 |
+
)
|
184 |
+
|
185 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
186 |
+
model_args.model_name_or_path,
|
187 |
+
cache_dir=training_args.cache_dir,
|
188 |
+
model_max_length=training_args.model_max_length,
|
189 |
+
padding_side="right",
|
190 |
+
use_fast=True,
|
191 |
+
)
|
192 |
+
if tokenizer.pad_token is None:
|
193 |
+
smart_tokenizer_and_embedding_resize(
|
194 |
+
special_tokens_dict=dict(pad_token=DEFAULT_PAD_TOKEN),
|
195 |
+
tokenizer=tokenizer,
|
196 |
+
model=model,
|
197 |
+
)
|
198 |
+
if "llama" in model_args.model_name_or_path:
|
199 |
+
tokenizer.add_special_tokens(
|
200 |
+
{
|
201 |
+
"eos_token": DEFAULT_EOS_TOKEN,
|
202 |
+
"bos_token": DEFAULT_BOS_TOKEN,
|
203 |
+
"unk_token": DEFAULT_UNK_TOKEN,
|
204 |
+
}
|
205 |
+
)
|
206 |
+
|
207 |
+
raw_train_datasets = load_dataset('json', data_files=data_args.data_path, split="train", cache_dir=training_args.cache_dir)
|
208 |
+
if training_args.local_rank > 0:
|
209 |
+
torch.distributed.barrier()
|
210 |
+
|
211 |
+
train_dataset = raw_train_datasets.map(
|
212 |
+
train_tokenize_function,
|
213 |
+
batched=True,
|
214 |
+
batch_size=3000,
|
215 |
+
num_proc=32,
|
216 |
+
remove_columns=raw_train_datasets.column_names,
|
217 |
+
load_from_cache_file=True, # not args.overwrite_cache
|
218 |
+
desc="Running tokenizer on train dataset",
|
219 |
+
fn_kwargs={"tokenizer": tokenizer}
|
220 |
+
)
|
221 |
+
|
222 |
+
if training_args.local_rank == 0:
|
223 |
+
torch.distributed.barrier()
|
224 |
+
|
225 |
+
if training_args.local_rank == 0:
|
226 |
+
print(len(train_dataset))
|
227 |
+
for index in random.sample(range(len(train_dataset)), 3):
|
228 |
+
print(f"Sample {index} of the training set: {train_dataset[index]}.")
|
229 |
+
|
230 |
+
data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
|
231 |
+
data_module = dict(train_dataset=train_dataset, eval_dataset=None, data_collator=data_collator)
|
232 |
+
|
233 |
+
#Tell Trainer not to attempt DataParallel
|
234 |
+
model.is_parallelizable = True
|
235 |
+
model.model_parallel = True
|
236 |
+
|
237 |
+
trainer = Trainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
|
238 |
+
model.config.use_cache = False
|
239 |
+
|
240 |
+
trainer.train()
|
241 |
+
trainer.save_state()
|
242 |
+
safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
|
243 |
+
|
244 |
+
|
245 |
+
if __name__ == "__main__":
|
246 |
+
train()
|
training/src/train_freeform_multiturn.py
ADDED
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
import json
|
15 |
+
import copy
|
16 |
+
import logging
|
17 |
+
from dataclasses import dataclass, field
|
18 |
+
from typing import Optional, Dict, Sequence
|
19 |
+
|
20 |
+
import torch
|
21 |
+
import transformers
|
22 |
+
from torch.utils.data import Dataset
|
23 |
+
from transformers import Trainer
|
24 |
+
from transformers.trainer_pt_utils import LabelSmoother
|
25 |
+
|
26 |
+
from conversation import SeparatorStyle, Conversation
|
27 |
+
# from fastchat.model.model_adapter import get_conversation_template
|
28 |
+
|
29 |
+
import utils
|
30 |
+
|
31 |
+
|
32 |
+
IGNORE_TOKEN_ID = LabelSmoother.ignore_index
|
33 |
+
|
34 |
+
# IGNORE_INDEX = -100
|
35 |
+
DEFAULT_PAD_TOKEN = "[PAD]"
|
36 |
+
DEFAULT_EOS_TOKEN = "</s>"
|
37 |
+
DEFAULT_BOS_TOKEN = "</s>"
|
38 |
+
DEFAULT_UNK_TOKEN = "</s>"
|
39 |
+
# PROMPT_DICT = {
|
40 |
+
# "prompt_input": (
|
41 |
+
# "{instruction}\n\n### Response:"
|
42 |
+
# ),
|
43 |
+
# "prompt_no_input": (
|
44 |
+
# "{instruction}\n\n### Response:"
|
45 |
+
# ),
|
46 |
+
# }
|
47 |
+
|
48 |
+
|
49 |
+
@dataclass
|
50 |
+
class ModelArguments:
|
51 |
+
model_name_or_path: Optional[str] = field(default="facebook/opt-125m")
|
52 |
+
|
53 |
+
|
54 |
+
@dataclass
|
55 |
+
class DataArguments:
|
56 |
+
data_path: str = field(default=None, metadata={"help": "Path to the training data."})
|
57 |
+
complex_data: Optional[str] = field(default=None)
|
58 |
+
|
59 |
+
|
60 |
+
@dataclass
|
61 |
+
class TrainingArguments(transformers.TrainingArguments):
|
62 |
+
cache_dir: Optional[str] = field(default=None)
|
63 |
+
optim: str = field(default="adamw_torch")
|
64 |
+
model_max_length: int = field(
|
65 |
+
default=2048,
|
66 |
+
metadata={"help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)."},
|
67 |
+
)
|
68 |
+
|
69 |
+
|
70 |
+
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str):
|
71 |
+
"""Collects the state dict and dump to disk."""
|
72 |
+
state_dict = trainer.model.state_dict()
|
73 |
+
if trainer.args.should_save:
|
74 |
+
cpu_state_dict = {key: value.cpu() for key, value in state_dict.items()}
|
75 |
+
del state_dict
|
76 |
+
trainer._save(output_dir, state_dict=cpu_state_dict) # noqa
|
77 |
+
|
78 |
+
|
79 |
+
def smart_tokenizer_and_embedding_resize(
|
80 |
+
special_tokens_dict: Dict,
|
81 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
82 |
+
model: transformers.PreTrainedModel,
|
83 |
+
):
|
84 |
+
"""Resize tokenizer and embedding.
|
85 |
+
|
86 |
+
Note: This is the unoptimized version that may make your embedding size not be divisible by 64.
|
87 |
+
"""
|
88 |
+
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
|
89 |
+
model.resize_token_embeddings(len(tokenizer))
|
90 |
+
|
91 |
+
if num_new_tokens > 0:
|
92 |
+
input_embeddings = model.get_input_embeddings().weight.data
|
93 |
+
output_embeddings = model.get_output_embeddings().weight.data
|
94 |
+
|
95 |
+
input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
96 |
+
output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
|
97 |
+
|
98 |
+
input_embeddings[-num_new_tokens:] = input_embeddings_avg
|
99 |
+
output_embeddings[-num_new_tokens:] = output_embeddings_avg
|
100 |
+
|
101 |
+
|
102 |
+
def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict:
|
103 |
+
"""Tokenize a list of strings."""
|
104 |
+
tokenized_list = [
|
105 |
+
tokenizer(
|
106 |
+
text,
|
107 |
+
return_tensors="pt",
|
108 |
+
padding="longest",
|
109 |
+
max_length=tokenizer.model_max_length,
|
110 |
+
truncation=True,
|
111 |
+
)
|
112 |
+
for text in strings
|
113 |
+
]
|
114 |
+
input_ids = labels = [tokenized.input_ids[0] for tokenized in tokenized_list]
|
115 |
+
input_ids_lens = labels_lens = [
|
116 |
+
tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list
|
117 |
+
]
|
118 |
+
return dict(
|
119 |
+
input_ids=input_ids,
|
120 |
+
labels=labels,
|
121 |
+
input_ids_lens=input_ids_lens,
|
122 |
+
labels_lens=labels_lens,
|
123 |
+
)
|
124 |
+
|
125 |
+
|
126 |
+
local_rank = None
|
127 |
+
|
128 |
+
|
129 |
+
def rank0_print(*args):
|
130 |
+
if local_rank == 0:
|
131 |
+
print(*args)
|
132 |
+
|
133 |
+
|
134 |
+
def preprocess(
|
135 |
+
sources: Sequence[str],
|
136 |
+
tokenizer: transformers.PreTrainedTokenizer,
|
137 |
+
) -> Dict:
|
138 |
+
"""Preprocess the data by tokenizing."""
|
139 |
+
|
140 |
+
conv = Conversation(
|
141 |
+
name="vicuna_v1.1",
|
142 |
+
system="A chat between a curious user and an artificial intelligence assistant. "
|
143 |
+
"The assistant gives helpful, detailed, and polite answers to the user's questions.",
|
144 |
+
roles=["USER", "ASSISTANT"],
|
145 |
+
messages=[],
|
146 |
+
offset=0,
|
147 |
+
sep_style=SeparatorStyle.ADD_COLON_TWO,
|
148 |
+
sep=" ",
|
149 |
+
sep2="</s>",
|
150 |
+
)
|
151 |
+
roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
|
152 |
+
|
153 |
+
# Apply prompt templates
|
154 |
+
conversations = []
|
155 |
+
for i, source in enumerate(sources):
|
156 |
+
if roles[source[0]["from"]] != conv.roles[0]:
|
157 |
+
# Skip the first one if it is not from human
|
158 |
+
source = source[1:]
|
159 |
+
|
160 |
+
conv.messages = []
|
161 |
+
for j, sentence in enumerate(source):
|
162 |
+
role = roles[sentence["from"]]
|
163 |
+
assert role == conv.roles[j % 2], f"{i}"
|
164 |
+
conv.append_message(role, sentence["value"])
|
165 |
+
conversations.append(conv.get_prompt())
|
166 |
+
#print("$$"+conv.get_prompt().strip()+"$$")
|
167 |
+
input_ids = tokenizer(
|
168 |
+
conversations,
|
169 |
+
return_tensors="pt",
|
170 |
+
padding="max_length",
|
171 |
+
max_length=tokenizer.model_max_length,
|
172 |
+
truncation=True,
|
173 |
+
).input_ids
|
174 |
+
targets = input_ids.clone()
|
175 |
+
|
176 |
+
assert conv.sep_style == SeparatorStyle.ADD_COLON_TWO
|
177 |
+
# Mask targets
|
178 |
+
sep = conv.sep + conv.roles[1] + ": "
|
179 |
+
for conversation, target in zip(conversations, targets):
|
180 |
+
total_len = int(target.ne(tokenizer.pad_token_id).sum())
|
181 |
+
|
182 |
+
rounds = conversation.split(conv.sep2)
|
183 |
+
cur_len = 1
|
184 |
+
target[:cur_len] = IGNORE_TOKEN_ID
|
185 |
+
for i, rou in enumerate(rounds):
|
186 |
+
if rou == "":
|
187 |
+
break
|
188 |
+
|
189 |
+
parts = rou.split(sep)
|
190 |
+
if len(parts) != 2:
|
191 |
+
break
|
192 |
+
parts[0] += sep
|
193 |
+
round_len = len(tokenizer(rou).input_ids)
|
194 |
+
instruction_len = len(tokenizer(parts[0]).input_ids) - 2
|
195 |
+
|
196 |
+
target[cur_len: cur_len + instruction_len] = IGNORE_TOKEN_ID
|
197 |
+
|
198 |
+
cur_len += round_len
|
199 |
+
target[cur_len:] = IGNORE_TOKEN_ID
|
200 |
+
|
201 |
+
if False:
|
202 |
+
z = target.clone()
|
203 |
+
z = torch.where(z == IGNORE_TOKEN_ID, tokenizer.unk_token_id, z)
|
204 |
+
rank0_print(tokenizer.decode(z))
|
205 |
+
|
206 |
+
if cur_len < tokenizer.model_max_length:
|
207 |
+
if cur_len != total_len:
|
208 |
+
target[:] = IGNORE_TOKEN_ID
|
209 |
+
rank0_print(
|
210 |
+
f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}."
|
211 |
+
f" (ignored)"
|
212 |
+
)
|
213 |
+
return dict(
|
214 |
+
input_ids=input_ids,
|
215 |
+
labels=targets,
|
216 |
+
attention_mask=input_ids.ne(tokenizer.pad_token_id),
|
217 |
+
)
|
218 |
+
|
219 |
+
|
220 |
+
class SupervisedDataset(Dataset):
|
221 |
+
"""Dataset for supervised fine-tuning."""
|
222 |
+
|
223 |
+
def __init__(self, data_path: str, tokenizer: transformers.PreTrainedTokenizer):
|
224 |
+
super(SupervisedDataset, self).__init__()
|
225 |
+
logging.warning("Loading data...")
|
226 |
+
list_data_dict = utils.jload(data_path)
|
227 |
+
|
228 |
+
sources = [example["conversations"] for example in list_data_dict]
|
229 |
+
data_dict = preprocess(sources, tokenizer)
|
230 |
+
|
231 |
+
self.input_ids = data_dict["input_ids"]
|
232 |
+
self.labels = data_dict["labels"]
|
233 |
+
self.attention_mask = data_dict["attention_mask"]
|
234 |
+
|
235 |
+
def __len__(self):
|
236 |
+
return len(self.input_ids)
|
237 |
+
|
238 |
+
def __getitem__(self, i) -> Dict[str, torch.Tensor]:
|
239 |
+
return dict(
|
240 |
+
input_ids=self.input_ids[i],
|
241 |
+
labels=self.labels[i],
|
242 |
+
attention_mask=self.attention_mask[i]
|
243 |
+
)
|
244 |
+
|
245 |
+
|
246 |
+
def make_supervised_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args) -> Dict:
|
247 |
+
"""Make dataset and collator for supervised fine-tuning."""
|
248 |
+
|
249 |
+
train_dataset = SupervisedDataset(tokenizer=tokenizer, data_path=data_args.data_path)
|
250 |
+
# data_collator = DataCollatorForSupervisedDataset(tokenizer=tokenizer)
|
251 |
+
return dict(train_dataset=train_dataset, eval_dataset=None)#), data_collator=data_collator)
|
252 |
+
|
253 |
+
|
254 |
+
def train():
|
255 |
+
parser = transformers.HfArgumentParser((ModelArguments, DataArguments, TrainingArguments))
|
256 |
+
model_args, data_args, training_args = parser.parse_args_into_dataclasses()
|
257 |
+
|
258 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
259 |
+
model_args.model_name_or_path,
|
260 |
+
cache_dir=training_args.cache_dir,
|
261 |
+
)
|
262 |
+
|
263 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(
|
264 |
+
model_args.model_name_or_path,
|
265 |
+
cache_dir=training_args.cache_dir,
|
266 |
+
model_max_length=training_args.model_max_length,
|
267 |
+
padding_side="right",
|
268 |
+
use_fast=False,
|
269 |
+
)
|
270 |
+
if tokenizer.pad_token is None:
|
271 |
+
smart_tokenizer_and_embedding_resize(
|
272 |
+
special_tokens_dict=dict(pad_token=DEFAULT_PAD_TOKEN),
|
273 |
+
tokenizer=tokenizer,
|
274 |
+
model=model,
|
275 |
+
)
|
276 |
+
if "llama" in model_args.model_name_or_path:
|
277 |
+
tokenizer.add_special_tokens(
|
278 |
+
{
|
279 |
+
"eos_token": DEFAULT_EOS_TOKEN,
|
280 |
+
"bos_token": DEFAULT_BOS_TOKEN,
|
281 |
+
"unk_token": DEFAULT_UNK_TOKEN,
|
282 |
+
}
|
283 |
+
)
|
284 |
+
|
285 |
+
data_module = make_supervised_data_module(tokenizer=tokenizer, data_args=data_args)
|
286 |
+
#Tell Trainer not to attempt DataParallel
|
287 |
+
model.is_parallelizable = True
|
288 |
+
model.model_parallel = True
|
289 |
+
|
290 |
+
trainer = Trainer(model=model, tokenizer=tokenizer, args=training_args, **data_module)
|
291 |
+
model.config.use_cache = False
|
292 |
+
|
293 |
+
trainer.train()
|
294 |
+
trainer.save_state()
|
295 |
+
safe_save_model_for_hf_trainer(trainer=trainer, output_dir=training_args.output_dir)
|
296 |
+
|
297 |
+
|
298 |
+
if __name__ == "__main__":
|
299 |
+
train()
|
300 |
+
|
301 |
+
|
training/src/utils.py
ADDED
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import dataclasses
|
2 |
+
import logging
|
3 |
+
import math
|
4 |
+
import os
|
5 |
+
import io
|
6 |
+
import sys
|
7 |
+
import time
|
8 |
+
import json
|
9 |
+
from typing import Optional, Sequence, Union
|
10 |
+
|
11 |
+
import openai
|
12 |
+
import tqdm
|
13 |
+
from openai import openai_object
|
14 |
+
import copy
|
15 |
+
|
16 |
+
StrOrOpenAIObject = Union[str, openai_object.OpenAIObject]
|
17 |
+
|
18 |
+
openai_org = os.getenv("OPENAI_ORG")
|
19 |
+
if openai_org is not None:
|
20 |
+
openai.organization = openai_org
|
21 |
+
logging.warning(f"Switching to organization: {openai_org} for OAI API key.")
|
22 |
+
|
23 |
+
|
24 |
+
@dataclasses.dataclass
|
25 |
+
class OpenAIDecodingArguments(object):
|
26 |
+
max_tokens: int = 1800
|
27 |
+
temperature: float = 0.2
|
28 |
+
top_p: float = 1.0
|
29 |
+
n: int = 1
|
30 |
+
stream: bool = False
|
31 |
+
stop: Optional[Sequence[str]] = None
|
32 |
+
presence_penalty: float = 0.0
|
33 |
+
frequency_penalty: float = 0.0
|
34 |
+
suffix: Optional[str] = None
|
35 |
+
logprobs: Optional[int] = None
|
36 |
+
echo: bool = False
|
37 |
+
|
38 |
+
|
39 |
+
def openai_completion(
|
40 |
+
prompts: Union[str, Sequence[str], Sequence[dict[str, str]], dict[str, str]],
|
41 |
+
decoding_args: OpenAIDecodingArguments,
|
42 |
+
model_name="text-davinci-003",
|
43 |
+
sleep_time=2,
|
44 |
+
batch_size=1,
|
45 |
+
max_instances=sys.maxsize,
|
46 |
+
max_batches=sys.maxsize,
|
47 |
+
return_text=False,
|
48 |
+
**decoding_kwargs,
|
49 |
+
) -> Union[Union[StrOrOpenAIObject], Sequence[StrOrOpenAIObject], Sequence[Sequence[StrOrOpenAIObject]],]:
|
50 |
+
"""Decode with OpenAI API.
|
51 |
+
|
52 |
+
Args:
|
53 |
+
prompts: A string or a list of strings to complete. If it is a chat model the strings should be formatted
|
54 |
+
as explained here: https://github.com/openai/openai-python/blob/main/chatml.md. If it is a chat model
|
55 |
+
it can also be a dictionary (or list thereof) as explained here:
|
56 |
+
https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
|
57 |
+
decoding_args: Decoding arguments.
|
58 |
+
model_name: Model name. Can be either in the format of "org/model" or just "model".
|
59 |
+
sleep_time: Time to sleep once the rate-limit is hit.
|
60 |
+
batch_size: Number of prompts to send in a single request. Only for non chat model.
|
61 |
+
max_instances: Maximum number of prompts to decode.
|
62 |
+
max_batches: Maximum number of batches to decode. This argument will be deprecated in the future.
|
63 |
+
return_text: If True, return text instead of full completion object (which contains things like logprob).
|
64 |
+
decoding_kwargs: Additional decoding arguments. Pass in `best_of` and `logit_bias` if you need them.
|
65 |
+
|
66 |
+
Returns:
|
67 |
+
A completion or a list of completions.
|
68 |
+
Depending on return_text, return_openai_object, and decoding_args.n, the completion type can be one of
|
69 |
+
- a string (if return_text is True)
|
70 |
+
- an openai_object.OpenAIObject object (if return_text is False)
|
71 |
+
- a list of objects of the above types (if decoding_args.n > 1)
|
72 |
+
"""
|
73 |
+
is_single_prompt = isinstance(prompts, (str, dict))
|
74 |
+
if is_single_prompt:
|
75 |
+
prompts = [prompts]
|
76 |
+
|
77 |
+
if max_batches < sys.maxsize:
|
78 |
+
logging.warning(
|
79 |
+
"`max_batches` will be deprecated in the future, please use `max_instances` instead."
|
80 |
+
"Setting `max_instances` to `max_batches * batch_size` for now."
|
81 |
+
)
|
82 |
+
max_instances = max_batches * batch_size
|
83 |
+
|
84 |
+
prompts = prompts[:max_instances]
|
85 |
+
num_prompts = len(prompts)
|
86 |
+
prompt_batches = [
|
87 |
+
prompts[batch_id * batch_size : (batch_id + 1) * batch_size]
|
88 |
+
for batch_id in range(int(math.ceil(num_prompts / batch_size)))
|
89 |
+
]
|
90 |
+
|
91 |
+
completions = []
|
92 |
+
for batch_id, prompt_batch in tqdm.tqdm(
|
93 |
+
enumerate(prompt_batches),
|
94 |
+
desc="prompt_batches",
|
95 |
+
total=len(prompt_batches),
|
96 |
+
):
|
97 |
+
batch_decoding_args = copy.deepcopy(decoding_args) # cloning the decoding_args
|
98 |
+
|
99 |
+
while True:
|
100 |
+
try:
|
101 |
+
shared_kwargs = dict(
|
102 |
+
model=model_name,
|
103 |
+
**batch_decoding_args.__dict__,
|
104 |
+
**decoding_kwargs,
|
105 |
+
)
|
106 |
+
completion_batch = openai.Completion.create(prompt=prompt_batch, **shared_kwargs)
|
107 |
+
choices = completion_batch.choices
|
108 |
+
|
109 |
+
for choice in choices:
|
110 |
+
choice["total_tokens"] = completion_batch.usage.total_tokens
|
111 |
+
completions.extend(choices)
|
112 |
+
break
|
113 |
+
except openai.error.OpenAIError as e:
|
114 |
+
logging.warning(f"OpenAIError: {e}.")
|
115 |
+
if "Please reduce your prompt" in str(e):
|
116 |
+
batch_decoding_args.max_tokens = int(batch_decoding_args.max_tokens * 0.8)
|
117 |
+
logging.warning(f"Reducing target length to {batch_decoding_args.max_tokens}, Retrying...")
|
118 |
+
else:
|
119 |
+
logging.warning("Hit request rate limit; retrying...")
|
120 |
+
time.sleep(sleep_time) # Annoying rate limit on requests.
|
121 |
+
|
122 |
+
if return_text:
|
123 |
+
completions = [completion.text for completion in completions]
|
124 |
+
if decoding_args.n > 1:
|
125 |
+
# make completions a nested list, where each entry is a consecutive decoding_args.n of original entries.
|
126 |
+
completions = [completions[i : i + decoding_args.n] for i in range(0, len(completions), decoding_args.n)]
|
127 |
+
if is_single_prompt:
|
128 |
+
# Return non-tuple if only 1 input and 1 generation.
|
129 |
+
(completions,) = completions
|
130 |
+
return completions
|
131 |
+
|
132 |
+
|
133 |
+
def _make_w_io_base(f, mode: str):
|
134 |
+
if not isinstance(f, io.IOBase):
|
135 |
+
f_dirname = os.path.dirname(f)
|
136 |
+
if f_dirname != "":
|
137 |
+
os.makedirs(f_dirname, exist_ok=True)
|
138 |
+
f = open(f, mode=mode)
|
139 |
+
return f
|
140 |
+
|
141 |
+
|
142 |
+
def _make_r_io_base(f, mode: str):
|
143 |
+
if not isinstance(f, io.IOBase):
|
144 |
+
f = open(f, mode=mode)
|
145 |
+
return f
|
146 |
+
|
147 |
+
|
148 |
+
def jdump(obj, f, mode="w", indent=4, default=str):
|
149 |
+
"""Dump a str or dictionary to a file in json format.
|
150 |
+
|
151 |
+
Args:
|
152 |
+
obj: An object to be written.
|
153 |
+
f: A string path to the location on disk.
|
154 |
+
mode: Mode for opening the file.
|
155 |
+
indent: Indent for storing json dictionaries.
|
156 |
+
default: A function to handle non-serializable entries; defaults to `str`.
|
157 |
+
"""
|
158 |
+
f = _make_w_io_base(f, mode)
|
159 |
+
if isinstance(obj, (dict, list)):
|
160 |
+
json.dump(obj, f, indent=indent, default=default)
|
161 |
+
elif isinstance(obj, str):
|
162 |
+
f.write(obj)
|
163 |
+
else:
|
164 |
+
raise ValueError(f"Unexpected type: {type(obj)}")
|
165 |
+
f.close()
|
166 |
+
|
167 |
+
|
168 |
+
def jload(f, mode="r"):
|
169 |
+
"""Load a .json file into a dictionary."""
|
170 |
+
f = _make_r_io_base(f, mode)
|
171 |
+
jdict = json.load(f)
|
172 |
+
f.close()
|
173 |
+
return jdict
|