|
from transformers import AutoModelForCausalLM, AutoTokenizer |
|
import torch |
|
import os |
|
|
|
|
|
TOP_P = 0.9 |
|
TOP_K = 80 |
|
TEMPERATURE = 0.3 |
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
current_directory = os.path.dirname(os.path.abspath(__file__)) |
|
|
|
|
|
model = AutoModelForCausalLM.from_pretrained( |
|
current_directory, |
|
torch_dtype="auto", |
|
device_map="auto" |
|
) |
|
tokenizer = AutoTokenizer.from_pretrained(current_directory) |
|
|
|
|
|
messages = [ |
|
{"role": "system", "content": ""} |
|
] |
|
|
|
while True: |
|
|
|
user_input = input("User: ").strip() |
|
|
|
|
|
messages.append({"role": "user", "content": user_input}) |
|
|
|
|
|
text = tokenizer.apply_chat_template( |
|
messages, |
|
tokenize=False, |
|
add_generation_prompt=True |
|
) |
|
model_inputs = tokenizer([text], return_tensors="pt").to(device) |
|
|
|
|
|
generated_ids = model.generate( |
|
model_inputs.input_ids, |
|
max_new_tokens=512, |
|
top_p=TOP_P, |
|
top_k=TOP_K, |
|
temperature=TEMPERATURE, |
|
do_sample=True, |
|
pad_token_id=tokenizer.eos_token_id |
|
) |
|
generated_ids = [ |
|
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids) |
|
] |
|
|
|
|
|
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0] |
|
print(f"Assistant: {response}") |
|
|
|
|
|
messages.append({"role": "assistant", "content": response}) |
|
|