File size: 5,245 Bytes
41a0653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Teacher-forced per-token capture for a GGUF model, in the exact format of s09 score_checkpoint.
// Reads artifacts/eval/heldout_text.bin (see scripts/s09_teacher_capture.py), runs each row as one
// sequence from an empty KV state, and for every position t whose gold token ids[t+1] != pad writes:
//   <out>.nll  f32 (-log p(gold))     <out>.argmax i32
//   <out>.tki  i32[32] top-32 ids     <out>.tkp    f32[32] their log-probs (descending)
// Rows are processed in file order, so the output concatenates to the teacher capture's text prefix.
#include "llama.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <string>
#include <vector>

static const int TOPK = 32;

int main(int argc, char ** argv) {
    if (argc < 4) { fprintf(stderr, "usage: %s model.gguf heldout_text.bin out_prefix [max_rows]\n", argv[0]); return 2; }
    const char * mpath = argv[1]; const char * hpath = argv[2]; std::string out = argv[3];
    long max_rows = argc > 4 ? atol(argv[4]) : -1;

    FILE * hf = fopen(hpath, "rb"); if (!hf) { perror(hpath); return 1; }
    int32_t hdr[3]; if (fread(hdr, 4, 3, hf) != 3 || hdr[0] != 0x48454C44) { fprintf(stderr, "bad heldout file\n"); return 1; }
    const int n_rows = hdr[1]; const int pad = hdr[2];
    std::vector<std::vector<int32_t>> rows(n_rows);
    int max_len = 0;
    for (int r = 0; r < n_rows; r++) {
        int32_t bn[2]; if (fread(bn, 4, 2, hf) != 2) { fprintf(stderr, "truncated at row %d\n", r); return 1; }
        rows[r].resize(bn[1]);
        if ((int) fread(rows[r].data(), 4, bn[1], hf) != bn[1]) { fprintf(stderr, "truncated row %d\n", r); return 1; }
        max_len = std::max(max_len, (int) bn[1]);
    }
    fclose(hf);
    if (max_rows > 0 && max_rows < n_rows) rows.resize(max_rows);

    llama_backend_init();
    auto mp = llama_model_default_params();
    mp.n_gpu_layers = 999;
    mp.load_mode = LLAMA_LOAD_MODE_NONE;   // same as the Part A servers: no mmap double-residency on unified memory
    llama_model * model = llama_model_load_from_file(mpath, mp);
    if (!model) { fprintf(stderr, "load failed\n"); return 1; }
    const llama_vocab * vocab = llama_model_get_vocab(model);
    const int n_vocab = llama_vocab_n_tokens(vocab);

    auto cp = llama_context_default_params();
    cp.n_ctx = max_len; cp.n_batch = max_len; cp.n_ubatch = 512; cp.n_seq_max = 1;
    cp.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED;
    cp.no_perf = true;
    llama_context * ctx = llama_init_from_model(model, cp);
    if (!ctx) { fprintf(stderr, "context failed\n"); return 1; }

    FILE * f_nll = fopen((out + ".nll").c_str(), "wb"); FILE * f_am = fopen((out + ".argmax").c_str(), "wb");
    FILE * f_tki = fopen((out + ".tki").c_str(), "wb"); FILE * f_tkp = fopen((out + ".tkp").c_str(), "wb");
    if (!f_nll || !f_am || !f_tki || !f_tkp) { perror("open out"); return 1; }

    llama_batch batch = llama_batch_init(max_len, 0, 1);
    std::vector<float> lp(n_vocab); std::vector<int32_t> idx(n_vocab);
    long n_tok = 0; double sum_nll = 0;
    for (size_t r = 0; r < rows.size(); r++) {
        const auto & ids = rows[r]; const int n = ids.size();
        if (n < 2) continue;
        llama_memory_clear(llama_get_memory(ctx), true);
        batch.n_tokens = n;
        for (int i = 0; i < n; i++) {
            batch.token[i] = ids[i]; batch.pos[i] = i; batch.n_seq_id[i] = 1; batch.seq_id[i][0] = 0;
            batch.logits[i] = i < n - 1;
        }
        if (llama_decode(ctx, batch) != 0) { fprintf(stderr, "decode failed on row %zu\n", r); return 1; }
        for (int t = 0; t < n - 1; t++) {
            const int gold = ids[t + 1];
            if (gold == pad) continue;
            const float * lg = llama_get_logits_ith(ctx, t);
            float mx = -INFINITY; for (int v = 0; v < n_vocab; v++) mx = std::max(mx, lg[v]);
            double s = 0; for (int v = 0; v < n_vocab; v++) s += std::exp((double) lg[v] - mx);
            const float lse = mx + (float) std::log(s);
            for (int v = 0; v < n_vocab; v++) lp[v] = lg[v] - lse;
            std::iota(idx.begin(), idx.end(), 0);
            std::partial_sort(idx.begin(), idx.begin() + TOPK, idx.end(), [&](int a, int b) { return lp[a] > lp[b]; });
            float nll = -lp[gold]; int32_t am = idx[0]; float tkp[TOPK];
            for (int k = 0; k < TOPK; k++) tkp[k] = lp[idx[k]];
            fwrite(&nll, 4, 1, f_nll); fwrite(&am, 4, 1, f_am);
            fwrite(idx.data(), 4, TOPK, f_tki); fwrite(tkp, 4, TOPK, f_tkp);
            n_tok++; sum_nll += nll;
        }
        if (r % 10 == 0 || r + 1 == rows.size())
            fprintf(stderr, "row %zu/%zu  tokens %ld  mean nll %.4f\n", r + 1, rows.size(), n_tok, sum_nll / std::max(1L, n_tok));
    }
    bool ok = true;
    for (FILE * f : {f_nll, f_am, f_tki, f_tkp}) ok &= fflush(f) == 0 && ferror(f) == 0 && fclose(f) == 0;
    if (!ok) { fprintf(stderr, "write error\n"); return 1; }
    FILE * done = fopen((out + ".done").c_str(), "w"); fprintf(done, "%ld\n", n_tok); fclose(done);
    llama_batch_free(batch); llama_free(ctx); llama_model_free(model);
    fprintf(stderr, "DONE %ld tokens, mean nll %.5f\n", n_tok, sum_nll / std::max(1L, n_tok));
    return 0;
}