File size: 3,972 Bytes
0afe019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
"""Continue text or chat with MP-01-100M-Chat (English).

Usage (from this folder):
  python run.py "The history of the printing press"
  python run.py "Once upon a time" --tokens 200 --temperature 0.7
  python run.py --chat                          # chat in the terminal
  python run.py --chat "What is 12 + 29?"       # one question

Runs on a CUDA GPU when one is available, otherwise on the CPU.
"""
import argparse
import json
import os
import sys
from pathlib import Path

import torch
from safetensors.torch import load_file
from tokenizers import Tokenizer

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
os.environ["VBQ_TOKENIZER"] = str(HERE / "tokenizer.json")
from vbq.chat import stream_reply  # noqa: E402
from vbq.model import VBQ, VBQConfig  # noqa: E402


def chat(model, question, a):
    """Every message is sent on its own: the model was chat-tuned on single turns."""
    def answer(text):
        with torch.no_grad():
            for piece in stream_reply(model, [{"role": "user", "content": text}], max_new=a.tokens,
                                      temperature=a.temperature, top_p=a.top_p, top_k=a.top_k,
                                      rep_penalty=a.repetition_penalty):
                print(piece, end="", flush=True)
        print()

    if question:
        return answer(question)
    print("MP-01-100M-Chat. English, no memory between messages. /quit to leave.")
    while True:
        try:
            text = input("\nYou: ").strip()
        except (EOFError, KeyboardInterrupt):
            return print()
        if text == "/quit":
            return
        if text:
            print("MP-01: ", end="", flush=True)
            try:
                answer(text)
            except ValueError as e:
                print(f"(can't send that: {e})")


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("prompt", nargs="?")
    p.add_argument("--chat", action="store_true", help="chat instead of continuing text")
    p.add_argument("--tokens", type=int, default=150, help="new tokens to generate")
    p.add_argument("--temperature", type=float, default=None, help="default 0.8, or 0.3 with --chat")
    p.add_argument("--top-k", type=int, default=50)
    p.add_argument("--top-p", type=float, default=0.95)
    p.add_argument("--repetition-penalty", type=float, default=None, help="default 1.1, or 1.0 with --chat")
    p.add_argument("--seed", type=int, default=None)
    a = p.parse_args()
    if a.temperature is None:
        a.temperature = 0.3 if a.chat else 0.8
    if a.repetition_penalty is None:
        a.repetition_penalty = 1.0 if a.chat else 1.1
    if a.seed is not None:
        torch.manual_seed(a.seed)

    device = "cuda" if torch.cuda.is_available() else "cpu"
    cfg = VBQConfig(**json.loads((HERE / "config.json").read_text())["model_cfg"])
    model = VBQ(cfg)
    model.load_state_dict(load_file(str(HERE / "model.safetensors")))
    model.to(device=device, dtype=torch.bfloat16 if device == "cuda" else torch.float32).eval()

    if a.chat:
        return chat(model, a.prompt, a)
    a.prompt = a.prompt or "The history of the printing press"
    tok = Tokenizer.from_file(str(HERE / "tokenizer.json"))
    ids = tok.encode(a.prompt, add_special_tokens=False).ids
    idx = torch.tensor([ids], device=device)
    print(a.prompt, end="", flush=True)
    new, shown = [], ""
    with torch.no_grad():
        for t in model.generate_cached(idx, max_new_tokens=a.tokens, temperature=a.temperature, top_k=a.top_k,
                                       top_p=a.top_p, eos_id=0, repetition_penalty=a.repetition_penalty):
            new.append(t)
            text = tok.decode(new)          # decode the whole tail so multi-byte characters print correctly
            print(text[len(shown):], end="", flush=True)
            shown = text
    print()


if __name__ == "__main__":
    main()