llama-grammar.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /**
  2. * llama.cpp - commit 8962422b1c6f9b8b15f5aeaea42600bcc2d44177 - do not edit this file
  3. *
  4. * MIT License
  5. *
  6. * Copyright (c) 2023-2024 The ggml authors
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all
  16. * copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. * SOFTWARE.
  25. */
  26. #include "llama-grammar.h"
  27. #include "llama-vocab.h"
  28. #include "llama-sampling.h"
  29. #include <algorithm>
  30. // Decodes a UTF-8 string which may end in an incomplete sequence. Adds a terminating 0 for use as
  31. // pointer. If an invalid sequence is encountered, returns `llama_partial_utf8.n_remain == -1`.
  32. std::pair<std::vector<uint32_t>, llama_partial_utf8> decode_utf8(
  33. const std::string & src,
  34. llama_partial_utf8 partial_start) {
  35. static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
  36. const char * pos = src.c_str();
  37. std::vector<uint32_t> code_points;
  38. // common english strings have the same number of codepoints and bytes. `+ 1` for the terminating 0.
  39. code_points.reserve(src.size() + 1);
  40. uint32_t value = partial_start.value;
  41. int n_remain = partial_start.n_remain;
  42. // continue previous decode, if applicable
  43. while (*pos != 0 && n_remain > 0) {
  44. uint8_t next_byte = static_cast<uint8_t>(*pos);
  45. if ((next_byte >> 6) != 2) {
  46. // invalid sequence, abort
  47. code_points.push_back(0);
  48. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, -1 });
  49. }
  50. value = (value << 6) + (next_byte & 0x3F);
  51. ++pos;
  52. --n_remain;
  53. }
  54. if (partial_start.n_remain > 0 && n_remain == 0) {
  55. code_points.push_back(value);
  56. }
  57. // decode any subsequent utf-8 sequences, which may end in an incomplete one
  58. while (*pos != 0) {
  59. uint8_t first_byte = static_cast<uint8_t>(*pos);
  60. uint8_t highbits = first_byte >> 4;
  61. n_remain = lookup[highbits] - 1;
  62. if (n_remain < 0) {
  63. // invalid sequence, abort
  64. code_points.clear();
  65. code_points.push_back(0);
  66. return std::make_pair(std::move(code_points), llama_partial_utf8{ 0, n_remain });
  67. }
  68. uint8_t mask = (1 << (7 - n_remain)) - 1;
  69. value = first_byte & mask;
  70. ++pos;
  71. while (*pos != 0 && n_remain > 0) {
  72. value = (value << 6) + (static_cast<uint8_t>(*pos) & 0x3F);
  73. ++pos;
  74. --n_remain;
  75. }
  76. if (n_remain == 0) {
  77. code_points.push_back(value);
  78. }
  79. }
  80. code_points.push_back(0);
  81. return std::make_pair(std::move(code_points), llama_partial_utf8{ value, n_remain });
  82. }
  83. const llama_grammar_rules & llama_grammar_get_rules(const struct llama_grammar * grammar) {
  84. return grammar->rules;
  85. }
  86. llama_grammar_stacks & llama_grammar_get_stacks(struct llama_grammar * grammar) {
  87. return grammar->stacks;
  88. }
  89. // returns true iff pos points to the end of one of the definitions of a rule
  90. static bool llama_grammar_is_end_of_sequence(const llama_grammar_element * pos) {
  91. switch (pos->type) {
  92. case LLAMA_GRETYPE_END: return true; // NOLINT
  93. case LLAMA_GRETYPE_ALT: return true; // NOLINT
  94. default: return false;
  95. }
  96. }
  97. // returns true iff chr satisfies the char range at pos (regular or inverse range)
  98. // asserts that pos is pointing to a char range element
  99. static std::pair<bool, const llama_grammar_element *> llama_grammar_match_char(
  100. const llama_grammar_element * pos,
  101. const uint32_t chr) {
  102. bool found = false;
  103. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR || pos->type == LLAMA_GRETYPE_CHAR_ANY;
  104. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT); // NOLINT
  105. do {
  106. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  107. // inclusive range, e.g. [a-z]
  108. found = found || (pos->value <= chr && chr <= pos[1].value);
  109. pos += 2;
  110. } else if (pos->type == LLAMA_GRETYPE_CHAR_ANY) {
  111. // Any character matches "."
  112. found = true;
  113. pos += 1;
  114. } else {
  115. // exact char match, e.g. [a] or "a"
  116. found = found || pos->value == chr;
  117. pos += 1;
  118. }
  119. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  120. return std::make_pair(found == is_positive_char, pos);
  121. }
  122. // returns true iff some continuation of the given partial UTF-8 sequence could satisfy the char
  123. // range at pos (regular or inverse range)
  124. // asserts that pos is pointing to a char range element
  125. static bool llama_grammar_match_partial_char(
  126. const llama_grammar_element * pos,
  127. const llama_partial_utf8 partial_utf8) {
  128. bool is_positive_char = pos->type == LLAMA_GRETYPE_CHAR || pos->type == LLAMA_GRETYPE_CHAR_ANY;
  129. GGML_ASSERT(is_positive_char || pos->type == LLAMA_GRETYPE_CHAR_NOT);
  130. uint32_t partial_value = partial_utf8.value;
  131. int n_remain = partial_utf8.n_remain;
  132. // invalid sequence or 7-bit char split across 2 bytes (overlong)
  133. if (n_remain < 0 || (n_remain == 1 && partial_value < 2)) {
  134. return false;
  135. }
  136. // range of possible code points this partial UTF-8 sequence could complete to
  137. uint32_t low = partial_value << (n_remain * 6);
  138. uint32_t high = low | ((1 << (n_remain * 6)) - 1);
  139. if (low == 0) {
  140. if (n_remain == 2) {
  141. low = 1 << 11;
  142. } else if (n_remain == 3) {
  143. low = 1 << 16;
  144. }
  145. }
  146. do {
  147. if (pos[1].type == LLAMA_GRETYPE_CHAR_RNG_UPPER) {
  148. // inclusive range, e.g. [a-z]
  149. if (pos->value <= high && low <= pos[1].value) {
  150. return is_positive_char;
  151. }
  152. pos += 2;
  153. } else if (pos->type == LLAMA_GRETYPE_CHAR_ANY) {
  154. // Any character matches "."
  155. return true;
  156. } else {
  157. // exact char match, e.g. [a] or "a"
  158. if (low <= pos->value && pos->value <= high) {
  159. return is_positive_char;
  160. }
  161. pos += 1;
  162. }
  163. } while (pos->type == LLAMA_GRETYPE_CHAR_ALT);
  164. return !is_positive_char;
  165. }
  166. // transforms a grammar pushdown stack into N possible stacks, all ending
  167. // at a character range (terminal element)
  168. static void llama_grammar_advance_stack(
  169. const llama_grammar_rules & rules,
  170. const llama_grammar_stack & stack,
  171. llama_grammar_stacks & new_stacks) {
  172. if (stack.empty()) {
  173. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  174. new_stacks.emplace_back(stack);
  175. }
  176. return;
  177. }
  178. const llama_grammar_element * pos = stack.back();
  179. switch (pos->type) {
  180. case LLAMA_GRETYPE_RULE_REF: {
  181. const size_t rule_id = static_cast<size_t>(pos->value);
  182. const llama_grammar_element * subpos = rules[rule_id].data();
  183. do {
  184. // init new stack without the top (pos)
  185. llama_grammar_stack new_stack(stack.begin(), stack.end() - 1);
  186. if (!llama_grammar_is_end_of_sequence(pos + 1)) {
  187. // if this rule ref is followed by another element, add that to stack
  188. new_stack.push_back(pos + 1);
  189. }
  190. if (!llama_grammar_is_end_of_sequence(subpos)) {
  191. // if alternate is nonempty, add to stack
  192. new_stack.push_back(subpos);
  193. }
  194. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  195. while (!llama_grammar_is_end_of_sequence(subpos)) {
  196. // scan to end of alternate def
  197. subpos++;
  198. }
  199. if (subpos->type == LLAMA_GRETYPE_ALT) {
  200. // there's another alternate def of this rule to process
  201. subpos++;
  202. } else {
  203. break;
  204. }
  205. } while (true);
  206. break;
  207. }
  208. case LLAMA_GRETYPE_CHAR:
  209. case LLAMA_GRETYPE_CHAR_NOT:
  210. case LLAMA_GRETYPE_CHAR_ANY:
  211. if (std::find(new_stacks.begin(), new_stacks.end(), stack) == new_stacks.end()) {
  212. // only add the stack if it's not a duplicate of one we already have
  213. new_stacks.emplace_back(stack);
  214. }
  215. break;
  216. default:
  217. // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
  218. // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
  219. // those
  220. GGML_ABORT("fatal error");
  221. }
  222. }
  223. // takes a set of possible pushdown stacks on a grammar, which are required to
  224. // be positioned at a character range (see `llama_grammar_advance_stack`), and
  225. // produces the N possible stacks if the given char is accepted at those
  226. // positions
  227. void llama_grammar_accept(
  228. const llama_grammar_rules & rules,
  229. const llama_grammar_stacks & stacks,
  230. const uint32_t chr,
  231. llama_grammar_stacks & new_stacks) {
  232. new_stacks.clear();
  233. for (const auto & stack : stacks) {
  234. if (stack.empty()) {
  235. continue;
  236. }
  237. auto match = llama_grammar_match_char(stack.back(), chr);
  238. if (match.first) {
  239. const llama_grammar_element * pos = match.second;
  240. // update top of stack to next element, if any
  241. llama_grammar_stack new_stack(stack.begin(), stack.end() - 1);
  242. if (!llama_grammar_is_end_of_sequence(pos)) {
  243. new_stack.push_back(pos);
  244. }
  245. llama_grammar_advance_stack(rules, new_stack, new_stacks);
  246. }
  247. }
  248. }
  249. static llama_grammar_candidates llama_grammar_reject_candidates(
  250. const llama_grammar_rules & rules,
  251. const llama_grammar_stacks & stacks,
  252. const llama_grammar_candidates & candidates) {
  253. GGML_ASSERT(!stacks.empty()); // REVIEW
  254. if (candidates.empty()) {
  255. return {};
  256. }
  257. auto rejects = llama_grammar_reject_candidates_for_stack(rules, stacks.front(), candidates);
  258. for (size_t i = 1, size = stacks.size(); i < size; ++i) {
  259. rejects = llama_grammar_reject_candidates_for_stack(rules, stacks[i], rejects);
  260. }
  261. return rejects;
  262. }
  263. llama_grammar_candidates llama_grammar_reject_candidates_for_stack(
  264. const llama_grammar_rules & rules,
  265. const llama_grammar_stack & stack,
  266. const llama_grammar_candidates & candidates) {
  267. llama_grammar_candidates rejects;
  268. rejects.reserve(candidates.size());
  269. if (stack.empty()) {
  270. for (const auto & tok : candidates) {
  271. if (*tok.code_points != 0 || tok.partial_utf8.n_remain != 0) {
  272. rejects.push_back(tok);
  273. }
  274. }
  275. return rejects;
  276. }
  277. const llama_grammar_element * stack_pos = stack.back();
  278. llama_grammar_candidates next_candidates;
  279. next_candidates.reserve(candidates.size());
  280. for (const auto & tok : candidates) {
  281. if (*tok.code_points == 0) {
  282. // reached end of full codepoints in token, reject iff it ended in a partial sequence
  283. // that cannot satisfy this position in grammar
  284. if (tok.partial_utf8.n_remain != 0 &&
  285. !llama_grammar_match_partial_char(stack_pos, tok.partial_utf8)) {
  286. rejects.push_back(tok);
  287. }
  288. } else if (llama_grammar_match_char(stack_pos, *tok.code_points).first) {
  289. next_candidates.push_back({ tok.index, tok.code_points + 1, tok.partial_utf8 });
  290. } else {
  291. rejects.push_back(tok);
  292. }
  293. }
  294. const auto * stack_pos_after = llama_grammar_match_char(stack_pos, 0).second;
  295. // update top of stack to next element, if any
  296. llama_grammar_stack stack_after(stack.begin(), stack.end() - 1);
  297. if (!llama_grammar_is_end_of_sequence(stack_pos_after)) {
  298. stack_after.push_back(stack_pos_after);
  299. }
  300. llama_grammar_stacks next_stacks;
  301. llama_grammar_advance_stack(rules, stack_after, next_stacks);
  302. auto next_rejects = llama_grammar_reject_candidates(rules, next_stacks, next_candidates);
  303. for (const auto & tok : next_rejects) {
  304. rejects.push_back({ tok.index, tok.code_points - 1, tok.partial_utf8 });
  305. }
  306. return rejects;
  307. }
  308. static bool llama_grammar_detect_left_recursion(
  309. const llama_grammar_rules & rules,
  310. size_t rule_index,
  311. std::vector<bool> * rules_visited,
  312. std::vector<bool> * rules_in_progress,
  313. std::vector<bool> * rules_may_be_empty) {
  314. if ((*rules_in_progress)[rule_index]) {
  315. return true;
  316. }
  317. (*rules_in_progress)[rule_index] = true;
  318. const llama_grammar_rule & rule = rules[rule_index];
  319. // First check if the rule might produce the empty string. This could be done combined with the second
  320. // step but it's more readable as two steps.
  321. bool at_rule_start = true;
  322. for (size_t i = 0; i < rule.size(); i++) {
  323. if (llama_grammar_is_end_of_sequence(&rule[i])) {
  324. if (at_rule_start) {
  325. (*rules_may_be_empty)[rule_index] = true;
  326. break;
  327. }
  328. at_rule_start = true;
  329. } else {
  330. at_rule_start = false;
  331. }
  332. }
  333. // Second, recurse into leftmost nonterminals (or next-leftmost as long as the previous nonterminal may
  334. // be empty)
  335. bool recurse_into_nonterminal = true;
  336. for (size_t i = 0; i < rule.size(); i++) {
  337. if (rule[i].type == LLAMA_GRETYPE_RULE_REF && recurse_into_nonterminal) {
  338. if (llama_grammar_detect_left_recursion(rules, (size_t)rule[i].value, rules_visited, rules_in_progress, rules_may_be_empty)) {
  339. return true;
  340. }
  341. if (!((*rules_may_be_empty)[(size_t)rule[i].value])) {
  342. recurse_into_nonterminal = false;
  343. }
  344. } else if (llama_grammar_is_end_of_sequence(&rule[i])) {
  345. recurse_into_nonterminal = true;
  346. } else {
  347. recurse_into_nonterminal = false;
  348. }
  349. }
  350. (*rules_in_progress)[rule_index] = false;
  351. (*rules_visited)[rule_index] = true;
  352. return false;
  353. }
  354. //
  355. // grammar - external
  356. //
  357. struct llama_grammar * llama_grammar_init_impl(
  358. const llama_grammar_element ** rules,
  359. size_t n_rules,
  360. size_t start_rule_index) {
  361. const llama_grammar_element * pos;
  362. // copy rule definitions into vectors
  363. llama_grammar_rules vec_rules(n_rules);
  364. for (size_t i = 0; i < n_rules; i++) {
  365. for (pos = rules[i]; pos->type != LLAMA_GRETYPE_END; pos++) {
  366. vec_rules[i].push_back(*pos);
  367. }
  368. vec_rules[i].push_back({LLAMA_GRETYPE_END, 0});
  369. }
  370. // Check for left recursion
  371. std::vector<bool> rules_visited(n_rules);
  372. std::vector<bool> rules_in_progress(n_rules);
  373. std::vector<bool> rules_may_be_empty(n_rules);
  374. for (size_t i = 0; i < n_rules; i++) {
  375. if (rules_visited[i]) {
  376. continue;
  377. }
  378. if (llama_grammar_detect_left_recursion(vec_rules, i, &rules_visited, &rules_in_progress, &rules_may_be_empty)) {
  379. LLAMA_LOG_ERROR("unsupported grammar, left recursion detected for nonterminal at index %zu", i);
  380. return nullptr;
  381. }
  382. }
  383. // loop over alternates of start rule to build initial stacks
  384. llama_grammar_stacks stacks;
  385. pos = vec_rules[start_rule_index].data();
  386. do {
  387. llama_grammar_stack stack;
  388. if (!llama_grammar_is_end_of_sequence(pos)) {
  389. // if alternate is nonempty, add to stack
  390. stack.push_back(pos);
  391. }
  392. llama_grammar_advance_stack(vec_rules, stack, stacks);
  393. while (!llama_grammar_is_end_of_sequence(pos)) {
  394. // scan to end of alternate def
  395. pos++;
  396. }
  397. if (pos->type == LLAMA_GRETYPE_ALT) {
  398. // there's another alternate def of this rule to process
  399. pos++;
  400. } else {
  401. break;
  402. }
  403. } while (true);
  404. // Important: vec_rules has to be moved here, not copied, because stacks contains
  405. // pointers to elements of vec_rules. If vec_rules were copied into llama_grammar
  406. // then the pointers would be invalidated when the local vec_rules goes out of scope.
  407. return new llama_grammar{ std::move(vec_rules), std::move(stacks), {} };
  408. }
  409. void llama_grammar_free_impl(struct llama_grammar * grammar) {
  410. delete grammar;
  411. }
  412. struct llama_grammar * llama_grammar_copy_impl(const struct llama_grammar * grammar) {
  413. llama_grammar * result = new llama_grammar{ grammar->rules, grammar->stacks, grammar->partial_utf8 };
  414. // redirect elements in stacks to point to new rules
  415. for (size_t is = 0; is < result->stacks.size(); is++) {
  416. for (size_t ie = 0; ie < result->stacks[is].size(); ie++) {
  417. for (size_t ir0 = 0; ir0 < grammar->rules.size(); ir0++) {
  418. for (size_t ir1 = 0; ir1 < grammar->rules[ir0].size(); ir1++) {
  419. if (grammar->stacks[is][ie] == &grammar->rules[ir0][ir1]) {
  420. result->stacks[is][ie] = &result->rules[ir0][ir1];
  421. }
  422. }
  423. }
  424. }
  425. }
  426. return result;
  427. }
  428. void llama_grammar_sample_impl(const struct llama_grammar * grammar, const struct llama_vocab * vocab, const struct llama_sampling * smpl, llama_token_data_array * candidates) {
  429. GGML_ASSERT(grammar);
  430. GGML_ASSERT(vocab);
  431. int64_t t_start_sample_us = ggml_time_us();
  432. bool allow_eog = false;
  433. for (const auto & stack : grammar->stacks) {
  434. if (stack.empty()) {
  435. allow_eog = true;
  436. break;
  437. }
  438. }
  439. std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded;
  440. candidates_decoded.reserve(candidates->size);
  441. llama_grammar_candidates candidates_grammar;
  442. candidates_grammar.reserve(candidates->size);
  443. for (size_t i = 0; i < candidates->size; ++i) {
  444. const llama_token id = candidates->data[i].id;
  445. const std::string & piece = vocab->cache_token_to_piece.at(id);
  446. if (llama_token_is_eog_impl(*vocab, id)) {
  447. if (!allow_eog) {
  448. candidates->data[i].logit = -INFINITY;
  449. }
  450. } else if (piece.empty() || piece[0] == 0) {
  451. candidates->data[i].logit = -INFINITY;
  452. } else {
  453. candidates_decoded.push_back(decode_utf8(piece, grammar->partial_utf8));
  454. candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second });
  455. }
  456. }
  457. const auto rejects = llama_grammar_reject_candidates(grammar->rules, grammar->stacks, candidates_grammar);
  458. for (const auto & reject : rejects) {
  459. candidates->data[reject.index].logit = -INFINITY;
  460. }
  461. smpl->t_sample_us += ggml_time_us() - t_start_sample_us;
  462. }
  463. void llama_grammar_accept_token_impl(struct llama_grammar * grammar, const struct llama_vocab * vocab, const struct llama_sampling * smpl, llama_token token) {
  464. const int64_t t_start_sample_us = ggml_time_us();
  465. if (llama_token_is_eog_impl(*vocab, token)) {
  466. for (const auto & stack : grammar->stacks) {
  467. if (stack.empty()) {
  468. return;
  469. }
  470. }
  471. GGML_ABORT("fatal error");
  472. }
  473. const std::string & piece = vocab->cache_token_to_piece.at(token);
  474. // Note terminating 0 in decoded string
  475. const auto decoded = decode_utf8(piece, grammar->partial_utf8);
  476. const auto & code_points = decoded.first;
  477. llama_grammar_stacks tmp_new_stacks;
  478. for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) {
  479. llama_grammar_accept(grammar->rules, grammar->stacks, *it, tmp_new_stacks);
  480. grammar->stacks = tmp_new_stacks;
  481. }
  482. grammar->partial_utf8 = decoded.second;
  483. GGML_ASSERT(!grammar->stacks.empty());
  484. smpl->t_sample_us += ggml_time_us() - t_start_sample_us;
  485. }