Spaces:
Running
Running
talk-llama : update to latest llama.cpp (improved performance)
Browse files- examples/talk-llama/llama.cpp +907 -843
- examples/talk-llama/llama.h +29 -9
- examples/talk-llama/llama_internal.h +12 -0
- examples/talk-llama/llama_util.h +383 -0
examples/talk-llama/llama.cpp
CHANGED
|
@@ -1,36 +1,26 @@
|
|
|
|
|
| 1 |
#include "llama.h"
|
|
|
|
| 2 |
|
| 3 |
#include "ggml.h"
|
| 4 |
|
|
|
|
| 5 |
#include <cinttypes>
|
| 6 |
#include <fstream>
|
| 7 |
#include <random>
|
| 8 |
#include <map>
|
| 9 |
#include <unordered_map>
|
| 10 |
#include <queue>
|
| 11 |
-
#include <regex>
|
| 12 |
#include <cassert>
|
| 13 |
#include <cstring>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
#define LLAMA_USE_SCRATCH
|
| 16 |
#define LLAMA_MAX_SCRATCH_BUFFERS 16
|
| 17 |
|
| 18 |
-
#define LLAMA_ASSERT(x) \
|
| 19 |
-
do { \
|
| 20 |
-
if (!(x)) { \
|
| 21 |
-
fprintf(stderr, "LLAMA_ASSERT: %s:%d: %s\n", __FILE__, __LINE__, #x); \
|
| 22 |
-
abort(); \
|
| 23 |
-
} \
|
| 24 |
-
} while (0)
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
// determine number of model parts based on the dimension
|
| 28 |
-
static const std::unordered_map<int, int> LLAMA_N_PARTS = {
|
| 29 |
-
{ 4096, 1 },
|
| 30 |
-
{ 5120, 2 },
|
| 31 |
-
{ 6656, 4 },
|
| 32 |
-
{ 8192, 8 },
|
| 33 |
-
};
|
| 34 |
|
| 35 |
// available llama models
|
| 36 |
enum e_model {
|
|
@@ -80,14 +70,18 @@ static const std::map<e_model, size_t> MEM_REQ_EVAL = {
|
|
| 80 |
|
| 81 |
// default hparams (LLaMA 7B)
|
| 82 |
struct llama_hparams {
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
};
|
| 92 |
|
| 93 |
struct llama_layer {
|
|
@@ -113,11 +107,17 @@ struct llama_kv_cache {
|
|
| 113 |
struct ggml_tensor * k;
|
| 114 |
struct ggml_tensor * v;
|
| 115 |
|
| 116 |
-
struct ggml_context * ctx;
|
| 117 |
|
| 118 |
-
|
| 119 |
|
| 120 |
int n; // number of tokens currently in the cache
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
};
|
| 122 |
|
| 123 |
struct llama_model {
|
|
@@ -133,18 +133,30 @@ struct llama_model {
|
|
| 133 |
std::vector<llama_layer> layers;
|
| 134 |
|
| 135 |
// context
|
| 136 |
-
struct ggml_context * ctx;
|
| 137 |
|
| 138 |
// key + value cache for the self attention
|
| 139 |
// TODO: move to llama_state
|
| 140 |
struct llama_kv_cache kv_self;
|
| 141 |
|
| 142 |
// the model memory buffer
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
//
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
};
|
| 149 |
|
| 150 |
struct llama_vocab {
|
|
@@ -165,6 +177,7 @@ struct llama_context {
|
|
| 165 |
|
| 166 |
int64_t t_load_us = 0;
|
| 167 |
int64_t t_start_us = 0;
|
|
|
|
| 168 |
|
| 169 |
int64_t t_sample_us = 0;
|
| 170 |
int64_t t_eval_us = 0;
|
|
@@ -188,8 +201,8 @@ struct llama_context {
|
|
| 188 |
|
| 189 |
// memory buffers used to evaluate the model
|
| 190 |
// TODO: move in llama_state
|
| 191 |
-
|
| 192 |
-
|
| 193 |
|
| 194 |
int buf_last = 0;
|
| 195 |
size_t buf_max_size[LLAMA_MAX_SCRATCH_BUFFERS] = { 0 };
|
|
@@ -202,7 +215,7 @@ struct llama_context {
|
|
| 202 |
last_size = ggml_set_scratch(ctx, { 0, 0, nullptr, });
|
| 203 |
} else {
|
| 204 |
auto & buf = buf_scratch[i];
|
| 205 |
-
last_size = ggml_set_scratch(ctx, { 0, buf.size
|
| 206 |
}
|
| 207 |
|
| 208 |
if (buf_last >= 0) {
|
|
@@ -226,6 +239,508 @@ struct llama_context {
|
|
| 226 |
}
|
| 227 |
};
|
| 228 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
//
|
| 230 |
// kv cache
|
| 231 |
//
|
|
@@ -238,14 +753,15 @@ static bool kv_cache_init(
|
|
| 238 |
const int n_embd = hparams.n_embd;
|
| 239 |
const int n_layer = hparams.n_layer;
|
| 240 |
|
| 241 |
-
const
|
| 242 |
-
const
|
| 243 |
|
| 244 |
cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
|
| 245 |
|
| 246 |
struct ggml_init_params params;
|
| 247 |
-
params.mem_size = cache.buf.size
|
| 248 |
-
params.mem_buffer = cache.buf.
|
|
|
|
| 249 |
|
| 250 |
cache.ctx = ggml_init(params);
|
| 251 |
|
|
@@ -260,13 +776,6 @@ static bool kv_cache_init(
|
|
| 260 |
return true;
|
| 261 |
}
|
| 262 |
|
| 263 |
-
static void kv_cache_free(struct llama_kv_cache & cache) {
|
| 264 |
-
if (cache.ctx) {
|
| 265 |
-
ggml_free(cache.ctx);
|
| 266 |
-
cache.ctx = nullptr;
|
| 267 |
-
}
|
| 268 |
-
}
|
| 269 |
-
|
| 270 |
struct llama_context_params llama_context_default_params() {
|
| 271 |
struct llama_context_params result = {
|
| 272 |
/*.n_ctx =*/ 512,
|
|
@@ -275,6 +784,7 @@ struct llama_context_params llama_context_default_params() {
|
|
| 275 |
/*.f16_kv =*/ false,
|
| 276 |
/*.logits_all =*/ false,
|
| 277 |
/*.vocab_only =*/ false,
|
|
|
|
| 278 |
/*.use_mlock =*/ false,
|
| 279 |
/*.embedding =*/ false,
|
| 280 |
/*.progress_callback =*/ nullptr,
|
|
@@ -284,209 +794,94 @@ struct llama_context_params llama_context_default_params() {
|
|
| 284 |
return result;
|
| 285 |
}
|
| 286 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
//
|
| 288 |
// model loading
|
| 289 |
//
|
| 290 |
|
| 291 |
-
static
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
const std::string & fname,
|
| 293 |
llama_context & lctx,
|
| 294 |
int n_ctx,
|
| 295 |
-
int n_parts,
|
| 296 |
ggml_type memory_type,
|
|
|
|
|
|
|
| 297 |
bool vocab_only,
|
| 298 |
llama_progress_callback progress_callback,
|
| 299 |
-
void *progress_callback_user_data) {
|
| 300 |
-
fprintf(stderr, "%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str());
|
| 301 |
-
|
| 302 |
-
const int64_t t_start_us = ggml_time_us();
|
| 303 |
|
| 304 |
-
lctx.t_start_us =
|
| 305 |
|
| 306 |
-
std::
|
| 307 |
|
|
|
|
| 308 |
auto & model = lctx.model;
|
| 309 |
-
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
-
auto fin = std::ifstream(fname, std::ios::binary);
|
| 312 |
-
fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
|
| 313 |
-
if (!fin) {
|
| 314 |
-
fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
|
| 315 |
-
return false;
|
| 316 |
-
}
|
| 317 |
-
|
| 318 |
-
// verify magic
|
| 319 |
{
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
return false;
|
| 326 |
-
}
|
| 327 |
-
if (magic != LLAMA_FILE_MAGIC) {
|
| 328 |
-
fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
|
| 329 |
-
return false;
|
| 330 |
}
|
| 331 |
|
| 332 |
-
uint32_t format_version;
|
| 333 |
-
fin.read((char *) &format_version, sizeof(format_version));
|
| 334 |
-
|
| 335 |
-
if (format_version != LLAMA_FILE_VERSION) {
|
| 336 |
-
fprintf(stderr, "%s: invalid model file '%s' (unsupported format version %" PRIu32 ", expected %d)\n",
|
| 337 |
-
__func__, fname.c_str(), format_version, LLAMA_FILE_VERSION);
|
| 338 |
-
return false;
|
| 339 |
-
}
|
| 340 |
-
}
|
| 341 |
-
|
| 342 |
-
int n_ff = 0;
|
| 343 |
-
|
| 344 |
-
// load hparams
|
| 345 |
-
{
|
| 346 |
-
auto & hparams = model.hparams;
|
| 347 |
-
|
| 348 |
-
fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
|
| 349 |
-
//fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
|
| 350 |
-
fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
|
| 351 |
-
fin.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
|
| 352 |
-
fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
|
| 353 |
-
fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
|
| 354 |
-
fin.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
|
| 355 |
-
fin.read((char *) &hparams.f16, sizeof(hparams.f16));
|
| 356 |
-
|
| 357 |
hparams.n_ctx = n_ctx;
|
| 358 |
-
|
| 359 |
-
n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
|
| 360 |
-
|
| 361 |
-
if (n_parts < 1) {
|
| 362 |
-
n_parts = LLAMA_N_PARTS.at(hparams.n_embd);
|
| 363 |
-
}
|
| 364 |
-
|
| 365 |
-
// temp warning to tell the user to use "--n_parts"
|
| 366 |
-
if (hparams.f16 == 4 && n_parts != 1) {
|
| 367 |
-
fprintf(stderr, "%s: GPTQ model detected - are you sure n_parts should be %d? we normally expect it to be 1\n", __func__, n_parts);
|
| 368 |
-
fprintf(stderr, "%s: use '--n_parts 1' if necessary\n", __func__);
|
| 369 |
-
}
|
| 370 |
-
|
| 371 |
-
if (hparams.n_layer == 32) {
|
| 372 |
-
model.type = e_model::MODEL_7B;
|
| 373 |
-
}
|
| 374 |
-
|
| 375 |
-
if (hparams.n_layer == 40) {
|
| 376 |
-
model.type = e_model::MODEL_13B;
|
| 377 |
-
}
|
| 378 |
-
|
| 379 |
-
if (hparams.n_layer == 60) {
|
| 380 |
-
model.type = e_model::MODEL_30B;
|
| 381 |
-
}
|
| 382 |
-
|
| 383 |
-
if (hparams.n_layer == 80) {
|
| 384 |
-
model.type = e_model::MODEL_65B;
|
| 385 |
-
}
|
| 386 |
-
|
| 387 |
-
fprintf(stderr, "%s: n_vocab = %d\n", __func__, hparams.n_vocab);
|
| 388 |
-
fprintf(stderr, "%s: n_ctx = %d\n", __func__, hparams.n_ctx);
|
| 389 |
-
fprintf(stderr, "%s: n_embd = %d\n", __func__, hparams.n_embd);
|
| 390 |
-
fprintf(stderr, "%s: n_mult = %d\n", __func__, hparams.n_mult);
|
| 391 |
-
fprintf(stderr, "%s: n_head = %d\n", __func__, hparams.n_head);
|
| 392 |
-
fprintf(stderr, "%s: n_layer = %d\n", __func__, hparams.n_layer);
|
| 393 |
-
fprintf(stderr, "%s: n_rot = %d\n", __func__, hparams.n_rot);
|
| 394 |
-
fprintf(stderr, "%s: f16 = %d\n", __func__, hparams.f16);
|
| 395 |
-
fprintf(stderr, "%s: n_ff = %d\n", __func__, n_ff);
|
| 396 |
-
fprintf(stderr, "%s: n_parts = %d\n", __func__, n_parts);
|
| 397 |
-
fprintf(stderr, "%s: type = %d\n", __func__, model.type);
|
| 398 |
}
|
| 399 |
|
| 400 |
-
// load vocab
|
| 401 |
{
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
word.assign(tmp.data(), len);
|
| 415 |
-
} else {
|
| 416 |
-
word.clear();
|
| 417 |
-
}
|
| 418 |
-
|
| 419 |
-
float score;
|
| 420 |
-
fin.read((char *) &score, sizeof(score));
|
| 421 |
-
|
| 422 |
-
vocab.token_to_id[word] = i;
|
| 423 |
-
|
| 424 |
-
auto &tok_score = vocab.id_to_token[i];
|
| 425 |
-
tok_score.tok = word;
|
| 426 |
-
tok_score.score = score;
|
| 427 |
-
}
|
| 428 |
}
|
| 429 |
|
| 430 |
if (vocab_only) {
|
| 431 |
-
return
|
| 432 |
-
}
|
| 433 |
-
|
| 434 |
-
// for the big tensors, we have the option to store the data in 16-bit floats or quantized
|
| 435 |
-
// in order to save memory and also to speed up the computation
|
| 436 |
-
// wtype is for per-layer weights, while vtype is for other weights
|
| 437 |
-
ggml_type wtype, vtype;
|
| 438 |
-
switch (model.hparams.f16) {
|
| 439 |
-
case 0: wtype = vtype = GGML_TYPE_F32; break;
|
| 440 |
-
case 1: wtype = vtype = GGML_TYPE_F16; break;
|
| 441 |
-
case 2: wtype = vtype = GGML_TYPE_Q4_0; break;
|
| 442 |
-
case 3: wtype = vtype = GGML_TYPE_Q4_1; break;
|
| 443 |
-
case 4: wtype = GGML_TYPE_Q4_1; vtype = GGML_TYPE_F16; break;
|
| 444 |
-
default:
|
| 445 |
-
{
|
| 446 |
-
fprintf(stderr, "%s: invalid model file '%s' (bad f16 value %d)\n",
|
| 447 |
-
__func__, fname.c_str(), model.hparams.f16);
|
| 448 |
-
return false;
|
| 449 |
-
}
|
| 450 |
}
|
| 451 |
|
| 452 |
auto & ctx = model.ctx;
|
| 453 |
|
| 454 |
-
size_t ctx_size
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
const auto & hparams = model.hparams;
|
| 458 |
-
|
| 459 |
-
const int n_embd = hparams.n_embd;
|
| 460 |
-
const int n_layer = hparams.n_layer;
|
| 461 |
-
const int n_ctx = hparams.n_ctx;
|
| 462 |
-
const int n_vocab = hparams.n_vocab;
|
| 463 |
-
|
| 464 |
-
ctx_size += n_embd*n_vocab*ggml_type_sizef(vtype); // tok_embeddings
|
| 465 |
-
|
| 466 |
-
ctx_size += n_embd*ggml_type_sizef(GGML_TYPE_F32); // norm
|
| 467 |
-
|
| 468 |
-
ctx_size += n_embd*n_vocab*ggml_type_sizef(vtype); // output
|
| 469 |
-
|
| 470 |
-
ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // attention_norm
|
| 471 |
-
|
| 472 |
-
ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wq
|
| 473 |
-
ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wk
|
| 474 |
-
ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wv
|
| 475 |
-
ctx_size += n_layer*(n_embd*n_embd*ggml_type_sizef(wtype)); // wo
|
| 476 |
-
|
| 477 |
-
ctx_size += n_layer*(n_embd*ggml_type_sizef(GGML_TYPE_F32)); // ffn_norm
|
| 478 |
-
|
| 479 |
-
ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w1
|
| 480 |
-
ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w2
|
| 481 |
-
ctx_size += n_layer*(n_ff*n_embd*ggml_type_sizef(wtype)); // w3
|
| 482 |
-
|
| 483 |
-
ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_k
|
| 484 |
-
ctx_size += n_ctx*n_layer*n_embd*ggml_type_sizef(memory_type); // memory_v
|
| 485 |
-
|
| 486 |
-
ctx_size += (5 + 10*n_layer)*256; // object overhead
|
| 487 |
-
|
| 488 |
-
fprintf(stderr, "%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
|
| 489 |
-
}
|
| 490 |
|
| 491 |
// print memory requirements
|
| 492 |
{
|
|
@@ -495,6 +890,7 @@ static bool llama_model_load(
|
|
| 495 |
// this is the total memory required to run the inference
|
| 496 |
const size_t mem_required =
|
| 497 |
ctx_size +
|
|
|
|
| 498 |
MEM_REQ_SCRATCH0.at(model.type) +
|
| 499 |
MEM_REQ_SCRATCH1.at(model.type) +
|
| 500 |
MEM_REQ_EVAL.at (model.type);
|
|
@@ -510,16 +906,20 @@ static bool llama_model_load(
|
|
| 510 |
// create the ggml context
|
| 511 |
{
|
| 512 |
lctx.model.buf.resize(ctx_size);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
|
| 514 |
struct ggml_init_params params = {
|
| 515 |
-
/*.mem_size =*/ lctx.model.buf.size
|
| 516 |
-
/*.mem_buffer =*/ lctx.model.buf.
|
|
|
|
| 517 |
};
|
| 518 |
|
| 519 |
model.ctx = ggml_init(params);
|
| 520 |
if (!model.ctx) {
|
| 521 |
-
|
| 522 |
-
return false;
|
| 523 |
}
|
| 524 |
}
|
| 525 |
|
|
@@ -527,289 +927,71 @@ static bool llama_model_load(
|
|
| 527 |
{
|
| 528 |
const auto & hparams = model.hparams;
|
| 529 |
|
| 530 |
-
const
|
| 531 |
-
const
|
| 532 |
-
const
|
| 533 |
-
|
| 534 |
-
model.layers.resize(n_layer);
|
| 535 |
-
|
| 536 |
-
model.tok_embeddings = ggml_new_tensor_2d(ctx, vtype, n_embd, n_vocab);
|
| 537 |
|
| 538 |
-
|
| 539 |
-
model.output = ggml_new_tensor_2d(ctx, vtype, n_embd, n_vocab);
|
| 540 |
|
| 541 |
-
|
| 542 |
-
model.
|
|
|
|
| 543 |
|
| 544 |
-
model.
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
for (int i = 0; i < n_layer; ++i) {
|
| 548 |
auto & layer = model.layers[i];
|
| 549 |
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
layer.wq = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
|
| 553 |
-
layer.wk = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
|
| 554 |
-
layer.wv = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
|
| 555 |
-
layer.wo = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
|
| 556 |
|
| 557 |
-
layer.
|
| 558 |
|
| 559 |
-
layer.
|
| 560 |
-
layer.
|
| 561 |
-
layer.
|
|
|
|
| 562 |
|
| 563 |
-
|
| 564 |
-
model.tensors["layers." + std::to_string(i) + ".attention_norm.weight"] = layer.attention_norm;
|
| 565 |
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
model.tensors["layers." + std::to_string(i) + ".attention.wo.weight"] = layer.wo;
|
| 570 |
-
|
| 571 |
-
model.tensors["layers." + std::to_string(i) + ".ffn_norm.weight"] = layer.ffn_norm;
|
| 572 |
-
|
| 573 |
-
model.tensors["layers." + std::to_string(i) + ".feed_forward.w1.weight"] = layer.w1;
|
| 574 |
-
model.tensors["layers." + std::to_string(i) + ".feed_forward.w2.weight"] = layer.w2;
|
| 575 |
-
model.tensors["layers." + std::to_string(i) + ".feed_forward.w3.weight"] = layer.w3;
|
| 576 |
}
|
| 577 |
}
|
| 578 |
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
fin.close();
|
| 582 |
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
progress_callback(0.0, progress_callback_user_data);
|
| 587 |
}
|
| 588 |
|
| 589 |
-
|
| 590 |
-
const int part_id = i;
|
| 591 |
-
//const int part_id = n_parts - i - 1;
|
| 592 |
-
|
| 593 |
-
std::string fname_part = fname;
|
| 594 |
-
if (i > 0) {
|
| 595 |
-
fname_part += "." + std::to_string(i);
|
| 596 |
-
}
|
| 597 |
-
|
| 598 |
-
fprintf(stderr, "%s: loading model part %d/%d from '%s'\n", __func__, i+1, n_parts, fname_part.c_str());
|
| 599 |
-
|
| 600 |
-
fin = std::ifstream(fname_part, std::ios::binary);
|
| 601 |
-
fin.rdbuf()->pubsetbuf(f_buf.data(), f_buf.size());
|
| 602 |
-
|
| 603 |
-
fin.seekg(0, fin.end);
|
| 604 |
-
const size_t file_size = fin.tellg();
|
| 605 |
-
|
| 606 |
-
fin.seekg(file_offset);
|
| 607 |
|
| 608 |
-
|
| 609 |
-
{
|
| 610 |
-
size_t total_size = 0;
|
| 611 |
-
|
| 612 |
-
model.n_loaded = 0;
|
| 613 |
-
|
| 614 |
-
fprintf(stderr, "%s: ", __func__);
|
| 615 |
-
|
| 616 |
-
while (true) {
|
| 617 |
-
int32_t n_dims;
|
| 618 |
-
int32_t length;
|
| 619 |
-
int32_t ftype;
|
| 620 |
-
|
| 621 |
-
fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
|
| 622 |
-
fin.read(reinterpret_cast<char *>(&length), sizeof(length));
|
| 623 |
-
fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
|
| 624 |
-
|
| 625 |
-
if (fin.eof()) {
|
| 626 |
-
break;
|
| 627 |
-
}
|
| 628 |
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
nelements *= ne[i];
|
| 634 |
-
}
|
| 635 |
-
|
| 636 |
-
std::string name(length, 0);
|
| 637 |
-
fin.read(&name[0], length);
|
| 638 |
-
|
| 639 |
-
if (model.tensors.find(name.data()) == model.tensors.end()) {
|
| 640 |
-
fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.data());
|
| 641 |
-
return false;
|
| 642 |
-
}
|
| 643 |
-
|
| 644 |
-
// split_type = 0: split by columns
|
| 645 |
-
// split_type = 1: split by rows
|
| 646 |
-
int split_type = 0;
|
| 647 |
-
|
| 648 |
-
// split_type = 0:
|
| 649 |
-
// regex:
|
| 650 |
-
// - tok_embeddings.*
|
| 651 |
-
// - layers.*.attention.wo.weight
|
| 652 |
-
// - layers.*.feed_forward.w2.weight
|
| 653 |
-
|
| 654 |
-
// split_type = 1:
|
| 655 |
-
// regex:
|
| 656 |
-
// - output.*
|
| 657 |
-
// - layers.*.attention.wq.weight
|
| 658 |
-
// - layers.*.attention.wk.weight
|
| 659 |
-
// - layers.*.attention.wv.weight
|
| 660 |
-
// - layers.*.feed_forward.w1.weight
|
| 661 |
-
// - layers.*.feed_forward.w3.weight
|
| 662 |
-
if (name.find("tok_embeddings") != std::string::npos) {
|
| 663 |
-
split_type = 0;
|
| 664 |
-
} else if (name.find("layers") != std::string::npos) {
|
| 665 |
-
if (name.find("attention.wo.weight") != std::string::npos) {
|
| 666 |
-
split_type = 0;
|
| 667 |
-
} else if (name.find("feed_forward.w2.weight") != std::string::npos) {
|
| 668 |
-
split_type = 0;
|
| 669 |
-
} else {
|
| 670 |
-
split_type = 1;
|
| 671 |
-
}
|
| 672 |
-
} else if (name.find("output") != std::string::npos) {
|
| 673 |
-
split_type = 1;
|
| 674 |
-
}
|
| 675 |
-
|
| 676 |
-
auto tensor = model.tensors[name.data()];
|
| 677 |
-
|
| 678 |
-
if (n_dims == 1) {
|
| 679 |
-
if (ggml_nelements(tensor) != nelements) {
|
| 680 |
-
fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
|
| 681 |
-
return false;
|
| 682 |
-
}
|
| 683 |
-
} else {
|
| 684 |
-
if (ggml_nelements(tensor)/n_parts != nelements) {
|
| 685 |
-
fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
|
| 686 |
-
return false;
|
| 687 |
-
}
|
| 688 |
-
}
|
| 689 |
-
|
| 690 |
-
if (n_dims == 1) {
|
| 691 |
-
if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
|
| 692 |
-
fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
|
| 693 |
-
__func__, name.data(), tensor->ne[0], tensor->ne[1], ne[0], ne[1]);
|
| 694 |
-
return false;
|
| 695 |
-
}
|
| 696 |
-
} else {
|
| 697 |
-
if (split_type == 0) {
|
| 698 |
-
if (tensor->ne[0]/n_parts != ne[0] || tensor->ne[1] != ne[1]) {
|
| 699 |
-
fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
|
| 700 |
-
__func__, name.data(), tensor->ne[0]/n_parts, tensor->ne[1], ne[0], ne[1]);
|
| 701 |
-
return false;
|
| 702 |
-
}
|
| 703 |
-
} else {
|
| 704 |
-
if (tensor->ne[0] != ne[0] || tensor->ne[1]/n_parts != ne[1]) {
|
| 705 |
-
fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
|
| 706 |
-
__func__, name.data(), tensor->ne[0], tensor->ne[1]/n_parts, ne[0], ne[1]);
|
| 707 |
-
return false;
|
| 708 |
-
}
|
| 709 |
-
}
|
| 710 |
-
}
|
| 711 |
-
|
| 712 |
-
if (0) {
|
| 713 |
-
static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
|
| 714 |
-
fprintf(stderr, "%24s - [%5d, %5d], type = %6s, split = %d\n", name.data(), ne[0], ne[1], ftype_str[ftype], split_type);
|
| 715 |
-
}
|
| 716 |
-
|
| 717 |
-
size_t bpe = 0;
|
| 718 |
-
|
| 719 |
-
switch (ftype) {
|
| 720 |
-
case 0: bpe = ggml_type_size(GGML_TYPE_F32); break;
|
| 721 |
-
case 1: bpe = ggml_type_size(GGML_TYPE_F16); break;
|
| 722 |
-
case 2: bpe = ggml_type_size(GGML_TYPE_Q4_0); assert(ne[0] % 64 == 0); break;
|
| 723 |
-
case 3: bpe = ggml_type_size(GGML_TYPE_Q4_1); assert(ne[0] % 64 == 0); break;
|
| 724 |
-
default:
|
| 725 |
-
{
|
| 726 |
-
fprintf(stderr, "%s: unknown ftype %d in model file\n", __func__, ftype);
|
| 727 |
-
return false;
|
| 728 |
-
}
|
| 729 |
-
};
|
| 730 |
-
|
| 731 |
-
if (n_dims == 1 || n_parts == 1) {
|
| 732 |
-
if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
|
| 733 |
-
fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
|
| 734 |
-
__func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
|
| 735 |
-
return false;
|
| 736 |
-
}
|
| 737 |
-
|
| 738 |
-
if (part_id == 0) {
|
| 739 |
-
fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
|
| 740 |
-
} else {
|
| 741 |
-
fin.seekg(ggml_nbytes(tensor), std::ios::cur);
|
| 742 |
-
}
|
| 743 |
-
|
| 744 |
-
total_size += ggml_nbytes(tensor);
|
| 745 |
-
} else {
|
| 746 |
-
if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)/n_parts) {
|
| 747 |
-
fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
|
| 748 |
-
__func__, name.data(), ggml_nbytes(tensor)/n_parts, nelements*bpe);
|
| 749 |
-
return false;
|
| 750 |
-
}
|
| 751 |
-
|
| 752 |
-
if (split_type == 0) {
|
| 753 |
-
const int np0 = ne[0];
|
| 754 |
-
|
| 755 |
-
const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
|
| 756 |
-
assert(row_size == tensor->nb[1]);
|
| 757 |
-
|
| 758 |
-
for (int i1 = 0; i1 < ne[1]; ++i1) {
|
| 759 |
-
const size_t offset_row = i1*row_size;
|
| 760 |
-
const size_t offset = offset_row + ((part_id*np0)/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
|
| 761 |
-
fin.read(reinterpret_cast<char *>(tensor->data) + offset, row_size/n_parts);
|
| 762 |
-
}
|
| 763 |
-
} else {
|
| 764 |
-
const int np1 = ne[1];
|
| 765 |
-
|
| 766 |
-
const size_t row_size = (tensor->ne[0]/ggml_blck_size(tensor->type))*ggml_type_size(tensor->type);
|
| 767 |
-
|
| 768 |
-
for (int i1 = 0; i1 < ne[1]; ++i1) {
|
| 769 |
-
const size_t offset_row = (i1 + part_id*np1)*row_size;
|
| 770 |
-
fin.read(reinterpret_cast<char *>(tensor->data) + offset_row, row_size);
|
| 771 |
-
}
|
| 772 |
-
}
|
| 773 |
-
|
| 774 |
-
total_size += ggml_nbytes(tensor)/n_parts;
|
| 775 |
-
}
|
| 776 |
-
|
| 777 |
-
//fprintf(stderr, "%42s - [%5d, %5d], type = %6s, %6.2f MB\n", name.data(), ne[0], ne[1], ftype == 0 ? "float" : "f16", ggml_nbytes(tensor)/1024.0/1024.0);
|
| 778 |
-
model.n_loaded++;
|
| 779 |
-
|
| 780 |
-
// progress
|
| 781 |
-
if (progress_callback) {
|
| 782 |
-
double current_file_progress = double(size_t(fin.tellg()) - file_offset) / double(file_size - file_offset);
|
| 783 |
-
double current_progress = (double(i) + current_file_progress) / double(n_parts);
|
| 784 |
-
progress_callback(current_progress, progress_callback_user_data);
|
| 785 |
-
}
|
| 786 |
-
if (model.n_loaded % 8 == 0) {
|
| 787 |
-
fprintf(stderr, ".");
|
| 788 |
-
fflush(stderr);
|
| 789 |
-
}
|
| 790 |
-
}
|
| 791 |
-
|
| 792 |
-
fprintf(stderr, " done\n");
|
| 793 |
-
|
| 794 |
-
fprintf(stderr, "%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size/1024.0/1024.0, model.n_loaded);
|
| 795 |
-
if (model.n_loaded == 0) {
|
| 796 |
-
fprintf(stderr, "%s: WARN no tensors loaded from model file - assuming empty model for testing\n", __func__);
|
| 797 |
-
} else if (model.n_loaded != (int) model.tensors.size()) {
|
| 798 |
-
fprintf(stderr, "%s: ERROR not all tensors loaded from model file - expected %zu, got %d\n", __func__, model.tensors.size(), model.n_loaded);
|
| 799 |
-
return false;
|
| 800 |
-
}
|
| 801 |
-
}
|
| 802 |
-
|
| 803 |
-
fin.close();
|
| 804 |
-
}
|
| 805 |
-
|
| 806 |
-
lctx.t_load_us = ggml_time_us() - t_start_us;
|
| 807 |
|
| 808 |
-
|
| 809 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 810 |
}
|
| 811 |
-
|
| 812 |
-
return true;
|
| 813 |
}
|
| 814 |
|
| 815 |
// evaluate the transformer
|
|
@@ -847,8 +1029,9 @@ static bool llama_eval_internal(
|
|
| 847 |
auto & buf_compute = lctx.buf_compute;
|
| 848 |
|
| 849 |
struct ggml_init_params params = {
|
| 850 |
-
/*.mem_size =*/ buf_compute.size
|
| 851 |
-
/*.mem_buffer =*/ buf_compute.
|
|
|
|
| 852 |
};
|
| 853 |
|
| 854 |
struct ggml_context * ctx0 = ggml_init(params);
|
|
@@ -856,7 +1039,7 @@ static bool llama_eval_internal(
|
|
| 856 |
// for big prompts, if BLAS is enabled, it is better to use only one thread
|
| 857 |
// otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
|
| 858 |
ggml_cgraph gf = {};
|
| 859 |
-
gf.n_threads = N
|
| 860 |
|
| 861 |
struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
|
| 862 |
memcpy(embd->data, tokens, N*ggml_element_size(embd));
|
|
@@ -882,37 +1065,35 @@ static bool llama_eval_internal(
|
|
| 882 |
|
| 883 |
// self-attention
|
| 884 |
{
|
| 885 |
-
|
| 886 |
-
struct ggml_tensor *
|
| 887 |
-
struct ggml_tensor *
|
| 888 |
|
| 889 |
// store key and value to memory
|
| 890 |
-
|
|
|
|
|
|
|
|
|
|
| 891 |
struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
|
| 892 |
-
struct ggml_tensor * v =
|
|
|
|
|
|
|
| 893 |
|
|
|
|
| 894 |
ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
|
| 895 |
ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
|
| 896 |
}
|
| 897 |
|
| 898 |
-
// Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
|
| 899 |
struct ggml_tensor * Q =
|
| 900 |
ggml_permute(ctx0,
|
| 901 |
-
|
| 902 |
-
ggml_cpy(ctx0,
|
| 903 |
-
Qcur,
|
| 904 |
-
ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd/n_head, n_head, N)),
|
| 905 |
-
n_past, n_rot, 0),
|
| 906 |
0, 2, 1, 3);
|
| 907 |
|
| 908 |
-
// K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
|
| 909 |
struct ggml_tensor * K =
|
| 910 |
ggml_permute(ctx0,
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
n_embd/n_head, n_head, n_past + N),
|
| 915 |
-
n_past, n_rot, 1),
|
| 916 |
0, 2, 1, 3);
|
| 917 |
|
| 918 |
// K * Q
|
|
@@ -922,7 +1103,7 @@ static bool llama_eval_internal(
|
|
| 922 |
struct ggml_tensor * KQ_scaled =
|
| 923 |
ggml_scale(ctx0,
|
| 924 |
KQ,
|
| 925 |
-
ggml_new_f32(ctx0, 1.0f/
|
| 926 |
|
| 927 |
// KQ_masked = mask_past(KQ_scaled)
|
| 928 |
struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
|
|
@@ -930,18 +1111,23 @@ static bool llama_eval_internal(
|
|
| 930 |
// KQ = soft_max(KQ_masked)
|
| 931 |
struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
|
| 932 |
|
| 933 |
-
//
|
| 934 |
-
struct ggml_tensor *
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
1, 2, 0, 3),
|
| 941 |
-
ggml_new_tensor_3d(ctx0, kv_self.v->type, n_past + N, n_embd/n_head, n_head));
|
| 942 |
|
| 943 |
-
|
| 944 |
-
struct ggml_tensor * KQV = ggml_mul_mat(ctx0,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 945 |
|
| 946 |
// KQV_merged = KQV.permute(0, 2, 1, 3)
|
| 947 |
struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
|
|
@@ -1027,9 +1213,13 @@ static bool llama_eval_internal(
|
|
| 1027 |
ggml_build_forward_expand(&gf, inpL);
|
| 1028 |
ggml_graph_compute (ctx0, &gf);
|
| 1029 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1030 |
//if (n_past%100 == 0) {
|
| 1031 |
-
//
|
| 1032 |
-
// ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
|
| 1033 |
//}
|
| 1034 |
|
| 1035 |
//embd_w.resize(n_vocab*N);
|
|
@@ -1240,12 +1430,12 @@ static std::vector<llama_vocab::id> llama_tokenize(const llama_vocab & vocab, co
|
|
| 1240 |
// sampling
|
| 1241 |
//
|
| 1242 |
|
| 1243 |
-
static void sample_top_k(std::vector<std::pair<
|
| 1244 |
// find the top k tokens
|
| 1245 |
std::partial_sort(
|
| 1246 |
logits_id.begin(),
|
| 1247 |
logits_id.begin() + top_k, logits_id.end(),
|
| 1248 |
-
[](const std::pair<
|
| 1249 |
return a.first > b.first;
|
| 1250 |
});
|
| 1251 |
|
|
@@ -1256,9 +1446,9 @@ static llama_vocab::id llama_sample_top_p_top_k(
|
|
| 1256 |
llama_context & lctx,
|
| 1257 |
const std::vector<llama_vocab::id> & last_n_tokens,
|
| 1258 |
int top_k,
|
| 1259 |
-
|
| 1260 |
-
|
| 1261 |
-
|
| 1262 |
auto & rng = lctx.rng;
|
| 1263 |
|
| 1264 |
const int n_logits = lctx.model.hparams.n_vocab;
|
|
@@ -1266,17 +1456,31 @@ static llama_vocab::id llama_sample_top_p_top_k(
|
|
| 1266 |
const auto & logits = lctx.logits;
|
| 1267 |
const auto * plogits = logits.data() + logits.size() - n_logits;
|
| 1268 |
|
| 1269 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1270 |
logits_id.reserve(n_logits);
|
| 1271 |
|
| 1272 |
{
|
| 1273 |
-
const
|
| 1274 |
for (int i = 0; i < n_logits; ++i) {
|
| 1275 |
// repetition penalty from ctrl paper (https://arxiv.org/abs/1909.05858)
|
| 1276 |
// credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
|
| 1277 |
if (std::find(last_n_tokens.begin(), last_n_tokens.end(), i) != last_n_tokens.end()) {
|
| 1278 |
// if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
|
| 1279 |
-
if (plogits[i] < 0.
|
| 1280 |
logits_id.push_back(std::make_pair(plogits[i]*scale*repeat_penalty, i));
|
| 1281 |
} else {
|
| 1282 |
logits_id.push_back(std::make_pair(plogits[i]*scale/repeat_penalty, i));
|
|
@@ -1287,20 +1491,16 @@ static llama_vocab::id llama_sample_top_p_top_k(
|
|
| 1287 |
}
|
| 1288 |
}
|
| 1289 |
|
| 1290 |
-
sample_top_k(logits_id, top_k);
|
| 1291 |
-
|
| 1292 |
-
double maxl = -std::numeric_limits<double>::infinity();
|
| 1293 |
-
for (const auto & kv : logits_id) {
|
| 1294 |
-
maxl = std::max(maxl, kv.first);
|
| 1295 |
-
}
|
| 1296 |
|
| 1297 |
// compute probs for the top k tokens
|
| 1298 |
-
std::vector<
|
| 1299 |
probs.reserve(logits_id.size());
|
| 1300 |
|
|
|
|
| 1301 |
double sum = 0.0;
|
| 1302 |
for (const auto & kv : logits_id) {
|
| 1303 |
-
|
| 1304 |
probs.push_back(p);
|
| 1305 |
sum += p;
|
| 1306 |
}
|
|
@@ -1310,8 +1510,8 @@ static llama_vocab::id llama_sample_top_p_top_k(
|
|
| 1310 |
p /= sum;
|
| 1311 |
}
|
| 1312 |
|
| 1313 |
-
if (top_p < 1.
|
| 1314 |
-
double cumsum = 0.
|
| 1315 |
for (int i = 0; i < (int) probs.size(); i++) {
|
| 1316 |
cumsum += probs[i];
|
| 1317 |
if (cumsum >= top_p) {
|
|
@@ -1320,16 +1520,11 @@ static llama_vocab::id llama_sample_top_p_top_k(
|
|
| 1320 |
break;
|
| 1321 |
}
|
| 1322 |
}
|
| 1323 |
-
|
| 1324 |
-
cumsum = 1.0/cumsum;
|
| 1325 |
-
for (int i = 0; i < (int) probs.size(); i++) {
|
| 1326 |
-
probs[i] *= cumsum;
|
| 1327 |
-
}
|
| 1328 |
}
|
| 1329 |
|
| 1330 |
//printf("\n");
|
| 1331 |
//for (int i = 0; i < (int) 10; i++) {
|
| 1332 |
-
// printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
|
| 1333 |
//}
|
| 1334 |
//printf("\n\n");
|
| 1335 |
//exit(0);
|
|
@@ -1344,285 +1539,118 @@ static llama_vocab::id llama_sample_top_p_top_k(
|
|
| 1344 |
// quantization
|
| 1345 |
//
|
| 1346 |
|
| 1347 |
-
|
| 1348 |
-
|
| 1349 |
-
ggml_type type = GGML_TYPE_Q4_1;
|
| 1350 |
-
|
| 1351 |
switch (itype) {
|
| 1352 |
-
case 2:
|
| 1353 |
-
case 3:
|
| 1354 |
-
default:
|
| 1355 |
};
|
| 1356 |
|
| 1357 |
-
|
| 1358 |
-
|
| 1359 |
-
|
| 1360 |
-
|
| 1361 |
-
|
| 1362 |
-
|
| 1363 |
-
|
| 1364 |
-
|
| 1365 |
-
|
| 1366 |
-
|
| 1367 |
-
|
| 1368 |
-
|
| 1369 |
-
|
| 1370 |
-
|
| 1371 |
-
|
| 1372 |
-
|
| 1373 |
-
|
| 1374 |
-
|
| 1375 |
-
|
| 1376 |
-
|
| 1377 |
-
|
| 1378 |
-
|
| 1379 |
-
|
| 1380 |
-
|
| 1381 |
-
|
| 1382 |
-
|
| 1383 |
-
|
| 1384 |
-
|
| 1385 |
-
|
| 1386 |
-
|
| 1387 |
-
|
| 1388 |
-
|
| 1389 |
-
|
| 1390 |
-
|
| 1391 |
-
|
| 1392 |
-
|
| 1393 |
-
|
| 1394 |
-
|
| 1395 |
-
|
| 1396 |
-
|
| 1397 |
-
|
| 1398 |
-
|
| 1399 |
-
|
| 1400 |
-
|
| 1401 |
-
|
| 1402 |
-
|
| 1403 |
-
|
| 1404 |
-
|
| 1405 |
-
|
| 1406 |
-
llama_hparams hparams;
|
| 1407 |
-
|
| 1408 |
-
// load hparams
|
| 1409 |
-
{
|
| 1410 |
-
finp.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
|
| 1411 |
-
//finp.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
|
| 1412 |
-
finp.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
|
| 1413 |
-
finp.read((char *) &hparams.n_mult, sizeof(hparams.n_mult));
|
| 1414 |
-
finp.read((char *) &hparams.n_head, sizeof(hparams.n_head));
|
| 1415 |
-
finp.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
|
| 1416 |
-
finp.read((char *) &hparams.n_rot, sizeof(hparams.n_rot));
|
| 1417 |
-
finp.read((char *) &hparams.f16, sizeof(hparams.f16));
|
| 1418 |
-
|
| 1419 |
-
printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
|
| 1420 |
-
printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
|
| 1421 |
-
printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
|
| 1422 |
-
printf("%s: n_mult = %d\n", __func__, hparams.n_mult);
|
| 1423 |
-
printf("%s: n_head = %d\n", __func__, hparams.n_head);
|
| 1424 |
-
printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
|
| 1425 |
-
printf("%s: f16 = %d\n", __func__, hparams.f16);
|
| 1426 |
-
|
| 1427 |
-
fout.write((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
|
| 1428 |
-
//fout.write((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
|
| 1429 |
-
fout.write((char *) &hparams.n_embd, sizeof(hparams.n_embd));
|
| 1430 |
-
fout.write((char *) &hparams.n_mult, sizeof(hparams.n_mult));
|
| 1431 |
-
fout.write((char *) &hparams.n_head, sizeof(hparams.n_head));
|
| 1432 |
-
fout.write((char *) &hparams.n_layer, sizeof(hparams.n_layer));
|
| 1433 |
-
fout.write((char *) &hparams.n_rot, sizeof(hparams.n_rot));
|
| 1434 |
-
fout.write((char *) &itype, sizeof(hparams.f16));
|
| 1435 |
-
}
|
| 1436 |
-
|
| 1437 |
-
// load vocab
|
| 1438 |
-
{
|
| 1439 |
-
const int32_t n_vocab = hparams.n_vocab;
|
| 1440 |
-
|
| 1441 |
-
if (n_vocab != hparams.n_vocab) {
|
| 1442 |
-
fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n",
|
| 1443 |
-
__func__, fname_inp.c_str(), n_vocab, hparams.n_vocab);
|
| 1444 |
-
return false;
|
| 1445 |
-
}
|
| 1446 |
-
|
| 1447 |
-
std::string word;
|
| 1448 |
-
vocab.id_to_token.resize(n_vocab);
|
| 1449 |
-
for (int i = 0; i < n_vocab; i++) {
|
| 1450 |
-
uint32_t len;
|
| 1451 |
-
finp.read ((char *) &len, sizeof(len));
|
| 1452 |
-
fout.write((char *) &len, sizeof(len));
|
| 1453 |
-
|
| 1454 |
-
word.resize(len);
|
| 1455 |
-
finp.read ((char *) word.data(), len);
|
| 1456 |
-
fout.write((char *) word.data(), len);
|
| 1457 |
-
|
| 1458 |
-
float score;
|
| 1459 |
-
finp.read ((char *) &score, sizeof(score));
|
| 1460 |
-
fout.write((char *) &score, sizeof(score));
|
| 1461 |
-
|
| 1462 |
-
vocab.token_to_id[word] = i;
|
| 1463 |
-
|
| 1464 |
-
auto &tok_score = vocab.id_to_token[i];
|
| 1465 |
-
tok_score.tok = word;
|
| 1466 |
-
tok_score.score = score;
|
| 1467 |
-
}
|
| 1468 |
-
}
|
| 1469 |
-
|
| 1470 |
-
// load weights
|
| 1471 |
-
{
|
| 1472 |
-
size_t total_size_org = 0;
|
| 1473 |
-
size_t total_size_new = 0;
|
| 1474 |
-
|
| 1475 |
-
std::vector<float> work;
|
| 1476 |
-
|
| 1477 |
-
std::vector<uint8_t> data_u8;
|
| 1478 |
-
std::vector<ggml_fp16_t> data_f16;
|
| 1479 |
-
std::vector<float> data_f32;
|
| 1480 |
-
|
| 1481 |
-
std::vector<int64_t> hist_all(1 << 4, 0);
|
| 1482 |
-
|
| 1483 |
-
while (true) {
|
| 1484 |
-
int32_t n_dims;
|
| 1485 |
-
int32_t length;
|
| 1486 |
-
int32_t ftype;
|
| 1487 |
-
|
| 1488 |
-
finp.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
|
| 1489 |
-
finp.read(reinterpret_cast<char *>(&length), sizeof(length));
|
| 1490 |
-
finp.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
|
| 1491 |
-
|
| 1492 |
-
if (finp.eof()) {
|
| 1493 |
-
break;
|
| 1494 |
-
}
|
| 1495 |
-
|
| 1496 |
-
int32_t nelements = 1;
|
| 1497 |
-
int32_t ne[2] = { 1, 1 };
|
| 1498 |
-
for (int i = 0; i < n_dims; ++i) {
|
| 1499 |
-
finp.read (reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
|
| 1500 |
-
nelements *= ne[i];
|
| 1501 |
-
}
|
| 1502 |
-
|
| 1503 |
-
std::string name(length, 0);
|
| 1504 |
-
finp.read (&name[0], length);
|
| 1505 |
-
|
| 1506 |
-
{
|
| 1507 |
-
static const char * ftype_str[] = { "f32", "f16", "q4_0", "q4_1", };
|
| 1508 |
-
printf("%48s - [%5d, %5d], type = %6s ", name.data(), ne[0], ne[1], ftype_str[ftype]);
|
| 1509 |
-
}
|
| 1510 |
-
|
| 1511 |
-
// regexes of tensor names to be quantized
|
| 1512 |
-
const std::vector<std::string> k_names = {
|
| 1513 |
-
".*weight",
|
| 1514 |
-
};
|
| 1515 |
-
|
| 1516 |
-
bool quantize = false;
|
| 1517 |
-
for (const auto & s : k_names) {
|
| 1518 |
-
if (std::regex_match(name, std::regex(s))) {
|
| 1519 |
-
quantize = true;
|
| 1520 |
-
break;
|
| 1521 |
-
}
|
| 1522 |
-
}
|
| 1523 |
-
|
| 1524 |
-
// quantize only 2D tensors
|
| 1525 |
-
quantize &= (n_dims == 2);
|
| 1526 |
-
|
| 1527 |
-
if (quantize) {
|
| 1528 |
-
if (ftype != 0 && ftype != 1) {
|
| 1529 |
-
fprintf(stderr, "%s: unsupported ftype %d for integer quantization\n", __func__, ftype);
|
| 1530 |
-
return false;
|
| 1531 |
-
}
|
| 1532 |
-
|
| 1533 |
-
if (ftype == 1) {
|
| 1534 |
-
data_f16.resize(nelements);
|
| 1535 |
-
finp.read(reinterpret_cast<char *>(data_f16.data()), nelements * sizeof(ggml_fp16_t));
|
| 1536 |
-
data_f32.resize(nelements);
|
| 1537 |
-
for (int i = 0; i < nelements; ++i) {
|
| 1538 |
-
data_f32[i] = ggml_fp16_to_fp32(data_f16[i]);
|
| 1539 |
-
}
|
| 1540 |
-
} else {
|
| 1541 |
-
data_f32.resize(nelements);
|
| 1542 |
-
finp.read(reinterpret_cast<char *>(data_f32.data()), nelements * sizeof(float));
|
| 1543 |
}
|
| 1544 |
-
|
| 1545 |
-
ftype = itype;
|
| 1546 |
} else {
|
| 1547 |
-
|
| 1548 |
-
|
| 1549 |
-
data_u8.resize(nelements*bpe);
|
| 1550 |
-
finp.read(reinterpret_cast<char *>(data_u8.data()), nelements * bpe);
|
| 1551 |
}
|
| 1552 |
|
| 1553 |
-
|
| 1554 |
-
|
| 1555 |
-
|
| 1556 |
-
|
| 1557 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1558 |
}
|
| 1559 |
-
fout.write(&name[0], length);
|
| 1560 |
-
|
| 1561 |
-
if (quantize) {
|
| 1562 |
-
printf("quantizing .. ");
|
| 1563 |
-
work.resize(nelements); // for quantization
|
| 1564 |
-
|
| 1565 |
-
size_t cur_size = 0;
|
| 1566 |
-
std::vector<int64_t> hist_cur(1 << 4, 0);
|
| 1567 |
-
|
| 1568 |
-
switch (type) {
|
| 1569 |
-
case GGML_TYPE_Q4_0:
|
| 1570 |
-
{
|
| 1571 |
-
cur_size = ggml_quantize_q4_0(data_f32.data(), work.data(), nelements, ne[0], qk, hist_cur.data());
|
| 1572 |
-
} break;
|
| 1573 |
-
case GGML_TYPE_Q4_1:
|
| 1574 |
-
{
|
| 1575 |
-
cur_size = ggml_quantize_q4_1(data_f32.data(), work.data(), nelements, ne[0], qk, hist_cur.data());
|
| 1576 |
-
} break;
|
| 1577 |
-
default:
|
| 1578 |
-
{
|
| 1579 |
-
fprintf(stderr, "%s: unsupported quantization type %d\n", __func__, type);
|
| 1580 |
-
return false;
|
| 1581 |
-
}
|
| 1582 |
-
}
|
| 1583 |
|
| 1584 |
-
|
| 1585 |
-
|
| 1586 |
-
|
| 1587 |
-
printf("size = %8.2f MB -> %8.2f MB | hist: ", nelements * sizeof(float)/1024.0/1024.0, cur_size/1024.0/1024.0);
|
| 1588 |
-
for (int i = 0; i < (int) hist_cur.size(); ++i) {
|
| 1589 |
-
hist_all[i] += hist_cur[i];
|
| 1590 |
-
}
|
| 1591 |
-
|
| 1592 |
-
for (int i = 0; i < (int) hist_cur.size(); ++i) {
|
| 1593 |
-
printf("%5.3f ", hist_cur[i] / (float)nelements);
|
| 1594 |
-
}
|
| 1595 |
-
printf("\n");
|
| 1596 |
-
} else {
|
| 1597 |
-
printf("size = %8.3f MB\n", data_u8.size()/1024.0/1024.0);
|
| 1598 |
-
fout.write(reinterpret_cast<char *>(data_u8.data()), data_u8.size());
|
| 1599 |
-
total_size_new += data_u8.size();
|
| 1600 |
}
|
| 1601 |
|
| 1602 |
-
|
| 1603 |
-
|
| 1604 |
-
|
| 1605 |
-
printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
|
| 1606 |
-
printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
|
| 1607 |
-
|
| 1608 |
-
{
|
| 1609 |
-
int64_t sum_all = 0;
|
| 1610 |
-
for (int i = 0; i < (int) hist_all.size(); ++i) {
|
| 1611 |
-
sum_all += hist_all[i];
|
| 1612 |
-
}
|
| 1613 |
-
|
| 1614 |
-
printf("%s: hist: ", __func__);
|
| 1615 |
-
for (int i = 0; i < (int) hist_all.size(); ++i) {
|
| 1616 |
-
printf("%5.3f ", hist_all[i] / (float)sum_all);
|
| 1617 |
}
|
| 1618 |
printf("\n");
|
| 1619 |
}
|
|
|
|
|
|
|
|
|
|
| 1620 |
}
|
| 1621 |
|
| 1622 |
-
|
| 1623 |
-
|
| 1624 |
|
| 1625 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1626 |
}
|
| 1627 |
|
| 1628 |
//
|
|
@@ -1640,31 +1668,38 @@ struct llama_context * llama_init_from_file(
|
|
| 1640 |
params.seed = time(NULL);
|
| 1641 |
}
|
| 1642 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1643 |
ctx->rng = std::mt19937(params.seed);
|
| 1644 |
ctx->logits_all = params.logits_all;
|
| 1645 |
|
| 1646 |
ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
|
| 1647 |
|
| 1648 |
-
if (!llama_model_load(path_model, *ctx, params.n_ctx,
|
| 1649 |
-
params.
|
| 1650 |
-
params.progress_callback_user_data)) {
|
| 1651 |
fprintf(stderr, "%s: failed to load model\n", __func__);
|
| 1652 |
llama_free(ctx);
|
| 1653 |
return nullptr;
|
| 1654 |
}
|
| 1655 |
|
| 1656 |
-
if (params.use_mlock) {
|
| 1657 |
-
char *err;
|
| 1658 |
-
if (!ggml_mlock(ctx->model.ctx, &err)) {
|
| 1659 |
-
fprintf(stderr, "%s\n", err);
|
| 1660 |
-
free(err);
|
| 1661 |
-
llama_free(ctx);
|
| 1662 |
-
return nullptr;
|
| 1663 |
-
}
|
| 1664 |
-
}
|
| 1665 |
-
|
| 1666 |
// reserve memory for context buffers
|
| 1667 |
-
{
|
| 1668 |
if (!kv_cache_init(ctx->model.hparams, ctx->model.kv_self, memory_type, ctx->model.hparams.n_ctx)) {
|
| 1669 |
fprintf(stderr, "%s: kv_cache_init() failed for self-attention cache\n", __func__);
|
| 1670 |
llama_free(ctx);
|
|
@@ -1699,26 +1734,47 @@ struct llama_context * llama_init_from_file(
|
|
| 1699 |
}
|
| 1700 |
|
| 1701 |
void llama_free(struct llama_context * ctx) {
|
| 1702 |
-
kv_cache_free(ctx->model.kv_self);
|
| 1703 |
-
|
| 1704 |
-
if (ctx->model.ctx) {
|
| 1705 |
-
ggml_free(ctx->model.ctx);
|
| 1706 |
-
}
|
| 1707 |
-
|
| 1708 |
delete ctx;
|
| 1709 |
}
|
| 1710 |
|
| 1711 |
int llama_model_quantize(
|
| 1712 |
const char * fname_inp,
|
| 1713 |
const char * fname_out,
|
| 1714 |
-
int itype
|
| 1715 |
-
|
| 1716 |
-
|
| 1717 |
-
|
|
|
|
|
|
|
| 1718 |
return 1;
|
| 1719 |
}
|
|
|
|
| 1720 |
|
| 1721 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1722 |
}
|
| 1723 |
|
| 1724 |
int llama_eval(
|
|
@@ -1731,7 +1787,11 @@ int llama_eval(
|
|
| 1731 |
fprintf(stderr, "%s: failed to eval\n", __func__);
|
| 1732 |
return 1;
|
| 1733 |
}
|
| 1734 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1735 |
return 0;
|
| 1736 |
}
|
| 1737 |
|
|
@@ -1796,9 +1856,9 @@ llama_token llama_sample_top_p_top_k(
|
|
| 1796 |
const llama_token * last_n_tokens_data,
|
| 1797 |
int last_n_tokens_size,
|
| 1798 |
int top_k,
|
| 1799 |
-
|
| 1800 |
-
|
| 1801 |
-
|
| 1802 |
const int64_t t_start_sample_us = ggml_time_us();
|
| 1803 |
|
| 1804 |
llama_token result = 0;
|
|
@@ -1829,16 +1889,15 @@ void llama_print_timings(struct llama_context * ctx) {
|
|
| 1829 |
const int32_t n_p_eval = std::max(1, ctx->n_p_eval);
|
| 1830 |
|
| 1831 |
fprintf(stderr, "\n");
|
| 1832 |
-
fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.
|
| 1833 |
-
fprintf(stderr, "%s: sample time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-
|
| 1834 |
-
fprintf(stderr, "%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token)\n", __func__, 1e-
|
| 1835 |
-
fprintf(stderr, "%s: eval time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-
|
| 1836 |
-
fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.
|
| 1837 |
}
|
| 1838 |
|
| 1839 |
void llama_reset_timings(struct llama_context * ctx) {
|
| 1840 |
ctx->t_start_us = ggml_time_us();
|
| 1841 |
-
|
| 1842 |
ctx->t_sample_us = ctx->n_sample = 0;
|
| 1843 |
ctx->t_eval_us = ctx->n_eval = 0;
|
| 1844 |
ctx->t_p_eval_us = ctx->n_p_eval = 0;
|
|
@@ -1863,3 +1922,8 @@ const char * llama_print_system_info(void) {
|
|
| 1863 |
|
| 1864 |
return s.c_str();
|
| 1865 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "llama_util.h"
|
| 2 |
#include "llama.h"
|
| 3 |
+
#include "llama_internal.h"
|
| 4 |
|
| 5 |
#include "ggml.h"
|
| 6 |
|
| 7 |
+
#include <array>
|
| 8 |
#include <cinttypes>
|
| 9 |
#include <fstream>
|
| 10 |
#include <random>
|
| 11 |
#include <map>
|
| 12 |
#include <unordered_map>
|
| 13 |
#include <queue>
|
|
|
|
| 14 |
#include <cassert>
|
| 15 |
#include <cstring>
|
| 16 |
+
#include <climits>
|
| 17 |
+
#include <memory>
|
| 18 |
+
#include <algorithm>
|
| 19 |
+
#include <initializer_list>
|
| 20 |
|
| 21 |
#define LLAMA_USE_SCRATCH
|
| 22 |
#define LLAMA_MAX_SCRATCH_BUFFERS 16
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
// available llama models
|
| 26 |
enum e_model {
|
|
|
|
| 70 |
|
| 71 |
// default hparams (LLaMA 7B)
|
| 72 |
struct llama_hparams {
|
| 73 |
+
uint32_t n_vocab = 32000;
|
| 74 |
+
uint32_t n_ctx = 512; // this is provided as user input?
|
| 75 |
+
uint32_t n_embd = 4096;
|
| 76 |
+
uint32_t n_mult = 256;
|
| 77 |
+
uint32_t n_head = 32;
|
| 78 |
+
uint32_t n_layer = 32;
|
| 79 |
+
uint32_t n_rot = 64;
|
| 80 |
+
uint32_t f16 = 1;
|
| 81 |
+
|
| 82 |
+
bool operator!=(const llama_hparams & other) const {
|
| 83 |
+
return memcmp(this, &other, sizeof(llama_hparams));
|
| 84 |
+
}
|
| 85 |
};
|
| 86 |
|
| 87 |
struct llama_layer {
|
|
|
|
| 107 |
struct ggml_tensor * k;
|
| 108 |
struct ggml_tensor * v;
|
| 109 |
|
| 110 |
+
struct ggml_context * ctx = NULL;
|
| 111 |
|
| 112 |
+
llama_buffer buf;
|
| 113 |
|
| 114 |
int n; // number of tokens currently in the cache
|
| 115 |
+
|
| 116 |
+
~llama_kv_cache() {
|
| 117 |
+
if (ctx) {
|
| 118 |
+
ggml_free(ctx);
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
};
|
| 122 |
|
| 123 |
struct llama_model {
|
|
|
|
| 133 |
std::vector<llama_layer> layers;
|
| 134 |
|
| 135 |
// context
|
| 136 |
+
struct ggml_context * ctx = NULL;
|
| 137 |
|
| 138 |
// key + value cache for the self attention
|
| 139 |
// TODO: move to llama_state
|
| 140 |
struct llama_kv_cache kv_self;
|
| 141 |
|
| 142 |
// the model memory buffer
|
| 143 |
+
llama_buffer buf;
|
| 144 |
+
|
| 145 |
+
// model memory mapped file
|
| 146 |
+
std::unique_ptr<llama_mmap> mapping;
|
| 147 |
+
|
| 148 |
+
// objects representing data potentially being locked in memory
|
| 149 |
+
llama_mlock mlock_buf;
|
| 150 |
+
llama_mlock mlock_mmap;
|
| 151 |
|
| 152 |
+
// for quantize-stats only
|
| 153 |
+
std::vector<std::pair<std::string, struct ggml_tensor *>> tensors_by_name;
|
| 154 |
+
|
| 155 |
+
~llama_model() {
|
| 156 |
+
if (ctx) {
|
| 157 |
+
ggml_free(ctx);
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
};
|
| 161 |
|
| 162 |
struct llama_vocab {
|
|
|
|
| 177 |
|
| 178 |
int64_t t_load_us = 0;
|
| 179 |
int64_t t_start_us = 0;
|
| 180 |
+
bool has_evaluated_once = false;
|
| 181 |
|
| 182 |
int64_t t_sample_us = 0;
|
| 183 |
int64_t t_eval_us = 0;
|
|
|
|
| 201 |
|
| 202 |
// memory buffers used to evaluate the model
|
| 203 |
// TODO: move in llama_state
|
| 204 |
+
llama_buffer buf_compute;
|
| 205 |
+
llama_buffer buf_scratch[LLAMA_MAX_SCRATCH_BUFFERS];
|
| 206 |
|
| 207 |
int buf_last = 0;
|
| 208 |
size_t buf_max_size[LLAMA_MAX_SCRATCH_BUFFERS] = { 0 };
|
|
|
|
| 215 |
last_size = ggml_set_scratch(ctx, { 0, 0, nullptr, });
|
| 216 |
} else {
|
| 217 |
auto & buf = buf_scratch[i];
|
| 218 |
+
last_size = ggml_set_scratch(ctx, { 0, buf.size, buf.addr, });
|
| 219 |
}
|
| 220 |
|
| 221 |
if (buf_last >= 0) {
|
|
|
|
| 239 |
}
|
| 240 |
};
|
| 241 |
|
| 242 |
+
template <typename T>
|
| 243 |
+
static T checked_mul(T a, T b) {
|
| 244 |
+
T ret = a * b;
|
| 245 |
+
if (a != 0 && ret / a != b) {
|
| 246 |
+
throw format("overflow multiplying %llu * %llu",
|
| 247 |
+
(unsigned long long) a, (unsigned long long) b);
|
| 248 |
+
}
|
| 249 |
+
return ret;
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
static size_t checked_div(size_t a, size_t b) {
|
| 253 |
+
if (b == 0 || a % b != 0) {
|
| 254 |
+
throw format("error dividing %zu / %zu", a, b);
|
| 255 |
+
}
|
| 256 |
+
return a / b;
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
static std::string llama_format_tensor_shape(const std::vector<uint32_t> & ne) {
|
| 260 |
+
std::string ret = "[" + std::to_string(ne.at(0));
|
| 261 |
+
for (size_t i = 1; i < ne.size(); i++) {
|
| 262 |
+
ret += " x " + std::to_string(ne.at(i));
|
| 263 |
+
}
|
| 264 |
+
ret += "]";
|
| 265 |
+
return ret;
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
static const char * llama_format_type(enum ggml_type type) {
|
| 269 |
+
switch (type) {
|
| 270 |
+
case GGML_TYPE_F32: return "f32";
|
| 271 |
+
case GGML_TYPE_F16: return "f16";
|
| 272 |
+
case GGML_TYPE_Q4_0: return "q4_0";
|
| 273 |
+
case GGML_TYPE_Q4_1: return "q4_1";
|
| 274 |
+
default: LLAMA_ASSERT(false);
|
| 275 |
+
}
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
static size_t llama_calc_tensor_size(const std::vector<uint32_t> & ne, enum ggml_type type) {
|
| 279 |
+
size_t size = ggml_type_size(type);
|
| 280 |
+
for (uint32_t dim : ne) {
|
| 281 |
+
size = checked_mul<size_t>(size, dim);
|
| 282 |
+
}
|
| 283 |
+
return size / ggml_blck_size(type);
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
struct llama_load_tensor_shard {
|
| 287 |
+
std::vector<uint32_t> ne;
|
| 288 |
+
size_t size;
|
| 289 |
+
enum ggml_type type;
|
| 290 |
+
size_t file_idx;
|
| 291 |
+
size_t file_off;
|
| 292 |
+
|
| 293 |
+
void calc_size() {
|
| 294 |
+
size = llama_calc_tensor_size(ne, type);
|
| 295 |
+
}
|
| 296 |
+
};
|
| 297 |
+
|
| 298 |
+
enum llama_split_type {
|
| 299 |
+
SPLIT_NONE,
|
| 300 |
+
SPLIT_BY_COLUMNS,
|
| 301 |
+
SPLIT_BY_ROWS
|
| 302 |
+
};
|
| 303 |
+
|
| 304 |
+
struct llama_load_tensor {
|
| 305 |
+
std::vector<llama_load_tensor_shard> shards;
|
| 306 |
+
|
| 307 |
+
std::string name;
|
| 308 |
+
enum ggml_type type = GGML_TYPE_F32;
|
| 309 |
+
llama_split_type split_type = SPLIT_NONE;
|
| 310 |
+
std::vector<uint32_t> ne;
|
| 311 |
+
size_t size;
|
| 312 |
+
struct ggml_tensor * ggml_tensor = NULL;
|
| 313 |
+
uint8_t * data;
|
| 314 |
+
|
| 315 |
+
llama_load_tensor(const std::string & name) : name(name) {}
|
| 316 |
+
|
| 317 |
+
void calc_all() {
|
| 318 |
+
calc_type();
|
| 319 |
+
calc_split_type();
|
| 320 |
+
calc_ne();
|
| 321 |
+
calc_size();
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
void calc_type() {
|
| 325 |
+
const auto & first_shard = shards.at(0);
|
| 326 |
+
for (const auto & shard : shards) {
|
| 327 |
+
if (shard.type != first_shard.type) {
|
| 328 |
+
throw format("inconsistent tensor shard type in '%s'", name.c_str());
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
type = first_shard.type;
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
void calc_split_type() {
|
| 335 |
+
if (shards.at(0).ne.size() == 1 || // 1D tensors are just duplicated in every file
|
| 336 |
+
shards.size() == 1) { // only one file?
|
| 337 |
+
split_type = SPLIT_NONE;
|
| 338 |
+
} else if (name.find("tok_embeddings.") == 0 ||
|
| 339 |
+
name.find(".attention.wo.weight") != std::string::npos ||
|
| 340 |
+
name.find(".feed_forward.w2.weight") != std::string::npos) {
|
| 341 |
+
split_type = SPLIT_BY_COLUMNS;
|
| 342 |
+
} else {
|
| 343 |
+
split_type = SPLIT_BY_ROWS;
|
| 344 |
+
}
|
| 345 |
+
}
|
| 346 |
+
|
| 347 |
+
void calc_ne() {
|
| 348 |
+
const auto & first_shard = shards.at(0);
|
| 349 |
+
for (const auto & shard : shards) {
|
| 350 |
+
if (shard.ne != first_shard.ne) {
|
| 351 |
+
throw format("inconsistent tensor shard shape in '%s': first was %s, other was %s",
|
| 352 |
+
name.c_str(), llama_format_tensor_shape(first_shard.ne).c_str(), llama_format_tensor_shape(shard.ne).c_str());
|
| 353 |
+
}
|
| 354 |
+
}
|
| 355 |
+
ne = first_shard.ne;
|
| 356 |
+
LLAMA_ASSERT(shards.size() <= UINT32_MAX);
|
| 357 |
+
uint32_t n_shards = (uint32_t) shards.size();
|
| 358 |
+
switch (split_type) {
|
| 359 |
+
case SPLIT_NONE:
|
| 360 |
+
ne = first_shard.ne;
|
| 361 |
+
break;
|
| 362 |
+
case SPLIT_BY_COLUMNS:
|
| 363 |
+
ne = {checked_mul<uint32_t>(first_shard.ne[0], n_shards),
|
| 364 |
+
first_shard.ne[1]};
|
| 365 |
+
break;
|
| 366 |
+
case SPLIT_BY_ROWS:
|
| 367 |
+
ne = {first_shard.ne[0],
|
| 368 |
+
checked_mul<uint32_t>(first_shard.ne[1], n_shards)};
|
| 369 |
+
break;
|
| 370 |
+
}
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
void calc_size() {
|
| 374 |
+
size = llama_calc_tensor_size(ne, type);
|
| 375 |
+
}
|
| 376 |
+
};
|
| 377 |
+
|
| 378 |
+
struct llama_load_tensors_map {
|
| 379 |
+
// tensors is kept in a separate vector to preserve file order
|
| 380 |
+
std::vector<llama_load_tensor> tensors;
|
| 381 |
+
std::unordered_map<std::string, size_t> name_to_idx;
|
| 382 |
+
};
|
| 383 |
+
|
| 384 |
+
enum llama_file_version {
|
| 385 |
+
LLAMA_FILE_VERSION_GGML,
|
| 386 |
+
LLAMA_FILE_VERSION_GGMF_V1, // added version field and scores in vocab
|
| 387 |
+
LLAMA_FILE_VERSION_GGJT_V1, // added padding
|
| 388 |
+
};
|
| 389 |
+
|
| 390 |
+
struct llama_file_loader {
|
| 391 |
+
llama_file file;
|
| 392 |
+
llama_file_version file_version;
|
| 393 |
+
llama_hparams hparams;
|
| 394 |
+
llama_vocab vocab;
|
| 395 |
+
|
| 396 |
+
llama_file_loader(const char * fname, size_t file_idx, llama_load_tensors_map & tensors_map)
|
| 397 |
+
: file(fname, "rb") {
|
| 398 |
+
fprintf(stderr, "llama.cpp: loading model from %s\n", fname);
|
| 399 |
+
read_magic();
|
| 400 |
+
read_hparams();
|
| 401 |
+
read_vocab();
|
| 402 |
+
read_tensor_metadata(file_idx, tensors_map);
|
| 403 |
+
}
|
| 404 |
+
void read_magic() {
|
| 405 |
+
uint32_t magic = file.read_u32();
|
| 406 |
+
uint32_t version = 0;
|
| 407 |
+
|
| 408 |
+
if (magic != 'ggml') {
|
| 409 |
+
version = file.read_u32();
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
if (magic == 'ggml' && version == 0) {
|
| 413 |
+
file_version = LLAMA_FILE_VERSION_GGML;
|
| 414 |
+
} else if (magic == 'ggmf' && version == 1) {
|
| 415 |
+
file_version = LLAMA_FILE_VERSION_GGMF_V1;
|
| 416 |
+
} else if (magic == 'ggjt' && version == 1) {
|
| 417 |
+
file_version = LLAMA_FILE_VERSION_GGJT_V1;
|
| 418 |
+
} else {
|
| 419 |
+
throw format("unknown (magic, version) combination: %08x, %08x; is this really a GGML file?",
|
| 420 |
+
magic, version);
|
| 421 |
+
}
|
| 422 |
+
}
|
| 423 |
+
void read_hparams() {
|
| 424 |
+
hparams.n_vocab = file.read_u32();
|
| 425 |
+
hparams.n_embd = file.read_u32();
|
| 426 |
+
hparams.n_mult = file.read_u32();
|
| 427 |
+
hparams.n_head = file.read_u32();
|
| 428 |
+
hparams.n_layer = file.read_u32();
|
| 429 |
+
hparams.n_rot = file.read_u32();
|
| 430 |
+
hparams.f16 = file.read_u32();
|
| 431 |
+
}
|
| 432 |
+
void read_vocab() {
|
| 433 |
+
vocab.id_to_token.resize(hparams.n_vocab);
|
| 434 |
+
|
| 435 |
+
for (uint32_t i = 0; i < hparams.n_vocab; i++) {
|
| 436 |
+
uint32_t len = file.read_u32();
|
| 437 |
+
std::string word = file.read_string(len);
|
| 438 |
+
|
| 439 |
+
float score = 0.0f;
|
| 440 |
+
if (file_version >= LLAMA_FILE_VERSION_GGMF_V1) {
|
| 441 |
+
file.read_raw(&score, sizeof(score));
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
vocab.token_to_id[word] = i;
|
| 445 |
+
|
| 446 |
+
auto & tok_score = vocab.id_to_token[i];
|
| 447 |
+
tok_score.tok = std::move(word);
|
| 448 |
+
tok_score.score = score;
|
| 449 |
+
}
|
| 450 |
+
}
|
| 451 |
+
void read_tensor_metadata(size_t file_idx, llama_load_tensors_map & tensors_map) {
|
| 452 |
+
while (file.tell() < file.size) {
|
| 453 |
+
llama_load_tensor_shard shard;
|
| 454 |
+
uint32_t n_dims = file.read_u32();
|
| 455 |
+
uint32_t name_len = file.read_u32();
|
| 456 |
+
uint32_t ftype = file.read_u32();
|
| 457 |
+
shard.ne.resize(n_dims);
|
| 458 |
+
file.read_raw(shard.ne.data(), sizeof(shard.ne[0]) * n_dims);
|
| 459 |
+
std::string name = file.read_string(name_len);
|
| 460 |
+
if (n_dims < 1 || n_dims > 2) {
|
| 461 |
+
throw format("llama.cpp: tensor '%s' should not be %u-dimensional", name.c_str(), n_dims);
|
| 462 |
+
}
|
| 463 |
+
switch (ftype) {
|
| 464 |
+
case 0: shard.type = GGML_TYPE_F32; break;
|
| 465 |
+
case 1: shard.type = GGML_TYPE_F16; break;
|
| 466 |
+
case 2: shard.type = GGML_TYPE_Q4_0; break;
|
| 467 |
+
case 3: shard.type = GGML_TYPE_Q4_1; break;
|
| 468 |
+
default: {
|
| 469 |
+
throw format("unrecognized ftype %u\n", ftype);
|
| 470 |
+
}
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
if (file_version >= LLAMA_FILE_VERSION_GGJT_V1) {
|
| 474 |
+
// skip to the next multiple of 32 bytes
|
| 475 |
+
file.seek(-file.tell() & 31, SEEK_CUR);
|
| 476 |
+
}
|
| 477 |
+
shard.file_idx = file_idx;
|
| 478 |
+
shard.file_off = file.tell();
|
| 479 |
+
|
| 480 |
+
shard.calc_size();
|
| 481 |
+
file.seek(shard.size, SEEK_CUR);
|
| 482 |
+
|
| 483 |
+
auto it = tensors_map.name_to_idx.find(name);
|
| 484 |
+
size_t idx;
|
| 485 |
+
if (it != tensors_map.name_to_idx.end()) {
|
| 486 |
+
idx = it->second;
|
| 487 |
+
} else {
|
| 488 |
+
tensors_map.tensors.emplace_back(name);
|
| 489 |
+
idx = tensors_map.tensors.size() - 1;
|
| 490 |
+
tensors_map.name_to_idx.emplace(name, idx);
|
| 491 |
+
}
|
| 492 |
+
tensors_map.tensors.at(idx).shards.push_back(shard);
|
| 493 |
+
}
|
| 494 |
+
}
|
| 495 |
+
};
|
| 496 |
+
|
| 497 |
+
struct llama_file_saver {
|
| 498 |
+
llama_file file;
|
| 499 |
+
llama_file_loader * any_file_loader;
|
| 500 |
+
llama_file_saver(const char * fname, llama_file_loader * any_file_loader, uint32_t new_f16)
|
| 501 |
+
: file(fname, "wb"), any_file_loader(any_file_loader) {
|
| 502 |
+
fprintf(stderr, "llama.cpp: saving model to %s\n", fname);
|
| 503 |
+
write_magic();
|
| 504 |
+
write_hparams(new_f16);
|
| 505 |
+
write_vocab();
|
| 506 |
+
}
|
| 507 |
+
void write_magic() {
|
| 508 |
+
file.write_u32('ggjt'); // magic
|
| 509 |
+
file.write_u32(1); // version
|
| 510 |
+
}
|
| 511 |
+
void write_hparams(uint32_t new_f16) {
|
| 512 |
+
const llama_hparams & hparams = any_file_loader->hparams;
|
| 513 |
+
file.write_u32(hparams.n_vocab);
|
| 514 |
+
file.write_u32(hparams.n_embd);
|
| 515 |
+
file.write_u32(hparams.n_mult);
|
| 516 |
+
file.write_u32(hparams.n_head);
|
| 517 |
+
file.write_u32(hparams.n_layer);
|
| 518 |
+
file.write_u32(hparams.n_rot);
|
| 519 |
+
file.write_u32(new_f16);
|
| 520 |
+
}
|
| 521 |
+
void write_vocab() {
|
| 522 |
+
if (any_file_loader->file_version == LLAMA_FILE_VERSION_GGML) {
|
| 523 |
+
fprintf(stderr, "llama.cpp: WARNING: input is an old file that doesn't have scores; will add dummy scores\n");
|
| 524 |
+
}
|
| 525 |
+
uint32_t n_vocab = any_file_loader->hparams.n_vocab;
|
| 526 |
+
for (uint32_t i = 0; i < n_vocab; i++) {
|
| 527 |
+
const auto & token_score = any_file_loader->vocab.id_to_token.at(i);
|
| 528 |
+
file.write_u32((uint32_t) token_score.tok.size());
|
| 529 |
+
file.write_raw(token_score.tok.data(), token_score.tok.size());
|
| 530 |
+
file.write_raw(&token_score.score, sizeof(token_score.score));
|
| 531 |
+
}
|
| 532 |
+
}
|
| 533 |
+
void write_tensor(llama_load_tensor & tensor, enum ggml_type new_type, const void * new_data, size_t new_size) {
|
| 534 |
+
uint32_t ftype;
|
| 535 |
+
switch (new_type) {
|
| 536 |
+
case GGML_TYPE_F32: ftype = 0; break;
|
| 537 |
+
case GGML_TYPE_F16: ftype = 1; break;
|
| 538 |
+
case GGML_TYPE_Q4_0: ftype = 2; break;
|
| 539 |
+
case GGML_TYPE_Q4_1: ftype = 3; break;
|
| 540 |
+
default: LLAMA_ASSERT(false);
|
| 541 |
+
}
|
| 542 |
+
file.write_u32((uint32_t) tensor.ne.size());
|
| 543 |
+
file.write_u32((uint32_t) tensor.name.size());
|
| 544 |
+
file.write_u32(ftype);
|
| 545 |
+
file.write_raw(tensor.ne.data(), sizeof(tensor.ne[0]) * tensor.ne.size());
|
| 546 |
+
file.write_raw(tensor.name.data(), tensor.name.size());
|
| 547 |
+
file.seek(-file.tell() & 31, SEEK_CUR);
|
| 548 |
+
LLAMA_ASSERT(new_size == llama_calc_tensor_size(tensor.ne, new_type));
|
| 549 |
+
file.write_raw(new_data, new_size);
|
| 550 |
+
}
|
| 551 |
+
};
|
| 552 |
+
|
| 553 |
+
struct llama_model_loader {
|
| 554 |
+
std::vector<std::unique_ptr<llama_file_loader>> file_loaders;
|
| 555 |
+
llama_load_tensors_map tensors_map;
|
| 556 |
+
bool use_mmap;
|
| 557 |
+
size_t num_ggml_tensors_created = 0;
|
| 558 |
+
struct ggml_context * ggml_ctx = NULL;
|
| 559 |
+
std::unique_ptr<llama_mmap> mapping;
|
| 560 |
+
|
| 561 |
+
llama_model_loader(const std::string & fname_base, bool use_mmap, bool vocab_only) {
|
| 562 |
+
auto first_file = new llama_file_loader(fname_base.c_str(), 0, tensors_map);
|
| 563 |
+
file_loaders.emplace_back(first_file);
|
| 564 |
+
uint32_t n_parts = vocab_only ? 1 : guess_n_parts();
|
| 565 |
+
for (uint32_t i = 1; i < n_parts; i++) {
|
| 566 |
+
std::string fname = fname_base + "." + std::to_string(i);
|
| 567 |
+
auto ith_file = new llama_file_loader(fname.c_str(), i, tensors_map);
|
| 568 |
+
file_loaders.emplace_back(ith_file);
|
| 569 |
+
if (ith_file->hparams != first_file->hparams) {
|
| 570 |
+
throw format("llama.cpp: hparams inconsistent between files");
|
| 571 |
+
}
|
| 572 |
+
}
|
| 573 |
+
if (!llama_mmap::SUPPORTED) {
|
| 574 |
+
use_mmap = false;
|
| 575 |
+
}
|
| 576 |
+
if (use_mmap && alignment_prevents_mmap()) {
|
| 577 |
+
fprintf(stderr, "llama.cpp: can't use mmap because tensors are not aligned; convert to new format to avoid this\n");
|
| 578 |
+
use_mmap = false;
|
| 579 |
+
}
|
| 580 |
+
this->use_mmap = use_mmap;
|
| 581 |
+
for (llama_load_tensor & lt : tensors_map.tensors) {
|
| 582 |
+
lt.calc_all();
|
| 583 |
+
}
|
| 584 |
+
}
|
| 585 |
+
|
| 586 |
+
bool alignment_prevents_mmap() {
|
| 587 |
+
for (const llama_load_tensor & lt : tensors_map.tensors) {
|
| 588 |
+
for (const llama_load_tensor_shard & shard : lt.shards) {
|
| 589 |
+
if (shard.file_off & 3) {
|
| 590 |
+
return true;
|
| 591 |
+
}
|
| 592 |
+
}
|
| 593 |
+
}
|
| 594 |
+
return false;
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
uint32_t guess_n_parts() const {
|
| 598 |
+
auto it = tensors_map.name_to_idx.find("tok_embeddings.weight");
|
| 599 |
+
if (it == tensors_map.name_to_idx.end()) {
|
| 600 |
+
throw std::string("missing tok_embeddings.weight");
|
| 601 |
+
}
|
| 602 |
+
const llama_load_tensor & lt = tensors_map.tensors.at(it->second);
|
| 603 |
+
return file_loaders.at(0)->hparams.n_embd / lt.shards.at(0).ne.at(0);
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
void calc_sizes(size_t * ctx_size_p, size_t * mmapped_size_p) const {
|
| 607 |
+
*ctx_size_p = *mmapped_size_p = 0;
|
| 608 |
+
for (const llama_load_tensor & lt : tensors_map.tensors) {
|
| 609 |
+
*ctx_size_p += sizeof(struct ggml_tensor) + GGML_OBJECT_SIZE;
|
| 610 |
+
*(use_mmap ? mmapped_size_p : ctx_size_p) += lt.size;
|
| 611 |
+
}
|
| 612 |
+
}
|
| 613 |
+
|
| 614 |
+
struct ggml_tensor * get_tensor(const std::string & name, std::vector<uint32_t> ne) {
|
| 615 |
+
auto it = tensors_map.name_to_idx.find(name);
|
| 616 |
+
if (it == tensors_map.name_to_idx.end()) {
|
| 617 |
+
throw format("llama.cpp: tensor '%s' is missing from model", name.c_str());
|
| 618 |
+
}
|
| 619 |
+
llama_load_tensor & lt = tensors_map.tensors.at(it->second);
|
| 620 |
+
if (lt.ne != ne) {
|
| 621 |
+
throw format("llama.cpp: tensor '%s' has wrong shape; expected %s, got %s",
|
| 622 |
+
name.c_str(), llama_format_tensor_shape(ne).c_str(), llama_format_tensor_shape(lt.ne).c_str());
|
| 623 |
+
}
|
| 624 |
+
return get_tensor_for(lt);
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
struct ggml_tensor * get_tensor_for(llama_load_tensor & lt) {
|
| 628 |
+
struct ggml_tensor * tensor;
|
| 629 |
+
if (lt.ne.size() == 2) {
|
| 630 |
+
tensor = ggml_new_tensor_2d(ggml_ctx, lt.type, lt.ne.at(0), lt.ne.at(1));
|
| 631 |
+
} else {
|
| 632 |
+
LLAMA_ASSERT(lt.ne.size() == 1);
|
| 633 |
+
tensor = ggml_new_tensor_1d(ggml_ctx, lt.type, lt.ne.at(0));
|
| 634 |
+
}
|
| 635 |
+
LLAMA_ASSERT(lt.ggml_tensor == NULL); // if this fails, we called get_tensor twice on the same tensor
|
| 636 |
+
lt.ggml_tensor = tensor;
|
| 637 |
+
num_ggml_tensors_created++;
|
| 638 |
+
return tensor;
|
| 639 |
+
}
|
| 640 |
+
|
| 641 |
+
void done_getting_tensors() {
|
| 642 |
+
if (num_ggml_tensors_created != tensors_map.tensors.size()) {
|
| 643 |
+
throw std::string("llama.cpp: file contained more tensors than expected");
|
| 644 |
+
}
|
| 645 |
+
}
|
| 646 |
+
|
| 647 |
+
void load_all_data(llama_progress_callback progress_callback, void * progress_callback_user_data, llama_mlock * lmlock) {
|
| 648 |
+
size_t data_size = 0;
|
| 649 |
+
for (const llama_load_tensor & lt : tensors_map.tensors) {
|
| 650 |
+
data_size += lt.size;
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
if (use_mmap) {
|
| 654 |
+
mapping.reset(new llama_mmap(&file_loaders.at(0)->file));
|
| 655 |
+
if (!lmlock) {
|
| 656 |
+
// Don't call the callback since the actual loading will be lazy
|
| 657 |
+
// and we can't measure it.
|
| 658 |
+
progress_callback = NULL;
|
| 659 |
+
}
|
| 660 |
+
if (lmlock) {
|
| 661 |
+
lmlock->init(mapping->addr);
|
| 662 |
+
}
|
| 663 |
+
}
|
| 664 |
+
|
| 665 |
+
size_t done_size = 0;
|
| 666 |
+
for (llama_load_tensor & lt : tensors_map.tensors) {
|
| 667 |
+
if (progress_callback) {
|
| 668 |
+
progress_callback((float) done_size / data_size, progress_callback_user_data);
|
| 669 |
+
}
|
| 670 |
+
LLAMA_ASSERT(lt.ggml_tensor); // unused tensors should have been caught by load_data already
|
| 671 |
+
lt.data = (uint8_t *) lt.ggml_tensor->data;
|
| 672 |
+
load_data_for(lt);
|
| 673 |
+
lt.ggml_tensor->data = lt.data;
|
| 674 |
+
done_size += lt.size;
|
| 675 |
+
if (use_mmap && lmlock) {
|
| 676 |
+
lmlock->grow_to(done_size);
|
| 677 |
+
}
|
| 678 |
+
}
|
| 679 |
+
if (progress_callback) {
|
| 680 |
+
progress_callback(1.0f, progress_callback_user_data);
|
| 681 |
+
}
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
void load_data_for(llama_load_tensor & lt) {
|
| 685 |
+
if (use_mmap) {
|
| 686 |
+
LLAMA_ASSERT(lt.shards.size() == 1);
|
| 687 |
+
lt.data = (uint8_t *) mapping->addr + lt.shards.at(0).file_off;
|
| 688 |
+
} else if (lt.split_type == SPLIT_NONE) {
|
| 689 |
+
llama_file & file = file_loaders.at(lt.shards.at(0).file_idx)->file;
|
| 690 |
+
file.seek(lt.shards.at(0).file_off, SEEK_SET);
|
| 691 |
+
file.read_raw(lt.data, lt.size);
|
| 692 |
+
} else if (lt.split_type == SPLIT_BY_ROWS) {
|
| 693 |
+
size_t offset = 0;
|
| 694 |
+
for (llama_load_tensor_shard & shard : lt.shards) {
|
| 695 |
+
llama_file & file = file_loaders.at(shard.file_idx)->file;
|
| 696 |
+
file.seek(shard.file_off, SEEK_SET);
|
| 697 |
+
file.read_raw(lt.data + offset, shard.size);
|
| 698 |
+
offset += shard.size;
|
| 699 |
+
}
|
| 700 |
+
LLAMA_ASSERT(offset == lt.size);
|
| 701 |
+
} else if (lt.split_type == SPLIT_BY_COLUMNS) {
|
| 702 |
+
// Let's load the data into temporary buffers to ensure the OS performs large loads.
|
| 703 |
+
std::vector<llama_buffer> tmp_bufs;
|
| 704 |
+
tmp_bufs.resize(lt.shards.size());
|
| 705 |
+
for (size_t i = 0; i < lt.shards.size(); i++) {
|
| 706 |
+
llama_load_tensor_shard & shard = lt.shards.at(i);
|
| 707 |
+
llama_file & file = file_loaders.at(shard.file_idx)->file;
|
| 708 |
+
file.seek(shard.file_off, SEEK_SET);
|
| 709 |
+
tmp_bufs.at(i).resize(shard.size);
|
| 710 |
+
file.read_raw(tmp_bufs.at(i).addr, shard.size);
|
| 711 |
+
}
|
| 712 |
+
// Then reshape.
|
| 713 |
+
size_t num_rows = lt.ne.at(1);
|
| 714 |
+
size_t per_shard_row_size = lt.shards.at(0).size / num_rows;
|
| 715 |
+
size_t out_offset = 0;
|
| 716 |
+
for (size_t row = 0; row < num_rows; row++) {
|
| 717 |
+
for (llama_buffer & tmp_buf : tmp_bufs) {
|
| 718 |
+
memcpy(lt.data + out_offset,
|
| 719 |
+
tmp_buf.addr + row * per_shard_row_size,
|
| 720 |
+
per_shard_row_size);
|
| 721 |
+
out_offset += per_shard_row_size;
|
| 722 |
+
}
|
| 723 |
+
}
|
| 724 |
+
LLAMA_ASSERT(out_offset == lt.size);
|
| 725 |
+
}
|
| 726 |
+
if (0) {
|
| 727 |
+
print_checksum(lt);
|
| 728 |
+
}
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
static void print_checksum(llama_load_tensor & lt) {
|
| 732 |
+
uint32_t sum = 0;
|
| 733 |
+
for (size_t i = 0; i < lt.size; i++) {
|
| 734 |
+
uint8_t byte = lt.data[i];
|
| 735 |
+
sum = byte + (sum << 6) + (sum << 16) - sum; // sdbm hash
|
| 736 |
+
}
|
| 737 |
+
fprintf(stderr, "%s checksum: %#08x (%s, size %zu)\n", lt.name.c_str(), sum,
|
| 738 |
+
llama_format_tensor_shape(lt.ne).c_str(), lt.size);
|
| 739 |
+
}
|
| 740 |
+
|
| 741 |
+
};
|
| 742 |
+
|
| 743 |
+
|
| 744 |
//
|
| 745 |
// kv cache
|
| 746 |
//
|
|
|
|
| 753 |
const int n_embd = hparams.n_embd;
|
| 754 |
const int n_layer = hparams.n_layer;
|
| 755 |
|
| 756 |
+
const int64_t n_mem = (int64_t)n_layer*n_ctx;
|
| 757 |
+
const int64_t n_elements = n_embd*n_mem;
|
| 758 |
|
| 759 |
cache.buf.resize(2u*n_elements*ggml_type_size(wtype) + 2u*MB);
|
| 760 |
|
| 761 |
struct ggml_init_params params;
|
| 762 |
+
params.mem_size = cache.buf.size;
|
| 763 |
+
params.mem_buffer = cache.buf.addr;
|
| 764 |
+
params.no_alloc = false;
|
| 765 |
|
| 766 |
cache.ctx = ggml_init(params);
|
| 767 |
|
|
|
|
| 776 |
return true;
|
| 777 |
}
|
| 778 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 779 |
struct llama_context_params llama_context_default_params() {
|
| 780 |
struct llama_context_params result = {
|
| 781 |
/*.n_ctx =*/ 512,
|
|
|
|
| 784 |
/*.f16_kv =*/ false,
|
| 785 |
/*.logits_all =*/ false,
|
| 786 |
/*.vocab_only =*/ false,
|
| 787 |
+
/*.use_mmap =*/ true,
|
| 788 |
/*.use_mlock =*/ false,
|
| 789 |
/*.embedding =*/ false,
|
| 790 |
/*.progress_callback =*/ nullptr,
|
|
|
|
| 794 |
return result;
|
| 795 |
}
|
| 796 |
|
| 797 |
+
bool llama_mmap_supported() {
|
| 798 |
+
return llama_mmap::SUPPORTED;
|
| 799 |
+
}
|
| 800 |
+
|
| 801 |
+
bool llama_mlock_supported() {
|
| 802 |
+
return llama_mlock::SUPPORTED;
|
| 803 |
+
}
|
| 804 |
+
|
| 805 |
//
|
| 806 |
// model loading
|
| 807 |
//
|
| 808 |
|
| 809 |
+
static const char *llama_file_version_name(llama_file_version version) {
|
| 810 |
+
switch (version) {
|
| 811 |
+
case LLAMA_FILE_VERSION_GGML: return "'ggml' (old version with low tokenizer quality and no mmap support)";
|
| 812 |
+
case LLAMA_FILE_VERSION_GGMF_V1: return "ggmf v1 (old version with no mmap support)";
|
| 813 |
+
case LLAMA_FILE_VERSION_GGJT_V1: return "ggjt v1 (latest)";
|
| 814 |
+
default: LLAMA_ASSERT(false);
|
| 815 |
+
}
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
static const char *llama_model_type_name(e_model type) {
|
| 819 |
+
switch (type) {
|
| 820 |
+
case MODEL_7B: return "7B";
|
| 821 |
+
case MODEL_13B: return "13B";
|
| 822 |
+
case MODEL_30B: return "30B";
|
| 823 |
+
case MODEL_65B: return "65B";
|
| 824 |
+
default: LLAMA_ASSERT(false);
|
| 825 |
+
}
|
| 826 |
+
}
|
| 827 |
+
|
| 828 |
+
static void llama_model_load_internal(
|
| 829 |
const std::string & fname,
|
| 830 |
llama_context & lctx,
|
| 831 |
int n_ctx,
|
|
|
|
| 832 |
ggml_type memory_type,
|
| 833 |
+
bool use_mmap,
|
| 834 |
+
bool use_mlock,
|
| 835 |
bool vocab_only,
|
| 836 |
llama_progress_callback progress_callback,
|
| 837 |
+
void * progress_callback_user_data) {
|
|
|
|
|
|
|
|
|
|
| 838 |
|
| 839 |
+
lctx.t_start_us = ggml_time_us();
|
| 840 |
|
| 841 |
+
std::unique_ptr<llama_model_loader> ml(new llama_model_loader(fname, use_mmap, vocab_only));
|
| 842 |
|
| 843 |
+
lctx.vocab = std::move(ml->file_loaders.at(0)->vocab);
|
| 844 |
auto & model = lctx.model;
|
| 845 |
+
model.hparams = ml->file_loaders.at(0)->hparams;
|
| 846 |
+
llama_file_version file_version = ml->file_loaders.at(0)->file_version;
|
| 847 |
+
auto & hparams = model.hparams;
|
| 848 |
+
uint32_t n_ff = ((2*(4*hparams.n_embd)/3 + hparams.n_mult - 1)/hparams.n_mult)*hparams.n_mult;
|
| 849 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 850 |
{
|
| 851 |
+
switch (hparams.n_layer) {
|
| 852 |
+
case 32: model.type = e_model::MODEL_7B; break;
|
| 853 |
+
case 40: model.type = e_model::MODEL_13B; break;
|
| 854 |
+
case 60: model.type = e_model::MODEL_30B; break;
|
| 855 |
+
case 80: model.type = e_model::MODEL_65B; break;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 856 |
}
|
| 857 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 858 |
hparams.n_ctx = n_ctx;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 859 |
}
|
| 860 |
|
|
|
|
| 861 |
{
|
| 862 |
+
fprintf(stderr, "%s: format = %s\n", __func__, llama_file_version_name(file_version));
|
| 863 |
+
fprintf(stderr, "%s: n_vocab = %u\n", __func__, hparams.n_vocab);
|
| 864 |
+
fprintf(stderr, "%s: n_ctx = %u\n", __func__, hparams.n_ctx);
|
| 865 |
+
fprintf(stderr, "%s: n_embd = %u\n", __func__, hparams.n_embd);
|
| 866 |
+
fprintf(stderr, "%s: n_mult = %u\n", __func__, hparams.n_mult);
|
| 867 |
+
fprintf(stderr, "%s: n_head = %u\n", __func__, hparams.n_head);
|
| 868 |
+
fprintf(stderr, "%s: n_layer = %u\n", __func__, hparams.n_layer);
|
| 869 |
+
fprintf(stderr, "%s: n_rot = %u\n", __func__, hparams.n_rot);
|
| 870 |
+
fprintf(stderr, "%s: f16 = %u\n", __func__, hparams.f16);
|
| 871 |
+
fprintf(stderr, "%s: n_ff = %u\n", __func__, n_ff);
|
| 872 |
+
fprintf(stderr, "%s: n_parts = %zu\n", __func__, ml->file_loaders.size());
|
| 873 |
+
fprintf(stderr, "%s: model size = %s\n", __func__, llama_model_type_name(model.type));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 874 |
}
|
| 875 |
|
| 876 |
if (vocab_only) {
|
| 877 |
+
return;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 878 |
}
|
| 879 |
|
| 880 |
auto & ctx = model.ctx;
|
| 881 |
|
| 882 |
+
size_t ctx_size, mmapped_size;
|
| 883 |
+
ml->calc_sizes(&ctx_size, &mmapped_size);
|
| 884 |
+
fprintf(stderr, "%s: ggml ctx size = %6.2f KB\n", __func__, ctx_size/1024.0);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 885 |
|
| 886 |
// print memory requirements
|
| 887 |
{
|
|
|
|
| 890 |
// this is the total memory required to run the inference
|
| 891 |
const size_t mem_required =
|
| 892 |
ctx_size +
|
| 893 |
+
mmapped_size +
|
| 894 |
MEM_REQ_SCRATCH0.at(model.type) +
|
| 895 |
MEM_REQ_SCRATCH1.at(model.type) +
|
| 896 |
MEM_REQ_EVAL.at (model.type);
|
|
|
|
| 906 |
// create the ggml context
|
| 907 |
{
|
| 908 |
lctx.model.buf.resize(ctx_size);
|
| 909 |
+
if (use_mlock) {
|
| 910 |
+
lctx.model.mlock_buf.init(lctx.model.buf.addr);
|
| 911 |
+
lctx.model.mlock_buf.grow_to(lctx.model.buf.size);
|
| 912 |
+
}
|
| 913 |
|
| 914 |
struct ggml_init_params params = {
|
| 915 |
+
/*.mem_size =*/ lctx.model.buf.size,
|
| 916 |
+
/*.mem_buffer =*/ lctx.model.buf.addr,
|
| 917 |
+
/*.no_alloc =*/ ml->use_mmap,
|
| 918 |
};
|
| 919 |
|
| 920 |
model.ctx = ggml_init(params);
|
| 921 |
if (!model.ctx) {
|
| 922 |
+
throw format("ggml_init() failed");
|
|
|
|
| 923 |
}
|
| 924 |
}
|
| 925 |
|
|
|
|
| 927 |
{
|
| 928 |
const auto & hparams = model.hparams;
|
| 929 |
|
| 930 |
+
const uint32_t n_embd = hparams.n_embd;
|
| 931 |
+
const uint32_t n_layer = hparams.n_layer;
|
| 932 |
+
const uint32_t n_vocab = hparams.n_vocab;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 933 |
|
| 934 |
+
ml->ggml_ctx = ctx;
|
|
|
|
| 935 |
|
| 936 |
+
model.tok_embeddings = ml->get_tensor("tok_embeddings.weight", {n_embd, n_vocab});
|
| 937 |
+
model.norm = ml->get_tensor("norm.weight", {n_embd});
|
| 938 |
+
model.output = ml->get_tensor("output.weight", {n_embd, n_vocab});
|
| 939 |
|
| 940 |
+
model.layers.resize(n_layer);
|
| 941 |
+
for (uint32_t i = 0; i < n_layer; ++i) {
|
|
|
|
|
|
|
| 942 |
auto & layer = model.layers[i];
|
| 943 |
|
| 944 |
+
std::string layers_i = "layers." + std::to_string(i);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 945 |
|
| 946 |
+
layer.attention_norm = ml->get_tensor(layers_i + ".attention_norm.weight", {n_embd});
|
| 947 |
|
| 948 |
+
layer.wq = ml->get_tensor(layers_i + ".attention.wq.weight", {n_embd, n_embd});
|
| 949 |
+
layer.wk = ml->get_tensor(layers_i + ".attention.wk.weight", {n_embd, n_embd});
|
| 950 |
+
layer.wv = ml->get_tensor(layers_i + ".attention.wv.weight", {n_embd, n_embd});
|
| 951 |
+
layer.wo = ml->get_tensor(layers_i + ".attention.wo.weight", {n_embd, n_embd});
|
| 952 |
|
| 953 |
+
layer.ffn_norm = ml->get_tensor(layers_i + ".ffn_norm.weight", {n_embd});
|
|
|
|
| 954 |
|
| 955 |
+
layer.w1 = ml->get_tensor(layers_i + ".feed_forward.w1.weight", {n_embd, n_ff});
|
| 956 |
+
layer.w2 = ml->get_tensor(layers_i + ".feed_forward.w2.weight", { n_ff, n_embd});
|
| 957 |
+
layer.w3 = ml->get_tensor(layers_i + ".feed_forward.w3.weight", {n_embd, n_ff});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 958 |
}
|
| 959 |
}
|
| 960 |
|
| 961 |
+
ml->done_getting_tensors();
|
|
|
|
|
|
|
| 962 |
|
| 963 |
+
// populate `tensors_by_name`
|
| 964 |
+
for (llama_load_tensor & lt : ml->tensors_map.tensors) {
|
| 965 |
+
model.tensors_by_name.emplace_back(lt.name, lt.ggml_tensor);
|
|
|
|
| 966 |
}
|
| 967 |
|
| 968 |
+
ml->load_all_data(progress_callback, progress_callback_user_data, use_mlock ? &lctx.model.mlock_mmap : NULL);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 969 |
|
| 970 |
+
model.mapping = std::move(ml->mapping);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 971 |
|
| 972 |
+
// loading time will be recalculate after the first eval, so
|
| 973 |
+
// we take page faults deferred by mmap() into consideration
|
| 974 |
+
lctx.t_load_us = ggml_time_us() - lctx.t_start_us;
|
| 975 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 976 |
|
| 977 |
+
static bool llama_model_load(
|
| 978 |
+
const std::string & fname,
|
| 979 |
+
llama_context & lctx,
|
| 980 |
+
int n_ctx,
|
| 981 |
+
ggml_type memory_type,
|
| 982 |
+
bool use_mmap,
|
| 983 |
+
bool use_mlock,
|
| 984 |
+
bool vocab_only,
|
| 985 |
+
llama_progress_callback progress_callback,
|
| 986 |
+
void *progress_callback_user_data) {
|
| 987 |
+
try {
|
| 988 |
+
llama_model_load_internal(fname, lctx, n_ctx, memory_type, use_mmap, use_mlock,
|
| 989 |
+
vocab_only, progress_callback, progress_callback_user_data);
|
| 990 |
+
return true;
|
| 991 |
+
} catch (const std::string & err) {
|
| 992 |
+
fprintf(stderr, "error loading model: %s\n", err.c_str());
|
| 993 |
+
return false;
|
| 994 |
}
|
|
|
|
|
|
|
| 995 |
}
|
| 996 |
|
| 997 |
// evaluate the transformer
|
|
|
|
| 1029 |
auto & buf_compute = lctx.buf_compute;
|
| 1030 |
|
| 1031 |
struct ggml_init_params params = {
|
| 1032 |
+
/*.mem_size =*/ buf_compute.size,
|
| 1033 |
+
/*.mem_buffer =*/ buf_compute.addr,
|
| 1034 |
+
/*.no_alloc =*/ false,
|
| 1035 |
};
|
| 1036 |
|
| 1037 |
struct ggml_context * ctx0 = ggml_init(params);
|
|
|
|
| 1039 |
// for big prompts, if BLAS is enabled, it is better to use only one thread
|
| 1040 |
// otherwise, the threads are spin-lock waiting for the BLAS calls and are degrading the performance
|
| 1041 |
ggml_cgraph gf = {};
|
| 1042 |
+
gf.n_threads = N >= 32 && ggml_cpu_has_blas() ? 1 : n_threads;
|
| 1043 |
|
| 1044 |
struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
|
| 1045 |
memcpy(embd->data, tokens, N*ggml_element_size(embd));
|
|
|
|
| 1065 |
|
| 1066 |
// self-attention
|
| 1067 |
{
|
| 1068 |
+
// compute Q and K and RoPE them
|
| 1069 |
+
struct ggml_tensor * Qcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wq, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
|
| 1070 |
+
struct ggml_tensor * Kcur = ggml_rope(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wk, cur), n_embd/n_head, n_head, N), n_past, n_rot, 0);
|
| 1071 |
|
| 1072 |
// store key and value to memory
|
| 1073 |
+
{
|
| 1074 |
+
// compute the transposed [N, n_embd] V matrix
|
| 1075 |
+
struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, model.layers[il].wv, cur), n_embd, N));
|
| 1076 |
+
|
| 1077 |
struct ggml_tensor * k = ggml_view_1d(ctx0, kv_self.k, N*n_embd, (ggml_element_size(kv_self.k)*n_embd)*(il*n_ctx + n_past));
|
| 1078 |
+
struct ggml_tensor * v = ggml_view_2d(ctx0, kv_self.v, N, n_embd,
|
| 1079 |
+
( n_ctx)*ggml_element_size(kv_self.v),
|
| 1080 |
+
(il*n_ctx)*ggml_element_size(kv_self.v)*n_embd + n_past*ggml_element_size(kv_self.v));
|
| 1081 |
|
| 1082 |
+
// important: storing RoPE-ed version of K in the KV cache!
|
| 1083 |
ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
|
| 1084 |
ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
|
| 1085 |
}
|
| 1086 |
|
|
|
|
| 1087 |
struct ggml_tensor * Q =
|
| 1088 |
ggml_permute(ctx0,
|
| 1089 |
+
Qcur,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1090 |
0, 2, 1, 3);
|
| 1091 |
|
|
|
|
| 1092 |
struct ggml_tensor * K =
|
| 1093 |
ggml_permute(ctx0,
|
| 1094 |
+
ggml_reshape_3d(ctx0,
|
| 1095 |
+
ggml_view_1d(ctx0, kv_self.k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(kv_self.k)*n_embd),
|
| 1096 |
+
n_embd/n_head, n_head, n_past + N),
|
|
|
|
|
|
|
| 1097 |
0, 2, 1, 3);
|
| 1098 |
|
| 1099 |
// K * Q
|
|
|
|
| 1103 |
struct ggml_tensor * KQ_scaled =
|
| 1104 |
ggml_scale(ctx0,
|
| 1105 |
KQ,
|
| 1106 |
+
ggml_new_f32(ctx0, 1.0f/sqrtf(float(n_embd)/n_head)));
|
| 1107 |
|
| 1108 |
// KQ_masked = mask_past(KQ_scaled)
|
| 1109 |
struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
|
|
|
|
| 1111 |
// KQ = soft_max(KQ_masked)
|
| 1112 |
struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
|
| 1113 |
|
| 1114 |
+
// split cached V into n_head heads
|
| 1115 |
+
struct ggml_tensor * V =
|
| 1116 |
+
ggml_view_3d(ctx0, kv_self.v,
|
| 1117 |
+
n_past + N, n_embd/n_head, n_head,
|
| 1118 |
+
n_ctx*ggml_element_size(kv_self.v),
|
| 1119 |
+
n_ctx*ggml_element_size(kv_self.v)*n_embd/n_head,
|
| 1120 |
+
il*n_ctx*ggml_element_size(kv_self.v)*n_embd);
|
|
|
|
|
|
|
| 1121 |
|
| 1122 |
+
#if 1
|
| 1123 |
+
struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max);
|
| 1124 |
+
#else
|
| 1125 |
+
// make V contiguous in memory to speed up the matmul, however we waste time on the copy
|
| 1126 |
+
// on M1 this is faster for the perplexity computation, but ~5% slower for the single-token generation
|
| 1127 |
+
// is there a better way?
|
| 1128 |
+
struct ggml_tensor * V_cont = ggml_cpy(ctx0, V, ggml_new_tensor_3d(ctx0, kv_self.v->type, n_past + N, n_embd/n_head, n_head));
|
| 1129 |
+
struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_cont, KQ_soft_max);
|
| 1130 |
+
#endif
|
| 1131 |
|
| 1132 |
// KQV_merged = KQV.permute(0, 2, 1, 3)
|
| 1133 |
struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
|
|
|
|
| 1213 |
ggml_build_forward_expand(&gf, inpL);
|
| 1214 |
ggml_graph_compute (ctx0, &gf);
|
| 1215 |
|
| 1216 |
+
// print timing information per ggml operation (for debugging purposes)
|
| 1217 |
+
// requires GGML_PERF to be defined
|
| 1218 |
+
//ggml_graph_print(&gf);
|
| 1219 |
+
|
| 1220 |
+
// plot the computation graph in dot format (for debugging purposes)
|
| 1221 |
//if (n_past%100 == 0) {
|
| 1222 |
+
// ggml_graph_dump_dot(&gf, NULL, "llama.dot");
|
|
|
|
| 1223 |
//}
|
| 1224 |
|
| 1225 |
//embd_w.resize(n_vocab*N);
|
|
|
|
| 1430 |
// sampling
|
| 1431 |
//
|
| 1432 |
|
| 1433 |
+
static void sample_top_k(std::vector<std::pair<float, llama_vocab::id>> & logits_id, int top_k) {
|
| 1434 |
// find the top k tokens
|
| 1435 |
std::partial_sort(
|
| 1436 |
logits_id.begin(),
|
| 1437 |
logits_id.begin() + top_k, logits_id.end(),
|
| 1438 |
+
[](const std::pair<float, llama_vocab::id> & a, const std::pair<float, llama_vocab::id> & b) {
|
| 1439 |
return a.first > b.first;
|
| 1440 |
});
|
| 1441 |
|
|
|
|
| 1446 |
llama_context & lctx,
|
| 1447 |
const std::vector<llama_vocab::id> & last_n_tokens,
|
| 1448 |
int top_k,
|
| 1449 |
+
float top_p,
|
| 1450 |
+
float temp,
|
| 1451 |
+
float repeat_penalty) {
|
| 1452 |
auto & rng = lctx.rng;
|
| 1453 |
|
| 1454 |
const int n_logits = lctx.model.hparams.n_vocab;
|
|
|
|
| 1456 |
const auto & logits = lctx.logits;
|
| 1457 |
const auto * plogits = logits.data() + logits.size() - n_logits;
|
| 1458 |
|
| 1459 |
+
if (temp <= 0) {
|
| 1460 |
+
// select the token with the highest logit directly
|
| 1461 |
+
float max_logit = plogits[0];
|
| 1462 |
+
llama_vocab::id max_id = 0;
|
| 1463 |
+
|
| 1464 |
+
for (int i = 1; i < n_logits; ++i) {
|
| 1465 |
+
if (plogits[i] > max_logit) {
|
| 1466 |
+
max_logit = plogits[i];
|
| 1467 |
+
max_id = i;
|
| 1468 |
+
}
|
| 1469 |
+
}
|
| 1470 |
+
return max_id;
|
| 1471 |
+
}
|
| 1472 |
+
|
| 1473 |
+
std::vector<std::pair<float, llama_vocab::id>> logits_id;
|
| 1474 |
logits_id.reserve(n_logits);
|
| 1475 |
|
| 1476 |
{
|
| 1477 |
+
const float scale = 1.0f/temp;
|
| 1478 |
for (int i = 0; i < n_logits; ++i) {
|
| 1479 |
// repetition penalty from ctrl paper (https://arxiv.org/abs/1909.05858)
|
| 1480 |
// credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
|
| 1481 |
if (std::find(last_n_tokens.begin(), last_n_tokens.end(), i) != last_n_tokens.end()) {
|
| 1482 |
// if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
|
| 1483 |
+
if (plogits[i] < 0.0f) {
|
| 1484 |
logits_id.push_back(std::make_pair(plogits[i]*scale*repeat_penalty, i));
|
| 1485 |
} else {
|
| 1486 |
logits_id.push_back(std::make_pair(plogits[i]*scale/repeat_penalty, i));
|
|
|
|
| 1491 |
}
|
| 1492 |
}
|
| 1493 |
|
| 1494 |
+
sample_top_k(logits_id, top_k > 0 ? std::min(top_k, n_logits) : n_logits);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1495 |
|
| 1496 |
// compute probs for the top k tokens
|
| 1497 |
+
std::vector<float> probs;
|
| 1498 |
probs.reserve(logits_id.size());
|
| 1499 |
|
| 1500 |
+
float maxl = logits_id[0].first;
|
| 1501 |
double sum = 0.0;
|
| 1502 |
for (const auto & kv : logits_id) {
|
| 1503 |
+
const float p = expf(kv.first - maxl);
|
| 1504 |
probs.push_back(p);
|
| 1505 |
sum += p;
|
| 1506 |
}
|
|
|
|
| 1510 |
p /= sum;
|
| 1511 |
}
|
| 1512 |
|
| 1513 |
+
if (top_p < 1.0) {
|
| 1514 |
+
double cumsum = 0.0;
|
| 1515 |
for (int i = 0; i < (int) probs.size(); i++) {
|
| 1516 |
cumsum += probs[i];
|
| 1517 |
if (cumsum >= top_p) {
|
|
|
|
| 1520 |
break;
|
| 1521 |
}
|
| 1522 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1523 |
}
|
| 1524 |
|
| 1525 |
//printf("\n");
|
| 1526 |
//for (int i = 0; i < (int) 10; i++) {
|
| 1527 |
+
// printf("%d: '%s' %f\n", i, lctx.vocab.id_to_token.at(logits_id[i].second).tok.c_str(), probs[i]);
|
| 1528 |
//}
|
| 1529 |
//printf("\n\n");
|
| 1530 |
//exit(0);
|
|
|
|
| 1539 |
// quantization
|
| 1540 |
//
|
| 1541 |
|
| 1542 |
+
static void llama_model_quantize_internal(const std::string & fname_inp, const std::string & fname_out, int itype) {
|
| 1543 |
+
ggml_type quantized_type;
|
|
|
|
|
|
|
| 1544 |
switch (itype) {
|
| 1545 |
+
case 2: quantized_type = GGML_TYPE_Q4_0; break;
|
| 1546 |
+
case 3: quantized_type = GGML_TYPE_Q4_1; break;
|
| 1547 |
+
default: throw format("invalid quantization type %d\n", itype);
|
| 1548 |
};
|
| 1549 |
|
| 1550 |
+
std::unique_ptr<llama_model_loader> model_loader(new llama_model_loader(fname_inp.c_str(), /*use_mmap*/ false,
|
| 1551 |
+
/*vocab_only*/ false));
|
| 1552 |
+
llama_file_saver file_saver(fname_out.c_str(), model_loader->file_loaders.at(0).get(), (uint32_t) itype);
|
| 1553 |
+
|
| 1554 |
+
size_t total_size_org = 0;
|
| 1555 |
+
size_t total_size_new = 0;
|
| 1556 |
+
std::vector<int64_t> hist_all(1 << 4, 0);
|
| 1557 |
+
|
| 1558 |
+
size_t idx = 0;
|
| 1559 |
+
for (llama_load_tensor & tensor : model_loader->tensors_map.tensors) {
|
| 1560 |
+
llama_buffer read_data;
|
| 1561 |
+
read_data.resize(tensor.size);
|
| 1562 |
+
tensor.data = read_data.addr;
|
| 1563 |
+
model_loader->load_data_for(tensor);
|
| 1564 |
+
|
| 1565 |
+
printf("[%zu/%zu] %36s - %s, type = %6s, ",
|
| 1566 |
+
++idx, model_loader->tensors_map.tensors.size(),
|
| 1567 |
+
tensor.name.c_str(), llama_format_tensor_shape(tensor.ne).c_str(),
|
| 1568 |
+
llama_format_type(tensor.type));
|
| 1569 |
+
|
| 1570 |
+
// This used to be a regex, but <regex> has an extreme cost to compile times.
|
| 1571 |
+
bool quantize = tensor.name.rfind("weight") == tensor.name.size() - 6; // ends with 'weight'?
|
| 1572 |
+
|
| 1573 |
+
// quantize only 2D tensors
|
| 1574 |
+
quantize &= (tensor.ne.size() == 2);
|
| 1575 |
+
|
| 1576 |
+
enum ggml_type new_type;
|
| 1577 |
+
void * new_data;
|
| 1578 |
+
size_t new_size;
|
| 1579 |
+
llama_buffer work;
|
| 1580 |
+
|
| 1581 |
+
if (!quantize) {
|
| 1582 |
+
new_type = tensor.type;
|
| 1583 |
+
new_data = tensor.data;
|
| 1584 |
+
new_size = tensor.size;
|
| 1585 |
+
printf("size = %8.3f MB\n", tensor.size/1024.0/1024.0);
|
| 1586 |
+
} else {
|
| 1587 |
+
new_type = quantized_type;
|
| 1588 |
+
float * f32_data;
|
| 1589 |
+
size_t nelements = tensor.ne.at(0) * tensor.ne.at(1);
|
| 1590 |
+
llama_buffer f32_conv_buf;
|
| 1591 |
+
if (tensor.type == GGML_TYPE_F32) {
|
| 1592 |
+
f32_data = (float *) tensor.data;
|
| 1593 |
+
} else if (tensor.type == GGML_TYPE_F16) {
|
| 1594 |
+
f32_conv_buf.resize(nelements * sizeof(float));
|
| 1595 |
+
f32_data = (float *) f32_conv_buf.addr;
|
| 1596 |
+
auto f16_data = (const ggml_fp16_t *) tensor.data;
|
| 1597 |
+
for (size_t i = 0; i < nelements; i++) {
|
| 1598 |
+
f32_data[i] = ggml_fp16_to_fp32(f16_data[i]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1599 |
}
|
|
|
|
|
|
|
| 1600 |
} else {
|
| 1601 |
+
throw format("type %s unsupported for integer quantization", llama_format_type(tensor.type));
|
|
|
|
|
|
|
|
|
|
| 1602 |
}
|
| 1603 |
|
| 1604 |
+
printf("quantizing .. ");
|
| 1605 |
+
fflush(stdout);
|
| 1606 |
+
|
| 1607 |
+
work.resize(nelements * 4); // upper bound on size
|
| 1608 |
+
new_data = work.addr;
|
| 1609 |
+
std::vector<int64_t> hist_cur(1 << 4, 0);
|
| 1610 |
+
|
| 1611 |
+
switch (new_type) {
|
| 1612 |
+
case GGML_TYPE_Q4_0:
|
| 1613 |
+
{
|
| 1614 |
+
new_size = ggml_quantize_q4_0(f32_data, new_data, nelements, (int) tensor.ne.at(0), hist_cur.data());
|
| 1615 |
+
} break;
|
| 1616 |
+
case GGML_TYPE_Q4_1:
|
| 1617 |
+
{
|
| 1618 |
+
new_size = ggml_quantize_q4_1(f32_data, new_data, nelements, (int) tensor.ne.at(0), hist_cur.data());
|
| 1619 |
+
} break;
|
| 1620 |
+
default:
|
| 1621 |
+
LLAMA_ASSERT(false);
|
| 1622 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1623 |
|
| 1624 |
+
printf("size = %8.2f MB -> %8.2f MB | hist: ", tensor.size/1024.0/1024.0, new_size/1024.0/1024.0);
|
| 1625 |
+
for (size_t i = 0; i < hist_cur.size(); i++) {
|
| 1626 |
+
hist_all[i] += hist_cur[i];
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1627 |
}
|
| 1628 |
|
| 1629 |
+
for (size_t i = 0; i < hist_cur.size(); i++) {
|
| 1630 |
+
printf("%5.3f ", hist_cur[i] / float(nelements));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1631 |
}
|
| 1632 |
printf("\n");
|
| 1633 |
}
|
| 1634 |
+
total_size_org += tensor.size;
|
| 1635 |
+
total_size_new += new_size;
|
| 1636 |
+
file_saver.write_tensor(tensor, new_type, new_data, new_size);
|
| 1637 |
}
|
| 1638 |
|
| 1639 |
+
printf("%s: model size = %8.2f MB\n", __func__, total_size_org/1024.0/1024.0);
|
| 1640 |
+
printf("%s: quant size = %8.2f MB\n", __func__, total_size_new/1024.0/1024.0);
|
| 1641 |
|
| 1642 |
+
{
|
| 1643 |
+
int64_t sum_all = 0;
|
| 1644 |
+
for (size_t i = 0; i < hist_all.size(); i++) {
|
| 1645 |
+
sum_all += hist_all[i];
|
| 1646 |
+
}
|
| 1647 |
+
|
| 1648 |
+
printf("%s: hist: ", __func__);
|
| 1649 |
+
for (size_t i = 0; i < hist_all.size(); i++) {
|
| 1650 |
+
printf("%5.3f ", hist_all[i] / float(sum_all));
|
| 1651 |
+
}
|
| 1652 |
+
printf("\n");
|
| 1653 |
+
}
|
| 1654 |
}
|
| 1655 |
|
| 1656 |
//
|
|
|
|
| 1668 |
params.seed = time(NULL);
|
| 1669 |
}
|
| 1670 |
|
| 1671 |
+
unsigned cur_percentage = 0;
|
| 1672 |
+
if (params.progress_callback == NULL) {
|
| 1673 |
+
params.progress_callback_user_data = &cur_percentage;
|
| 1674 |
+
params.progress_callback = [](float progress, void * ctx) {
|
| 1675 |
+
unsigned * cur_percentage_p = (unsigned *) ctx;
|
| 1676 |
+
unsigned percentage = (unsigned) (100 * progress);
|
| 1677 |
+
while (percentage > *cur_percentage_p) {
|
| 1678 |
+
++*cur_percentage_p;
|
| 1679 |
+
fprintf(stderr, ".");
|
| 1680 |
+
fflush(stderr);
|
| 1681 |
+
if (percentage >= 100) {
|
| 1682 |
+
fprintf(stderr, "\n");
|
| 1683 |
+
}
|
| 1684 |
+
}
|
| 1685 |
+
};
|
| 1686 |
+
}
|
| 1687 |
+
|
| 1688 |
ctx->rng = std::mt19937(params.seed);
|
| 1689 |
ctx->logits_all = params.logits_all;
|
| 1690 |
|
| 1691 |
ggml_type memory_type = params.f16_kv ? GGML_TYPE_F16 : GGML_TYPE_F32;
|
| 1692 |
|
| 1693 |
+
if (!llama_model_load(path_model, *ctx, params.n_ctx, memory_type,
|
| 1694 |
+
params.use_mmap, params.use_mlock, params.vocab_only,
|
| 1695 |
+
params.progress_callback, params.progress_callback_user_data)) {
|
| 1696 |
fprintf(stderr, "%s: failed to load model\n", __func__);
|
| 1697 |
llama_free(ctx);
|
| 1698 |
return nullptr;
|
| 1699 |
}
|
| 1700 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1701 |
// reserve memory for context buffers
|
| 1702 |
+
if (!params.vocab_only) {
|
| 1703 |
if (!kv_cache_init(ctx->model.hparams, ctx->model.kv_self, memory_type, ctx->model.hparams.n_ctx)) {
|
| 1704 |
fprintf(stderr, "%s: kv_cache_init() failed for self-attention cache\n", __func__);
|
| 1705 |
llama_free(ctx);
|
|
|
|
| 1734 |
}
|
| 1735 |
|
| 1736 |
void llama_free(struct llama_context * ctx) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1737 |
delete ctx;
|
| 1738 |
}
|
| 1739 |
|
| 1740 |
int llama_model_quantize(
|
| 1741 |
const char * fname_inp,
|
| 1742 |
const char * fname_out,
|
| 1743 |
+
int itype) {
|
| 1744 |
+
try {
|
| 1745 |
+
llama_model_quantize_internal(fname_inp, fname_out, itype);
|
| 1746 |
+
return 0;
|
| 1747 |
+
} catch (const std::string & err) {
|
| 1748 |
+
fprintf(stderr, "%s: failed to quantize: %s\n", __func__, err.c_str());
|
| 1749 |
return 1;
|
| 1750 |
}
|
| 1751 |
+
}
|
| 1752 |
|
| 1753 |
+
// Returns the KV cache that will contain the context for the
|
| 1754 |
+
// ongoing prediction with the model.
|
| 1755 |
+
const uint8_t * llama_get_kv_cache(struct llama_context * ctx) {
|
| 1756 |
+
return ctx->model.kv_self.buf.addr;
|
| 1757 |
+
}
|
| 1758 |
+
|
| 1759 |
+
// Returns the size of the KV cache
|
| 1760 |
+
size_t llama_get_kv_cache_size(struct llama_context * ctx) {
|
| 1761 |
+
return ctx->model.kv_self.buf.size;
|
| 1762 |
+
}
|
| 1763 |
+
|
| 1764 |
+
int llama_get_kv_cache_token_count(struct llama_context * ctx) {
|
| 1765 |
+
return ctx->model.kv_self.n;
|
| 1766 |
+
}
|
| 1767 |
+
|
| 1768 |
+
// Sets the KV cache containing the current context for the model
|
| 1769 |
+
void llama_set_kv_cache(
|
| 1770 |
+
struct llama_context * ctx,
|
| 1771 |
+
const uint8_t * kv_cache,
|
| 1772 |
+
size_t n_size,
|
| 1773 |
+
int n_token_count) {
|
| 1774 |
+
// Make sure we have the same kv cache setup
|
| 1775 |
+
LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);
|
| 1776 |
+
memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);
|
| 1777 |
+
ctx->model.kv_self.n = n_token_count;
|
| 1778 |
}
|
| 1779 |
|
| 1780 |
int llama_eval(
|
|
|
|
| 1787 |
fprintf(stderr, "%s: failed to eval\n", __func__);
|
| 1788 |
return 1;
|
| 1789 |
}
|
| 1790 |
+
// get a more accurate load time, upon first eval
|
| 1791 |
+
if (!ctx->has_evaluated_once) {
|
| 1792 |
+
ctx->t_load_us = ggml_time_us() - ctx->t_start_us;
|
| 1793 |
+
ctx->has_evaluated_once = true;
|
| 1794 |
+
}
|
| 1795 |
return 0;
|
| 1796 |
}
|
| 1797 |
|
|
|
|
| 1856 |
const llama_token * last_n_tokens_data,
|
| 1857 |
int last_n_tokens_size,
|
| 1858 |
int top_k,
|
| 1859 |
+
float top_p,
|
| 1860 |
+
float temp,
|
| 1861 |
+
float repeat_penalty) {
|
| 1862 |
const int64_t t_start_sample_us = ggml_time_us();
|
| 1863 |
|
| 1864 |
llama_token result = 0;
|
|
|
|
| 1889 |
const int32_t n_p_eval = std::max(1, ctx->n_p_eval);
|
| 1890 |
|
| 1891 |
fprintf(stderr, "\n");
|
| 1892 |
+
fprintf(stderr, "%s: load time = %8.2f ms\n", __func__, ctx->t_load_us / 1000.0);
|
| 1893 |
+
fprintf(stderr, "%s: sample time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3 * ctx->t_sample_us, n_sample, 1e-3 * ctx->t_sample_us / n_sample);
|
| 1894 |
+
fprintf(stderr, "%s: prompt eval time = %8.2f ms / %5d tokens (%8.2f ms per token)\n", __func__, 1e-3 * ctx->t_p_eval_us, n_p_eval, 1e-3 * ctx->t_p_eval_us / n_p_eval);
|
| 1895 |
+
fprintf(stderr, "%s: eval time = %8.2f ms / %5d runs (%8.2f ms per run)\n", __func__, 1e-3 * ctx->t_eval_us, n_eval, 1e-3 * ctx->t_eval_us / n_eval);
|
| 1896 |
+
fprintf(stderr, "%s: total time = %8.2f ms\n", __func__, (t_end_us - ctx->t_start_us)/1000.0);
|
| 1897 |
}
|
| 1898 |
|
| 1899 |
void llama_reset_timings(struct llama_context * ctx) {
|
| 1900 |
ctx->t_start_us = ggml_time_us();
|
|
|
|
| 1901 |
ctx->t_sample_us = ctx->n_sample = 0;
|
| 1902 |
ctx->t_eval_us = ctx->n_eval = 0;
|
| 1903 |
ctx->t_p_eval_us = ctx->n_p_eval = 0;
|
|
|
|
| 1922 |
|
| 1923 |
return s.c_str();
|
| 1924 |
}
|
| 1925 |
+
|
| 1926 |
+
// For internal test use
|
| 1927 |
+
std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx) {
|
| 1928 |
+
return ctx->model.tensors_by_name;
|
| 1929 |
+
}
|
examples/talk-llama/llama.h
CHANGED
|
@@ -6,7 +6,7 @@
|
|
| 6 |
#include <stdbool.h>
|
| 7 |
|
| 8 |
#ifdef LLAMA_SHARED
|
| 9 |
-
#
|
| 10 |
# ifdef LLAMA_BUILD
|
| 11 |
# define LLAMA_API __declspec(dllexport)
|
| 12 |
# else
|
|
@@ -20,7 +20,7 @@
|
|
| 20 |
#endif
|
| 21 |
|
| 22 |
#define LLAMA_FILE_VERSION 1
|
| 23 |
-
#define LLAMA_FILE_MAGIC
|
| 24 |
#define LLAMA_FILE_MAGIC_UNVERSIONED 0x67676d6c // pre-versioned files
|
| 25 |
|
| 26 |
#ifdef __cplusplus
|
|
@@ -45,7 +45,7 @@ extern "C" {
|
|
| 45 |
|
| 46 |
} llama_token_data;
|
| 47 |
|
| 48 |
-
typedef void (*llama_progress_callback)(
|
| 49 |
|
| 50 |
struct llama_context_params {
|
| 51 |
int n_ctx; // text context
|
|
@@ -55,6 +55,7 @@ extern "C" {
|
|
| 55 |
bool f16_kv; // use fp16 for KV cache
|
| 56 |
bool logits_all; // the llama_eval() call computes all logits, not just the last one
|
| 57 |
bool vocab_only; // only load the vocabulary, no weights
|
|
|
|
| 58 |
bool use_mlock; // force system to keep model in RAM
|
| 59 |
bool embedding; // embedding mode only
|
| 60 |
|
|
@@ -66,6 +67,9 @@ extern "C" {
|
|
| 66 |
|
| 67 |
LLAMA_API struct llama_context_params llama_context_default_params();
|
| 68 |
|
|
|
|
|
|
|
|
|
|
| 69 |
// Various functions for loading a ggml llama model.
|
| 70 |
// Allocate (almost) all memory needed for the model.
|
| 71 |
// Return NULL on failure
|
|
@@ -81,8 +85,24 @@ extern "C" {
|
|
| 81 |
LLAMA_API int llama_model_quantize(
|
| 82 |
const char * fname_inp,
|
| 83 |
const char * fname_out,
|
| 84 |
-
int itype
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
|
| 87 |
// Run the llama inference to obtain the logits and probabilities for the next token.
|
| 88 |
// tokens + n_tokens is the provided batch of new tokens to process
|
|
@@ -135,9 +155,9 @@ extern "C" {
|
|
| 135 |
const llama_token * last_n_tokens_data,
|
| 136 |
int last_n_tokens_size,
|
| 137 |
int top_k,
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
|
| 142 |
// Performance information
|
| 143 |
LLAMA_API void llama_print_timings(struct llama_context * ctx);
|
|
@@ -150,4 +170,4 @@ extern "C" {
|
|
| 150 |
}
|
| 151 |
#endif
|
| 152 |
|
| 153 |
-
#endif
|
|
|
|
| 6 |
#include <stdbool.h>
|
| 7 |
|
| 8 |
#ifdef LLAMA_SHARED
|
| 9 |
+
# if defined(_WIN32) && !defined(__MINGW32__)
|
| 10 |
# ifdef LLAMA_BUILD
|
| 11 |
# define LLAMA_API __declspec(dllexport)
|
| 12 |
# else
|
|
|
|
| 20 |
#endif
|
| 21 |
|
| 22 |
#define LLAMA_FILE_VERSION 1
|
| 23 |
+
#define LLAMA_FILE_MAGIC 0x67676a74 // 'ggjt' in hex
|
| 24 |
#define LLAMA_FILE_MAGIC_UNVERSIONED 0x67676d6c // pre-versioned files
|
| 25 |
|
| 26 |
#ifdef __cplusplus
|
|
|
|
| 45 |
|
| 46 |
} llama_token_data;
|
| 47 |
|
| 48 |
+
typedef void (*llama_progress_callback)(float progress, void *ctx);
|
| 49 |
|
| 50 |
struct llama_context_params {
|
| 51 |
int n_ctx; // text context
|
|
|
|
| 55 |
bool f16_kv; // use fp16 for KV cache
|
| 56 |
bool logits_all; // the llama_eval() call computes all logits, not just the last one
|
| 57 |
bool vocab_only; // only load the vocabulary, no weights
|
| 58 |
+
bool use_mmap; // use mmap if possible
|
| 59 |
bool use_mlock; // force system to keep model in RAM
|
| 60 |
bool embedding; // embedding mode only
|
| 61 |
|
|
|
|
| 67 |
|
| 68 |
LLAMA_API struct llama_context_params llama_context_default_params();
|
| 69 |
|
| 70 |
+
LLAMA_API bool llama_mmap_supported();
|
| 71 |
+
LLAMA_API bool llama_mlock_supported();
|
| 72 |
+
|
| 73 |
// Various functions for loading a ggml llama model.
|
| 74 |
// Allocate (almost) all memory needed for the model.
|
| 75 |
// Return NULL on failure
|
|
|
|
| 85 |
LLAMA_API int llama_model_quantize(
|
| 86 |
const char * fname_inp,
|
| 87 |
const char * fname_out,
|
| 88 |
+
int itype);
|
| 89 |
+
|
| 90 |
+
// Returns the KV cache that will contain the context for the
|
| 91 |
+
// ongoing prediction with the model.
|
| 92 |
+
LLAMA_API const uint8_t * llama_get_kv_cache(struct llama_context * ctx);
|
| 93 |
+
|
| 94 |
+
// Returns the size of the KV cache
|
| 95 |
+
LLAMA_API size_t llama_get_kv_cache_size(struct llama_context * ctx);
|
| 96 |
+
|
| 97 |
+
// Returns the number of tokens in the KV cache
|
| 98 |
+
LLAMA_API int llama_get_kv_cache_token_count(struct llama_context * ctx);
|
| 99 |
+
|
| 100 |
+
// Sets the KV cache containing the current context for the model
|
| 101 |
+
LLAMA_API void llama_set_kv_cache(
|
| 102 |
+
struct llama_context * ctx,
|
| 103 |
+
const uint8_t * kv_cache,
|
| 104 |
+
size_t n_size,
|
| 105 |
+
int n_token_count);
|
| 106 |
|
| 107 |
// Run the llama inference to obtain the logits and probabilities for the next token.
|
| 108 |
// tokens + n_tokens is the provided batch of new tokens to process
|
|
|
|
| 155 |
const llama_token * last_n_tokens_data,
|
| 156 |
int last_n_tokens_size,
|
| 157 |
int top_k,
|
| 158 |
+
float top_p,
|
| 159 |
+
float temp,
|
| 160 |
+
float repeat_penalty);
|
| 161 |
|
| 162 |
// Performance information
|
| 163 |
LLAMA_API void llama_print_timings(struct llama_context * ctx);
|
|
|
|
| 170 |
}
|
| 171 |
#endif
|
| 172 |
|
| 173 |
+
#endif // LLAMA_H
|
examples/talk-llama/llama_internal.h
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Internal header to be included by llama.cpp and tests/benchmarks only.
|
| 2 |
+
|
| 3 |
+
#ifndef LLAMA_INTERNAL_H
|
| 4 |
+
#define LLAMA_INTERNAL_H
|
| 5 |
+
|
| 6 |
+
#include <vector>
|
| 7 |
+
#include <string>
|
| 8 |
+
struct ggml_tensor;
|
| 9 |
+
|
| 10 |
+
std::vector<std::pair<std::string, struct ggml_tensor *>>& llama_internal_get_tensor_map(struct llama_context * ctx);
|
| 11 |
+
|
| 12 |
+
#endif // LLAMA_INTERNAL_H
|
examples/talk-llama/llama_util.h
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Internal header to be included only by llama.cpp.
|
| 2 |
+
// Contains wrappers around OS interfaces.
|
| 3 |
+
|
| 4 |
+
#ifndef LLAMA_UTIL_H
|
| 5 |
+
#define LLAMA_UTIL_H
|
| 6 |
+
|
| 7 |
+
#include <cstdio>
|
| 8 |
+
#include <cstdint>
|
| 9 |
+
#include <cerrno>
|
| 10 |
+
#include <cstring>
|
| 11 |
+
#include <cstdarg>
|
| 12 |
+
#include <cstdlib>
|
| 13 |
+
#include <climits>
|
| 14 |
+
|
| 15 |
+
#include <string>
|
| 16 |
+
#include <vector>
|
| 17 |
+
|
| 18 |
+
#ifdef __has_include
|
| 19 |
+
#if __has_include(<unistd.h>)
|
| 20 |
+
#include <unistd.h>
|
| 21 |
+
#if defined(_POSIX_MAPPED_FILES)
|
| 22 |
+
#include <sys/mman.h>
|
| 23 |
+
#endif
|
| 24 |
+
#endif
|
| 25 |
+
#endif
|
| 26 |
+
|
| 27 |
+
#if defined(_WIN32)
|
| 28 |
+
#define WIN32_LEAN_AND_MEAN
|
| 29 |
+
#define NOMINMAX
|
| 30 |
+
#include <windows.h>
|
| 31 |
+
#include <io.h>
|
| 32 |
+
#include <stdio.h> // for _fseeki64
|
| 33 |
+
#endif
|
| 34 |
+
|
| 35 |
+
#define LLAMA_ASSERT(x) \
|
| 36 |
+
do { \
|
| 37 |
+
if (!(x)) { \
|
| 38 |
+
fprintf(stderr, "LLAMA_ASSERT: %s:%d: %s\n", __FILE__, __LINE__, #x); \
|
| 39 |
+
abort(); \
|
| 40 |
+
} \
|
| 41 |
+
} while (0)
|
| 42 |
+
|
| 43 |
+
#ifdef __GNUC__
|
| 44 |
+
__attribute__((format(printf, 1, 2)))
|
| 45 |
+
#endif
|
| 46 |
+
static std::string format(const char * fmt, ...) {
|
| 47 |
+
va_list ap, ap2;
|
| 48 |
+
va_start(ap, fmt);
|
| 49 |
+
va_copy(ap2, ap);
|
| 50 |
+
int size = vsnprintf(NULL, 0, fmt, ap);
|
| 51 |
+
LLAMA_ASSERT(size >= 0 && size < INT_MAX);
|
| 52 |
+
std::vector<char> buf(size + 1);
|
| 53 |
+
int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
|
| 54 |
+
LLAMA_ASSERT(size2 == size);
|
| 55 |
+
va_end(ap2);
|
| 56 |
+
va_end(ap);
|
| 57 |
+
return std::string(buf.data(), size);
|
| 58 |
+
};
|
| 59 |
+
|
| 60 |
+
struct llama_file {
|
| 61 |
+
// use FILE * so we don't have to re-open the file to mmap
|
| 62 |
+
FILE * fp;
|
| 63 |
+
size_t size;
|
| 64 |
+
|
| 65 |
+
llama_file(const char * fname, const char * mode) {
|
| 66 |
+
fp = std::fopen(fname, mode);
|
| 67 |
+
if (fp == NULL) {
|
| 68 |
+
throw format("failed to open %s: %s", fname, std::strerror(errno));
|
| 69 |
+
}
|
| 70 |
+
seek(0, SEEK_END);
|
| 71 |
+
size = tell();
|
| 72 |
+
seek(0, SEEK_SET);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
size_t tell() const {
|
| 76 |
+
#ifdef _WIN32
|
| 77 |
+
__int64 ret = _ftelli64(fp);
|
| 78 |
+
#else
|
| 79 |
+
long ret = std::ftell(fp);
|
| 80 |
+
#endif
|
| 81 |
+
LLAMA_ASSERT(ret != -1); // this really shouldn't fail
|
| 82 |
+
return (size_t) ret;
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
void seek(size_t offset, int whence) {
|
| 86 |
+
#ifdef _WIN32
|
| 87 |
+
int ret = _fseeki64(fp, (__int64) offset, whence);
|
| 88 |
+
#else
|
| 89 |
+
int ret = std::fseek(fp, (long) offset, whence);
|
| 90 |
+
#endif
|
| 91 |
+
LLAMA_ASSERT(ret == 0); // same
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
void read_raw(void * ptr, size_t size) {
|
| 95 |
+
if (size == 0) {
|
| 96 |
+
return;
|
| 97 |
+
}
|
| 98 |
+
errno = 0;
|
| 99 |
+
std::size_t ret = std::fread(ptr, size, 1, fp);
|
| 100 |
+
if (ferror(fp)) {
|
| 101 |
+
throw format("read error: %s", strerror(errno));
|
| 102 |
+
}
|
| 103 |
+
if (ret != 1) {
|
| 104 |
+
throw std::string("unexpectedly reached end of file");
|
| 105 |
+
}
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
std::uint32_t read_u32() {
|
| 109 |
+
std::uint32_t ret;
|
| 110 |
+
read_raw(&ret, sizeof(ret));
|
| 111 |
+
return ret;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
std::string read_string(std::uint32_t len) {
|
| 115 |
+
std::vector<char> chars(len);
|
| 116 |
+
read_raw(chars.data(), len);
|
| 117 |
+
return std::string(chars.data(), len);
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
void write_raw(const void * ptr, size_t size) {
|
| 121 |
+
if (size == 0) {
|
| 122 |
+
return;
|
| 123 |
+
}
|
| 124 |
+
errno = 0;
|
| 125 |
+
size_t ret = std::fwrite(ptr, size, 1, fp);
|
| 126 |
+
if (ret != 1) {
|
| 127 |
+
throw format("write error: %s", strerror(errno));
|
| 128 |
+
}
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
void write_u32(std::uint32_t val) {
|
| 132 |
+
write_raw(&val, sizeof(val));
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
~llama_file() {
|
| 136 |
+
if (fp) {
|
| 137 |
+
std::fclose(fp);
|
| 138 |
+
}
|
| 139 |
+
}
|
| 140 |
+
};
|
| 141 |
+
|
| 142 |
+
#if defined(_WIN32)
|
| 143 |
+
static std::string llama_format_win_err(DWORD err) {
|
| 144 |
+
LPSTR buf;
|
| 145 |
+
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
|
| 146 |
+
NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL);
|
| 147 |
+
if (!size) {
|
| 148 |
+
return "FormatMessageA failed";
|
| 149 |
+
}
|
| 150 |
+
std::string ret(buf, size);
|
| 151 |
+
LocalFree(buf);
|
| 152 |
+
return ret;
|
| 153 |
+
}
|
| 154 |
+
#endif
|
| 155 |
+
|
| 156 |
+
struct llama_mmap {
|
| 157 |
+
void * addr;
|
| 158 |
+
size_t size;
|
| 159 |
+
|
| 160 |
+
llama_mmap(const llama_mmap &) = delete;
|
| 161 |
+
|
| 162 |
+
#ifdef _POSIX_MAPPED_FILES
|
| 163 |
+
static constexpr bool SUPPORTED = true;
|
| 164 |
+
|
| 165 |
+
llama_mmap(struct llama_file * file) {
|
| 166 |
+
size = file->size;
|
| 167 |
+
int fd = fileno(file->fp);
|
| 168 |
+
int flags = MAP_SHARED;
|
| 169 |
+
#ifdef __linux__
|
| 170 |
+
flags |= MAP_POPULATE;
|
| 171 |
+
#endif
|
| 172 |
+
addr = mmap(NULL, file->size, PROT_READ, flags, fd, 0);
|
| 173 |
+
close(fd);
|
| 174 |
+
if (addr == MAP_FAILED) {
|
| 175 |
+
throw format("mmap failed: %s", strerror(errno));
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
// Advise the kernel to preload the mapped memory
|
| 179 |
+
if (madvise(addr, file->size, MADV_WILLNEED)) {
|
| 180 |
+
fprintf(stderr, "warning: madvise(.., MADV_WILLNEED) failed: %s\n",
|
| 181 |
+
strerror(errno));
|
| 182 |
+
}
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
~llama_mmap() {
|
| 186 |
+
munmap(addr, size);
|
| 187 |
+
}
|
| 188 |
+
#elif defined(_WIN32)
|
| 189 |
+
static constexpr bool SUPPORTED = true;
|
| 190 |
+
|
| 191 |
+
llama_mmap(struct llama_file * file) {
|
| 192 |
+
size = file->size;
|
| 193 |
+
|
| 194 |
+
HANDLE hFile = (HANDLE) _get_osfhandle(_fileno(file->fp));
|
| 195 |
+
|
| 196 |
+
HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
|
| 197 |
+
DWORD error = GetLastError();
|
| 198 |
+
CloseHandle(hFile);
|
| 199 |
+
|
| 200 |
+
if (hMapping == NULL) {
|
| 201 |
+
throw format("CreateFileMappingA failed: %s", llama_format_win_err(error).c_str());
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
addr = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
|
| 205 |
+
error = GetLastError();
|
| 206 |
+
CloseHandle(hMapping);
|
| 207 |
+
|
| 208 |
+
if (addr == NULL) {
|
| 209 |
+
throw format("MapViewOfFile failed: %s", llama_format_win_err(error).c_str());
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
// Advise the kernel to preload the mapped memory
|
| 213 |
+
WIN32_MEMORY_RANGE_ENTRY range;
|
| 214 |
+
range.VirtualAddress = addr;
|
| 215 |
+
range.NumberOfBytes = (SIZE_T)size;
|
| 216 |
+
if (!PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0)) {
|
| 217 |
+
fprintf(stderr, "warning: PrefetchVirtualMemory failed: %s\n",
|
| 218 |
+
llama_format_win_err(GetLastError()).c_str());
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
~llama_mmap() {
|
| 223 |
+
if (!UnmapViewOfFile(addr)) {
|
| 224 |
+
fprintf(stderr, "warning: UnmapViewOfFile failed: %s\n",
|
| 225 |
+
llama_format_win_err(GetLastError()).c_str());
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
#else
|
| 229 |
+
static constexpr bool SUPPORTED = false;
|
| 230 |
+
|
| 231 |
+
llama_mmap(struct llama_file *) {
|
| 232 |
+
throw std::string("mmap not supported");
|
| 233 |
+
}
|
| 234 |
+
#endif
|
| 235 |
+
};
|
| 236 |
+
|
| 237 |
+
// Represents some region of memory being locked using mlock or VirtualLock;
|
| 238 |
+
// will automatically unlock on destruction.
|
| 239 |
+
struct llama_mlock {
|
| 240 |
+
void * addr = NULL;
|
| 241 |
+
size_t size = 0;
|
| 242 |
+
bool failed_already = false;
|
| 243 |
+
|
| 244 |
+
llama_mlock() {}
|
| 245 |
+
llama_mlock(const llama_mlock &) = delete;
|
| 246 |
+
|
| 247 |
+
~llama_mlock() {
|
| 248 |
+
if (size) {
|
| 249 |
+
raw_unlock(addr, size);
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
void init(void * addr) {
|
| 254 |
+
LLAMA_ASSERT(this->addr == NULL && this->size == 0);
|
| 255 |
+
this->addr = addr;
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
void grow_to(size_t target_size) {
|
| 259 |
+
LLAMA_ASSERT(addr);
|
| 260 |
+
if (failed_already) {
|
| 261 |
+
return;
|
| 262 |
+
}
|
| 263 |
+
size_t granularity = lock_granularity();
|
| 264 |
+
target_size = (target_size + granularity - 1) & ~(granularity - 1);
|
| 265 |
+
if (target_size > size) {
|
| 266 |
+
if (raw_lock((uint8_t *) addr + size, target_size - size)) {
|
| 267 |
+
size = target_size;
|
| 268 |
+
} else {
|
| 269 |
+
failed_already = true;
|
| 270 |
+
}
|
| 271 |
+
}
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
#ifdef _POSIX_MEMLOCK_RANGE
|
| 275 |
+
static constexpr bool SUPPORTED = true;
|
| 276 |
+
|
| 277 |
+
size_t lock_granularity() {
|
| 278 |
+
return (size_t) sysconf(_SC_PAGESIZE);
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
#ifdef __APPLE__
|
| 282 |
+
#define MLOCK_SUGGESTION \
|
| 283 |
+
"Try increasing the sysctl values 'vm.user_wire_limit' and 'vm.global_user_wire_limit' and/or " \
|
| 284 |
+
"decreasing 'vm.global_no_user_wire_amount'. Also try increasing RLIMIT_MLOCK (ulimit -l).\n"
|
| 285 |
+
#else
|
| 286 |
+
#define MLOCK_SUGGESTION \
|
| 287 |
+
"Try increasing RLIMIT_MLOCK ('ulimit -l' as root).\n"
|
| 288 |
+
#endif
|
| 289 |
+
|
| 290 |
+
bool raw_lock(const void * addr, size_t size) {
|
| 291 |
+
if (!mlock(addr, size)) {
|
| 292 |
+
return true;
|
| 293 |
+
} else {
|
| 294 |
+
fprintf(stderr, "warning: failed to mlock %zu-byte buffer (after previously locking %zu bytes): %s\n" MLOCK_SUGGESTION,
|
| 295 |
+
size, this->size, std::strerror(errno));
|
| 296 |
+
return false;
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
#undef MLOCK_SUGGESTION
|
| 301 |
+
|
| 302 |
+
void raw_unlock(void * addr, size_t size) {
|
| 303 |
+
if (munlock(addr, size)) {
|
| 304 |
+
fprintf(stderr, "warning: failed to munlock buffer: %s\n", std::strerror(errno));
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
#elif defined(_WIN32)
|
| 308 |
+
static constexpr bool SUPPORTED = true;
|
| 309 |
+
|
| 310 |
+
size_t lock_granularity() {
|
| 311 |
+
SYSTEM_INFO si;
|
| 312 |
+
GetSystemInfo(&si);
|
| 313 |
+
return (size_t) si.dwPageSize;
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
bool raw_lock(void * addr, size_t size) {
|
| 317 |
+
for (int tries = 1; ; tries++) {
|
| 318 |
+
if (VirtualLock(addr, size)) {
|
| 319 |
+
return true;
|
| 320 |
+
}
|
| 321 |
+
if (tries == 2) {
|
| 322 |
+
fprintf(stderr, "warning: failed to VirtualLock %zu-byte buffer (after previously locking %zu bytes): %s\n",
|
| 323 |
+
size, this->size, llama_format_win_err(GetLastError()).c_str());
|
| 324 |
+
return false;
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
// It failed but this was only the first try; increase the working
|
| 328 |
+
// set size and try again.
|
| 329 |
+
SIZE_T min_ws_size, max_ws_size;
|
| 330 |
+
if (!GetProcessWorkingSetSize(GetCurrentProcess(), &min_ws_size, &max_ws_size)) {
|
| 331 |
+
fprintf(stderr, "warning: GetProcessWorkingSetSize failed: %s\n",
|
| 332 |
+
llama_format_win_err(GetLastError()).c_str());
|
| 333 |
+
return false;
|
| 334 |
+
}
|
| 335 |
+
// Per MSDN: "The maximum number of pages that a process can lock
|
| 336 |
+
// is equal to the number of pages in its minimum working set minus
|
| 337 |
+
// a small overhead."
|
| 338 |
+
// Hopefully a megabyte is enough overhead:
|
| 339 |
+
size_t increment = size + 1048576;
|
| 340 |
+
// The minimum must be <= the maximum, so we need to increase both:
|
| 341 |
+
min_ws_size += size;
|
| 342 |
+
max_ws_size += size;
|
| 343 |
+
if (!SetProcessWorkingSetSize(GetCurrentProcess(), min_ws_size, max_ws_size)) {
|
| 344 |
+
fprintf(stderr, "warning: SetProcessWorkingSetSize failed: %s\n",
|
| 345 |
+
llama_format_win_err(GetLastError()).c_str());
|
| 346 |
+
return false;
|
| 347 |
+
}
|
| 348 |
+
}
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
void raw_unlock(void * addr, size_t size) {
|
| 352 |
+
if (!VirtualUnlock(addr, size)) {
|
| 353 |
+
fprintf(stderr, "warning: failed to VirtualUnlock buffer: %s\n",
|
| 354 |
+
llama_format_win_err(GetLastError()).c_str());
|
| 355 |
+
}
|
| 356 |
+
}
|
| 357 |
+
#else
|
| 358 |
+
static constexpr bool SUPPORTED = false;
|
| 359 |
+
|
| 360 |
+
void raw_lock(const void * addr, size_t size) {
|
| 361 |
+
fprintf(stderr, "warning: mlock not supported on this system\n");
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
void raw_unlock(const void * addr, size_t size) {}
|
| 365 |
+
#endif
|
| 366 |
+
};
|
| 367 |
+
|
| 368 |
+
// Replacement for std::vector<uint8_t> that doesn't require zero-initialization.
|
| 369 |
+
struct llama_buffer {
|
| 370 |
+
uint8_t * addr = NULL;
|
| 371 |
+
size_t size = 0;
|
| 372 |
+
|
| 373 |
+
void resize(size_t size) {
|
| 374 |
+
delete[] addr;
|
| 375 |
+
addr = new uint8_t[size];
|
| 376 |
+
this->size = size;
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
~llama_buffer() {
|
| 380 |
+
delete[] addr;
|
| 381 |
+
}
|
| 382 |
+
};
|
| 383 |
+
#endif
|