Märkus.
Juurdepääs sellele lehele nõuab autoriseerimist. Võite proovida sisse logida või kausta vahetada.
Juurdepääs sellele lehele nõuab autoriseerimist. Võite proovida kausta vahetada.
The Microsoft.ML.Tokenizers library provides a comprehensive set of tools for tokenizing text in .NET applications. Tokenization is essential when you work with large language models (LLMs), as it allows you to manage token counts, estimate costs, and preprocess text for AI models.
This article shows you how to use the library's key features and work with different tokenizer models.
Prerequisites
- .NET 8 SDK or later
Note
The Microsoft.ML.Tokenizers library also supports .NET Standard 2.0, making it compatible with .NET Framework 4.6.1 and later.
Install the package
Install the Microsoft.ML.Tokenizers NuGet package:
dotnet add package Microsoft.ML.Tokenizers
For Tiktoken models (like GPT-4), you also need to install the corresponding data package:
dotnet add package Microsoft.ML.Tokenizers.Data.O200kBase
Key features
The Microsoft.ML.Tokenizers library provides:
- Extensible tokenizer architecture: Allows specialization of Normalizer, PreTokenizer, Model/Encoder, and Decoder components.
- Multiple tokenization algorithms: Supports BPE (byte-pair encoding), Tiktoken, Llama, CodeGen, and more.
- Token counting and estimation: Helps manage costs and context limits when working with AI services.
- Flexible encoding options: Provides methods to encode text to token IDs, count tokens, and decode tokens back to text.
Use Tiktoken tokenizer
The Tiktoken tokenizer is commonly used with OpenAI models like GPT-4. The following example shows how to initialize a Tiktoken tokenizer and perform common operations:
// Initialize the tokenizer for the gpt-4o model.
Tokenizer tokenizer = TiktokenTokenizer.CreateForModel("gpt-4o");
string source = "Text tokenization is the process of splitting a string into a list of tokens.";
// Count the tokens in the text.
Console.WriteLine($"Tokens: {tokenizer.CountTokens(source)}");
// Output: Tokens: 16
// Encode text to token IDs.
IReadOnlyList<int> ids = tokenizer.EncodeToIds(source);
Console.WriteLine($"Token IDs: {string.Join(", ", ids)}");
// Output: Token IDs: 1279, 6602, 2860, 382, 290, 2273, 328, 87130, 261, 1621, 1511, 261, 1562, 328, 20290, 13
// Decode token IDs back to text.
string? decoded = tokenizer.Decode(ids);
Console.WriteLine($"Decoded: {decoded}");
// Output: Decoded: Text tokenization is the process of splitting a string into a list of tokens.
For better performance, you should cache and reuse the tokenizer instance throughout your app.
When you work with LLMs, you often need to manage text within token limits. The following example shows how to trim text to a specific token count:
Tokenizer tokenizer = TiktokenTokenizer.CreateForModel("gpt-4o");
string source = "Text tokenization is the process of splitting a string into a list of tokens.";
// Get the last 5 tokens from the text.
var trimIndex = tokenizer.GetIndexByTokenCountFromEnd(source, 5, out string? processedText, out _);
processedText ??= source;
Console.WriteLine($"Last 5 tokens: {processedText.Substring(trimIndex)}");
// Output: Last 5 tokens: a list of tokens.
// Get the first 5 tokens from the text.
trimIndex = tokenizer.GetIndexByTokenCount(source, 5, out processedText, out _);
processedText ??= source;
Console.WriteLine($"First 5 tokens: {processedText.Substring(0, trimIndex)}");
// Output: First 5 tokens: Text tokenization is the
Use Llama tokenizer
The Llama tokenizer is designed for the Llama family of models. It requires a tokenizer model file, which you can download from model repositories like Hugging Face:
// Open a stream to the remote Llama tokenizer model data file.
using HttpClient httpClient = new();
const string modelUrl = @"https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model";
using Stream remoteStream = await httpClient.GetStreamAsync(modelUrl);
// Create the Llama tokenizer using the remote stream.
Tokenizer llamaTokenizer = LlamaTokenizer.Create(remoteStream);
string input = "Hello, world!";
// Encode text to token IDs.
IReadOnlyList<int> ids = llamaTokenizer.EncodeToIds(input);
Console.WriteLine($"Token IDs: {string.Join(", ", ids)}");
// Output: Token IDs: 1, 15043, 29892, 3186, 29991
// Count the tokens.
Console.WriteLine($"Tokens: {llamaTokenizer.CountTokens(input)}");
// Output: Tokens: 5
// Decode token IDs back to text.
string? decoded = llamaTokenizer.Decode(ids);
Console.WriteLine($"Decoded: {decoded}");
// Output: Decoded: Hello, world!
All tokenizers support advanced encoding options, such as controlling normalization and pretokenization:
ReadOnlySpan<char> textSpan = "Hello World".AsSpan();
// Bypass normalization during encoding.
ids = llamaTokenizer.EncodeToIds(textSpan, considerNormalization: false);
// Bypass pretokenization during encoding.
ids = llamaTokenizer.EncodeToIds(textSpan, considerPreTokenization: false);
// Bypass both normalization and pretokenization.
ids = llamaTokenizer.EncodeToIds(textSpan, considerNormalization: false, considerPreTokenization: false);
Use BPE tokenizer
Byte-pair encoding (BPE) is the underlying algorithm used by many tokenizers, including Tiktoken. BPE was initially developed as an algorithm to compress texts, and then used by OpenAI for tokenization when it pretrained the GPT model. The following example demonstrates BPE tokenization:
// BPE (Byte Pair Encoding) tokenizer can be created from vocabulary and merges files.
// Download the GPT-2 tokenizer files from Hugging Face.
using HttpClient httpClient = new();
const string vocabUrl = @"https://huggingface.co/openai-community/gpt2/raw/main/vocab.json";
const string mergesUrl = @"https://huggingface.co/openai-community/gpt2/raw/main/merges.txt";
using Stream vocabStream = await httpClient.GetStreamAsync(vocabUrl);
using Stream mergesStream = await httpClient.GetStreamAsync(mergesUrl);
// Create the BPE tokenizer using the vocabulary and merges streams.
Tokenizer bpeTokenizer = BpeTokenizer.Create(vocabStream, mergesStream);
string text = "Hello, how are you doing today?";
// Encode text to token IDs.
IReadOnlyList<int> ids = bpeTokenizer.EncodeToIds(text);
Console.WriteLine($"Token IDs: {string.Join(", ", ids)}");
// Count tokens.
int tokenCount = bpeTokenizer.CountTokens(text);
Console.WriteLine($"Token count: {tokenCount}");
// Get detailed token information.
IReadOnlyList<EncodedToken> tokens = bpeTokenizer.EncodeToTokens(text, out string? normalizedString);
Console.WriteLine("Tokens:");
foreach (EncodedToken token in tokens)
{
Console.WriteLine($" ID: {token.Id}, Value: '{token.Value}'");
}
// Decode tokens back to text.
string? decoded = bpeTokenizer.Decode(ids);
Console.WriteLine($"Decoded: {decoded}");
// Note: BpeTokenizer might not always decode IDs to the exact original text
// as it can remove spaces during tokenization depending on the model configuration.
The library also provides specialized tokenizers like BpeTokenizer and EnglishRobertaTokenizer that you can configure with custom vocabularies for specific models.
For more information about BPE, see Byte-pair encoding tokenization.
Common tokenizer operations
All tokenizers in the library implement the Tokenizer base class. The following table shows the available methods.
| Method | Description |
|---|---|
| EncodeToIds | Converts text to a list of token IDs. |
| Decode | Converts token IDs back to text. |
| CountTokens | Returns the number of tokens in a text string. |
| EncodeToTokens | Returns detailed token information including values and IDs. |
| GetIndexByTokenCount | Finds the character index for a specific token count from the start. |
| GetIndexByTokenCountFromEnd | Finds the character index for a specific token count from the end. |
Migrate from other libraries
If you're currently using DeepDev.TokenizerLib or SharpToken, consider migrating to Microsoft.ML.Tokenizers. The library has been enhanced to cover scenarios from those libraries and provides better performance and support. For migration guidance, see the migration guide.