File size: 5,440 Bytes
3a77415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Micro-batch shares of likelihood scoring: a CPU re-implementation of the scorer's batch
construction (llama-perplexity --multiple-choice) and of the hybrid memory's split_equal on the bench settings
(-c 1024 -np 16 -ub 512; MMLU and HellaSwag -c 4096 -np 4), counting micro-batches of at most eight tokens (every layer
runs matrix-vector products) and scored rows whose final layer and head run in products of at most eight columns.
Not a GPU trace. Tokenizer: the teacher's Hugging Face tokenizer.json, whose token ids were checked against the engine's
on Winogrande sentences by winogrande_ramo.py (Winogrande itself is not simulated here). Inputs from the environment: THOR_BENCH_INPUT (the bench dataset's bench/ directory, with
OpenBookQA and PIQA rebuilt by ricostruisci_banchi.py) and THOR_TOKENIZER (hf/tokenizer/tokenizer.json).
Usage: python3 microbatch_shares.py OUT.json [task,task,...]"""
import json
import os
import struct
import sys
from pathlib import Path

from tokenizers import Tokenizer

_TK = Tokenizer.from_file(os.environ["THOR_TOKENIZER"])


def tok(s):
    return _TK.encode(s, add_special_tokens=True).ids


def read_mc(p):
    if p.endswith(".txt"):
        LN=open(p,encoding="utf-8").read().split("\n")
        while LN and LN[-1]=="": LN.pop()
        return [(LN[6*i],LN[6*i+2:6*i+6]) for i in range(len(LN)//6)]
    b=open(p,"rb").read(); n=struct.unpack_from("<I",b,0)[0]; off=4+4*n; T=[]
    def s(o):
        Ln=struct.unpack_from("<I",b,o)[0]; return b[o+4:o+4+Ln].decode("utf-8","replace"),o+4+Ln
    def ans(o):
        k=struct.unpack_from("<I",b,o)[0]; o+=4; A=[]
        for _ in range(k):
            a,o=s(o); A.append(a)
        lab=list(struct.unpack_from("<%di"%k,b,o)); return A,lab,o+4*k
    for _ in range(n):
        q,off=s(off); A,lab,off=ans(off); _,_,off=ans(off); T.append((q,A))
    return T
def prep(q,A):
    seqs=[tok(q+" "+a) for a in A]
    ml=min(map(len,seqs)); cp=0
    while cp<ml and all(s[cp]==seqs[0][cp] for s in seqs): cp+=1
    req=cp+sum(len(s)-cp for s in seqs)
    return seqs,cp,req
def split_equal(toks,used,n_ub):
    # toks: list of (frozenset, out, relevant, task)
    cur=[]
    for i,t in enumerate(toks):
        if used[i]: continue
        if all(not (c & t[0]) for c in cur):
            cur.append(t[0])
            if len(cur)>n_ub: break
    if not cur: return None
    idx=[[i for i,t in enumerate(toks) if t[0]==c and not used[i]] for c in cur]
    ns=len(cur); got=[[] for _ in cur]; k=0
    while all(k<len(x) for x in idx):
        for s in range(ns):
            got[s].append(idx[s][k]); used[idx[s][k]]=True
        k+=1
        if (len(got[0])+1)*ns>n_ub: break
    return [i for g in got for i in g]
def run(name,path,np_,c,n_ub=512,n_batch_req=2048,limit=None):
    T=read_mc(path)
    if limit: T=T[:limit]
    n_ctx=np_*c; n_batch=min(n_ctx,n_batch_req); max_seq=min(128,np_)
    P=[prep(q,A) for q,A in T]
    st=dict(ub=0,ub_small=0,rel=0,rel_small=0,out=0,out_mv=0,items=len(T),items_body=0,items_head=0)
    i0=0
    while i0<len(T):
        toks=[]; n_cur=0; s0=0; i1=i0
        while i1<len(T) and n_cur+P[i1][2]<=n_ctx:
            seqs,cp,req=P[i1]; na=len(seqs)
            if s0+na>max_seq: break
            pre=frozenset(range(s0,s0+na))
            for j in range(cp): toks.append([pre,j==cp-1,True,i1])
            for s,sq in enumerate(seqs):
                for j in range(cp,len(sq)):
                    nl=j<len(sq)-1
                    toks.append([frozenset([s0+s]),nl,nl,i1])
            s0+=na; n_cur+=req; i1+=1
        # decode_helper chunks by n_batch, each chunk is a separate llama_decode
        body=set(); head=set()
        for c0 in range(0,len(toks),n_batch):
            ch=toks[c0:c0+n_batch]; used=[False]*len(ch)
            while True:
                ub=split_equal(ch,used,n_ub)
                if ub is None: break
                nt=len(ub); no=sum(ch[i][1] for i in ub); nr=sum(ch[i][2] for i in ub)
                st['ub']+=1; st['rel']+=nr; st['out']+=no
                if nt<=8:
                    st['ub_small']+=1; st['rel_small']+=nr
                    for i in ub:
                        if ch[i][2]: body.add(ch[i][3])
                if 1<=no<=8:
                    st['out_mv']+=no
                    for i in ub:
                        if ch[i][1]: head.add(ch[i][3])
        st['items_body']+=len(body); st['items_head']+=len(head)
        i0=i1
    st['name']=name
    print(json.dumps(st),flush=True)
    return st


if __name__ == "__main__":
    # flat layout of the bench dataset (bench/<file>); OpenBookQA and PIQA are rebuilt by ricostruisci_banchi.py
    B = os.environ.get("THOR_BENCH_INPUT", "")
    j = lambda n: os.path.join(B, n)
    jobs = {"arc_easy": (j("arc_easy_test.bin"), 16, 1024), "arc_challenge": (j("arc_challenge_test.bin"), 16, 1024),
            "openbookqa": (j("openbookqa_test.bin"), 16, 1024), "boolq": (j("boolq_test.bin"), 16, 1024),
            "truthfulqa_mc1": (j("truthfulqa_mc1_test.bin"), 16, 1024), "piqa_full": (j("piqa_full.bin"), 16, 1024),
            "mmlu_pro_mc": (j("mmlu_pro_mc.bin"), 16, 1024), "mmlu_full": (j("mmlu_test.bin"), 4, 4096),
            "hellaswag": (j("hellaswag_val_full.txt"), 4, 4096)}
    out = Path(sys.argv[1])
    names = sys.argv[2].split(",") if len(sys.argv) > 2 else list(jobs)
    res = {k: run(k, *jobs[k]) for k in names}
    out.write_text(json.dumps(res, indent=1))