File size: 13,984 Bytes
9d62c0e | 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | // nnopt contract runner (text_to_text) over the customer's PrismML llama.cpp fork.
// Runs the model the way llama-cli does on Metal (-ngl 99, n_batch 2048, n_ubatch 512,
// flash attention auto, f16 KV cache), with greedy decoding instead of sampling.
#include "llama.h"
#include <sys/resource.h>
#include <sys/sysctl.h>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using clk = std::chrono::steady_clock;
static const clk::time_point t_start = clk::now();
static double ms_since(clk::time_point t) {
return std::chrono::duration<double, std::milli>(clk::now() - t).count();
}
static void die(const std::string & msg) {
fprintf(stderr, "nnopt_runner: %s\n", msg.c_str());
exit(1);
}
static std::string read_file(const std::string & path) {
std::ifstream f(path, std::ios::binary);
if (!f) die("cannot read " + path);
std::stringstream ss;
ss << f.rdbuf();
return ss.str();
}
static void write_file(const std::string & path, const std::string & data) {
std::ofstream f(path, std::ios::binary | std::ios::trunc);
if (!f) die("cannot write " + path);
f << data;
}
// Replace invalid UTF-8 with U+FFFD (like Python's errors="replace") so the JSON stays valid.
static std::string sanitize_utf8(const std::string & s) {
std::string out;
size_t i = 0, n = s.size();
while (i < n) {
unsigned char c = s[i];
int len = c < 0x80 ? 1 : (c >> 5) == 0x6 ? 2 : (c >> 4) == 0xE ? 3 : (c >> 3) == 0x1E ? 4 : 0;
bool ok = len > 0 && i + len <= n;
for (int k = 1; ok && k < len; k++) ok = (((unsigned char) s[i + k]) & 0xC0) == 0x80;
if (ok) { out.append(s, i, len); i += len; }
else { out += "\xEF\xBF\xBD"; i += 1; }
}
return out;
}
static std::string json_str(const std::string & s) {
std::string o = "\"";
for (unsigned char c : s) {
switch (c) {
case '"': o += "\\\""; break;
case '\\': o += "\\\\"; break;
case '\n': o += "\\n"; break;
case '\r': o += "\\r"; break;
case '\t': o += "\\t"; break;
default:
if (c < 0x20) { char b[8]; snprintf(b, sizeof b, "\\u%04x", c); o += b; }
else o += (char) c;
}
}
return o + "\"";
}
template <typename T>
static std::string json_arr(const std::vector<T> & v, const char * fmt) {
std::string o = "[";
char b[64];
for (size_t i = 0; i < v.size(); i++) {
snprintf(b, sizeof b, fmt, v[i]);
if (i) o += ", ";
o += b;
}
return o + "]";
}
// Parses {"tokens": [int, ...]}.
static std::vector<llama_token> parse_tokens_json(const std::string & s) {
size_t p = s.find("\"tokens\"");
if (p == std::string::npos) die("no \"tokens\" key in score input");
p = s.find('[', p);
size_t e = s.find(']', p);
if (p == std::string::npos || e == std::string::npos) die("malformed tokens array");
std::vector<llama_token> out;
const char * c = s.c_str() + p + 1;
const char * end = s.c_str() + e;
while (c < end) {
char * nx;
long v = strtol(c, &nx, 10);
if (nx == c) { c++; continue; }
out.push_back((llama_token) v);
c = nx;
}
return out;
}
static int perf_cores() {
int n = 0; size_t sz = sizeof n;
if (sysctlbyname("hw.perflevel0.physicalcpu", &n, &sz, nullptr, 0) != 0 || n <= 0) n = 4;
return n;
}
static double peak_mem_mb() {
struct rusage ru; getrusage(RUSAGE_SELF, &ru);
return ru.ru_maxrss / (1024.0 * 1024.0); // bytes on macOS
}
// Greedy argmax, ties to the lowest id.
static llama_token argmax(const float * logits, int n_vocab) {
int best = 0;
for (int i = 1; i < n_vocab; i++) if (logits[i] > logits[best]) best = i;
return best;
}
int main(int argc, char ** argv) {
std::string model_path, prompt_file, score_file, out_path, metrics_path;
int max_new = 128, repeat = 1, top_k = 0;
bool ignore_eos = false;
for (int i = 1; i < argc; i++) {
std::string a = argv[i];
auto next = [&]() -> std::string { if (i + 1 >= argc) die("missing value for " + a); return argv[++i]; };
if (a == "--model") model_path = next();
else if (a == "--prompt-file") prompt_file = next();
else if (a == "--max-new-tokens") max_new = std::stoi(next());
else if (a == "--ignore-eos") ignore_eos = true;
else if (a == "--repeat") repeat = std::max(1, std::stoi(next()));
else if (a == "--score-tokens") score_file = next();
else if (a == "--top-k") top_k = std::stoi(next());
else if (a == "--out") out_path = next();
else if (a == "--metrics") metrics_path = next();
else die("unknown argument " + a);
}
if (model_path.empty() || out_path.empty() || metrics_path.empty()) die("need --model, --out, --metrics");
const bool score = !score_file.empty();
if (!score && prompt_file.empty()) die("need --prompt-file or --score-tokens");
if (score && top_k <= 0) die("--score-tokens needs --top-k > 0");
if (score) repeat = 1;
// Inputs are read while loading.
std::string prompt_text;
std::vector<llama_token> score_tokens;
if (score) score_tokens = parse_tokens_json(read_file(score_file));
else prompt_text = read_file(prompt_file);
llama_backend_init();
llama_model_params mparams = llama_model_default_params();
mparams.n_gpu_layers = 999; // -ngl 99: every layer on the Metal GPU
// read the weights into Metal buffers (no mmap): the loader repacks the Q1_0 tensors into the tile layout
// the patched Metal kernels read (src/patches, q1_0_locate)
mparams.load_mode = LLAMA_LOAD_MODE_NONE;
llama_model * model = llama_model_load_from_file(model_path.c_str(), mparams);
if (!model) die("failed to load model " + model_path);
const llama_vocab * vocab = llama_model_get_vocab(model);
const int n_vocab = llama_vocab_n_tokens(vocab);
std::vector<llama_token> prompt;
if (!score) {
int n = -llama_tokenize(vocab, prompt_text.data(), (int32_t) prompt_text.size(), nullptr, 0, true, true);
prompt.resize(n);
if (llama_tokenize(vocab, prompt_text.data(), (int32_t) prompt_text.size(), prompt.data(), n, true, true) != n)
die("tokenize failed");
if (prompt.empty()) die("empty prompt");
} else {
if (score_tokens.empty()) die("empty score input");
for (llama_token t : score_tokens) if (t < 0 || t >= n_vocab) die("token id out of range");
}
// Context: 4096 by default (llama-cli's fit minimum), larger only if a request needs it.
const int need = score ? (int) score_tokens.size() : (int) prompt.size() + max_new;
int n_ctx = 4096;
if (need > n_ctx) n_ctx = ((need + 255) / 256) * 256;
if (n_ctx > (int) llama_model_n_ctx_train(model)) die("request longer than the model's context");
llama_context_params cparams = llama_context_default_params();
cparams.n_ctx = n_ctx;
cparams.n_batch = 2048;
cparams.n_ubatch = 512;
cparams.n_seq_max = 1;
cparams.n_threads = perf_cores();
cparams.n_threads_batch = perf_cores();
cparams.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_AUTO;
cparams.type_k = GGML_TYPE_F16;
cparams.type_v = GGML_TYPE_F16;
cparams.no_perf = true;
// n_rs_seq 1: the fork's "rows mode" for the gated delta net, which reads and writes the recurrent state in
// the cache inside the fused GDN kernel instead of gathering and copying back 3 MB per layer each token
// (same math, identical outputs). NNOPT_RS_SEQ overrides it for A/B runs.
cparams.n_rs_seq = getenv("NNOPT_RS_SEQ") ? (uint32_t) atoi(getenv("NNOPT_RS_SEQ")) : 1;
llama_context * ctx = llama_init_from_model(model, cparams);
if (!ctx) die("failed to create context");
llama_memory_t mem = llama_get_memory(ctx);
const int n_batch = (int) llama_n_batch(ctx);
// Warm the Metal pipelines once so load_ms covers shader compilation (not timed as a request).
{
llama_token t0 = score ? score_tokens[0] : prompt[0];
llama_batch b = llama_batch_get_one(&t0, 1);
if (llama_decode(ctx, b) != 0) die("warmup decode failed");
llama_synchronize(ctx);
llama_memory_clear(mem, true);
}
const double load_ms = ms_since(t_start);
fprintf(stderr, "nnopt_runner: loaded in %.1f ms (n_ctx %d, n_vocab %d)\n", load_ms, n_ctx, n_vocab);
std::string runs_json;
std::string out_json;
if (score) {
const int L = (int) score_tokens.size();
clk::time_point t0 = clk::now();
llama_memory_clear(mem, true);
llama_batch batch = llama_batch_init(n_batch, 0, 1);
std::vector<std::vector<int>> top_ids(L);
std::vector<std::vector<float>> top_logits(L);
std::vector<int> idx(n_vocab);
for (int s = 0; s < L; s += n_batch) {
const int n = std::min(n_batch, L - s);
batch.n_tokens = n;
for (int j = 0; j < n; j++) {
batch.token[j] = score_tokens[s + j];
batch.pos[j] = s + j;
batch.n_seq_id[j] = 1;
batch.seq_id[j][0] = 0;
batch.logits[j] = 1;
}
if (llama_decode(ctx, batch) != 0) die("decode failed (score)");
for (int j = 0; j < n; j++) {
const float * lg = llama_get_logits_ith(ctx, j);
const int k = std::min(top_k, n_vocab);
for (int v = 0; v < n_vocab; v++) idx[v] = v;
std::partial_sort(idx.begin(), idx.begin() + k, idx.end(), [&](int a, int b) {
return lg[a] > lg[b] || (lg[a] == lg[b] && a < b);
});
for (int q = 0; q < k; q++) {
top_ids[s + j].push_back(idx[q]);
top_logits[s + j].push_back(lg[idx[q]]);
}
}
}
llama_batch_free(batch);
const double total = ms_since(t0);
std::string ids = "[", lgs = "[";
for (int i = 0; i < L; i++) {
if (i) { ids += ", "; lgs += ", "; }
ids += json_arr(top_ids[i], "%d");
lgs += json_arr(top_logits[i], "%.9g");
}
out_json = "{\"top_ids\": " + ids + "], \"top_logits\": " + lgs + "]}\n";
char b[128]; snprintf(b, sizeof b, "{\"total_ms\": %.3f}", total);
runs_json = b;
} else {
const int P = (int) prompt.size();
llama_batch batch = llama_batch_init(std::max(n_batch, 1), 0, 1);
std::vector<llama_token> gen;
for (int r = 0; r < repeat; r++) {
gen.clear();
std::vector<double> token_ms;
clk::time_point t0 = clk::now();
llama_memory_clear(mem, true);
// prefill: logits only for the last prompt token
for (int s = 0; s < P; s += n_batch) {
const int n = std::min(n_batch, P - s);
batch.n_tokens = n;
for (int j = 0; j < n; j++) {
batch.token[j] = prompt[s + j];
batch.pos[j] = s + j;
batch.n_seq_id[j] = 1;
batch.seq_id[j][0] = 0;
batch.logits[j] = (s + j == P - 1);
}
if (llama_decode(ctx, batch) != 0) die("decode failed (prefill)");
}
llama_token tok = argmax(llama_get_logits_ith(ctx, -1), n_vocab);
const double ttft = ms_since(t0);
token_ms.push_back(ttft);
gen.push_back(tok);
clk::time_point tp = clk::now();
while ((int) gen.size() < max_new && (ignore_eos || !llama_vocab_is_eog(vocab, tok))) {
batch.n_tokens = 1;
batch.token[0] = tok;
batch.pos[0] = P + (int) gen.size() - 1;
batch.n_seq_id[0] = 1;
batch.seq_id[0][0] = 0;
batch.logits[0] = 1;
if (llama_decode(ctx, batch) != 0) die("decode failed (generate)");
tok = argmax(llama_get_logits_ith(ctx, -1), n_vocab);
gen.push_back(tok);
token_ms.push_back(ms_since(tp));
tp = clk::now();
}
const double total = ms_since(t0);
char b[256];
snprintf(b, sizeof b, "{\"total_ms\": %.3f, \"ttft_ms\": %.3f, \"prompt_tokens\": %d, \"new_tokens\": %d, \"token_ms\": ",
total, ttft, P, (int) gen.size());
if (r) runs_json += ", ";
runs_json += std::string(b) + json_arr(token_ms, "%.3f") + "}";
fprintf(stderr, "nnopt_runner: run %d: ttft %.1f ms, %d tokens in %.1f ms\n", r, ttft, (int) gen.size(), total);
}
llama_batch_free(batch);
std::string text;
{
int n = llama_detokenize(vocab, gen.data(), (int32_t) gen.size(), nullptr, 0, false, true);
text.resize(n < 0 ? -n : n);
n = llama_detokenize(vocab, gen.data(), (int32_t) gen.size(), &text[0], (int32_t) text.size(), false, true);
if (n < 0) die("detokenize failed");
text.resize(n);
}
out_json = "{\"prompt_tokens\": " + json_arr(prompt, "%d") + ", \"tokens\": " + json_arr(gen, "%d") +
", \"text\": " + json_str(sanitize_utf8(text)) + "}\n";
}
write_file(out_path, out_json);
char b[128];
snprintf(b, sizeof b, "{\"load_ms\": %.3f, \"peak_mem_mb\": %.1f, \"runs\": [", load_ms, peak_mem_mb());
write_file(metrics_path, std::string(b) + runs_json + "]}\n");
llama_free(ctx);
llama_model_free(model);
llama_backend_free();
return 0;
}
|