utils.cpp 18 KB

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