okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-qwen36 into f-144-rel (geometry: #2179's read_geometry guard kept for qwen4exp, Qwen3.6's family guard on top)4cfeaa0f4

main
7.3 KiB157 linesraw
1// tools/qwen35/q36_llama_dump.cpp - llama.cpp's side of the Qwen3.6 parity check (NEW-MODELS-PLAN.md T1): the same GGUF,
2// the same token ids, llama.cpp's own graph.  Prints the prompt's ids and the greedy ids, and dumps every processed
3// position's layer outputs ("l_out-N", through the scheduler's eval callback) in strata-q36ref's format
4// ([pos][layer][n_embd] f32) plus each greedy step's top-2 (id, logit).
5//
6// Built against a llama.cpp checkout (not part of Strata's build):
7//   g++ -O2 -std=c++17 q36_llama_dump.cpp -I<llama>/include -I<llama>/ggml/include -L<llama>/build/bin -lllama -lggml
8//       -lggml-base -Wl,-rpath,<llama>/build/bin -o q36_llama_dump
9// Usage: q36_llama_dump --model GGUF (--prompt TEXT | --tokens ID,ID,...) [--n 64] [--ngl 99] [--dump-layers F]
10//                       [--dump-logits F] [--force ID,ID,...] [--dump-full-logits F]
11//   --force feeds that continuation instead of the greedy ids (teacher forcing); --dump-full-logits writes every
12//   step's logits (f32, [step][vocab]).
13//   --prompt is tokenized with special tokens parsed and no BOS added (Qwen adds none).
14#include "llama.h"
15#include "ggml-backend.h"
16
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <map>
21#include <string>
22#include <vector>
23
24namespace {
25struct Capture {
26    int n_embd = 0, n_layer = 0, n_tok = 0;
27    std::map<int, std::vector<float>> layers;   // layer -> [n_tok][n_embd] of the current batch
28};
29
30bool on_tensor(struct ggml_tensor* t, bool ask, void* user) {
31    auto* c = (Capture*) user;
32    const char* name = ggml_get_name(t);
33    if (std::strncmp(name, "l_out-", 6) != 0) return ask ? false : true;
34    if (ask) return true;
35    const int il = std::atoi(name + 6);
36    if (t->type != GGML_TYPE_F32 || t->ne[0] != c->n_embd) return true;
37    std::vector<float>& v = c->layers[il];
38    v.resize((size_t) ggml_nelements(t));
39    ggml_backend_tensor_get(t, v.data(), 0, ggml_nbytes(t));
40    return true;
41}
42
43std::vector<int> parse_ids(const std::string& s) {
44    std::vector<int> v;
45    const char* p = s.c_str();
46    while (*p) {
47        while (*p == ',' || *p == ' ') ++p;
48        if (!*p) break;
49        v.push_back(std::atoi(p));
50        while (*p && *p != ',' && *p != ' ') ++p;
51    }
52    return v;
53}
54}  // namespace
55
56int main(int argc, char** argv) {
57    std::string model, prompt, tokens, dump_layers, dump_logits, force, dump_full;
58    int n_gen = 64, ngl = 99;
59    for (int i = 1; i + 1 < argc; i += 2) {
60        const std::string a = argv[i], v = argv[i + 1];
61        if (a == "--model") model = v;
62        else if (a == "--prompt") prompt = v;
63        else if (a == "--tokens") tokens = v;
64        else if (a == "--n") n_gen = std::atoi(v.c_str());
65        else if (a == "--ngl") ngl = std::atoi(v.c_str());
66        else if (a == "--dump-layers") dump_layers = v;
67        else if (a == "--dump-logits") dump_logits = v;
68        else if (a == "--force") force = v;
69        else if (a == "--dump-full-logits") dump_full = v;
70        else { std::fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; }
71    }
72    // STRATA_DUMP_NGL: the GPU layers when the caller asks for the GPU (--ngl > 0) but the file does not fit (UD-Q4_K_XL
73    // on a 12 GB card); the other layers run on llama.cpp's CPU backend
74    if (const char* g = std::getenv("STRATA_DUMP_NGL"); g != nullptr && ngl > 0) ngl = std::atoi(g);
75    llama_backend_init();
76    llama_model_params mp = llama_model_default_params();
77    mp.n_gpu_layers = ngl;
78    llama_model* mdl = llama_model_load_from_file(model.c_str(), mp);
79    if (!mdl) { std::fprintf(stderr, "cannot load %s\n", model.c_str()); return 1; }
80    const llama_vocab* vocab = llama_model_get_vocab(mdl);
81    std::vector<llama_token> ids;
82    if (!tokens.empty()) {
83        for (int t : parse_ids(tokens)) ids.push_back(t);
84    } else {
85        ids.resize(prompt.size() + 16);
86        const int n = llama_tokenize(vocab, prompt.c_str(), (int) prompt.size(), ids.data(), (int) ids.size(), false, true);
87        if (n < 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; }
88        ids.resize(n);
89    }
90    Capture cap;
91    cap.n_embd = llama_model_n_embd(mdl);
92    cap.n_layer = llama_model_n_layer(mdl);
93    llama_context_params cp = llama_context_default_params();
94    // STRATA_DUMP_CTX: a smaller context / batch (the parity sequences are a few hundred tokens) for a file whose
95    // weights leave no VRAM for the 4096-token compute buffers (UD-Q6_K_XL on a 32 GB card)
96    const char* cx = std::getenv("STRATA_DUMP_CTX");
97    const int nctx = cx ? std::atoi(cx) : 4096;
98    cp.n_ctx = nctx;
99    cp.n_batch = cp.n_ubatch = nctx;
100    cp.op_offload = ngl > 0;   // --ngl 0 is the CPU backend: no prompt matmuls offloaded to a GPU either
101    cp.cb_eval = on_tensor;
102    cp.cb_eval_user_data = &cap;
103    llama_context* ctx = llama_init_from_model(mdl, cp);
104    if (!ctx) { std::fprintf(stderr, "cannot create the context\n"); return 1; }
105    FILE* fl = dump_layers.empty() ? nullptr : std::fopen(dump_layers.c_str(), "wb");
106    FILE* fg = dump_logits.empty() ? nullptr : std::fopen(dump_logits.c_str(), "wb");
107    FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb");
108    const std::vector<int> forced = parse_ids(force);
109    if (!forced.empty()) n_gen = (int) forced.size() + 1;
110    const int V = llama_vocab_n_tokens(vocab);
111    auto write_layers = [&](int n_tok) {
112        if (!fl) return;
113        // a layer may keep fewer rows than the batch (the last layer keeps only the output rows): those are the
114        // batch's LAST positions; the positions it did not compute are written as zeros
115        std::vector<float> zero(cap.n_embd, 0.f);
116        for (int t = 0; t < n_tok; ++t)
117            for (int l = 0; l < cap.n_layer; ++l) {
118                auto it = cap.layers.find(l);
119                const int rows = it == cap.layers.end() ? 0 : (int) (it->second.size() / cap.n_embd);
120                const int r = t - (n_tok - rows);
121                const float* src = r >= 0 ? it->second.data() + (size_t) r * cap.n_embd : zero.data();
122                std::fwrite(src, 4, cap.n_embd, fl);
123            }
124        cap.layers.clear();
125    };
126    std::printf("prompt:");
127    for (int t : ids) std::printf(" %d", t);
128    std::printf("\n");
129    std::vector<llama_token> gen;
130    llama_batch b = llama_batch_get_one(ids.data(), (int) ids.size());
131    if (llama_decode(ctx, b) != 0) { std::fprintf(stderr, "decode failed\n"); return 1; }
132    write_layers((int) ids.size());
133    for (int i = 0; i < n_gen; ++i) {
134        const float* lg = llama_get_logits_ith(ctx, -1);
135        int a = 0, c = -1;
136        for (int j = 1; j < V; ++j) if (lg[j] > lg[a]) a = j;
137        for (int j = 0; j < V; ++j) if (j != a && (c < 0 || lg[j] > lg[c])) c = j;
138        if (fg) { const float rec[4] = {(float) a, lg[a], (float) c, lg[c]}; std::fwrite(rec, 4, 4, fg); }
139        gen.push_back(a);
140        if (ff) std::fwrite(lg, 4, V, ff);
141        if (i + 1 == n_gen) break;
142        llama_token t = i < (int) forced.size() ? forced[i] : a;
143        llama_batch one = llama_batch_get_one(&t, 1);
144        if (llama_decode(ctx, one) != 0) { std::fprintf(stderr, "decode failed\n"); return 1; }
145        write_layers(1);
146    }
147    std::printf("gen:");
148    for (int t : gen) std::printf(" %d", t);
149    std::printf("\n");
150    if (fl) std::fclose(fl);
151    if (fg) std::fclose(fg);
152    if (ff) std::fclose(ff);
153    llama_free(ctx);
154    llama_model_free(mdl);
155    llama_backend_free();
156    return 0;
157}