utils.cpp 19 KB

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