utils.cpp 16 KB

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