utils.cpp 19 KB

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