utils.cpp 19 KB

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