utils.cpp 16 KB

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