WizardCoder:写代码能力测评 Use Golang Write LSM tree code (WizardCoder-15B)
WizardCoder-15B
https://github.com/nlpxucan/WizardLM
An Instruction-following Code LLM Using Evol-Instruct. Now, our model generates answer with greedy decoding and only supports English. Please only use code-related instructions.
Input 0: func MergeBinaryTree

Output 1:
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func MergeBinaryTree(root1 *TreeNode, root2 *TreeNode) *TreeNode {
if root1 == nil {
return root2
}
if root2 == nil {
return root1
}
root := &TreeNode{Val: 0}
if root1.Val < root2.Val {
root.Val = root1.Val
root.Left = MergeBinaryTree(root1.Left, root2)
} else {
root.Val = root2.Val
root.Left = MergeBinaryTree(root1, root2.Left)
}
root.Right = MergeBinaryTree(root1.Right, root2.Right)
return root
}
代码解读
Input 1: use golang write LSM tree code
Output 1
Sure, I can help you with that. Here’s an example implementation of an LSM tree in Go:
package main
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"os"
"sort"
)
type KeyValue struct {
Key []byte
Value []byte
}
type SSTable struct {
file *os.File
data []KeyValue
}
type LSMTree struct {
sstableMap map[string]*SSTable
tmpFile *os.File
}
func NewLSMTree() *LSMTree {
return &LSMTree{
sstableMap: make(map[string]*SSTable),
}
}
func (l *LSMTree) Open(path string) error {
files, err := os.ReadDir(path)
if err!= nil {
return err
}
for _, file := range files {
if!file.IsDir() {
f, err := os.Open(path + "/" + file.Name())
if err!= nil {
return err
}
sstable := &SSTable{
file: f,
}
if err := sstable.read(); err!= nil {
return err
}
l.sstableMap[file.Name()] = sstable
}
}
return nil
}
func (l *LSMTree) Close() error {
for _, sstable := range l.sstableMap {
if err := sstable.file.Close(); err!= nil {
return err
}
}
if l.tmpFile!= nil {
if err := l.tmpFile.Close(); err!= nil {
return err
}
}
return nil
}
func (l *LSMTree) Get(key []byte) ([]byte, error) {
sstable := l.findSSTable(key)
if sstable == nil {
return nil, fmt.Errorf("key not found")
}
return sstable.Get(key)
}
func (l *LSMTree) Set(key, value []byte) error {
sstable := l.findSSTable(key)
if sstable == nil {
sstable = l.newSSTable()
}
if err := sstable.Set(key, value); err!= nil {
return err
}
if len(sstable.data) >= 10000 {
if err := l.flushSSTable(sstable); err!= nil {
return err
}
}
return nil
}
func (l *LSMTree) findSSTable(key []byte) *SSTable {
for _, sstable := range l.sstableMap {
if bytes.Compare(sstable.data[len(sstable.data)-1].Key, key) <= 0 {
return sstable
}
}
return nil
}
func (l *LSMTree) newSSTable() *SSTable {
if l.tmpFile == nil {
tmpFile, err := os.CreateTemp("", "sstable")
if err!= nil {
panic(err)
}
l.tmpFile = tmpFile
}
sstable := &SSTable{
file: l.tmpFile,
}
l.sstableMap[sstable.file.Name()] = sstable
return sstable
}
func (l *LSMTree) flushSSTable(sstable *SSTable) error {
sort.Slice(sstable.data, func(i, j int) bool {
return bytes.Compare(sstable.data[i].Key, sstable.data[j].Key) < 0
})
if err := sstable.write(); err!= nil {
return err
}
if err := sstable.file.Sync(); err!= nil {
return err
}
if err := sstable.file.Close(); err!= nil {
return err
}
l.tmpFile = nil
return nil
}
type SSTableWriter struct {
file *os.File
}
func NewSSTableWriter(file *os.File) *SSTableWriter {
return &SSTableWriter{
file: file,
}
}
func (w *SSTableWriter) Write(key, value []byte) error {
if err := binary.Write(w.file, binary.BigEndian, uint64(len(key))); err!= nil {
return err
}
if _, err := w.file.Write(key); err!= nil {
return err
}
if err := binary.Write(w.file, binary.BigEndian, uint64(len(value))); err!= nil {
return err
}
if _, err := w.file.Write(value); err!= nil {
return err
}
return nil
}
type SSTableReader struct {
file *os.File
}
func NewSSTableReader(file *os.File) *SSTableReader {
return &SSTableReader{
file: file,
}
}
func (r *SSTableReader) Read() ([]KeyValue, error) {
var data []KeyValue
for {
var keyLen uint64
if err := binary.Read(r.file, binary.BigEndian, &keyLen); err!= nil {
if err == io.EOF {
break
}
return nil, err
}
key := make([]byte, keyLen)
if _, err := io.ReadFull(r.file, key); err!= nil {
return nil, err
}
var valueLen uint64
if err := binary.Read(r.file, binary.BigEndian, &valueLen); err!= nil {
return nil, err
}
value := make([]byte, valueLen)
if _, err := io.ReadFull(r.file, value); err!= nil {
return nil, err
}
data = append(data, KeyValue{
Key: key,
Value: value,
})
}
return data, nil
}
func (s *SSTable) read() error {
reader := NewSSTableReader(s.file)
s.data, err = reader.Read()
if err!= nil {
return err
}
return nil
}
func (s *SSTable) write() error {
writer := NewSSTableWriter(s.file)
for _, kv := range s.data {
if err := writer.Write(kv.Key, kv.Value); err!= nil {
return err
}
}
return nil
}
func (s *SSTable) Get(key []byte) ([]byte, error) {
i := sort.Search(len(s.data), func(i int) bool {
return bytes.Compare(s.data[i].Key, key) >= 0
})
if i == len(s.data) || bytes.Compare(s.data[i].Key, key)!= 0 {
return nil, fmt.Errorf("key not found")
}
return s.data[i].Value, nil
}
func (s *SSTable) Set(key, value []byte) error {
i := sort.Search(len(s.data), func(i int) bool {
return bytes.Compare(s.data[i].Key, key) >= 0
})
if i == len(s.data) || bytes.Compare(s.data[i].Key, key)!= 0 {
s.data = append(s.data, KeyValue{})
copy(s.data[i+1:], s.data[i:])
s.data[i] = KeyValue{
Key: key,
Value: value,
}
} else {
s.data[i].Value = value
}
return nil
}
代码解读
This implementation uses a temporary file to store new key-value pairs before they are flushed to disk. The SSTable struct represents a sorted string table, and the LSMTree struct manages a collection of SSTables.
WizardCoder: Empowering Code Large Language Models with Evol-Instruct
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 LLM, StarCoder, utilizing the newly created instruction-following training set.
News
- 🔥 Our WizardCoder-15B-V1.0 model achieves the 57.3 pass@1 on the HumanEval Benchmarks, which is 22.3 points higher than the SOTA open-source Code LLMs.
- 🔥 We released WizardCoder-15B-V1.0 trained with 78k evolved code instructions. Please checkout the Model Weights, Demo (Only support code-related English instructions now.), Backup Demo1, Backup Demo2, and Paper.
- 📣 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.
Comparing WizardCoder with the Closed-Source Models.
🔥 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.

