| 58 | } |
| 59 | |
| 60 | bool Qwen3::insert(chat_meta_info_t& meta_info, lm_uniform_input_t& input, std::function<bool()> is_cancelled) { |
| 61 | // preprocess |
| 62 | this->profiler_list[TKOEN_ENCODE_TIME].start(); |
| 63 | std::string templated_text; |
| 64 | if (input.messages.empty() && input.prompt.empty()) { |
| 65 | header_print("WARNING", "No messages or prompt provided"); |
| 66 | return false; |
| 67 | } |
| 68 | if (!input.messages.empty()) { // already a formated messages, usually from REST API |
| 69 | templated_text = this->apply_chat_template(input.messages, input.tools); |
| 70 | } |
| 71 | else if (!input.prompt.empty()) { // a pure text, usually from the cli |
| 72 | nlohmann::ordered_json messages; |
| 73 | |
| 74 | messages.push_back({ {"role", "user"}, {"content", input.prompt} }); |
| 75 | templated_text = this->apply_chat_template(messages); |
| 76 | } |
| 77 | |
| 78 | std::vector<int> tokens = this->tokenizer->encode(templated_text); |
| 79 | |
| 80 | this->profiler_list[TKOEN_ENCODE_TIME].stop(tokens.size()); |
| 81 | |
| 82 | // hardware |
| 83 | int restore_idx = -1; |
| 84 | qwen3_npu *qwen3_engine = dynamic_cast<qwen3_npu*>(this->lm_engine.get()); |
| 85 | |
| 86 | if (meta_info.restore_allowed) { |
| 87 | restore_idx = qwen3_engine->restore(); |
| 88 | this->total_tokens = restore_idx; |
| 89 | this->token_history = checkpoint_his; // restore the token history to be consistent with the restored KV cache, which is crucial for correct functioning of _shared_insert's prefix-matching logic |
| 90 | } |
| 91 | |
| 92 | size_t n = tokens.size(); |
| 93 | tokens.resize(n - (this->enable_think ? 0 : 4)); |
| 94 | |
| 95 | bool success = this->_shared_insert(meta_info, tokens, is_cancelled, nullptr); |
| 96 | |
| 97 | checkpoint_his = token_history; |
| 98 | int checkpoint_idx = qwen3_engine->checkpoint(); |
| 99 | return success; |
| 100 | } |
| 101 | |
| 102 | std::string Qwen3::generate(chat_meta_info_t& meta_info, int length_limit, std::ostream& os, std::function<bool()> is_cancelled) { |
| 103 | std::vector<int> sampled_tokens; |
no test coverage detected