utils.cpp 18 KB

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