File size: 1,152 Bytes
a81c16a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"""Minimal chat with SalgrAI-v2 (transformers). Run: python chat_example.py [path-or-repo]. Commands: /reset, /exit."""
import sys

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

repo = sys.argv[1] if len(sys.argv) > 1 else "."
tok = AutoTokenizer.from_pretrained(repo)
model = AutoModelForCausalLM.from_pretrained(repo, dtype=torch.bfloat16).eval()
history = []
while True:
    try:
        text = input("you> ").strip()
    except EOFError:
        break
    if text == "/exit":
        break
    if text == "/reset":
        history = []
        continue
    if not text:
        continue
    history.append({"role": "user", "content": text})
    inputs = tok.apply_chat_template(history, add_generation_prompt=True, return_tensors="pt", return_dict=True)
    inputs.pop("token_type_ids", None)
    with torch.no_grad():
        out = model.generate(**inputs)  # sampling settings come from generation_config.json
    reply = tok.decode(out[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
    history.append({"role": "assistant", "content": reply})
    history = history[-8:]
    print("ai>", reply)