| 1910 | } |
| 1911 | |
| 1912 | bool common_prompt_batch_decode( |
| 1913 | struct llama_context * ctx, |
| 1914 | const std::vector<llama_token> & tokens, |
| 1915 | int & n_past, |
| 1916 | int n_batch, |
| 1917 | std::string_view state_path, |
| 1918 | bool save_state) { |
| 1919 | const int n_eval = tokens.size(); |
| 1920 | if (n_eval == 0) { |
| 1921 | return true; |
| 1922 | } |
| 1923 | |
| 1924 | if (save_state && n_eval > 1) { |
| 1925 | const int n_tokens_before_last = n_eval - 1; |
| 1926 | |
| 1927 | GGML_ASSERT(n_eval <= n_batch); |
| 1928 | |
| 1929 | // Decode all but the last token so we can save the memory state before decoding the last token. |
| 1930 | // This is done so we can restore the session state later and replay the last token. |
| 1931 | // Memory implementations in recurrent/hybrid models don't support removing tokens from their |
| 1932 | // memory, so we can't just remove the last token from the memory and replay the last token which |
| 1933 | // is the reason for this logic. |
| 1934 | if (llama_decode(ctx, llama_batch_get_one(const_cast<llama_token*>(tokens.data()), n_tokens_before_last))) { |
| 1935 | LOG_ERR("%s : failed to eval\n", __func__); |
| 1936 | return false; |
| 1937 | } |
| 1938 | n_past += n_tokens_before_last; |
| 1939 | |
| 1940 | llama_state_save_file(ctx, state_path.data(), tokens.data(), n_tokens_before_last); |
| 1941 | LOG_INF("saved session before last token to %s, n_tokens = %d\n", state_path.data(), n_tokens_before_last); |
| 1942 | |
| 1943 | llama_token last_token = tokens.back(); |
| 1944 | llama_batch batch = llama_batch_get_one(&last_token, 1); |
| 1945 | int32_t pos = n_past; |
| 1946 | batch.pos = &pos; |
| 1947 | |
| 1948 | if (llama_decode(ctx, batch)) { |
| 1949 | LOG_ERR("%s : failed to eval last token\n", __func__); |
| 1950 | return false; |
| 1951 | } |
| 1952 | n_past++; |
| 1953 | } else { |
| 1954 | if (llama_decode(ctx, llama_batch_get_one(const_cast<llama_token*>(tokens.data()), n_eval))) { |
| 1955 | LOG_ERR("%s : failed to eval\n", __func__); |
| 1956 | return false; |
| 1957 | } |
| 1958 | n_past += n_eval; |
| 1959 | } |
| 1960 | |
| 1961 | return true; |
| 1962 | } |
no test coverage detected