ki-brain / src /llm_backend.cpp
Arian8888's picture
fix llama.cpp API: llama_batch_get_one(2 args), sampler params by value
65c0e45
Raw History Blame Contribute Delete
6.25 kB
#include "llm_backend.h"
#include "llama.h"
#include <curl/curl.h>
#include <atomic>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
namespace llm {
static llama_model* g_model = nullptr;
static llama_context* g_ctx = nullptr;
static std::mutex g_mtx;
static std::atomic<bool> g_loading{false};
static std::string g_status = "nicht geladen";
static std::string g_model_path = "/data/llama.gguf";
static size_t curl_write_file(char* ptr, size_t size, size_t nmemb, void* ud) {
auto* f = (std::ofstream*)ud;
f->write(ptr, size * nmemb);
return size * nmemb;
}
static bool download_model() {
// Bereits da und groß genug?
std::ifstream check(g_model_path, std::ios::binary | std::ios::ate);
if (check.good() && check.tellg() > 100*1024*1024) {
g_status = "Modell bereits vorhanden (" + std::to_string((long long)check.tellg() / (1024*1024)) + " MB)";
std::cout << "[llm] " << g_status << std::endl;
return true;
}
const char* token = std::getenv("HF_TOKEN");
if (!token) { g_status = "FEHLER: HF_TOKEN nicht gesetzt"; return false; }
const char* repo_env = std::getenv("HF_DATASET_REPO");
std::string repo = repo_env ? repo_env : "Arian8888/ki-brain-storage";
const char* file_env = std::getenv("LLM_MODEL_FILE");
std::string file = file_env ? file_env : "Meta-Llama-3-8B.Q4_K_M.gguf";
std::string url = "https://huggingface.co/datasets/" + repo + "/resolve/main/" + file;
g_status = "Lade Modell aus HF Hub: " + file;
std::cout << "[llm] " << g_status << std::endl;
std::ofstream out(g_model_path, std::ios::binary);
if (!out) { g_status = "FEHLER: kann /data/llama.gguf nicht schreiben"; return false; }
CURL* c = curl_easy_init();
if (!c) { g_status = "FEHLER: curl init"; return false; }
struct curl_slist* hdr = nullptr;
hdr = curl_slist_append(hdr, (std::string("Authorization: Bearer ") + token).c_str());
hdr = curl_slist_append(hdr, "User-Agent: KI-Brain-LLM");
curl_easy_setopt(c, CURLOPT_URL, url.c_str());
curl_easy_setopt(c, CURLOPT_HTTPHEADER, hdr);
curl_easy_setopt(c, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, curl_write_file);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &out);
curl_easy_setopt(c, CURLOPT_NOPROGRESS, 0L);
CURLcode rc = curl_easy_perform(c);
long code = 0;
curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &code);
curl_slist_free_all(hdr);
curl_easy_cleanup(c);
out.close();
if (rc != CURLE_OK || code != 200) {
g_status = "FEHLER: Download HTTP " + std::to_string(code);
std::cerr << "[llm] " << g_status << std::endl;
std::remove(g_model_path.c_str());
return false;
}
g_status = "Modell heruntergeladen";
std::cout << "[llm] " << g_status << std::endl;
return true;
}
static bool load_model() {
llama_backend_init();
llama_model_params mp = llama_model_default_params();
mp.n_gpu_layers = 0; // CPU
g_model = llama_load_model_from_file(g_model_path.c_str(), mp);
if (!g_model) { g_status = "FEHLER: Modell-Load fehlgeschlagen"; std::cerr << "[llm] " << g_status << std::endl; return false; }
llama_context_params cp = llama_context_default_params();
cp.n_ctx = 4096;
cp.n_threads = 4;
cp.n_threads_batch = 4;
g_ctx = llama_new_context_with_model(g_model, cp);
if (!g_ctx) { g_status = "FEHLER: Context create fehlgeschlagen"; return false; }
g_status = "BEREIT (Llama 3 8B Q4_K_M)";
std::cout << "[llm] " << g_status << std::endl;
return true;
}
void init_async() {
if (g_loading.exchange(true)) return;
std::thread([](){
if (download_model()) load_model();
g_loading = false;
}).detach();
}
bool is_loaded() { return g_model != nullptr && g_ctx != nullptr; }
std::string status() { return g_status; }
std::string generate(const std::string& system_prompt, const std::string& user_msg, int max_tokens) {
std::lock_guard<std::mutex> lk(g_mtx);
if (!is_loaded()) return "[LLM nicht bereit: " + g_status + "]";
// Llama 3 Chat-Template
std::string prompt =
"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n" +
system_prompt + "<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n" +
user_msg + "<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n";
// Tokenize
int n_max = (int)prompt.size() + 8;
std::vector<llama_token> tokens(n_max);
int n_tok = llama_tokenize(g_model, prompt.c_str(), (int)prompt.size(),
tokens.data(), n_max, true, true);
if (n_tok < 0) return "[Tokenize-Fehler]";
tokens.resize(n_tok);
// Initial decode
llama_batch batch = llama_batch_get_one(tokens.data(), n_tok);
if (llama_decode(g_ctx, batch) != 0) return "[Decode-Fehler]";
// Sampler
auto sparams = llama_sampler_chain_default_params();
auto* sampler = llama_sampler_chain_init(sparams);
llama_sampler_chain_add(sampler, llama_sampler_init_temp(0.7f));
llama_sampler_chain_add(sampler, llama_sampler_init_top_k(40));
llama_sampler_chain_add(sampler, llama_sampler_init_top_p(0.95f, 1));
llama_sampler_chain_add(sampler, llama_sampler_init_dist(LLAMA_DEFAULT_SEED));
std::string result;
int n_cur = n_tok;
for (int i = 0; i < max_tokens; ++i) {
llama_token new_token = llama_sampler_sample(sampler, g_ctx, -1);
llama_sampler_accept(sampler, new_token);
if (llama_token_is_eog(g_model, new_token)) break;
char buf[256];
int len = llama_token_to_piece(g_model, new_token, buf, sizeof(buf), 0, false);
if (len > 0) result.append(buf, len);
batch = llama_batch_get_one(&new_token, 1);
if (llama_decode(g_ctx, batch) != 0) break;
n_cur++;
}
llama_sampler_free(sampler);
return result;
}
void shutdown() {
std::lock_guard<std::mutex> lk(g_mtx);
if (g_ctx) { llama_free(g_ctx); g_ctx = nullptr; }
if (g_model) { llama_free_model(g_model); g_model = nullptr; }
llama_backend_free();
}
} // namespace llm