File size: 3,023 Bytes
7e91f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Generate an answer with a GPU-resident stock Transformers BF16 reference."""

import argparse

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

BASE = "HyperionGrayAI/qwennifer-flash-bf16"
REVISION = "v0.1"


def load(base=BASE, revision=REVISION, device="cuda"):
    if device == "cuda" and not torch.cuda.is_available():
        raise RuntimeError(
            "CUDA is required for GPU-resident serving. For a host-memory control, choose --device cpu."
        )
    kwargs = {"revision": revision, "dtype": torch.bfloat16, "trust_remote_code": False}
    tokenizer = AutoTokenizer.from_pretrained(
        base, revision=revision, trust_remote_code=False
    )
    if device == "cuda":
        free = [torch.cuda.mem_get_info(i)[0] for i in range(torch.cuda.device_count())]
        if sum(free) < 159348782592:
            raise RuntimeError(
                "The BF16 weights alone need 148.4 GiB. Supply enough free GPU memory plus room for context."
            )
        kwargs["device_map"] = "auto"
    else:
        kwargs["device_map"] = {"": "cpu"}
    model = AutoModelForCausalLM.from_pretrained(base, **kwargs).eval()
    if model.config.num_experts_per_tok != 6:
        raise ValueError("The model configuration must route six experts per token.")
    if device == "cuda" and (
        any(p.device.type != "cuda" for p in model.parameters())
        or any(str(d) in ("cpu", "disk", "meta") for d in model.hf_device_map.values())
    ):
        raise RuntimeError(
            "The device map offloaded part of the checkpoint. Provide more GPU memory or use --device cpu."
        )
    return model, tokenizer


@torch.inference_mode()
def generate(model, tokenizer, question, max_tokens):
    text = tokenizer.apply_chat_template(
        [{"role": "user", "content": question}],
        tokenize=False,
        add_generation_prompt=True,
    )
    inputs = tokenizer(text, add_special_tokens=False, return_tensors="pt").to(
        model.get_input_embeddings().weight.device
    )
    output = model.generate(**inputs, max_new_tokens=max_tokens, do_sample=False)
    suffix = output[0, inputs.input_ids.shape[1] :]
    return (
        tokenizer.decode(suffix, skip_special_tokens=True),
        int(inputs.input_ids.shape[1]),
        int(suffix.numel()),
    )


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("question")
    p.add_argument("--adapter", help="PEFT adapter directory or Hub model ID")
    p.add_argument("--adapter-revision", default="v0.1")
    p.add_argument("--max-tokens", type=int, default=160)
    p.add_argument("--device", choices=["cuda", "cpu"], default="cuda")
    args = p.parse_args()
    model, tokenizer = load(device=args.device)
    if args.adapter:
        from peft import PeftModel

        model = PeftModel.from_pretrained(
            model, args.adapter, revision=args.adapter_revision
        ).eval()
    print(generate(model, tokenizer, args.question, args.max_tokens)[0])