使用 Microsoft.ML.Tokenizers 進行文字標記化

Microsoft.ML.Tokenizers函式庫提供了一套完整的工具,用於.NET應用程式中的文字分詞。 當你使用大型語言模型(LLM)時,代幣化是不可或缺的,因為它能讓你管理代幣數量、估算成本,並為 AI 模型預處理文字。

本文將教你如何使用函式庫的主要功能,以及使用不同的分詞器模型。

先決條件

備註

Microsoft.ML.Tokenizers 函式庫也支援 .NET 標準 2.0,使其與 .NET Framework 4.6.1 及更新版本相容。

安裝套件

安裝 Microsoft.ML.Tokenizers NuGet 套件:

dotnet add package Microsoft.ML.Tokenizers

對於 Tiktoken 模型(如 GPT-4),也請安裝相應的資料包:

dotnet add package Microsoft.ML.Tokenizers.Data.O200kBase

主要功能

Microsoft.ML.Tokenizers 函式庫提供:

  • 可擴充分詞器架構:允許正規化器、預分詞器、模型/編碼器及解碼器元件的專用化。
  • 多重標記化演算法:支援 BPE(位元組對編碼)、Tiktoken、Llama、CodeGen 等多種技術。
  • 代幣計數與估算:協助管理 AI 服務時的成本與上下文限制。
  • 彈性編碼選項:提供將文字編碼為標記 ID、計數標記,以及將標記解碼回文字的方法。

使用 Tiktoken 分詞器

Tiktoken 代幣工具常用於像 GPT-4 這類 OpenAI 模型。 以下範例展示了如何初始化 Tiktoken 分詞器並執行常見操作:

// Initialize the tokenizer for the gpt-5 model.
Tokenizer tokenizer = TiktokenTokenizer.CreateForModel("gpt-5");

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.

為了提升效能,建議在整個應用程式中快取並重複使用分詞器實例。

當你使用大型語言模型時,通常需要在令牌限制內管理文字。 以下範例說明如何將文字裁剪至特定的標記數量:

Tokenizer tokenizer = TiktokenTokenizer.CreateForModel("gpt-5");

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

使用 Llama 分詞器

Llama 代幣管理器是為 Llama 系列模型設計的。 它需要一個分詞器模型檔案,你可以從像 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!

所有分詞器都支援進階編碼選項,例如控制正規化與預分詞:

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);

使用 BPE 分詞器

字節對編碼(BPE)是許多分詞器所使用的底層演算法,包括 Tiktoken。 BPE 最初是作為壓縮文字的演算法開發的,後來 OpenAI 在預訓練 GPT 模型時用它來分詞化。 以下範例展示了 BPE 的標記化:

// 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.

函式庫也提供專門的分詞器,例如BpeTokenizerEnglishRobertaTokenizer,你可以針對特定模型設定自訂詞彙。

欲了解更多關於 BPE 的資訊,請參見位元組對編碼標記化。

常見的分詞器操作

函式庫中的所有分詞器都實現了Tokenizer基底類別。 下表顯示可用的方法。

方法 Description
EncodeToIds 將文字轉換成代幣 ID 清單。
Decode 將標記 ID 轉換回文本。
CountTokens 回傳文字字串中的標記數量。
EncodeToTokens 回傳詳細的代幣資訊,包括數值與 ID。
GetIndexByTokenCount 從一開始就找到特定代幣數量的角色索引。
GetIndexByTokenCountFromEnd 從結尾計算出特定標記數所對應的字元索引。

從其他函式庫遷移

如果你目前使用 DeepDev.TokenizerLib 或 SharpToken,考慮遷移到 Microsoft.ML.Tokenizers。 該函式庫已強化以涵蓋這些函式庫的情境,並提供更佳的效能與支援。 關於遷移指引,請參閱 遷移指南。