Views
No views yet


['ada', 'agda', 'alloy', 'antlr', 'applescript', 'assembly', 'augeas', 'awk', 'batchfile', 'bluespec', 'c', 'c-sharp', 'clojure', 'cmake', 'coffeescript', 'common-lisp', 'cpp', 'css', 'cuda', 'dart', 'dockerfile', 'elixir', 'elm', 'emacs-lisp', 'erlang', 'f-sharp', 'fortran', 'glsl', 'go', 'groovy', 'haskell', 'html', 'idris', 'isabelle', 'java', 'java-server-pages', 'javascript', 'json', 'julia', 'jupyter-notebook', 'kotlin', 'lean', 'literate-agda', 'literate-coffeescript', 'literate-haskell', 'lua', 'makefile', 'maple', 'markdown', 'mathematica', 'matlab', 'ocaml', 'pascal', 'perl', 'php', 'powershell', 'prolog', 'protocol-buffer', 'python', 'r', 'racket', 'restructuredtext', 'rmarkdown', 'ruby', 'rust', 'sas', 'scala', 'scheme', 'shell', 'smalltalk', 'solidity', 'sparql', 'sql', 'stan', 'standard-ml', 'stata', 'systemverilog', 'tcl', 'tcsh', 'tex', 'thrift', 'typescript', 'verilog', 'vhdl', 'visual-basic', 'xslt', 'yacc', 'yaml', 'zig']pass@1 results on HumanEval (Python and Multilingual), MBPP, and DS-1000 are reported here:


pip install -r requirements.txtapp.py in the demo folder. (Thanks to all the HF team for their support)1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
3tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True)
4model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
5input_text = "#write a quick sort algorithm"
6inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
7outputs = model.generate(**inputs, max_length=128)
8print(tokenizer.decode(outputs[0], skip_special_tokens=True))def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = []
right = []
for i in range(1, len(arr)):
if arr[i] < pivot:
left.append(arr[i])
else:
right.append(arr[i])
return quick_sort(left) + [pivot] + quick_sort(right)1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
3tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True)
4model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
5input_text = """<|fim▁begin|>def quick_sort(arr):
6 if len(arr) <= 1:
7 return arr
8 pivot = arr[0]
9 left = []
10 right = []
11<|fim▁hole|>
12 if arr[i] < pivot:
13 left.append(arr[i])
14 else:
15 right.append(arr[i])
16 return quick_sort(left) + [pivot] + quick_sort(right)<|fim▁end|>"""
17inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
18outputs = model.generate(**inputs, max_length=128)
19print(tokenizer.decode(outputs[0], skip_special_tokens=True)[len(input_text):]) for i in range(1, len(arr)):1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
3tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-6.7b-instruct", trust_remote_code=True)
4model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-6.7b-instruct", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
5messages=[
6 { 'role': 'user', 'content': "write a quick sort algorithm in python."}
7]
8inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
9# tokenizer.eos_token_id is the id of <|EOT|> token
10outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)
11print(tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True))Sure, here is a simple implementation of the Quick Sort algorithm in Python:
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
less_than_pivot = [x for x in arr[1:] if x <= pivot]
greater_than_pivot = [x for x in arr[1:] if x > pivot]
return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot)
# Test the function
arr = [10, 7, 8, 9, 1, 5]
print("Original array:", arr)
print("Sorted array:", quick_sort(arr))
This code works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The pivot element is then in its final position. The process is then repeated for the sub-arrays.apply_chat_template which loads the template from tokenizer_config.json, you can use the following template to chat with our model. Replace the ['content'] with your instructions and the model's previous (if any) responses, then the model will generate the response to the currently given instruction.You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.
### Instruction:
['content']
### Response:
['content']
<|EOT|>
### Instruction:
['content']
### Response:
1from transformers import AutoTokenizer, AutoModelForCausalLM
2import torch
3tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True)
4model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-6.7b-base", trust_remote_code=True, torch_dtype=torch.bfloat16).cuda()
5
6input_text = """#utils.py
7import torch
8from sklearn import datasets
9from sklearn.model_selection import train_test_split
10from sklearn.preprocessing import StandardScaler
11from sklearn.metrics import accuracy_score
12
13def load_data():
14 iris = datasets.load_iris()
15 X = iris.data
16 y = iris.target
17
18 # Standardize the data
19 scaler = StandardScaler()
20 X = scaler.fit_transform(X)
21
22 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
23
24 # Convert numpy data to PyTorch tensors
25 X_train = torch.tensor(X_train, dtype=torch.float32)
26 X_test = torch.tensor(X_test, dtype=torch.float32)
27 y_train = torch.tensor(y_train, dtype=torch.int64)
28 y_test = torch.tensor(y_test, dtype=torch.int64)
29
30 return X_train, X_test, y_train, y_test
31
32def evaluate_predictions(y_test, y_pred):
33 return accuracy_score(y_test, y_pred)
34
35
36# model.py
37import torch
38import torch.nn as nn
39import torch.optim as optim
40from torch.utils.data import DataLoader, TensorDataset
41
42class IrisClassifier(nn.Module):
43 def __init__(self):
44 super(IrisClassifier, self).__init__()
45 self.fc = nn.Sequential(
46 nn.Linear(4, 16),
47 nn.ReLU(),
48 nn.Linear(16, 3)
49 )
50
51 def forward(self, x):
52 return self.fc(x)
53
54 def train_model(self, X_train, y_train, epochs, lr, batch_size):
55 criterion = nn.CrossEntropyLoss()
56 optimizer = optim.Adam(self.parameters(), lr=lr)
57
58 # Create DataLoader for batches
59 dataset = TensorDataset(X_train, y_train)
60 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
61
62 for epoch in range(epochs):
63 for batch_X, batch_y in dataloader:
64 optimizer.zero_grad()
65 outputs = self(batch_X)
66 loss = criterion(outputs, batch_y)
67 loss.backward()
68 optimizer.step()
69
70 def predict(self, X_test):
71 with torch.no_grad():
72 outputs = self(X_test)
73 _, predicted = outputs.max(1)
74 return predicted.numpy()
75
76
77# main.py
78from utils import load_data, evaluate_predictions
79from model import IrisClassifier as Classifier
80
81def main():
82 # Model training and evaluation
83"""
84inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
85outputs = model.generate(**inputs, max_new_tokens=140)
86print(tokenizer.decode(outputs[0]))model.py file, and also utilizes functions from the utils.py file, to correctly complete the main function in the main.py file for model training and evaluation.
finetune/finetune_deepseekcoder.py for users to finetune our models on downstream tasks.pip install -r finetune/requirements.txtinstruction and output.deepseek-ai/deepseek-coder-6.7b-instruct.
Remember to specify DATA_PATH, OUTPUT_PATH.
And please choose appropriate hyper-parameters(e.g., learning_rate, per_device_train_batch_size) according to your scenario.1DATA_PATH="<your_data_path>"
2OUTPUT_PATH="<your_output_path>"
3MODEL="deepseek-ai/deepseek-coder-6.7b-instruct"
4
5cd finetune && deepspeed finetune_deepseekcoder.py \
6 --model_name_or_path $MODEL_PATH \
7 --data_path $DATA_PATH \
8 --output_dir $OUTPUT_PATH \
9 --num_train_epochs 3 \
10 --model_max_length 1024 \
11 --per_device_train_batch_size 16 \
12 --per_device_eval_batch_size 1 \
13 --gradient_accumulation_steps 4 \
14 --evaluation_strategy "no" \
15 --save_strategy "steps" \
16 --save_steps 100 \
17 --save_total_limit 100 \
18 --learning_rate 2e-5 \
19 --warmup_steps 10 \
20 --logging_steps 1 \
21 --lr_scheduler_type "cosine" \
22 --gradient_checkpointing True \
23 --report_to "tensorboard" \
24 --deepspeed configs/ds_config_zero3.json \
25 --bf16 True



