| 1116 | } |
| 1117 | |
| 1118 | void llama_grammar_apply_impl(const struct llama_grammar & grammar, llama_token_data_array * cur_p) { |
| 1119 | GGML_ASSERT(grammar.vocab != nullptr); |
| 1120 | |
| 1121 | if (grammar.awaiting_trigger) { |
| 1122 | return; |
| 1123 | } |
| 1124 | |
| 1125 | bool allow_eog = false; |
| 1126 | for (const auto & stack : grammar.stacks) { |
| 1127 | if (stack.empty()) { |
| 1128 | allow_eog = true; |
| 1129 | break; |
| 1130 | } |
| 1131 | } |
| 1132 | |
| 1133 | std::vector<std::pair<std::vector<uint32_t>, llama_partial_utf8>> candidates_decoded; |
| 1134 | candidates_decoded.reserve(cur_p->size); |
| 1135 | |
| 1136 | llama_grammar_candidates candidates_grammar; |
| 1137 | candidates_grammar.reserve(cur_p->size); |
| 1138 | |
| 1139 | for (size_t i = 0; i < cur_p->size; ++i) { |
| 1140 | const llama_token id = cur_p->data[i].id; |
| 1141 | const std::string & piece = grammar.vocab->token_to_piece(id); |
| 1142 | |
| 1143 | if (grammar.vocab->is_eog(id)) { |
| 1144 | if (!allow_eog) { |
| 1145 | cur_p->data[i].logit = -INFINITY; |
| 1146 | } |
| 1147 | } else if (piece.empty() || piece[0] == 0) { |
| 1148 | cur_p->data[i].logit = -INFINITY; |
| 1149 | } else { |
| 1150 | candidates_decoded.push_back(decode_utf8(piece, grammar.partial_utf8)); |
| 1151 | candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second }); |
| 1152 | } |
| 1153 | } |
| 1154 | |
| 1155 | const auto rejects = llama_grammar_reject_candidates(grammar.rules, grammar.stacks, candidates_grammar); |
| 1156 | for (const auto & reject : rejects) { |
| 1157 | cur_p->data[reject.index].logit = -INFINITY; |
| 1158 | } |
| 1159 | } |
| 1160 | |
| 1161 | void llama_grammar_accept_impl(struct llama_grammar & grammar, llama_token token) { |
| 1162 | GGML_ASSERT(grammar.vocab != nullptr); |
no test coverage detected