utils.cpp 17 KB

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