1from vllm import LLM, SamplingParams
2
3tp_size = 4 # Tensor Parallelism
4sampling_params = SamplingParams(temperature=0.7, top_p=0.9, max_tokens=100)
5model_name = "deepseek-ai/deepseek-coder-6.7b-base"
6llm = LLM(model=model_name, trust_remote_code=True, gpu_memory_utilization=0.9, tensor_parallel_size=tp_size)
7
8prompts = [
9 "If everyone in a country loves one another,",
10 "The research should also focus on the technologies",
11 "To determine if the label is correct, we need to"
12]
13outputs = llm.generate(prompts, sampling_params)
14
15generated_text = [output.outputs[0].text for output in outputs]
16print(generated_text)1from transformers import AutoTokenizer
2from vllm import LLM, SamplingParams
3
4tp_size = 4 # Tensor Parallelism
5sampling_params = SamplingParams(temperature=0.7, top_p=0.9, max_tokens=100)
6model_name = "deepseek-ai/deepseek-coder-6.7b-instruct"
7tokenizer = AutoTokenizer.from_pretrained(model_name)
8llm = LLM(model=model_name, trust_remote_code=True, gpu_memory_utilization=0.9, tensor_parallel_size=tp_size)
9
10messages_list = [
11 [{"role": "user", "content": "Who are you?"}],
12 [{"role": "user", "content": "What can you do?"}],
13 [{"role": "user", "content": "Explain Transformer briefly."}],
14]
15prompts = [tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False) for messages in messages_list]
16
17sampling_params.stop = [tokenizer.eos_token]
18outputs = llm.generate(prompts, sampling_params)
19
20generated_text = [output.outputs[0].text for output in outputs]
21print(generated_text)1git clone https://github.com/DOGEwbx/llama.cpp.git
2cd llama.cpp
3git checkout regex_gpt2_preprocess
4# set up the environment according to README
5make
6python3 -m pip install -r requirements.txt
7# generate GGUF model
8python convert-hf-to-gguf.py <MODEL_PATH> --outfile <GGUF_PATH> --model-name deepseekcoder
9# use q4_0 quantization as an example
10./quantize <GGUF_PATH> <OUTPUT_PATH> q4_0
11./main -m <OUTPUT_PATH> -n 128 -p <PROMPT>UPDATE:exllamav2 has been able to support Huggingface Tokenizer. Please pull the latest version and try out.@misc{deepseek-coder,
author = {Daya Guo, Qihao Zhu, Dejian Yang, Zhenda Xie, Kai Dong, Wentao Zhang, Guanting Chen, Xiao Bi, Y. Wu, Y.K. Li, Fuli Luo, Yingfei Xiong, Wenfeng Liang},
title = {DeepSeek-Coder: When the Large Language Model Meets Programming -- The Rise of Code Intelligence},
journal = {CoRR},
volume = {abs/2401.14196},
year = {2024},
url = {https://arxiv.org/abs/2401.14196},
}