-
Notifications
You must be signed in to change notification settings - Fork 470
Custom Sampler Stages #961
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
martindevans
merged 7 commits into
SciSharp:master
from
martindevans:experimental_custom_sampler_wip
Oct 29, 2024
+337
−38
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
79aca7f
WIP custom sampler, doesn't work
martindevans 03f4b34
- Fixed calls causing an access violation exception (the pointer is t…
martindevans 7c05517
Added cloning for custom samplers
martindevans a88ecba
Fixed spelling
martindevans 6b10049
- Replaced `Free` with more conventional `IDisposable` on `ICustomSam…
martindevans 44c1ff0
Fixed example project
martindevans 8af713e
Fixed getting name of sampler stages:
martindevans 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,114 @@ | ||
using LLama.Common; | ||
using LLama.Examples.Extensions; | ||
using LLama.Native; | ||
using LLama.Sampling; | ||
|
||
namespace LLama.Examples.Examples | ||
{ | ||
public class CustomSampler | ||
{ | ||
public static async Task Run() | ||
{ | ||
var modelPath = UserSettings.GetModelPath(); | ||
|
||
var parameters = new ModelParams(modelPath); | ||
using var model = await LLamaWeights.LoadFromFileAsync(parameters); | ||
|
||
var ex = new StatelessExecutor(model, parameters); | ||
|
||
Console.ForegroundColor = ConsoleColor.Yellow; | ||
Console.WriteLine("In this example a custom sampling pipeline with a custom sampler stage is being used. This demonstrates how to customise the samplers used, and " + | ||
"how to create a completely custom sampler stage which modifies the logits or selects a token." + | ||
"" + | ||
"In this case the custom sampler stage removes the most likely token. This will probably produce bad results, it's just a demo!" | ||
); | ||
Console.ForegroundColor = ConsoleColor.White; | ||
|
||
var inferenceParams = new InferenceParams | ||
{ | ||
SamplingPipeline = new CustomSamplingPipeline(), | ||
MaxTokens = 50 | ||
}; | ||
|
||
while (true) | ||
{ | ||
Console.Write("\nQuestion: "); | ||
Console.ForegroundColor = ConsoleColor.Green; | ||
var prompt = Console.ReadLine(); | ||
Console.ForegroundColor = ConsoleColor.White; | ||
Console.Write("Answer: "); | ||
prompt = $"Question: {prompt?.Trim()} Answer: "; | ||
await foreach (var text in ex.InferAsync(prompt, inferenceParams).Spinner()) | ||
{ | ||
Console.Write(text); | ||
} | ||
} | ||
} | ||
} | ||
|
||
public class CustomSamplingPipeline | ||
: BaseSamplingPipeline | ||
{ | ||
protected override SafeLLamaSamplerChainHandle CreateChain(SafeLLamaContextHandle context) | ||
{ | ||
var chain = SafeLLamaSamplerChainHandle.Create(LLamaSamplerChainParams.Default()); | ||
|
||
// Take only the 10 most likely tokens | ||
chain.AddTopK(10); | ||
|
||
// Remove the most likely token | ||
chain.AddCustom(new RemoveMostLikelyToken()); | ||
|
||
// Select from the distribution | ||
chain.AddSoftmax(); | ||
chain.AddDistributionSampler(42); | ||
|
||
return chain; | ||
} | ||
} | ||
|
||
public class RemoveMostLikelyToken | ||
: ICustomSampler | ||
{ | ||
public string Name => "Remove Most Likely Token"; | ||
|
||
public void Apply(ref LLamaTokenDataArrayNative tokenData) | ||
{ | ||
// Doesn't make sense to run this stage if there is only one candidate left | ||
if (tokenData.Size <= 1) | ||
return; | ||
|
||
// Ensure token data is sorted, so most likely token is first. | ||
// Note that this is a descending sort, the **largest** value is first. | ||
if (!tokenData.Sorted) | ||
tokenData.Data.Sort((a, b) => b.Logit.CompareTo(a.Logit)); | ||
|
||
// Make the most likely token impossible to pick | ||
tokenData.Data[0].Logit = float.NegativeInfinity; | ||
|
||
// It's **critically** important to set this if the logits are no longer sorted after the custom | ||
// sampler has run. If you're not sure, it's always safer to set it to false. | ||
// | ||
// In this case, because the first logit has just been set to negative infinity | ||
// the token data is definitely not sorted! | ||
tokenData.Sorted = false; | ||
} | ||
|
||
public void Accept(LLamaToken token) | ||
{ | ||
} | ||
|
||
public void Reset() | ||
{ | ||
} | ||
|
||
public ICustomSampler Clone() | ||
{ | ||
return new RemoveMostLikelyToken(); | ||
} | ||
|
||
public void Dispose() | ||
{ | ||
} | ||
} | ||
} |
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.
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.