| 2875 | } |
| 2876 | |
| 2877 | void llm_graph_context::build_sampling() const { |
| 2878 | if (samplers.empty() || !res->t_logits) { |
| 2879 | return; |
| 2880 | } |
| 2881 | |
| 2882 | std::array<ggml_tensor *, 2> outs; |
| 2883 | outs[0] = res->t_logits; |
| 2884 | |
| 2885 | auto inp_sampling = std::make_unique<llm_graph_input_sampling>(samplers); |
| 2886 | res->add_input(std::move(inp_sampling)); |
| 2887 | |
| 2888 | std::map<llama_seq_id, int32_t> seq_to_logit_row; |
| 2889 | int32_t logit_row_idx = 0; |
| 2890 | |
| 2891 | for (uint32_t i = 0; i < ubatch.n_tokens; i++) { |
| 2892 | if (ubatch.output[i]) { |
| 2893 | llama_seq_id seq_id = ubatch.seq_id[i][0]; |
| 2894 | seq_to_logit_row[seq_id] = logit_row_idx; |
| 2895 | logit_row_idx++; |
| 2896 | } |
| 2897 | } |
| 2898 | |
| 2899 | // res->t_logits will contain logits for all tokens that want the logits calculated (logits=1 or output=1) |
| 2900 | GGML_ASSERT(res->t_logits != nullptr && "missing t_logits tensor"); |
| 2901 | |
| 2902 | // add a dummy row of logits |
| 2903 | // this trick makes the graph static, regardless of which samplers are activated |
| 2904 | // this is important in order to minimize graph reallocations |
| 2905 | ggml_tensor * logits_t = ggml_pad(ctx0, res->t_logits, 0, 1, 0, 0); |
| 2906 | |
| 2907 | for (const auto & [seq_id, sampler] : samplers) { |
| 2908 | const auto it = seq_to_logit_row.find(seq_id); |
| 2909 | |
| 2910 | // inactive samplers always work on the first row |
| 2911 | const auto row_idx = it != seq_to_logit_row.end() ? it->second : 0; |
| 2912 | const int i_out = it != seq_to_logit_row.end() ? 1 : 0; |
| 2913 | |
| 2914 | ggml_tensor * logits_seq = ggml_view_1d(ctx0, logits_t, logits_t->ne[0], row_idx * logits_t->nb[1]); |
| 2915 | ggml_format_name(logits_seq, "logits_seq_%d", seq_id); |
| 2916 | |
| 2917 | struct llama_sampler_data data = { |
| 2918 | /*.logits =*/ logits_seq, |
| 2919 | /*.probs =*/ nullptr, |
| 2920 | /*.sampled =*/ nullptr, |
| 2921 | /*.candidates =*/ nullptr, |
| 2922 | }; |
| 2923 | |
| 2924 | assert(sampler->iface->backend_apply); |
| 2925 | sampler->iface->backend_apply(sampler, ctx0, gf, &data); |
| 2926 | |
| 2927 | if (data.sampled != nullptr) { |
| 2928 | res->t_sampled[seq_id] = data.sampled; |
| 2929 | outs[1] = data.sampled; |
| 2930 | ggml_build_forward_select(gf, outs.data(), outs.size(), i_out); |
| 2931 | } |
| 2932 | |
| 2933 | if (data.probs != nullptr) { |
| 2934 | res->t_sampled_probs[seq_id] = data.probs; |
no test coverage detected