| 1990 | } |
| 1991 | |
| 1992 | server_prompt * server_prompt_cache::alloc(const server_prompt & prompt, size_t state_size) { |
| 1993 | // first check if the current state is contained fully in the cache |
| 1994 | for (auto it = states.begin(); it != states.end(); ++it) { |
| 1995 | const int cur_lcp_len = it->tokens.get_common_prefix(prompt.tokens); |
| 1996 | |
| 1997 | if (cur_lcp_len == (int) prompt.tokens.size()) { |
| 1998 | SRV_WRN("%s", " - prompt is already in the cache, skipping\n"); |
| 1999 | return nullptr; |
| 2000 | } |
| 2001 | } |
| 2002 | |
| 2003 | // next, remove any cached prompts that are fully contained in the current prompt |
| 2004 | for (auto it = states.begin(); it != states.end();) { |
| 2005 | const int len = it->tokens.get_common_prefix(prompt.tokens); |
| 2006 | |
| 2007 | if (len == (int) it->tokens.size()) { |
| 2008 | SRV_WRN(" - removing obsolete cached prompt with length %d\n", len); |
| 2009 | |
| 2010 | it = states.erase(it); |
| 2011 | } else { |
| 2012 | ++it; |
| 2013 | } |
| 2014 | } |
| 2015 | |
| 2016 | std::vector<uint8_t> state_data; |
| 2017 | |
| 2018 | // check if we can allocate enough memory for the new state |
| 2019 | try { |
| 2020 | state_data.resize(state_size); |
| 2021 | } catch (const std::bad_alloc & e) { |
| 2022 | SRV_ERR("failed to allocate memory for prompt cache state: %s\n", e.what()); |
| 2023 | |
| 2024 | limit_size = std::max<size_t>(1, 0.4*size()); |
| 2025 | |
| 2026 | SRV_WRN(" - cache size limit reduced to %.3f MiB\n", limit_size / (1024.0 * 1024.0)); |
| 2027 | |
| 2028 | update(); |
| 2029 | |
| 2030 | return nullptr; |
| 2031 | } |
| 2032 | |
| 2033 | auto & cur = states.emplace_back(); |
| 2034 | cur = { |
| 2035 | /*.tokens =*/ prompt.tokens.clone(), |
| 2036 | /*.data =*/ std::move(state_data), |
| 2037 | /*.checkpoints =*/ prompt.checkpoints, |
| 2038 | }; |
| 2039 | |
| 2040 | return &cur; |
| 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); |
no test coverage detected