❗**Note: In this study, we copy the scores for HumanEval and HumanEval+ from theLLM-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
(https://github.com/evalplus/evalplus).**
### Comparing WizardCoder with the Open-Source Models.
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.**
|Model|HumanEval Pass@1|MBPP Pass@1|
|---|---|---|
|CodeGen-16B-Multi|18.3|20.9|
|CodeGeeX|22.9|24.4|
|LLaMA-33B|21.7|30.2|
|LLaMA-65B|23.7|37.7|
|PaLM-540B|26.2|36.8|
|PaLM-Coder-540B|36.0|47.0|
|PaLM 2-S|37.6|50.0|
|CodeGen-16B-Mono|29.3|35.3|
|Code-Cushman-001|33.5|45.9|
|StarCoder-15B|33.6|43.6*|
|InstructCodeT5+|35.0|–|
|WizardLM-30B 1.0|37.8|–|
|WizardCoder-15B 1.0|**57.3**|**51.8**|
❗**Note: The reproduced result of StarCoder on MBPP.**
❗**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
(https://github.com/openai/human-eval/tree/master). The scores of GPT4 and GPT3.5 reported by OpenAI are 67.0 and 48.1 (maybe these are the early version GPT4&3.5).**
Call for Feedbacks
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 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.
Unofficial Video Introductions
Thanks to the enthusiastic friends, their video introductions are more lively and interesting.
Contents
Online Demo
Fine-tuning
Inference
Evaluation
Citation
Disclaimer
Online Demo
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.
Demo Link (We adopt the greedy decoding now.)
Fine-tuning
We fine-tune WizardCoder using the modified code train.py from Llama-X.
We fine-tune StarCoder-15B with the following hyperparameters:
| Hyperparameter | StarCoder-15B |
|---|---|
| Batch size | 512 |
| Learning rate | 2e-5 |
| Epochs | 3 |
| Max length | 2048 |
| Warmup step | 30 |
| LR scheduler | cosine |
To reproduce our fine-tuning of WizardCoder, please follow the following steps:
- According to the instructions of Llama-X, install the environment, download the training code, and deploy. (Note:
deepspeed==0.9.2andtransformers==4.29.2) - Replace the
train.pywith thetrain_wizardcoder.pyin our repo (src/train_wizardcoder.py) - Login Huggingface:
huggingface-cli login
代码解读
- Execute the following training command:
deepspeed train_wizardcoder.py \
--model_name_or_path "bigcode/starcoder" \
--data_path "/your/path/to/code_instruction_data.json" \
--output_dir "/your/path/to/ckpt" \
--num_train_epochs 3 \
--model_max_length 2048 \
--per_device_train_batch_size 16 \
--per_device_eval_batch_size 1 \
--gradient_accumulation_steps 4 \
--evaluation_strategy "no" \
--save_strategy "steps" \
--save_steps 50 \
--save_total_limit 2 \
--learning_rate 2e-5 \
--warmup_steps 30 \
--logging_steps 2 \
--lr_scheduler_type "cosine" \
--report_to "tensorboard" \
--gradient_checkpointing True \
--deepspeed configs/deepspeed_config.json \
--fp16 True
代码解读
Inference
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.
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.
pip install jsonlines
代码解读
The decoding command is:
python src\inference_wizardcoder.py \
--base_model "/your/path/to/ckpt" \
--input_data_path "/your/path/to/input/data.jsonl" \
--output_data_path "/your/path/to/output/result.jsonl"
代码解读
The format of data.jsonl should be:
{"idx": 11, "Instruction": "Write a Python code to count 1 to 10."}
{"idx": 12, "Instruction": "Write a Java code to sum 1 to 10."}
代码解读
The prompt for our WizardCoder in src\inference_wizardcoder.py is:
Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
{instruction}
### Response:
代码解读
Evaluation
HumanEval
- According to the instructions of HumanEval, install the environment.
- Run the following script to generate the answer.
model="/path/to/your/model"
temp=0.2
max_len=2048
pred_num=200
num_seqs_per_iter=2
output_path=preds/T${temp}_N${pred_num}
mkdir -p ${output_path}
echo 'Output path: '$output_path
echo 'Model to eval: '$model
# 164 problems, 21 per GPU if GPU=8
index=0
gpu_num=8
for ((i = 0; i < $gpu_num; i++)); do
start_index=$((i * 21))
end_index=$(((i + 1) * 21))
gpu=$((i))
echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
((index++))
(
CUDA_VISIBLE_DEVICES=$gpu python humaneval_gen.py --model ${model} \
--start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path}
) &
if (($index % $gpu_num == 0)); then wait; fi
done
代码解读
- Run the post processing code
src/process_humaneval.pyto collect the code completions from all answer files.
output_path=preds/T${temp}_N${pred_num}
echo 'Output path: '$output_path
python process_humaneval.py --path ${output_path} --out_path ${output_path}.jsonl --add_prompt
evaluate_functional_correctness ${output_path}.jsonl
代码解读
MBPP
- Run the following script to generate the answer.
model="/path/to/your/model"
temp=0.2
max_len=2048
pred_num=200
num_seqs_per_iter=2
output_path=preds/MBPP_T${temp}_N${pred_num}
mbpp_path=data/mbpp.test.jsonl # we provide this file in data/mbpp.test.zip
mkdir -p ${output_path}
echo 'Output path: '$output_path
echo 'Model to eval: '$model
# 500 problems, 63 per GPU if GPU=8
index=0
gpu_num=8
for ((i = 0; i < $gpu_num; i++)); do
start_index=$((i * 50))
end_index=$(((i + 1) * 50))
gpu=$((i))
echo 'Running process #' ${i} 'from' $start_index 'to' $end_index 'on GPU' ${gpu}
((index++))
(
CUDA_VISIBLE_DEVICES=$gpu python mbpp_gen.py --model ${model} \
--start_index ${start_index} --end_index ${end_index} --temperature ${temp} \
--num_seqs_per_iter ${num_seqs_per_iter} --N ${pred_num} --max_len ${max_len} --output_path ${output_path} --mbpp_path ${mbpp_path}
) &
if (($index % $gpu_num == 0)); then wait; fi
done
代码解读
- Run the post processing code
src/process_mbpp.pyto collect the code completions from all answer files.
output_path=preds/MBPP_T${temp}_N${pred_num}
mbpp_path=data/mbpp.test.jsonl # we provide this file in data/mbpp.test.zip
echo 'Output path: '$output_path
python process_mbpp.py --path ${output_path} --out_path ${output_path}.jsonl --mbpp_path ${mbpp_path} --add_prompt
代码解读
- Evaluate the
MBPP_T${temp}_N${pred_num}.jsonlwith bigcode-evaluation-harness.
Acknowledgement: The evaluation code humaneval_gen.py, mbpp_gen.py and bash scripts are modified from the great works of CodeT5.
Citation
Please cite the repo if you use the data or code in this repo.
@misc{luo2023wizardcoder,
title={WizardCoder: Empowering Code Large Language Models with Evol-Instruct},
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},
year={2023},
eprint={2306.08568},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
代码解读
Disclaimer
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 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.
