utils.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. #include "utils.h"
  2. #include <cassert>
  3. #include <cstring>
  4. #include <fstream>
  5. #include <regex>
  6. #include <iostream>
  7. #include <iterator>
  8. #include <string>
  9. #include <math.h>
  10. #if defined(_MSC_VER) || defined(__MINGW32__)
  11. #include <malloc.h> // using malloc.h with MSC/MINGW
  12. #elif !defined(__FreeBSD__) && !defined(__NetBSD__)
  13. #include <alloca.h>
  14. #endif
  15. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  16. // determine sensible default number of threads.
  17. // std::thread::hardware_concurrency may not be equal to the number of cores, or may return 0.
  18. #ifdef __linux__
  19. std::ifstream cpuinfo("/proc/cpuinfo");
  20. params.n_threads = std::count(std::istream_iterator<std::string>(cpuinfo),
  21. std::istream_iterator<std::string>(),
  22. std::string("processor"));
  23. #endif
  24. if (params.n_threads == 0) {
  25. params.n_threads = std::max(1, (int32_t) std::thread::hardware_concurrency());
  26. }
  27. for (int i = 1; i < argc; i++) {
  28. std::string arg = argv[i];
  29. if (arg == "-s" || arg == "--seed") {
  30. params.seed = std::stoi(argv[++i]);
  31. } else if (arg == "-t" || arg == "--threads") {
  32. params.n_threads = std::stoi(argv[++i]);
  33. } else if (arg == "-p" || arg == "--prompt") {
  34. params.prompt = argv[++i];
  35. } else if (arg == "-f" || arg == "--file") {
  36. std::ifstream file(argv[++i]);
  37. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  38. if (params.prompt.back() == '\n') {
  39. params.prompt.pop_back();
  40. }
  41. } else if (arg == "-n" || arg == "--n_predict") {
  42. params.n_predict = std::stoi(argv[++i]);
  43. } else if (arg == "--top_k") {
  44. params.top_k = std::stoi(argv[++i]);
  45. } else if (arg == "-c" || arg == "--ctx_size") {
  46. params.n_ctx = std::stoi(argv[++i]);
  47. } else if (arg == "--memory_f16") {
  48. params.memory_f16 = true;
  49. } else if (arg == "--top_p") {
  50. params.top_p = std::stof(argv[++i]);
  51. } else if (arg == "--temp") {
  52. params.temp = std::stof(argv[++i]);
  53. } else if (arg == "--repeat_last_n") {
  54. params.repeat_last_n = std::stoi(argv[++i]);
  55. } else if (arg == "--repeat_penalty") {
  56. params.repeat_penalty = std::stof(argv[++i]);
  57. } else if (arg == "-b" || arg == "--batch_size") {
  58. params.n_batch = std::stoi(argv[++i]);
  59. } else if (arg == "-m" || arg == "--model") {
  60. params.model = argv[++i];
  61. } else if (arg == "-i" || arg == "--interactive") {
  62. params.interactive = true;
  63. } else if (arg == "-ins" || arg == "--instruct") {
  64. params.instruct = true;
  65. } else if (arg == "--color") {
  66. params.use_color = true;
  67. } else if (arg == "-r" || arg == "--reverse-prompt") {
  68. params.antiprompt = argv[++i];
  69. } else if (arg == "--ignore-eos") {
  70. params.ignore_eos = true;
  71. } else if (arg == "-h" || arg == "--help") {
  72. gpt_print_usage(argc, argv, params);
  73. exit(0);
  74. } else {
  75. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  76. gpt_print_usage(argc, argv, params);
  77. exit(0);
  78. }
  79. }
  80. return true;
  81. }
  82. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  83. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  84. fprintf(stderr, "\n");
  85. fprintf(stderr, "options:\n");
  86. fprintf(stderr, " -h, --help show this help message and exit\n");
  87. fprintf(stderr, " -i, --interactive run in interactive mode\n");
  88. fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  89. fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
  90. fprintf(stderr, " in interactive mode, poll user input upon seeing PROMPT\n");
  91. fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
  92. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1)\n");
  93. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  94. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  95. fprintf(stderr, " prompt to start generation with (default: random)\n");
  96. fprintf(stderr, " -f FNAME, --file FNAME\n");
  97. fprintf(stderr, " prompt file to start generation.\n");
  98. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d)\n", params.n_predict);
  99. fprintf(stderr, " --top_k N top-k sampling (default: %d)\n", params.top_k);
  100. fprintf(stderr, " --top_p N top-p sampling (default: %.1f)\n", params.top_p);
  101. fprintf(stderr, " --repeat_last_n N last n tokens to consider for penalize (default: %d)\n", params.repeat_last_n);
  102. fprintf(stderr, " --repeat_penalty N penalize repeat sequence of tokens (default: %.1f)\n", params.repeat_penalty);
  103. fprintf(stderr, " -c N, --ctx_size N size of the prompt context (default: %d)\n", params.n_ctx);
  104. fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating\n");
  105. fprintf(stderr, " --memory_f16 use f16 instead of f32 for memory key+value\n");
  106. fprintf(stderr, " --temp N temperature (default: %.1f)\n", params.temp);
  107. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  108. fprintf(stderr, " -m FNAME, --model FNAME\n");
  109. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  110. fprintf(stderr, "\n");
  111. }
  112. std::string gpt_random_prompt(std::mt19937 & rng) {
  113. const int r = rng() % 10;
  114. switch (r) {
  115. case 0: return "So";
  116. case 1: return "Once upon a time";
  117. case 2: return "When";
  118. case 3: return "The";
  119. case 4: return "After";
  120. case 5: return "If";
  121. case 6: return "import";
  122. case 7: return "He";
  123. case 8: return "She";
  124. case 9: return "They";
  125. default: return "To";
  126. }
  127. return "The";
  128. }
  129. void replace(std::string & str, const std::string & needle, const std::string & replacement) {
  130. size_t pos = 0;
  131. while ((pos = str.find(needle, pos)) != std::string::npos) {
  132. str.replace(pos, needle.length(), replacement);
  133. pos += replacement.length();
  134. }
  135. }
  136. std::map<std::string, int32_t> json_parse(const std::string & fname) {
  137. std::map<std::string, int32_t> result;
  138. // read file into string
  139. std::string json;
  140. {
  141. std::ifstream ifs(fname);
  142. if (!ifs) {
  143. fprintf(stderr, "Failed to open %s\n", fname.c_str());
  144. exit(1);
  145. }
  146. json = std::string((std::istreambuf_iterator<char>(ifs)),
  147. (std::istreambuf_iterator<char>()));
  148. }
  149. if (json[0] != '{') {
  150. return result;
  151. }
  152. // parse json
  153. {
  154. bool has_key = false;
  155. bool in_token = false;
  156. std::string str_key = "";
  157. std::string str_val = "";
  158. int n = json.size();
  159. for (int i = 1; i < n; ++i) {
  160. if (!in_token) {
  161. if (json[i] == ' ') continue;
  162. if (json[i] == '"') {
  163. in_token = true;
  164. continue;
  165. }
  166. } else {
  167. if (json[i] == '\\' && i+1 < n) {
  168. if (has_key == false) {
  169. str_key += json[i];
  170. } else {
  171. str_val += json[i];
  172. }
  173. ++i;
  174. } else if (json[i] == '"') {
  175. if (has_key == false) {
  176. has_key = true;
  177. ++i;
  178. while (json[i] == ' ') ++i;
  179. ++i; // :
  180. while (json[i] == ' ') ++i;
  181. if (json[i] != '\"') {
  182. while (json[i] != ',' && json[i] != '}') {
  183. str_val += json[i++];
  184. }
  185. has_key = false;
  186. } else {
  187. in_token = true;
  188. continue;
  189. }
  190. } else {
  191. has_key = false;
  192. }
  193. ::replace(str_key, "\\u0120", " " ); // \u0120 -> space
  194. ::replace(str_key, "\\u010a", "\n"); // \u010a -> new line
  195. ::replace(str_key, "\\\"", "\""); // \\\" -> "
  196. try {
  197. result[str_key] = std::stoi(str_val);
  198. } catch (...) {
  199. //fprintf(stderr, "%s: ignoring key '%s' with value '%s'\n", fname.c_str(), str_key.c_str(), str_val.c_str());
  200. }
  201. str_key = "";
  202. str_val = "";
  203. in_token = false;
  204. continue;
  205. }
  206. if (has_key == false) {
  207. str_key += json[i];
  208. } else {
  209. str_val += json[i];
  210. }
  211. }
  212. }
  213. }
  214. return result;
  215. }
  216. std::vector<gpt_vocab::id> gpt_tokenize(const gpt_vocab & vocab, const std::string & text) {
  217. std::vector<std::string> words;
  218. // first split the text into words
  219. {
  220. std::string str = text;
  221. std::string pat = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
  222. std::regex re(pat);
  223. std::smatch m;
  224. while (std::regex_search(str, m, re)) {
  225. for (auto x : m) {
  226. words.push_back(x);
  227. }
  228. str = m.suffix();
  229. }
  230. }
  231. // find the longest tokens that form the words:
  232. std::vector<gpt_vocab::id> tokens;
  233. for (const auto & word : words) {
  234. if (word.size() == 0) continue;
  235. int i = 0;
  236. int n = word.size();
  237. while (i < n) {
  238. int j = n;
  239. while (j > i) {
  240. auto it = vocab.token_to_id.find(word.substr(i, j-i));
  241. if (it != vocab.token_to_id.end()) {
  242. tokens.push_back(it->second);
  243. i = j;
  244. break;
  245. }
  246. --j;
  247. }
  248. if (i == n) {
  249. break;
  250. }
  251. if (j == i) {
  252. auto sub = word.substr(i, 1);
  253. if (vocab.token_to_id.find(sub) != vocab.token_to_id.end()) {
  254. tokens.push_back(vocab.token_to_id.at(sub));
  255. } else {
  256. fprintf(stderr, "%s: unknown token '%s'\n", __func__, sub.data());
  257. }
  258. ++i;
  259. }
  260. }
  261. }
  262. return tokens;
  263. }
  264. // TODO: Calculate this constant from the vocabulary
  265. #define MAX_TOKEN_LEN 18
  266. // SentencePiece implementation after https://guillaume-be.github.io/2020-05-30/sentence_piece
  267. std::vector<gpt_vocab::id> llama_tokenize(const gpt_vocab & vocab, const std::string & text, bool bos) {
  268. std::vector<gpt_vocab::id> res;
  269. std::vector<int> score;
  270. std::vector<gpt_vocab::id> prev;
  271. int len = text.length();
  272. score.resize(len + 1);
  273. prev.resize(len + 1);
  274. // Forward pass
  275. for (int i = 0; i < len; i++) {
  276. int max_len = std::min(len - i, MAX_TOKEN_LEN);
  277. for (int sub_len = 1; sub_len <= max_len; sub_len++) {
  278. auto sub = text.substr(i, sub_len);
  279. auto token = vocab.token_to_id.find(sub);
  280. if (token != vocab.token_to_id.end()) {
  281. int token_score = sub.length() * sub.length();
  282. int local_score = score[i] + token_score;
  283. int next = i + sub_len;
  284. if (score[next] < local_score) {
  285. score[next] = local_score;
  286. prev[next] = (*token).second;
  287. }
  288. }
  289. }
  290. }
  291. // Backward pass
  292. int i = len;
  293. while (i > 0) {
  294. gpt_vocab::id token_id = prev[i];
  295. if (token_id == 0) {
  296. // TODO: Return error or something more meaningful
  297. printf("failed to tokenize string!\n");
  298. break;
  299. }
  300. res.push_back(token_id);
  301. auto token = (*vocab.id_to_token.find(token_id)).second;
  302. i -= token.length();
  303. }
  304. if (bos) {
  305. res.push_back(1); // TODO: replace with vocab.bos
  306. }
  307. // Pieces are in reverse order so correct that
  308. std::reverse(res.begin(), res.end());
  309. return res;
  310. }
  311. bool gpt_vocab_init(const std::string & fname, gpt_vocab & vocab) {
  312. printf("%s: loading vocab from '%s'\n", __func__, fname.c_str());
  313. vocab.token_to_id = ::json_parse(fname);
  314. for (const auto & kv : vocab.token_to_id) {
  315. vocab.id_to_token[kv.second] = kv.first;
  316. }
  317. printf("%s: vocab size = %d\n", __func__, (int) vocab.token_to_id.size());
  318. // print the vocabulary
  319. //for (auto kv : vocab.token_to_id) {
  320. // printf("'%s' -> %d\n", kv.first.data(), kv.second);
  321. //}
  322. return true;
  323. }
  324. void sample_top_k(std::vector<std::pair<double, gpt_vocab::id>> & logits_id, int top_k) {
  325. // find the top K tokens
  326. std::partial_sort(
  327. logits_id.begin(),
  328. logits_id.begin() + top_k, logits_id.end(),
  329. [](const std::pair<double, gpt_vocab::id> & a, const std::pair<double, gpt_vocab::id> & b) {
  330. return a.first > b.first;
  331. });
  332. logits_id.resize(top_k);
  333. }
  334. gpt_vocab::id llama_sample_top_p_top_k(
  335. const gpt_vocab & vocab,
  336. const float * logits,
  337. std::vector<gpt_vocab::id> & last_n_tokens,
  338. double repeat_penalty,
  339. int top_k,
  340. double top_p,
  341. double temp,
  342. std::mt19937 & rng) {
  343. int n_logits = vocab.id_to_token.size();
  344. std::vector<std::pair<double, gpt_vocab::id>> logits_id;
  345. logits_id.reserve(n_logits);
  346. {
  347. const double scale = 1.0/temp;
  348. for (int i = 0; i < n_logits; ++i) {
  349. // repetition penalty from CTRL paper (https://arxiv.org/abs/1909.05858)
  350. // credit https://github.com/facebookresearch/llama/compare/main...shawwn:llama:main
  351. if (std::find(last_n_tokens.begin(), last_n_tokens.end(), i) != last_n_tokens.end()) {
  352. // if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
  353. if (logits[i] < 0.0) {
  354. logits_id.push_back(std::make_pair(logits[i]*scale*repeat_penalty, i));
  355. } else {
  356. logits_id.push_back(std::make_pair(logits[i]*scale/repeat_penalty, i));
  357. }
  358. } else {
  359. logits_id.push_back(std::make_pair(logits[i]*scale, i));
  360. }
  361. }
  362. }
  363. sample_top_k(logits_id, top_k);
  364. double maxl = -INFINITY;
  365. for (const auto & kv : logits_id) {
  366. maxl = std::max(maxl, kv.first);
  367. }
  368. // compute probs for the top K tokens
  369. std::vector<double> probs;
  370. probs.reserve(logits_id.size());
  371. double sum = 0.0;
  372. for (const auto & kv : logits_id) {
  373. double p = exp(kv.first - maxl);
  374. probs.push_back(p);
  375. sum += p;
  376. }
  377. // normalize the probs
  378. for (auto & p : probs) {
  379. p /= sum;
  380. }
  381. if (top_p < 1.0f) {
  382. double cumsum = 0.0f;
  383. for (int i = 0; i < (int) probs.size(); i++) {
  384. cumsum += probs[i];
  385. if (cumsum >= top_p) {
  386. probs.resize(i + 1);
  387. logits_id.resize(i + 1);
  388. break;
  389. }
  390. }
  391. cumsum = 1.0/cumsum;
  392. for (int i = 0; i < (int) probs.size(); i++) {
  393. probs[i] *= cumsum;
  394. }
  395. }
  396. //printf("\n");
  397. //for (int i = 0; i < (int) 10; i++) {
  398. // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), probs[i]);
  399. //}
  400. //printf("\n\n");
  401. //exit(0);
  402. std::discrete_distribution<> dist(probs.begin(), probs.end());
  403. int idx = dist(rng);
  404. return logits_id[idx].second;
  405. }
  406. size_t ggml_quantize_q4_0(float * src, void * dst, int n, int k, int qk, int64_t * hist) {
  407. const int nb = k / qk;
  408. const size_t bs = (sizeof(float) + sizeof(uint8_t)*qk/2);
  409. const size_t row_size = nb*bs;
  410. assert(k % qk == 0);
  411. const size_t pp_size = qk / 2;
  412. uint8_t *pp = static_cast<uint8_t*>(alloca(pp_size));
  413. char * pdst = (char *) dst;
  414. for (int j = 0; j < n; j += k) {
  415. uint8_t * pd = (uint8_t *) (pdst + (j/k)*row_size + 0*bs);
  416. uint8_t * pb = (uint8_t *) (pdst + (j/k)*row_size + 0*bs + sizeof(float));
  417. for (int i = 0; i < nb; i++) {
  418. float amax = 0.0f; // absolute max
  419. {
  420. for (int l = 0; l < qk; l++) {
  421. const float v = src[j + i*qk + l];
  422. amax = std::max(amax, fabsf(v));
  423. }
  424. const float d = amax / ((1 << 3) - 1);
  425. const float id = d ? 1.0f/d : 0.0f;
  426. *(float *) pd = d;
  427. pd += bs;
  428. for (int l = 0; l < qk; l += 2) {
  429. const float v0 = (src[j + i*qk + l + 0])*id;
  430. const float v1 = (src[j + i*qk + l + 1])*id;
  431. const uint8_t vi0 = ((int8_t) (round(v0))) + 8;
  432. const uint8_t vi1 = ((int8_t) (round(v1))) + 8;
  433. assert(vi0 >= 0 && vi0 < 16);
  434. assert(vi1 >= 0 && vi1 < 16);
  435. hist[vi0]++;
  436. hist[vi1]++;
  437. pp[l/2] = vi0 | (vi1 << 4);
  438. }
  439. memcpy(pb, pp, pp_size);
  440. pb += bs;
  441. }
  442. }
  443. }
  444. return (n/k)*row_size;
  445. }
  446. size_t ggml_quantize_q4_1(float * src, void * dst, int n, int k, int qk, int64_t * hist) {
  447. const int nb = k / qk;
  448. const size_t bs = (2*sizeof(float) + sizeof(uint8_t)*qk/2);
  449. const size_t row_size = nb*bs;
  450. assert(k % qk == 0);
  451. const size_t pp_size = qk / 2;
  452. uint8_t *pp = static_cast<uint8_t*>(alloca(pp_size));
  453. char * pdst = (char *) dst;
  454. for (int j = 0; j < n; j += k) {
  455. uint8_t * pd = (uint8_t *) (pdst + (j/k)*row_size + 0*bs);
  456. uint8_t * pm = (uint8_t *) (pdst + (j/k)*row_size + 0*bs + sizeof(float));
  457. uint8_t * pb = (uint8_t *) (pdst + (j/k)*row_size + 0*bs + 2*sizeof(float));
  458. //printf("n = %d, k = %d, nb = %d, row_size = %d, j = %d, pm = %p, pd = %p, pb = %p\n", n, k, nb, row_size, j, pm, pd, pb);
  459. for (int i = 0; i < nb; i++) {
  460. float min = std::numeric_limits<float>::max();
  461. float max = std::numeric_limits<float>::min();
  462. {
  463. for (int l = 0; l < qk; l++) {
  464. const float v = src[j + i*qk + l];
  465. if (v < min) min = v;
  466. if (v > max) max = v;
  467. }
  468. const float d = (max - min) / ((1 << 4) - 1);
  469. const float id = d ? 1.0f/d : 0.0f;
  470. *(float *) pd = d;
  471. *(float *) pm = min;
  472. pd += bs;
  473. pm += bs;
  474. for (int l = 0; l < qk; l += 2) {
  475. const float v0 = (src[j + i*qk + l + 0] - min)*id;
  476. const float v1 = (src[j + i*qk + l + 1] - min)*id;
  477. const uint8_t vi0 = round(v0);
  478. const uint8_t vi1 = round(v1);
  479. assert(vi0 >= 0 && vi0 < 16);
  480. assert(vi1 >= 0 && vi1 < 16);
  481. hist[vi0]++;
  482. hist[vi1]++;
  483. pp[l/2] = vi0 | (vi1 << 4);
  484. }
  485. memcpy(pb, pp, pp_size);
  486. pb += bs;
  487. }
  488. }
  489. }
  490. return (n/k)*row_size;
  491. }