MCPcopy Create free account
hub / github.com/Tiiny-AI/PowerInfer / llama_grammar_advance_stack

Function llama_grammar_advance_stack

llama.cpp:7902–7953  ·  view source on GitHub ↗

transforms a grammar pushdown stack into N possible stacks, all ending at a character range (terminal element)

Source from the content-addressed store, hash-verified

7900// transforms a grammar pushdown stack into N possible stacks, all ending
7901// at a character range (terminal element)
7902static void llama_grammar_advance_stack(
7903 const std::vector<std::vector<llama_grammar_element>> & rules,
7904 const std::vector<const llama_grammar_element *> & stack,
7905 std::vector<std::vector<const llama_grammar_element *>> & new_stacks) {
7906
7907 if (stack.empty()) {
7908 new_stacks.emplace_back(stack);
7909 return;
7910 }
7911
7912 const llama_grammar_element * pos = stack.back();
7913
7914 switch (pos->type) {
7915 case LLAMA_GRETYPE_RULE_REF: {
7916 const size_t rule_id = static_cast<size_t>(pos->value);
7917 const llama_grammar_element * subpos = rules[rule_id].data();
7918 do {
7919 // init new stack without the top (pos)
7920 std::vector<const llama_grammar_element *> new_stack(stack.begin(), stack.end() - 1);
7921 if (!llama_grammar_is_end_of_sequence(pos + 1)) {
7922 // if this rule ref is followed by another element, add that to stack
7923 new_stack.push_back(pos + 1);
7924 }
7925 if (!llama_grammar_is_end_of_sequence(subpos)) {
7926 // if alternate is nonempty, add to stack
7927 new_stack.push_back(subpos);
7928 }
7929 llama_grammar_advance_stack(rules, new_stack, new_stacks);
7930 while (!llama_grammar_is_end_of_sequence(subpos)) {
7931 // scan to end of alternate def
7932 subpos++;
7933 }
7934 if (subpos->type == LLAMA_GRETYPE_ALT) {
7935 // there's another alternate def of this rule to process
7936 subpos++;
7937 } else {
7938 break;
7939 }
7940 } while (true);
7941 break;
7942 }
7943 case LLAMA_GRETYPE_CHAR:
7944 case LLAMA_GRETYPE_CHAR_NOT:
7945 new_stacks.emplace_back(stack);
7946 break;
7947 default:
7948 // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range
7949 // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on
7950 // those
7951 GGML_ASSERT(false);
7952 }
7953}
7954
7955// takes a set of possible pushdown stacks on a grammar, which are required to
7956// be positioned at a character range (see `llama_grammar_advance_stack`), and

Callers 3

llama_grammar_acceptFunction · 0.70
llama_grammar_initFunction · 0.70

Calls 6

emptyMethod · 0.45
dataMethod · 0.45
beginMethod · 0.45
endMethod · 0.45
push_backMethod · 0.45

Tested by

no test coverage detected