utils.cpp 18 KB

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