次の方法で共有


テキスト トークン化に Microsoft.ML.Tokenizers を使用する

Microsoft.ML.Tokenizers ライブラリには、.NET アプリケーションでテキストをトークン化するための包括的なツール セットが用意されています。 トークン化は、大規模な言語モデル (LLM) を使用する場合に不可欠です。これにより、トークン数の管理、コストの見積もり、AI モデルのテキストの前処理が可能になります。

この記事では、ライブラリの主な機能を使用し、さまざまなトークナイザー モデルを操作する方法について説明します。

[前提条件]

Microsoft.ML.Tokenizers ライブラリは .NET Standard 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 ライブラリには、次のものが用意されています。

  • 拡張可能なトークナイザー アーキテクチャ: ノーマライザー、PreTokenizer、Model/Encoder、デコーダー コンポーネントの特殊化が可能です。
  • 複数のトークン化アルゴリズム: 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.

パフォーマンスを向上させるには、アプリ全体でトークナイザー インスタンスをキャッシュして再利用する必要があります。

LLM を使用する場合、多くの場合、トークンの制限内でテキストを管理する必要があります。 次の例は、テキストを特定のトークン数にトリミングする方法を示しています。

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 トークナイザーを使用する

ラマトークナイザーは、ラマファミリーのモデル向けに設計されています。 これにはトークナイザー モデル ファイルが必要です。このファイルは、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 は当初、テキストを圧縮するアルゴリズムとして開発され、GPT モデルの事前トレーニング時に OpenAI によってトークン化に使用されました。 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 への移行を検討してください。 ライブラリは、これらのライブラリのシナリオに対応するように強化され、パフォーマンスとサポートが向上しました。 移行ガイダンスについては、 移行ガイドを参照してください。