File size: 5,615 Bytes
3d81e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
"""Teacher-force complete answers on an offline copy of the admitted packed Flash."""

import argparse
import hashlib
import inspect
import json
from collections import Counter
from pathlib import Path

import numpy as np
import torch
from belikewater_transformers.models.qwennifer.flash_serving import (
    QwenniferFlashModel,
)
from flash_revision import packed_revision


def load(settings):
    cfg = json.loads(settings.read_text())
    inputs = Path(cfg["inputs"])
    bank, hot = Path(cfg["flat_cache"]), Path(cfg["hot_experts_file"])
    if not bank.is_file() or not hot.is_file():
        msg = "expected existing Flash assets"
        raise FileNotFoundError(msg)
    flash = QwenniferFlashModel(
        inputs_dir=inputs,
        flat_cache=bank,
        hot_experts_file=hot,
        cache_slots=cfg.get("capture_cache_slots", 9000),
        **({"map_flat_cache": True} if cfg.get("map_flat_cache") else {}),
        max_context_tokens=1024,
        prefill_chunk_tokens=1024,
    )
    return flash, packed_revision(inputs)


def prompt_ids(tok, row):
    text = tok.apply_chat_template(
        [{"role": "user", "content": row["prompt"]}],
        tokenize=False,
        add_generation_prompt=True,
    )
    return tok.encode(text, add_special_tokens=False)


def name(row):
    return row["id"] + "-" + row["condition"]


def capture_sequence(flash, ids):
    # The frozen runner hands its final norm only the last position. For a
    # single chunk the same activation tensor already contains every position.
    # Inspect only that one call, without changing serving or recomputing layers.
    runner = flash.runner
    found = []
    code = inspect.unwrap(type(runner).prefill).__code__

    def collect(_module, args):
        frame = inspect.currentframe().f_back
        while frame is not None and frame.f_code is not code:
            frame = frame.f_back
        if frame is None:
            msg = "unrecognized Flash prefill call"
            raise RuntimeError(msg)
        all_hidden = frame.f_locals["hs"]
        if (
            all_hidden.shape[1] != len(ids)
            or all_hidden[:, -1:].data_ptr() != args[0].data_ptr()
        ):
            msg = "expected last position of a single prefill chunk"
            raise RuntimeError(msg)
        found.append(all_hidden)

    with flash.model.model.norm.register_forward_pre_hook(collect):
        last = runner.prefill(torch.tensor([ids], device=flash.device))
    (hs,) = found
    return hs, last


@torch.inference_mode()
def capture(settings, dataset, directory):
    directory.mkdir(exist_ok=False)
    flash, revision = load(settings)
    rows = [json.loads(x) for x in dataset.read_text().splitlines()]
    tok = flash.tokenizer
    answers = [
        [*tok.encode(r["answer"], add_special_tokens=False), tok.eos_token_id]
        for r in rows
    ]
    freq = Counter(
        t
        for r, ids in zip(rows, answers, strict=True)
        if r["split"] == "train"
        for t in ids
    )
    vocab = sorted(
        k for k, _ in sorted(freq.items(), key=lambda kv: (-kv[1], kv[0]))[:256]
    )
    select = torch.tensor(vocab, device=flash.device)
    meta = {
        "model": "qwennifer-flash",
        "revision": revision,
        "rows": vocab,
        "gpu": torch.cuda.get_device_name(),
        "dataset_sha256": hashlib.sha256(dataset.read_bytes()).hexdigest(),
    }
    for i, (r, answer) in enumerate(zip(rows, answers, strict=True)):
        prefix = prompt_ids(tok, r)
        ids = prefix + answer[:-1]
        if len(ids) > flash.max_context_tokens:
            msg = "supervised prompt exceeds offline capture budget"
            raise ValueError(msg)
        hs, last = capture_sequence(flash, ids)
        h = flash.model.model.norm(hs[:, len(prefix) - 1 :, :]).squeeze(0)
        scores = flash.model.lm_head(h.unsqueeze(0)).squeeze(0).float()
        y = torch.tensor(answer, device=flash.device)
        top = scores.argmax(1)
        if i == 0:
            independent = flash.runner.prefill(
                torch.tensor([prefix], device=flash.device)
            )
            control = {
                "prompt_only_top1": independent,
                "teacher_forced_first_top1": top[0].item(),
                "stock_last_top1": last,
                "captured_last_top1": top[-1].item(),
            }
            if independent != top[0].item() or last != top[-1].item():
                msg = f"causal/alignment control disagrees: {control}"
                raise RuntimeError(msg)
            meta.update(control=control, vocabulary=scores.shape[1])
            (directory / "meta.json").write_text(json.dumps(meta))
        selected = scores[:, select]
        label = scores.gather(1, y[:, None]).squeeze(1)
        scores[:, select] = -torch.inf
        outside_max, outside_id = scores.max(1)

        def array(x):
            return x.cpu().numpy()

        np.savez(
            directory / (name(r) + ".npz"),
            h=array(h.half()),
            y=array(y),
            selected=array(selected),
            label=array(label),
            outside_lse=array(scores.logsumexp(1)),
            outside_max=array(outside_max),
            outside_id=array(outside_id),
        )
        if i % 20 == 0 or i + 1 == len(rows):
            print(f"{i + 1}/{len(rows)} complete", flush=True)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    for arg in ("settings", "dataset", "directory"):
        parser.add_argument(arg, type=Path)
    args = parser.parse_args()
    capture(args.settings, args.dataset, args.directory)