|
| 1 | +# Batch decoding |
| 2 | + |
| 3 | +```cs |
| 4 | +using System.Diagnostics; |
| 5 | +using System.Text; |
| 6 | +using LLama.Common; |
| 7 | +using LLama.Native; |
| 8 | +using LLama.Sampling; |
| 9 | + |
| 10 | +public class BatchedDecoding |
| 11 | +{ |
| 12 | + private const int n_parallel = 8; |
| 13 | + private const int n_len = 32; |
| 14 | + |
| 15 | + public static async Task Run() |
| 16 | + { |
| 17 | + Console.Write("Please input your model path: "); |
| 18 | + var modelPath = Console.ReadLine(); |
| 19 | + |
| 20 | + Console.WriteLine("Prompt (leave blank to select automatically):"); |
| 21 | + var prompt = Console.ReadLine(); |
| 22 | + if (string.IsNullOrWhiteSpace(prompt)) |
| 23 | + prompt = "Not many people know that"; |
| 24 | + |
| 25 | + // Load model |
| 26 | + var parameters = new ModelParams(modelPath); |
| 27 | + |
| 28 | + using var model = LLamaWeights.LoadFromFile(parameters); |
| 29 | + |
| 30 | + // Tokenize prompt |
| 31 | + var prompt_tokens = model.Tokenize(prompt, true, false, Encoding.UTF8); |
| 32 | + var n_kv_req = prompt_tokens.Length + (n_len - prompt_tokens.Length) * n_parallel; |
| 33 | + |
| 34 | + // Create a context |
| 35 | + parameters.ContextSize = (uint)model.ContextSize; |
| 36 | + parameters.BatchSize = (uint)Math.Max(n_len, n_parallel); |
| 37 | + using var context = model.CreateContext(parameters); |
| 38 | + |
| 39 | + var n_ctx = context.ContextSize; |
| 40 | + |
| 41 | + // make sure the KV cache is big enough to hold all the prompt and generated tokens |
| 42 | + if (n_kv_req > n_ctx) |
| 43 | + { |
| 44 | + await Console.Error.WriteLineAsync($"error: n_kv_req ({n_kv_req}) > n_ctx, the required KV cache size is not big enough\n"); |
| 45 | + await Console.Error.WriteLineAsync(" either reduce n_parallel or increase n_ctx\n"); |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + var batch = new LLamaBatch(); |
| 50 | + |
| 51 | + // evaluate the initial prompt |
| 52 | + batch.AddRange(prompt_tokens, 0, LLamaSeqId.Zero, true); |
| 53 | + |
| 54 | + if (await context.DecodeAsync(batch) != DecodeResult.Ok) |
| 55 | + { |
| 56 | + await Console.Error.WriteLineAsync("llama_decode failed"); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + // assign the system KV cache to all parallel sequences |
| 61 | + // this way, the parallel sequences will "reuse" the prompt tokens without having to copy them |
| 62 | + for (var i = 1; i < n_parallel; ++i) |
| 63 | + { |
| 64 | + context.NativeHandle.KvCacheSequenceCopy((LLamaSeqId)0, (LLamaSeqId)i, 0, batch.TokenCount); |
| 65 | + } |
| 66 | + |
| 67 | + if (n_parallel > 1) |
| 68 | + { |
| 69 | + Console.WriteLine(); |
| 70 | + Console.WriteLine($"generating {n_parallel} sequences..."); |
| 71 | + } |
| 72 | + |
| 73 | + // remember the batch index of the last token for each parallel sequence |
| 74 | + // we need this to determine which logits to sample from |
| 75 | + List<int> i_batch = new(); |
| 76 | + for (var i = 0; i < n_parallel; i++) |
| 77 | + i_batch.Add(batch.TokenCount - 1); |
| 78 | + |
| 79 | + // Create per-stream decoder and sampler |
| 80 | + var decoders = new StreamingTokenDecoder[n_parallel]; |
| 81 | + var samplers = new ISamplingPipeline[n_parallel]; |
| 82 | + for (var i = 0; i < n_parallel; i++) |
| 83 | + { |
| 84 | + decoders[i] = new StreamingTokenDecoder(context); |
| 85 | + samplers[i] = new DefaultSamplingPipeline |
| 86 | + { |
| 87 | + Temperature = 0.1f + (float)i / n_parallel, |
| 88 | + MinP = 0.25f, |
| 89 | + }; |
| 90 | + } |
| 91 | + |
| 92 | + var n_cur = batch.TokenCount; |
| 93 | + var n_decode = 0; |
| 94 | + |
| 95 | + var timer = new Stopwatch(); |
| 96 | + timer.Start(); |
| 97 | + while (n_cur <= n_len) |
| 98 | + { |
| 99 | + batch.Clear(); |
| 100 | + |
| 101 | + for (var i = 0; i < n_parallel; i++) |
| 102 | + { |
| 103 | + // Skip completed streams |
| 104 | + if (i_batch[i] < 0) |
| 105 | + continue; |
| 106 | + |
| 107 | + // Use the sampling pipeline to select a token |
| 108 | + var new_token_id = samplers[i].Sample( |
| 109 | + context.NativeHandle, |
| 110 | + context.NativeHandle.GetLogitsIth(i_batch[i]), |
| 111 | + Array.Empty<LLamaToken>() |
| 112 | + ); |
| 113 | + |
| 114 | + // Finish this stream early if necessary |
| 115 | + if (new_token_id == model.EndOfSentenceToken || new_token_id == model.NewlineToken) |
| 116 | + { |
| 117 | + i_batch[i] = -1; |
| 118 | + Console.WriteLine($"Completed Stream {i} early"); |
| 119 | + continue; |
| 120 | + } |
| 121 | + |
| 122 | + // Add this token to the decoder, so it will be turned into text |
| 123 | + decoders[i].Add(new_token_id); |
| 124 | + |
| 125 | + i_batch[i] = batch.TokenCount; |
| 126 | + |
| 127 | + // push this new token for next evaluation |
| 128 | + batch.Add(new_token_id, n_cur, (LLamaSeqId)i, true); |
| 129 | + |
| 130 | + n_decode++; |
| 131 | + } |
| 132 | + |
| 133 | + // Check if all streams are finished |
| 134 | + if (batch.TokenCount == 0) |
| 135 | + { |
| 136 | + break; |
| 137 | + } |
| 138 | + |
| 139 | + n_cur++; |
| 140 | + |
| 141 | + // evaluate the current batch with the transformer model |
| 142 | + if (await context.DecodeAsync(batch) != 0) |
| 143 | + { |
| 144 | + await Console.Error.WriteLineAsync("failed to eval"); |
| 145 | + return; |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + timer.Stop(); |
| 150 | + Console.ForegroundColor = ConsoleColor.Yellow; |
| 151 | + Console.WriteLine(); |
| 152 | + Console.WriteLine($"Decoded {n_decode} tokens in {timer.ElapsedMilliseconds}ms"); |
| 153 | + Console.WriteLine($"Rate: {n_decode / timer.Elapsed.TotalSeconds:##.000} tokens/second"); |
| 154 | + |
| 155 | + var index = 0; |
| 156 | + foreach (var stream in decoders) |
| 157 | + { |
| 158 | + var text = stream.Read(); |
| 159 | + |
| 160 | + Console.ForegroundColor = ConsoleColor.Green; |
| 161 | + Console.Write($"{index++}. {prompt}"); |
| 162 | + Console.ForegroundColor = ConsoleColor.Red; |
| 163 | + Console.WriteLine(text); |
| 164 | + } |
| 165 | + |
| 166 | + Console.WriteLine("Press any key to exit demo"); |
| 167 | + Console.ReadKey(true); |
| 168 | + } |
| 169 | +} |
| 170 | +``` |
0 commit comments