File size: 3,545 Bytes
c7f2c56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Serve one trained specialist with its source pack on the bounded Flash runtime."""

import argparse
import hashlib
import json
import os
from pathlib import Path

import uvicorn
from belikewater_transformers.http_server import create_app
from belikewater_transformers.models.qwennifer.flash_serving import QwenniferFlashModel
from grounding import ground
from runtime.flash_revision import packed_revision
from safetensors.torch import load_file


class SpecialistFlash(QwenniferFlashModel):
    def prepare_chat_messages(self, conversation):
        for i in range(len(conversation) - 1, -1, -1):
            if conversation[i]["role"] == "user":
                messages = list(conversation)
                messages[i] = {
                    **conversation[i],
                    "content": ground(
                        self.reference_index,
                        self.specialist,
                        conversation[i]["content"],
                    ),
                }
                return messages
        return conversation


def configure_head(root):
    weights = load_file(str(root / "adapter_model.safetensors"), device="cuda:0")
    config = json.loads((root / "adapter_config.json").read_text())
    a = weights["base_model.model.lm_head.lora_A.weight"]
    b = weights["base_model.model.lm_head.lora_B.weight"]
    active = b.any(dim=1).nonzero().flatten()
    compact = b.index_select(0, active).T.contiguous()
    scale = config["lora_alpha"] / config["r"]

    def update(_head, inputs, output):
        delta = ((inputs[0].float() @ a.T) @ compact) * scale
        return output.float().index_add(-1, active, delta)

    def install(model):
        model.lm_head.register_forward_hook(update)

    return install


def serve(path):
    cfg = json.loads(path.read_text())
    settings = cfg["settings"]
    root = Path(settings["assets"])
    identity = (root / "release.json").read_bytes()
    release = json.loads(identity)
    inputs = Path(settings["inputs"])
    if packed_revision(inputs) != release["base_revision"]:
        raise ValueError(
            "Flash checkpoint or implementation differs from the training run"
        )
    token = Path(cfg["token_file"]).read_text().strip()
    if not token or os.environ.get("CUDA_VISIBLE_DEVICES") != cfg["gpus"][0]:
        raise RuntimeError("missing worker credential or assigned GPU")
    specialist = json.loads((root / "specialist.json").read_text())
    model_id = specialist["model"]
    model = SpecialistFlash(
        inputs_dir=inputs,
        flat_cache=Path(settings["flat_cache"]),
        hot_experts_file=Path(settings["hot_experts_file"]),
        map_flat_cache=True,
        cache_slots=settings["cache_slots"],
        max_context_tokens=settings["max_context_tokens"],
        prefill_chunk_tokens=1024,
        configure_head=configure_head(root),
        aliases=(model_id,),
        routing_family=model_id,
        compatibility_sha256=hashlib.sha256(identity).hexdigest(),
    )
    model.specialist = specialist
    model.reference_index = root / "references.sqlite"
    app = create_app(
        model=model,
        api_key=token,
        max_queue_size=12,
        prompt_lookup_tokens=0,
        usage_role="primary",
        close_supplied_model=True,
    )
    uvicorn.run(app, host=settings["host"], port=settings["port"], workers=1)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--config", type=Path, required=True)
    serve(parser.parse_args().config)