File size: 10,336 Bytes
dc47fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Clean Conversational NIAH (`dialog` mode) without substring / unclosed-<think> false positives.

Fixes all bugs from eval_niah.py:
  1. Uses 4 unambiguous needles (no 2-digit numbers like "14" that collide with times/indices).
  2. Parses `<think>...</think>` via regex and checks `answer in visible_reply` ONLY.
  3. Enforces production `max_think=64` (force-closing `</think>`) + `rep_pen=1.03`, `no_repeat=3`.
  4. Logs separately: `visible_hit`, `think_hit`, `think_closed`, across N=4 needles x 4 depths x 4 lengths = 64 trials.
"""
import argparse
import json
import os
import re
import time
import torch
from tokenizers import Tokenizer

from model.config import UDreamConfig
from model.model import UDream
from eval_niah import load_haystack_turns, build_prompt
from udata.real_dialog_loader import H_MEAN_DLG

TID_THINK_OPEN = 64024
TID_THINK_CLOSE = 64025

CLEAN_NEEDLES = [
    {
        "dialog_fact": "<turn><speaker>Оля</speaker>до речі, запиши про всяк випадок: код від камери схову на вокзалі 7492, і ключ лишила в баристи на ім'я Тимур</turn><turn><speaker>Юді</speaker><think>Оля назвала код камери схову 7492 та ім'я баристи Тимур.</think>ок, запам'ятав: 7492 і Тимур)</turn>",
        "dialog_q": "<turn><speaker>Оля</speaker>слухай, я вже біля вокзалу і вилетіло з голови, який там був код від камери схову?</turn><turn><speaker>Юді</speaker>",
        "answer": "7492",
    },
    {
        "dialog_fact": "<turn><speaker>Макс</speaker>о, чуть не забув сказати: мій новий поїзд прибуває о 19:47 на колію 831, вагон дев'ятий</turn><turn><speaker>Юді</speaker><think>Макс сказав про поїзд: 19:47, колія 831.</think>прийняв, колія 831 о 19:47</turn>",
        "dialog_q": "<turn><speaker>Макс</speaker>нагадай швидко, на яку саме колію (номер з трьох цифр) прибуває мій поїзд?</turn><turn><speaker>Юді</speaker>",
        "answer": "831",
    },
    {
        "dialog_fact": "<turn><speaker>Денис</speaker>слухай, пароль від нашого спільного архіву цього тижня — «Смарагд47», нікому не скидай</turn><turn><speaker>Юді</speaker><think>Денис дав пароль від архіву Смарагд47.</think>домовились, Смарагд47 тримаю в голові</turn>",
        "dialog_q": "<turn><speaker>Денис</speaker>вилетіло з голови, яке там було слово-пароль до архіву?</turn><turn><speaker>Юді</speaker>",
        "answer": "Смарагд47",
    },
    {
        "dialog_fact": "<turn><speaker>Аня</speaker>мій новий номер комірки в поштоматі 5208, забери будь ласка посилку ввечері</turn><turn><speaker>Юді</speaker><think>Аня попросила запам'ятати комірку 5208.</think>окей, 5208, записав</turn>",
        "dialog_q": "<turn><speaker>Аня</speaker>ти пам'ятаєш, який номер комірки в поштоматі я казала?</turn><turn><speaker>Юді</speaker>",
        "answer": "5208",
    },
]


@torch.inference_mode()
def chunked_prefill_and_gen_clean(m, tk, prompt_ids, h_vec, dev, max_new=96, max_think=64,
                                  rep_pen=1.03, no_repeat=3, chunk=512):
    kv_cache = {}
    T = len(prompt_ids)
    last_logits = None
    for s in range(0, T, chunk):
        part = torch.tensor([prompt_ids[s:s + chunk]], dtype=torch.long, device=dev)
        out = m(part, hormones=h_vec, use_hormones=True, kv_cache=kv_cache, pos_offset=s, last_only=(s + chunk >= T))
        if s + chunk >= T:
            last_logits = out["logits"][0, -1].float()

    stop_ids = {tk.token_to_id(t) for t in ("</turn>", "<turn>", "</dialog>", "<speaker>", "<eos>")
                if tk.token_to_id(t) is not None}
    bad_ids = list((0, 1, 3, 4, 5, 8, 9, 12, 13, 14, 15, 16, 17, 18, 19))
    bad_ids.extend(range(64000, 64013))
    bad_ids.extend(range(64015, 64024))
    bad_ids.extend(range(64026, 64128))
    bad_t = torch.tensor(bad_ids, dtype=torch.long, device=dev)

    gen = []
    pos = T
    lg = last_logits
    for i in range(max_new):
        has_open = TID_THINK_OPEN in gen
        has_close = TID_THINK_CLOSE in gen
        if has_open and not has_close and len(gen) >= max_think:
            nxt = TID_THINK_CLOSE
            gen.append(nxt)
            nxt_t = torch.tensor([[nxt]], dtype=torch.long, device=dev)
            lg = m(nxt_t, hormones=h_vec, use_hormones=True, kv_cache=kv_cache, pos_offset=pos, last_only=True)["logits"][0, -1].float()
            pos += 1
            continue

        lg = lg.clone()
        lg.index_fill_(0, bad_t, float("-inf"))
        if has_open:
            lg[TID_THINK_OPEN] = float("-inf")
        if has_close:
            lg[TID_THINK_CLOSE] = float("-inf")
        elif has_open:
            for sid in stop_ids:
                lg[sid] = float("-inf")

        if has_close:
            end_idx = len(gen) - 1 - gen[::-1].index(TID_THINK_CLOSE)
            phase = gen[end_idx + 1:]
        else:
            phase = gen

        if rep_pen != 1.0 and phase:
            u = torch.unique(torch.tensor(phase, dtype=torch.long, device=dev))
            v = lg[u]
            lg[u] = torch.where(v > 0, v / rep_pen, v * rep_pen)
        if no_repeat > 1 and len(phase) >= no_repeat:
            tail = tuple(phase[-(no_repeat - 1):])
            banned = [phase[j + no_repeat - 1] for j in range(len(phase) - no_repeat + 1)
                      if tuple(phase[j:j + no_repeat - 1]) == tail]
            if banned:
                lg[banned] = float("-inf")

        nxt = int(lg.argmax().item())
        if i >= 2 and nxt in stop_ids:
            break
        gen.append(nxt)
        nxt_t = torch.tensor([[nxt]], dtype=torch.long, device=dev)
        lg = m(nxt_t, hormones=h_vec, use_hormones=True, kv_cache=kv_cache, pos_offset=pos, last_only=True)["logits"][0, -1].float()
        pos += 1

    raw = tk.decode(gen, skip_special_tokens=False)
    mth = re.search(r"<think>(.*?)</think>(.*)", raw, re.S)
    if mth:
        return raw, mth.group(1).strip(), mth.group(2).strip(), True
    if "<think>" in raw:
        return raw, raw.split("<think>", 1)[1].strip(), "", False
    return raw, "", raw.strip(), True


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ckpt", default="/home/katie/udream/ckpt/udream_v1_sft2b_v2_last.pt")
    ap.add_argument("--tok", default="/home/katie/udream/tok/udream_bpe_64k_tags.json")
    ap.add_argument("--long-file", default="/home/katie/synth_gen/dataset/sft_v1_final/long.jsonl")
    ap.add_argument("--dev", default="cuda:0")
    ap.add_argument("--lengths", default="4096,8192,16384,28672")
    ap.add_argument("--depths", default="0.10,0.35,0.65,0.90")
    ap.add_argument("--out", default="/home/katie/udream/data_survey/niah_sft2b_v2_dialog_clean.json")
    a = ap.parse_args()

    lengths = [int(x) for x in a.lengths.split(",")]
    depths = [float(x) for x in a.depths.split(",")]

    t0 = time.time()
    st = torch.load(a.ckpt, map_location="cpu", mmap=True, weights_only=False)
    cfg = UDreamConfig(**st["cfg"])
    sd = {k.replace("_orig_mod.", ""): v for k, v in st["model"].items()}
    with torch.device("cpu"):
        m = UDream(cfg).to(torch.bfloat16)
    m.load_state_dict(sd, strict=False)
    del st, sd
    m = m.to(a.dev).eval()
    tk = Tokenizer.from_file(a.tok)
    hay_turns = load_haystack_turns(a.long_file, tk)
    h_vec = torch.tensor([H_MEAN_DLG.tolist()], dtype=torch.bfloat16, device=a.dev)

    results = []
    tot_vis, tot_th, tot_trials = 0, 0, 0
    for L in lengths:
        row = []
        for d in depths:
            vhits, thits, closed_cnt = 0, 0, 0
            samples = []
            for nd in CLEAN_NEEDLES:
                p_ids = build_prompt(tk, hay_turns, nd, L, d, "dialog")
                raw, th, vis, closed = chunked_prefill_and_gen_clean(m, tk, p_ids, h_vec, a.dev)
                ans_l = nd["answer"].lower()
                vis_ok = ans_l in vis.lower()
                th_ok = ans_l in th.lower()
                vhits += int(vis_ok)
                thits += int(th_ok)
                closed_cnt += int(closed)
                tot_vis += int(vis_ok)
                tot_th += int(th_ok)
                tot_trials += 1
                samples.append({
                    "ans": nd["answer"],
                    "visible_ok": vis_ok,
                    "think_ok": th_ok,
                    "think_closed": closed,
                    "think": th[:120],
                    "visible": vis[:160],
                })
            acc = vhits / len(CLEAN_NEEDLES)
            row.append(f"{int(acc*100):3d}%")
            results.append({
                "length": L,
                "depth": d,
                "visible_acc": acc,
                "think_acc": thits / len(CLEAN_NEEDLES),
                "think_closed_rate": closed_cnt / len(CLEAN_NEEDLES),
                "samples": samples,
            })
        print(f"  L={L:5d} | depths {depths} -> visible recall: {' '.join(row)}", flush=True)

    summary = {
        "ckpt": a.ckpt,
        "mode": "dialog_clean_visible_only",
        "n_needles_per_cell": len(CLEAN_NEEDLES),
        "total_trials": tot_trials,
        "overall_visible_hits": tot_vis,
        "overall_visible_acc": round(tot_vis / max(tot_trials, 1), 4),
        "overall_think_hits": tot_th,
        "elapsed_sec": round(time.time() - t0, 1),
        "results": results,
    }
    os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
    with open(a.out, "w", encoding="utf-8", newline="\n") as f:
        json.dump(summary, f, ensure_ascii=False, indent=2)
    print(f"[DONE] visible={tot_vis}/{tot_trials} ({summary['overall_visible_acc']*100:.1f}%) think={tot_th}/{tot_trials} -> {a.out}")


if __name__ == "__main__":
    main()