utils.cpp 20 KB

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