| 872 | } |
| 873 | |
| 874 | int llama_context::decode(llama_batch & inp_batch) { |
| 875 | if (!memory) { |
| 876 | LLAMA_LOG_DEBUG("%s: cannot decode batches with this context (calling encode() instead)\n", __func__); |
| 877 | return encode(inp_batch); |
| 878 | } |
| 879 | |
| 880 | if (inp_batch.n_tokens == 0) { |
| 881 | LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__); |
| 882 | return -1; |
| 883 | } |
| 884 | |
| 885 | if (!inp_batch.pos) { |
| 886 | if (inp_batch.seq_id) { |
| 887 | LLAMA_LOG_ERROR("%s: pos == NULL, but seq_id != NULL\n", __func__); |
| 888 | return -1; |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | llama_kv_cache * kv_self = static_cast<llama_kv_cache *>(memory.get()); |
| 893 | |
| 894 | // temporary allocate memory for the input batch if needed |
| 895 | llama_batch_allocr batch_allocr(inp_batch, inp_batch.pos ? -1 : kv_self->seq_pos_max(0) + 1); |
| 896 | |
| 897 | const llama_batch & batch = batch_allocr.batch; |
| 898 | |
| 899 | const auto & vocab = model.vocab; |
| 900 | const auto & hparams = model.hparams; |
| 901 | |
| 902 | const int32_t n_vocab = vocab.n_tokens(); |
| 903 | |
| 904 | const int64_t n_tokens_all = batch.n_tokens; |
| 905 | const int64_t n_embd = hparams.n_embd; |
| 906 | |
| 907 | GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); // NOLINT |
| 908 | |
| 909 | // TODO: move the validation to the llama_batch_allocr |
| 910 | if (batch.token) { |
| 911 | for (int64_t i = 0; i < n_tokens_all; ++i) { |
| 912 | if (batch.token[i] < 0 || (uint32_t) batch.token[i] >= model.vocab.n_tokens()) { |
| 913 | LLAMA_LOG_ERROR("%s: invalid token[%" PRId64 "] = %d\n", __func__, i, batch.token[i]); |
| 914 | return -1; |
| 915 | } |
| 916 | |
| 917 | if (batch.seq_id && (batch.seq_id[i][0] < 0 || batch.seq_id[i][0] >= LLAMA_MAX_PARALLEL_SEQUENCES)) { |
| 918 | LLAMA_LOG_ERROR("%s: invalid seq_id[%" PRId64 "] = %d >= %d\n", __func__, i, batch.seq_id[i][0], LLAMA_MAX_PARALLEL_SEQUENCES); |
| 919 | return -1; |
| 920 | } |
| 921 | } |
| 922 | } |
| 923 | |
| 924 | GGML_ASSERT(n_tokens_all <= cparams.n_batch); |
| 925 | |
| 926 | GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); |
| 927 | |
| 928 | if (t_compute_start_us == 0) { |
| 929 | t_compute_start_us = ggml_time_us(); |
| 930 | } |
| 931 | n_queued_tokens += n_tokens_all; |