| 2041 | } |
| 2042 | |
| 2043 | bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx, int32_t id_slot) { |
| 2044 | const int lcp_best = prompt.tokens.get_common_prefix(tokens_new); |
| 2045 | |
| 2046 | float f_keep_best = prompt.tokens.size() > 0 ? float(lcp_best) / prompt.tokens.size() : -1.0f; // empty slot: any cache entry wins |
| 2047 | float sim_best = float(lcp_best) / tokens_new.size(); |
| 2048 | |
| 2049 | SRV_WRN(" - looking for better prompt, base f_keep = %.3f, sim = %.3f\n", f_keep_best, sim_best); |
| 2050 | |
| 2051 | auto it_best = states.end(); |
| 2052 | |
| 2053 | // find the most similar cached prompt, that would also preserve the most context |
| 2054 | for (auto it = states.begin(); it != states.end(); ++it) { |
| 2055 | const int lcp_cur = it->tokens.get_common_prefix(tokens_new); |
| 2056 | |
| 2057 | const float f_keep_cur = float(lcp_cur) / it->tokens.size(); |
| 2058 | const float sim_cur = float(lcp_cur) / tokens_new.size(); |
| 2059 | |
| 2060 | // don't trash large prompts |
| 2061 | if (f_keep_cur < 0.25f) { |
| 2062 | continue; |
| 2063 | } |
| 2064 | |
| 2065 | if (f_keep_best < f_keep_cur && sim_best < sim_cur) { |
| 2066 | f_keep_best = f_keep_cur; |
| 2067 | sim_best = sim_cur; |
| 2068 | |
| 2069 | it_best = it; |
| 2070 | } |
| 2071 | } |
| 2072 | |
| 2073 | if (it_best != states.end()) { |
| 2074 | SRV_WRN(" - found better prompt with f_keep = %.3f, sim = %.3f\n", f_keep_best, sim_best); |
| 2075 | |
| 2076 | const size_t size = it_best->data.size(); |
| 2077 | const size_t n = llama_state_seq_set_data_ext(ctx, it_best->data.data(), size, id_slot, 0); |
| 2078 | if (n != size) { |
| 2079 | SRV_WRN("failed to restore state with size %zu\n", size); |
| 2080 | |
| 2081 | return false; |
| 2082 | } |
| 2083 | |
| 2084 | it_best->data.clear(); |
| 2085 | it_best->data.shrink_to_fit(); |
| 2086 | |
| 2087 | prompt = std::move(*it_best); |
| 2088 | |
| 2089 | states.erase(it_best); |
| 2090 | } |
| 2091 | |
| 2092 | return true; |
| 2093 | } |
| 2094 | |
| 2095 | void server_prompt_cache::update() { |
| 2096 | if (limit_size > 0) { |