Jeveration-GGUF / tools /jev_backbone.cpp
Meshwa's picture
Model card, CPU inference code (llama.cpp helper + Python), set-up scripts, examples
6a8ca2a verified
Raw History Blame Contribute Delete
6.33 kB
// jev-backbone: the Jeveration backbone pass (jeveration/backbone.py: backbone_forward) on a GGUF model.
//
// One request = one forward pass of the reference code, done in two llama.cpp passes:
// pass 1 (causal) the prefix (prompt tokens, and image embeddings for dense / image-to-image) -> KV cache + recurrent state
// pass 2 (non-causal) the decision tokens / spatial queries -> final hidden states
// In pass 2 these tokens see the whole cached prefix and each other in both directions in the full-attention layers,
// which is the mask of backbone_forward. The linear-attention layers are causal in both passes.
// Image tokens share their t position; llama.cpp then masks them causally in raster (y, x) order, as the reference does.
//
// Protocol (stdin/stdout, little-endian, persistent process):
// startup -> int32 n_embd
// request <- int32 n1, int32 n2,
// (n1 + n2) x int32[4] entries {token, t, y, x} token = -1: an embedding entry
// float32 embd[n_embd] for every embedding entry, in entry order
// reply -> int32 status (0 = ok), float32 hidden[n2 * n_embd] (the pass-2 entries, in order)
// Logs go to stderr.
//
// usage: jev-backbone MODEL.gguf [n_threads] [n_ubatch] (n_ubatch >= the number of pass-2 entries)
#include "llama.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
struct entry { int32_t tok, t, y, x; };
static bool read_all(void * dst, size_t n) { return fread(dst, 1, n, stdin) == n; }
static void write_all(const void * src, size_t n) { fwrite(src, 1, n, stdout); }
// add entries [i0, i1) to the batch; embd points at the embedding of the first embedding entry in the range
static int fill(llama_batch_ext * b, const std::vector<entry> & es, int i0, int i1, const float *& embd, int n_embd, bool out) {
for (int i = i0; i < i1; ++i) {
const entry & e = es[i];
int idx;
if (e.tok >= 0) {
idx = llama_batch_ext_add_token(b, 0, e.tok);
if (idx < 0 || !llama_batch_ext_set_pos(b, idx, &e.t)) return -1;
} else {
idx = llama_batch_ext_add_embd(b, 0, llama_embd{ embd, 1, (size_t) n_embd });
embd += n_embd;
const llama_pos pos[4] = { e.t, e.y, e.x, 0 };
if (idx < 0 || !llama_batch_ext_set_pos(b, idx, pos)) return -1;
}
llama_batch_ext_set_output_embd(b, idx, out);
}
return 0;
}
static int run(llama_context * ctx, int n_embd, int n_batch, const std::vector<entry> & es, int n1, const std::vector<float> & embd,
std::vector<float> & out) {
llama_memory_clear(llama_get_memory(ctx), true);
const int n2 = (int) es.size() - n1;
const float * e = embd.data();
llama_batch_ext * b = llama_batch_ext_init(ctx);
// pass 1: prefix, causal, in chunks of n_batch
llama_set_causal_attn(ctx, true);
for (int i0 = 0; i0 < n1; i0 += n_batch) {
llama_batch_ext_clear(b);
const int i1 = i0 + n_batch < n1 ? i0 + n_batch : n1;
if (fill(b, es, i0, i1, e, n_embd, false) != 0) { fprintf(stderr, "bad prefix entry\n"); llama_batch_ext_free(b); return 1; }
const int rc = llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, b);
if (rc != 0) { fprintf(stderr, "prefix pass failed: %d\n", rc); llama_batch_ext_free(b); return 2; }
}
// pass 2: decision tokens / queries, non-causal, one batch
llama_batch_ext_clear(b);
llama_set_causal_attn(ctx, false);
if (fill(b, es, n1, n1 + n2, e, n_embd, true) != 0) { fprintf(stderr, "bad decision entry\n"); llama_batch_ext_free(b); return 3; }
const int rc = llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, b);
llama_batch_ext_free(b);
if (rc != 0) { fprintf(stderr, "decision pass failed: %d\n", rc); return 4; }
out.resize((size_t) n2 * n_embd);
for (int i = 0; i < n2; ++i) {
const float * h = llama_get_embeddings_ith(ctx, i);
if (!h) { fprintf(stderr, "no embedding for %d\n", i); return 5; }
memcpy(out.data() + (size_t) i * n_embd, h, sizeof(float) * n_embd);
}
return 0;
}
int main(int argc, char ** argv) {
if (argc < 2) { fprintf(stderr, "usage: %s MODEL.gguf [n_threads] [n_ubatch]\n", argv[0]); return 1; }
const int n_threads = argc > 2 ? atoi(argv[2]) : 4;
const int n_ubatch = argc > 3 ? atoi(argv[3]) : 256;
llama_backend_init();
llama_model_params mp = llama_model_default_params();
mp.load_mode = LLAMA_LOAD_MODE_NONE; // read once into RAM: with mmap, repacked tensors also stay resident as file pages
llama_model * model = llama_model_load_from_file(argv[1], mp);
if (!model) { fprintf(stderr, "cannot load %s\n", argv[1]); return 1; }
llama_context_params cp = llama_context_default_params();
cp.n_ctx = 1536; // dense: ~500-token prefix + 432 queries; text-to-image: ~150 + 128
cp.n_batch = n_ubatch;
cp.n_ubatch = n_ubatch; // the non-causal pass must fit in one ubatch
cp.n_seq_max = 1;
cp.embeddings = true;
cp.pooling_type = LLAMA_POOLING_TYPE_NONE;
cp.n_threads = cp.n_threads_batch = n_threads;
llama_context * ctx = llama_init_from_model(model, cp);
if (!ctx) { fprintf(stderr, "cannot create context\n"); return 1; }
const int32_t n_embd = llama_model_n_embd(model);
write_all(&n_embd, sizeof n_embd);
fflush(stdout);
std::vector<entry> es;
std::vector<float> embd, out;
for (;;) {
int32_t hdr[2];
if (!read_all(hdr, sizeof hdr)) break; // EOF: done
const int n1 = hdr[0], n2 = hdr[1];
es.resize(n1 + n2);
if (!read_all(es.data(), sizeof(entry) * es.size())) break;
size_t n_e = 0;
for (const auto & x : es) n_e += x.tok < 0;
embd.resize(n_e * n_embd);
if (!read_all(embd.data(), sizeof(float) * embd.size())) break;
int32_t status = n2 > n_ubatch ? 6 : run(ctx, n_embd, n_ubatch, es, n1, embd, out);
if (status == 6) fprintf(stderr, "%d decision entries > n_ubatch %d\n", n2, n_ubatch);
write_all(&status, sizeof status);
if (status == 0) write_all(out.data(), sizeof(float) * out.size());
fflush(stdout);
}
llama_free(ctx);
llama_model_free(model);
llama_backend_free();
return 0;
}