File size: 2,667 Bytes
7c516cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Локальный диалог с SalgrAI v2.1 Pro или Pro Coder в Transformers."""

import argparse

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer


def fit_history(tokenizer, messages, budget):
    """Сохранить последние полные пары, помещающиеся в контекст."""
    history = messages
    while history:
        inputs = tokenizer.apply_chat_template(
            history, add_generation_prompt=True, tokenize=True,
            return_dict=True, return_tensors="pt",
        )
        if inputs["input_ids"].shape[1] <= budget:
            return history, inputs
        history = history[2:]
    raise ValueError("Последнее сообщение превышает лимит контекста.")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("model", nargs="?", default=".", help="Папка или репозиторий модели")
    parser.add_argument("--context", type=int, default=4096, help="Лимит токенов вместе с ответом")
    args = parser.parse_args()

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    dtype = torch.bfloat16 if device.type == "cuda" and torch.cuda.is_bf16_supported() else torch.float32
    tokenizer = AutoTokenizer.from_pretrained(args.model)
    model = AutoModelForCausalLM.from_pretrained(args.model, dtype=dtype).to(device).eval()
    max_new = model.generation_config.max_new_tokens
    if not max_new or not max_new < args.context <= model.config.max_position_embeddings:
        parser.error("--context должен вмещать ответ и укладываться в лимит модели")

    history = []
    while True:
        try:
            text = input("вы> ").strip()
        except (EOFError, KeyboardInterrupt):
            break
        if text == "/exit":
            break
        if text == "/reset":
            history = []
            continue
        if not text:
            continue
        pending = history + [{"role": "user", "content": text}]
        try:
            history, inputs = fit_history(tokenizer, pending, args.context - max_new)
        except ValueError as exc:
            print(exc)
            continue
        inputs = inputs.to(device)
        with torch.inference_mode():
            output = model.generate(**inputs)
        answer = tokenizer.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()
        history.append({"role": "assistant", "content": answer})
        print("SalgrAI>", answer)


if __name__ == "__main__":
    main()