okami.mom/strata

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

Niko1221Merge f-q36-vp (Qwen3.6 parallel requests and pictures)db4dd65e5

main
6.7 KiB138 linesraw
1// tools/qwen35/q36_mtmd_dump.cpp - llama.cpp's side of the Qwen3.6 PICTURE check: the same GGUF and mmproj, llama.cpp's own
2// mtmd library and graph (the M-RoPE positions of mtmd_helper_eval_chunk_single, qwen35moe's IMROPE).  Prints the prompt's
3// chunks (the text ids, the picture's token count) and the greedy ids, and dumps every step's full logits (f32,
4// [step][vocab]) so the first token's logits can be compared with strata-q36's (--dump-full-logits there).
5//
6// Built against a llama.cpp checkout with its mtmd library (not part of Strata's build):
7//   g++ -O2 -std=c++17 q36_mtmd_dump.cpp -I<llama>/include -I<llama>/ggml/include -I<llama>/tools/mtmd -L<llama>/build/bin
8//       -lllama -lmtmd -lggml -lggml-base -Wl,-rpath,<llama>/build/bin -o q36_mtmd_dump
9// Usage: q36_mtmd_dump --model GGUF --mmproj F --image F [--image F2 ...] --prompt TEXT [--n 32] [--ngl 99] [--max-tokens N] [--mm-cpu 1]
10//                      [--dump-full-logits F] [--force ID,ID,...]
11//   TEXT holds one <__media__> marker where the picture goes (the chat template's user turn); it is tokenized with
12//   special tokens parsed and no BOS.  --force feeds that continuation instead of the greedy ids (teacher forcing).
13#include "llama.h"
14#include "mtmd.h"
15#include "mtmd-helper.h"
16
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <string>
21#include <vector>
22
23static std::vector<int> parse_ids(const std::string& s) {
24    std::vector<int> v;
25    const char* p = s.c_str();
26    while (*p) {
27        while (*p == ',' || *p == ' ') ++p;
28        if (!*p) break;
29        v.push_back(std::atoi(p));
30        while (*p && *p != ',' && *p != ' ') ++p;
31    }
32    return v;
33}
34
35int main(int argc, char** argv) {
36    std::string model, mmproj, prompt, dump_full, force;
37    std::vector<std::string> images;
38    int n_gen = 32, ngl = 99, max_tokens = 0, mm_cpu = 0;
39    for (int i = 1; i + 1 < argc; i += 2) {
40        const std::string a = argv[i], v = argv[i + 1];
41        if (a == "--model") model = v;
42        else if (a == "--mmproj") mmproj = v;
43        else if (a == "--image") images.push_back(v);   // repeat for several pictures (one <__media__> each)
44        else if (a == "--prompt") prompt = v;
45        else if (a == "--n") n_gen = std::atoi(v.c_str());
46        else if (a == "--ngl") ngl = std::atoi(v.c_str());
47        else if (a == "--max-tokens") max_tokens = std::atoi(v.c_str());
48        else if (a == "--mm-cpu") mm_cpu = std::atoi(v.c_str());   // the encoder on the CPU (as strata-vision's default)
49        else if (a == "--dump-full-logits") dump_full = v;
50        else if (a == "--force") force = v;
51        else { std::fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; }
52    }
53    llama_backend_init();
54    llama_model_params mp = llama_model_default_params();
55    mp.n_gpu_layers = ngl;
56    llama_model* mdl = llama_model_load_from_file(model.c_str(), mp);
57    if (!mdl) { std::fprintf(stderr, "cannot load %s\n", model.c_str()); return 1; }
58    const llama_vocab* vocab = llama_model_get_vocab(mdl);
59    llama_context_params cp = llama_context_default_params();
60    cp.n_ctx = 8192;
61    cp.n_batch = cp.n_ubatch = 2048;
62    cp.op_offload = ngl > 0;
63    llama_context* ctx = llama_init_from_model(mdl, cp);
64    if (!ctx) { std::fprintf(stderr, "cannot create the context\n"); return 1; }
65    mtmd_context_params mcp = mtmd_context_params_default();
66    mcp.use_gpu = ngl > 0 && !mm_cpu;
67    mcp.print_timings = false;
68    mcp.warmup = false;
69    if (max_tokens > 0) mcp.image_max_tokens = max_tokens;
70    mtmd_context* mctx = mtmd_init_from_file(mmproj.c_str(), mdl, mcp);
71    if (!mctx) { std::fprintf(stderr, "cannot load %s\n", mmproj.c_str()); return 1; }
72    std::vector<mtmd_helper_bitmap_wrapper> bws;
73    std::vector<const mtmd_bitmap*> bms;
74    for (const std::string& image : images) {
75        mtmd_helper_bitmap_wrapper bw = mtmd_helper_bitmap_init_from_file(mctx, image.c_str(), false, mtmd_helper_init_opt_default());
76        if (!bw.bitmap) { std::fprintf(stderr, "cannot read %s\n", image.c_str()); return 1; }
77        bws.push_back(bw);
78        bms.push_back(bw.bitmap);
79    }
80    mtmd_input_chunks* chunks = mtmd_input_chunks_init();
81    mtmd_input_text txt{prompt.c_str(), prompt.size(), false, true};
82    if (mtmd_tokenize(mctx, chunks, &txt, bms.data(), bms.size()) != 0) { std::fprintf(stderr, "tokenize failed\n"); return 1; }
83    const size_t nc = mtmd_input_chunks_size(chunks);
84    llama_pos n_past = 0;
85    for (size_t c = 0; c < nc; ++c) {
86        const mtmd_input_chunk* ch = mtmd_input_chunks_get(chunks, c);
87        if (mtmd_input_chunk_get_type(ch) == MTMD_INPUT_CHUNK_TYPE_TEXT) {
88            size_t n = 0;
89            const llama_token* t = mtmd_input_chunk_get_tokens_text(ch, &n);
90            std::printf("text:");
91            for (size_t i = 0; i < n; ++i) std::printf(" %d", (int) t[i]);
92            std::printf("\n");
93        } else {
94            std::printf("image: %d tokens, %d positions\n", (int) mtmd_input_chunk_get_n_tokens(ch),
95                        (int) mtmd_input_chunk_get_n_pos(ch));
96        }
97        llama_pos np = n_past;
98        if (mtmd_helper_eval_chunk_single(mctx, ctx, ch, n_past, 0, (int32_t) cp.n_batch, c + 1 == nc, &np) != 0) {
99            std::fprintf(stderr, "eval failed at chunk %zu\n", c);
100            return 1;
101        }
102        n_past = np;
103    }
104    const std::vector<int> forced = parse_ids(force);
105    if (!forced.empty()) n_gen = (int) forced.size() + 1;
106    const int V = llama_vocab_n_tokens(vocab);
107    FILE* ff = dump_full.empty() ? nullptr : std::fopen(dump_full.c_str(), "wb");
108    std::vector<llama_token> gen;
109    for (int i = 0; i < n_gen; ++i) {
110        const float* lg = llama_get_logits_ith(ctx, -1);
111        int a = 0;
112        for (int j = 1; j < V; ++j) if (lg[j] > lg[a]) a = j;
113        if (i == 0) {
114            int b = -1;
115            for (int j = 0; j < V; ++j) if (j != a && (b < 0 || lg[j] > lg[b])) b = j;
116            std::printf("first: top1 %d (%.4f) top2 %d (%.4f)\n", a, lg[a], b, lg[b]);
117        }
118        gen.push_back(a);
119        if (ff) std::fwrite(lg, 4, V, ff);
120        if (i + 1 == n_gen) break;
121        llama_token t = i < (int) forced.size() ? forced[i] : a;
122        llama_pos pp = n_past++;   // the text after a picture continues at n_past (max(nx, ny) past its first position)
123        llama_batch one = llama_batch_get_one(&t, 1);
124        one.pos = &pp;
125        if (llama_decode(ctx, one) != 0) { std::fprintf(stderr, "decode failed\n"); return 1; }
126    }
127    std::printf("gen:");
128    for (int t : gen) std::printf(" %d", t);
129    std::printf("\n");
130    if (ff) std::fclose(ff);
131    mtmd_input_chunks_free(chunks);
132    for (auto& bw : bws) mtmd_bitmap_free(bw.bitmap);
133    mtmd_free(mctx);
134    llama_free(ctx);
135    llama_model_free(mdl);
136    llama_backend_free();
137    return 0;
138}