-
Notifications
You must be signed in to change notification settings - Fork 455
Batched Beam Search #796
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Batched Beam Search #796
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,134 @@ | ||
using LLama.Batched; | ||
using LLama.Common; | ||
using LLama.Native; | ||
using Spectre.Console; | ||
|
||
namespace LLama.Examples.Examples; | ||
|
||
/// <summary> | ||
/// This demonstrates beam search using the batched executor | ||
/// </summary> | ||
public class BatchedExecutorBeamSearch | ||
{ | ||
public static async Task Run() | ||
{ | ||
// Load model weights | ||
var parameters = new ModelParams(UserSettings.GetModelPath()); | ||
using var model = await LLamaWeights.LoadFromFileAsync(parameters); | ||
|
||
var prompt = AnsiConsole.Ask("Prompt (or ENTER for default):", "The cat sat on"); | ||
var tokensGenerate = AnsiConsole.Ask<int>("How many tokens to generate?", 8); | ||
var beamsCount = AnsiConsole.Ask<int>("How many parallel beams to keep track of?", 8); | ||
|
||
// Create an executor that can evaluate a batch of conversations together | ||
using var executor = new BatchedExecutor(model, parameters); | ||
|
||
// Print some info | ||
var name = model.Metadata.GetValueOrDefault("general.name", "unknown model name"); | ||
Console.WriteLine($"Created executor with model: {name}"); | ||
|
||
// Evaluate the initial prompt to create one conversation | ||
var conversation = executor.Create(); | ||
var startTokens = executor.Context.Tokenize(prompt); | ||
conversation.Prompt(startTokens); | ||
|
||
// Create one beam, containing that conversation | ||
var beams = new List<Beam>(); | ||
beams.Add(new Beam(conversation, 1.0, startTokens, [conversation.ConversationId])); | ||
|
||
// Print the prompt | ||
Console.ForegroundColor = ConsoleColor.Green; | ||
Console.WriteLine(prompt); | ||
|
||
// Generate loop | ||
for (var i = 0; i < tokensGenerate; i++) | ||
{ | ||
await executor.Infer(); | ||
|
||
// Create new beams, forked from all original beams | ||
beams = (from oldBeam in beams | ||
from beam in oldBeam.Sample(beamsCount) | ||
select beam).OrderBy(a => a.CumulativeProbability).ToList(); | ||
|
||
// Trim down list by removing low probability beams | ||
while (beams.Count > beamsCount) | ||
{ | ||
var beam = beams[0]; | ||
AnsiConsole.MarkupLineInterpolated($"[red]Culling Beam {beam.Conversation.ConversationId} (prob:{beam.CumulativeProbability:P10})[/]: {beam}"); | ||
|
||
beam.Dispose(); | ||
beams.RemoveAt(0); | ||
} | ||
} | ||
|
||
// Print out all remaining beams | ||
AnsiConsole.MarkupLineInterpolated($"Final Beams:"); | ||
beams.Reverse(); | ||
foreach (var beam in beams) | ||
AnsiConsole.MarkupLineInterpolated($"[green](prob:{beam.CumulativeProbability:P10})[/]: {beam}"); | ||
|
||
Console.WriteLine("Press any key to exit demo"); | ||
Console.ReadKey(true); | ||
} | ||
|
||
private class Beam | ||
: IDisposable | ||
{ | ||
public readonly Conversation Conversation; | ||
public readonly double CumulativeProbability; | ||
public readonly IReadOnlyList<LLamaToken> Tokens; | ||
public readonly IReadOnlyList<LLamaSeqId> Sequence; | ||
|
||
public Beam(Conversation conversation, double prob, IReadOnlyList<LLamaToken> tokens, IReadOnlyList<LLamaSeqId> sequence) | ||
{ | ||
Conversation = conversation; | ||
CumulativeProbability = prob; | ||
Tokens = tokens; | ||
Sequence = sequence; | ||
} | ||
|
||
public void Dispose() | ||
{ | ||
Conversation.Dispose(); | ||
} | ||
|
||
public List<Beam> Sample(int nbeams) | ||
{ | ||
// Apply softmax, this calculates probabilities and sorts tokens into descending order | ||
var logitsArr = LLamaTokenDataArray.Create(Conversation.Sample()); | ||
logitsArr.Softmax(Conversation.Executor.Context.NativeHandle); | ||
|
||
// Create new forked conversations, one for each beam | ||
var results = new List<Beam>(); | ||
for (var i = 0; i < nbeams; i++) | ||
{ | ||
var item = logitsArr.Data.Span[i]; | ||
|
||
var c = Conversation.Fork(); | ||
c.Prompt(item.id); | ||
|
||
var p = CumulativeProbability * item.p; | ||
|
||
var t = Tokens.ToList(); | ||
t.Add(item.id); | ||
|
||
var s = Sequence.ToList(); | ||
s.Add(c.ConversationId); | ||
|
||
results.Add(new Beam(c, p, t, s)); | ||
} | ||
|
||
// Dispose self now that child beams have spawned | ||
Conversation.Dispose(); | ||
return results; | ||
} | ||
|
||
public override string ToString() | ||
{ | ||
#pragma warning disable CS0618 // Type or member is obsolete | ||
return Conversation.Executor.Context.DeTokenize(Tokens); | ||
#pragma warning restore CS0618 // Type or member is obsolete | ||
|
||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.