chat_completion.py 954 Bytes
Newer Older
Rayyyyy's avatar
Rayyyyy committed
1
2
3
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig

Rayyyyy's avatar
Rayyyyy committed
4
5

model_name_or_path = "deepseek-ai/DeepSeek-V2-Lite-Chat"
Rayyyyy's avatar
Rayyyyy committed
6
7

tokenizer = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True)
Rayyyyy's avatar
update  
Rayyyyy committed
8
9
10
11
12
13
# `device_map` cannot be set to `auto`
model = AutoModelForCausalLM.from_pretrained(
    model_name_or_path,
    trust_remote_code=True,
    torch_dtype=torch.bfloat16).cuda()

Rayyyyy's avatar
Rayyyyy committed
14
15
16
17
18
19
model.generation_config = GenerationConfig.from_pretrained(model_name_or_path)
model.generation_config.pad_token_id = model.generation_config.eos_token_id

messages = [
    {"role": "user", "content": "Write a piece of quicksort code in C++"}
]
Rayyyyy's avatar
Rayyyyy committed
20

Rayyyyy's avatar
Rayyyyy committed
21
22
23
input_tensor = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
outputs = model.generate(input_tensor.to(model.device), max_new_tokens=100)
result = tokenizer.decode(outputs[0][input_tensor.shape[1]:], skip_special_tokens=True)
Rayyyyy's avatar
update  
Rayyyyy committed
24

Rayyyyy's avatar
Rayyyyy committed
25
print("result", result)