IVE-4B-GGUF / decision_forward.cpp
Hansda's picture
Publish IVE-4B projector, decision readout, and model documentation
b1ed28e verified
Raw History Blame Contribute Delete
9.16 kB
#include "ggml.h"
#include "gguf.h"
#include "llama.h"
#include "mtmd.h"
#include <cstdint>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <vector>
template<class T>
void read(std::istream & input, T * dest, size_t count) {
if (!input.read(reinterpret_cast<char *>(dest), count * sizeof(T))) {
throw std::runtime_error("Truncated input");
}
}
class token_embeddings {
public:
token_embeddings(const char * path, int width, int vocabulary) :
file(path, std::ios::binary), width(width), vocabulary(vocabulary) {
std::unique_ptr<gguf_context, decltype(&gguf_free)> meta(
gguf_init_from_file(path, {true, nullptr}), gguf_free);
if (!meta) {
throw std::runtime_error("Cannot read GGUF metadata");
}
auto tensor = gguf_find_tensor(meta.get(), "token_embd.weight");
if (tensor < 0) {
throw std::runtime_error("Missing token embedding tensor");
}
type = gguf_get_tensor_type(meta.get(), tensor);
offset = gguf_get_data_offset(meta.get()) + gguf_get_tensor_offset(meta.get(), tensor);
row.resize(ggml_row_size(type, width));
if (type != GGML_TYPE_F32 && !ggml_get_type_traits(type)->to_float) {
throw std::runtime_error("Unsupported token embedding type");
}
}
void get(int token, float * output) {
if (token < 0 || token >= vocabulary) {
throw std::runtime_error("Token outside vocabulary");
}
file.seekg(offset + token * row.size());
read(file, row.data(), row.size());
if (type == GGML_TYPE_F32) {
std::memcpy(output, row.data(), row.size());
} else {
ggml_get_type_traits(type)->to_float(row.data(), output, width);
}
}
private:
std::ifstream file;
int width;
int vocabulary;
ggml_type type;
size_t offset;
std::vector<uint8_t> row;
};
void image_features(mtmd_context * vision, int width, int height, const uint8_t * pixels,
uint32_t expected, int dimensions, float * output) {
std::unique_ptr<mtmd_bitmap, decltype(&mtmd_bitmap_free)> bitmap(
mtmd_bitmap_init(width, height, pixels), mtmd_bitmap_free);
std::unique_ptr<mtmd_input_chunks, decltype(&mtmd_input_chunks_free)> chunks(
mtmd_input_chunks_init(), mtmd_input_chunks_free);
if (!bitmap || !chunks) {
throw std::runtime_error("Cannot allocate image input");
}
const mtmd_bitmap * input[] = {bitmap.get()};
const char * marker = mtmd_default_marker();
const mtmd_input_text prompt{marker, std::strlen(marker), false, true};
if (mtmd_tokenize(vision, chunks.get(), &prompt, input, 1) != 0) {
throw std::runtime_error("Cannot prepare vision input");
}
for (size_t i = 0; i < mtmd_input_chunks_size(chunks.get()); ++i) {
const auto * chunk = mtmd_input_chunks_get(chunks.get(), i);
if (mtmd_input_chunk_get_type(chunk) != MTMD_INPUT_CHUNK_TYPE_IMAGE) {
continue;
}
if (mtmd_input_chunk_get_n_tokens(chunk) != expected) {
throw std::runtime_error("Vision patch count differs from the source processor");
}
if (mtmd_encode_chunk(vision, chunk) != 0) {
throw std::runtime_error("Vision encoding failed");
}
const float * features = mtmd_get_output_embd(vision);
if (!features) {
throw std::runtime_error("Projector returned no vision features");
}
std::memcpy(output, features, sizeof(float) * expected * dimensions);
return;
}
throw std::runtime_error("Projector returned no image chunk");
}
int main(int argc, char ** argv) {
try {
if (argc != 6) {
throw std::runtime_error("Usage: decision-forward BACKBONE MMPROJ|- MAX_TOKENS THREADS GPU_LAYERS");
}
const auto limit = std::stoul(argv[3]);
const auto threads = std::stoi(argv[4]);
auto model_params = llama_model_default_params();
model_params.n_gpu_layers = std::stoi(argv[5]);
llama_backend_init();
std::unique_ptr<llama_model, decltype(&llama_model_free)> model(
llama_model_load_from_file(argv[1], model_params), llama_model_free);
if (!model) {
throw std::runtime_error("Cannot load backbone");
}
const int dimensions = llama_model_n_embd_inp(model.get());
token_embeddings weights(argv[1], dimensions, llama_vocab_n_tokens(llama_model_get_vocab(model.get())));
auto params = llama_context_default_params();
params.n_ctx = params.n_batch = params.n_ubatch = limit;
params.n_threads = params.n_threads_batch = threads;
params.attention_type = LLAMA_ATTENTION_TYPE_NON_CAUSAL;
params.pooling_type = LLAMA_POOLING_TYPE_NONE;
params.embeddings = true;
params.type_k = GGML_TYPE_F32;
params.type_v = GGML_TYPE_F32;
std::unique_ptr<llama_context, decltype(&llama_free)> context(
llama_init_from_model(model.get(), params), llama_free);
if (!context) {
throw std::runtime_error("Cannot allocate backbone context");
}
std::unique_ptr<mtmd_context, decltype(&mtmd_free)> vision(nullptr, mtmd_free);
if (std::strcmp(argv[2], "-") != 0) {
auto visual_params = mtmd_context_params_default();
visual_params.n_threads = threads;
visual_params.use_gpu = model_params.n_gpu_layers != 0;
visual_params.warmup = false;
visual_params.image_min_tokens = 1;
visual_params.image_max_tokens = 4096;
vision.reset(mtmd_init_from_file(argv[2], model.get(), visual_params));
if (!vision) {
throw std::runtime_error("Cannot load projector");
}
}
while (std::cin.peek() != std::char_traits<char>::eof()) {
uint32_t n, images, dump_vision;
read(std::cin, &n, 1);
read(std::cin, &images, 1);
read(std::cin, &dump_vision, 1);
if (n == 0 || n > limit || images > n || (images && !vision)) {
throw std::runtime_error("Invalid token count or missing projector");
}
std::vector<llama_token> tokens(n);
read(std::cin, tokens.data(), n);
llama_memory_clear(llama_get_memory(context.get()), true);
llama_batch batch{};
batch.n_tokens = n;
std::vector<float> embeddings;
std::vector<llama_pos> positions;
std::vector<float> visual_output;
batch.token = tokens.data();
if (images) {
positions.resize(4 * n);
read(std::cin, positions.data(), positions.size());
embeddings.resize(size_t(n) * dimensions);
for (size_t i = 0; i < n; ++i) {
weights.get(tokens[i], embeddings.data() + i * dimensions);
}
uint32_t previous_end = 0;
for (uint32_t i = 0; i < images; ++i) {
uint32_t span[4];
read(std::cin, span, 4);
const uint32_t start = span[0], count = span[1], width = span[2], height = span[3];
if (start < previous_end || start >= n || count == 0 || count > n - start ||
width == 0 || height == 0 || uint64_t(width) * height > 10000000) {
throw std::runtime_error("Invalid image span or dimensions");
}
std::vector<uint8_t> rgb(size_t(width) * height * 3);
read(std::cin, rgb.data(), rgb.size());
auto * first = embeddings.data() + size_t(start) * dimensions;
image_features(vision.get(), width, height, rgb.data(), count, dimensions, first);
if (dump_vision) {
visual_output.insert(visual_output.end(), first, first + size_t(count) * dimensions);
}
previous_end = start + count;
}
batch.token = nullptr;
batch.embd = embeddings.data();
batch.pos = positions.data();
}
if (llama_decode(context.get(), batch) != 0) {
throw std::runtime_error("Full-row decode failed");
}
const float * hidden = llama_get_embeddings_ith(context.get(), -1);
if (!hidden) {
throw std::runtime_error("No final hidden state");
}
std::cout.write(reinterpret_cast<const char *>(hidden), sizeof(float) * dimensions);
if (!visual_output.empty()) {
std::cout.write(reinterpret_cast<const char *>(visual_output.data()),
sizeof(float) * visual_output.size());
}
std::cout.flush();
}
} catch (const std::exception & error) {
std::cerr << error.what() << '\n';
return 1;
}
}