File size: 6,253 Bytes
027d3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65c0e45
027d3a0
 
 
65c0e45
027d3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65c0e45
027d3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#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