File size: 5,668 Bytes
e8a992b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Parity verification & benchmark for WebBrain-LingLoop-8B-A1.3B native Windows CUDA runtime."""

import json
import math
import os
import sys
import time
from pathlib import Path

os.environ["HF_HUB_DISABLE_XET"] = "1"
ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT))

import torch
import torch.nn.functional as F
from transformers import AutoTokenizer

from lingloop_cuda.modeling_lingloop_cuda import LingLoopCache, LingLoopCudaModel


def _load_wikitext_text() -> str:
    local_wt = ROOT / "upstream" / "wikitext2_test.txt"
    if local_wt.exists():
        return local_wt.read_text(encoding="utf-8")
    raise FileNotFoundError(f"Missing cached wikitext2_test.txt at {local_wt}")


def eval_ppl(model: LingLoopCudaModel, token_ids: list[int], chunk_len: int = 256, num_passes: int = 2) -> float:
    total_nll = 0.0
    total_tok = 0
    for start in range(0, len(token_ids) - 1, chunk_len):
        end = min(len(token_ids), start + chunk_len + 1)
        if end - start < 2:
            continue
        seg = token_ids[start:end]
        inp = torch.tensor([seg[:-1]], device=model.device, dtype=torch.long)
        tgt = torch.tensor(seg[1:], device=model.device, dtype=torch.long)
        logits = model.forward_logits(inp, cache=None, num_passes=num_passes, last_token_only=False)[0]
        nll = F.cross_entropy(logits.float(), tgt, reduction="sum").item()
        total_nll += nll
        total_tok += tgt.numel()
    return math.exp(total_nll / max(1, total_tok))


def main() -> None:
    gguf_path = str(ROOT / "upstream" / "WebBrain-LingLoop-8B-A1.3B-Q6_K.gguf")
    meta_dir = str(ROOT / "upstream" / "hf_meta")
    cfg_path = str(ROOT / "upstream" / "hf_meta" / "config.json")

    torch.cuda.reset_peak_memory_stats()
    t0 = time.perf_counter()
    tok = AutoTokenizer.from_pretrained(meta_dir, trust_remote_code=True)
    model = LingLoopCudaModel.from_gguf(gguf_path, cfg_path, device=torch.device("cuda:0"))
    load_s = time.perf_counter() - t0
    vram_loaded_gb = torch.cuda.memory_allocated() / (1024 ** 3)
    print(f"[load] {load_s:.2f}s | VRAM={vram_loaded_gb:.3f} GiB")

    # 1. Prefill vs step-by-step decode cache parity check
    sample_ids = tok.encode("Question: What is 17 times 23? Answer:", add_special_tokens=False)
    logits_prefill = model.forward_logits(
        torch.tensor([sample_ids], device=model.device, dtype=torch.long), cache=None, last_token_only=True
    )[0, 0]
    cache = LingLoopCache(model.cfg, model.device, max_seq=512)
    # Split prefill first half + step second half
    half = len(sample_ids) - 3
    _ = model.forward_logits(torch.tensor([sample_ids[:half]], device=model.device), cache=cache, last_token_only=True)
    for tid in sample_ids[half:]:
        logits_step = model.forward_logits(torch.tensor([[tid]], device=model.device), cache=cache, last_token_only=True)[0, 0]
    cache_diff = (logits_prefill - logits_step).abs().max().item()
    cache_top1_match = int(logits_prefill.argmax().item() == logits_step.argmax().item())
    print(f"[cache_parity] max_logit_diff={cache_diff:.4f} top1_match={cache_top1_match}")

    # 2. TEST_CARD.md exact arithmetic prompt
    gen_ids, tok_s = model.generate(sample_ids, max_new_tokens=24, temperature=0.0)
    ans_text = tok.decode(gen_ids, skip_special_tokens=True).strip()
    print(f"[test_card_prompt] '{ans_text}' | tok/s={tok_s:.2f} | pass={'391' in ans_text}")

    # 3. Chat template sanity (non-thinking & thinking)
    msgs = [{"role": "user", "content": "What is 19 * 24? Answer with just the number."}]
    nt_txt_p = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False)
    nt_ids = tok.encode(nt_txt_p, add_special_tokens=False)
    nt_out, nt_tps = model.generate(nt_ids, max_new_tokens=64, temperature=0.0)
    nt_txt = tok.decode(nt_out, skip_special_tokens=False)
    print(f"[chat_nt] ({nt_tps:.2f} tok/s): {nt_txt!r}")

    th_txt_p = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=True)
    th_ids = tok.encode(th_txt_p, add_special_tokens=False)
    th_out, th_tps = model.generate(th_ids, max_new_tokens=256, temperature=0.0)
    th_txt = tok.decode(th_out, skip_special_tokens=False)
    print(f"[chat_th] ({th_tps:.2f} tok/s): {th_txt[:300]!r}")

    # 4. WikiText-2 2K PPL: 1-pass vs 2-pass (proves loop adapter active & improves quality)
    wt_text = _load_wikitext_text()
    wt_ids = tok.encode(wt_text, add_special_tokens=False)[:2049]
    ppl_1p = eval_ppl(model, wt_ids, chunk_len=256, num_passes=1)
    ppl_2p = eval_ppl(model, wt_ids, chunk_len=256, num_passes=2)
    peak_gb = torch.cuda.max_memory_allocated() / (1024 ** 3)
    print(f"[wikitext2_2k] 1-pass PPL={ppl_1p:.3f} | 2-pass PPL={ppl_2p:.3f} | peak VRAM={peak_gb:.3f} GiB")

    out = {
        "load_seconds": round(load_s, 3),
        "vram_loaded_gib": round(vram_loaded_gb, 3),
        "vram_peak_gib": round(peak_gb, 3),
        "cache_max_logit_diff": round(cache_diff, 5),
        "cache_top1_match": bool(cache_top1_match),
        "test_card_391_text": ans_text,
        "test_card_391_pass": "391" in ans_text,
        "chat_nt_text": nt_txt,
        "chat_nt_tok_s": round(nt_tps, 2),
        "chat_th_text": th_txt[:500],
        "chat_th_tok_s": round(th_tps, 2),
        "wikitext2_2k_ppl_1pass": round(ppl_1p, 4),
        "wikitext2_2k_ppl_2pass": round(ppl_2p, 4),
        "loop_improves_ppl": ppl_2p < ppl_1p,
    }
    res_path = ROOT / "results" / "baseline_parity_lingloop.json"
    res_path.write_text(json.dumps(out, indent=2), encoding="utf-8")
    print(f"Saved {res_path}")


if __name__ == "__main__":
    main()