utils.cpp 18 KB

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