File size: 2,242 Bytes
2f04653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Cross-check: teacher-forced prompt logprobs from the vLLM plugin (vllm_probe.py JSON)
vs. the PyTorch trainer forward with the same adapter/depth. Both are fp32 if the probe
was run with --dtype float32."""
from __future__ import annotations

import argparse
import json

import torch


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--probe", required=True)
    ap.add_argument("--model", required=True)
    ap.add_argument("--adapter", default=None)
    ap.add_argument("--passes", type=int, default=3)
    ap.add_argument("--dtype", default="float32")
    args = ap.parse_args()

    from looped_qwen_moe.adapter import LoopAdapter, LoopAdapterConfig, load_adapter
    from looped_qwen_moe.training.model import LoopedTrainModel

    dt = getattr(torch, args.dtype)
    if args.adapter:
        ad = load_adapter(args.adapter)
    else:
        cfgj = json.load(open(f"{args.model}/config.json"))
        t = cfgj.get("text_config", cfgj)
        L = t["num_hidden_layers"]
        ad = LoopAdapter(LoopAdapterConfig(hidden_size=t["hidden_size"], num_layers=L, num_experts=t["num_experts"],
                                           core_start=max(4, 4 * round(0.4 * L / 4)),
                                           core_end=min(L - 4, max(4, 4 * round(0.7 * L / 4)))))
    m = LoopedTrainModel(args.model, ad.cuda(), device="cuda", expert_device="cuda", dtype=dt, log=lambda *_: None)
    worst, n, agree = 0.0, 0, 0
    for r in json.load(open(args.probe))["results"]:
        ids = torch.tensor([r["prompt_token_ids"]], device="cuda")
        with torch.no_grad():
            lp = torch.log_softmax(m.logits(m.forward_hidden(ids, args.passes)).float(), -1)[0]
        for pos, step in enumerate(r["prompt_logprobs"]):
            if not step:
                continue
            best_v = max(step, key=lambda k: step[k])
            agree += int(lp[pos - 1].argmax().item() == int(best_v))
            n += 1
            for tokid, v in step.items():
                worst = max(worst, abs(lp[pos - 1, int(tokid)].item() - v))
    print(json.dumps({"positions": n, "top1_agreement": agree / max(1, n), "max_abs_logprob_diff": worst}))


if __name__ == "__main__":
    main()