Aracılığıyla paylaş


Metin belirleme için Microsoft.ML.Tokenizers kullanın

Microsoft.ML.Tokenizers kitaplığı, .NET uygulamalarında metni belirteç haline getirmeye yönelik kapsamlı bir araç kümesi sağlar. Belirteç sayısını yönetmenize, maliyetleri tahmin etmenizi ve yapay zeka modelleri için metinleri ön işlemenize olanak sağladığı için, büyük dil modelleriyle (LLM) çalışırken belirteç oluşturma önemlidir.

Bu makalede kitaplığın temel özelliklerini kullanma ve farklı belirteç oluşturucu modelleriyle çalışma gösterilmektedir.

Önkoşullar

Uyarı

Microsoft.ML.Tokenizers kitaplığı .NET Standard 2.0'ı da destekler ve .NET Framework 4.6.1 ve üzeriyle uyumlu hale getirir.

Paketi yükle

Microsoft.ML.Tokenizers NuGet paketini yükleyin:

dotnet add package Microsoft.ML.Tokenizers

Tiktoken modelleri için (GPT-4 gibi) ilgili veri paketini de yüklemeniz gerekir:

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

Temel özellikler

Microsoft.ML.Tokenizers kitaplığı aşağıdakileri sağlar:

  • Genişletilebilir belirteç oluşturucu mimarisi: Normalizer, PreTokenizer, Model/Encoder ve Kod Çözücü bileşenlerinin özelleştirilmesine izin verir.
  • Birden çok belirteçleştirme algoritması: BPE (bayt çifti kodlama), Tiktoken, Lama, CodeGen ve daha fazlasını destekler.
  • Belirteç sayma ve tahmin: Yapay zeka hizmetleriyle çalışırken maliyetleri ve bağlam sınırlarını yönetmeye yardımcı olur.
  • Esnek kodlama seçenekleri: Metni belirteç kimliklerine kodlamak, belirteçleri saymak ve belirteçleri metne geri döndürmek için yöntemler sağlar.

Tiktoken tokenizer'ı kullan

Tiktoken belirteç oluşturucu yaygın olarak GPT-4 gibi OpenAI modellerinde kullanılır. Aşağıdaki örnekte, Tiktoken belirteç oluşturucunun nasıl başlatılıp yaygın işlemler gerçekleştirebileceğiniz gösterilmektedir:

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

Daha iyi performans için belirteç oluşturucu örneğini uygulamanızda önbelleğe alıp yeniden kullanmanız gerekir.

LLM'lerle çalışırken, genellikle belirteç sınırları içinde metinleri yönetmeniz gerekir. Aşağıdaki örnekte, metnin belirli bir belirteç sayısına nasıl kırpılır gösterilmektedir:

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

Llama belirteç kullanmak

Llama belirteç oluşturucu, Lama model ailesi için tasarlanmıştır. Model depolarından, örneğin Hugging Face gibi, indirebileceğiniz bir belirteçleyici model dosyası gerektirir.

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

Tüm belirteç oluşturucular, normalleştirmeyi ve önceden belirteçlemeyi denetleme gibi gelişmiş kodlama seçeneklerini destekler.

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 belirteç oluşturucusunu kullan

Bayt çifti kodlaması (BPE), Tiktoken dahil olmak üzere birçok belirteç oluşturucu tarafından kullanılan temel algoritmadır. BPE başlangıçta metinleri sıkıştırmak amacıyla bir algoritma olarak geliştirilmiş ve ardından OpenAI tarafından GPT modelini önceden eğitmek için belirteçleme işlemlerinde kullanılmıştır. Aşağıdaki örnekte BPE belirteci oluşturma işlemi gösterilmektedir:

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

Kitaplık, BpeTokenizer ve EnglishRobertaTokenizer gibi belirli modeller için özel sözlüklerle yapılandırabileceğiniz özel belirteçleyiciler de sağlar.

BPE hakkında daha fazla bilgi için bkz Bayt çifti kodlama belirteçleme.

Yaygın token oluşturucu işlemleri

Kitaplıktaki tüm belirteç oluşturucular temel sınıfı uygular Tokenizer . Aşağıdaki tabloda kullanılabilir yöntemler gösterilmektedir.

Yöntem Description
EncodeToIds Metni belirteç kimlikleri listesine dönüştürür.
Decode Token kimliklerini tekrar metne dönüştürür.
CountTokens Metin dizesindeki belirteç sayısını döndürür.
EncodeToTokens Değerler ve kimlikler de dahil olmak üzere ayrıntılı belirteç bilgilerini döndürür.
GetIndexByTokenCount Başlangıçtan belirli bir belirteç sayısı için karakter dizinini bulur.
GetIndexByTokenCountFromEnd Sonundan belirli bir belirteç sayısı için karakter dizinini bulur.

Diğer kütüphanelerden geçiş

Eğer şu anda DeepDev.TokenizerLib veya SharpToken kullanıyorsanız, Microsoft.ML.Tokenizers'a bir geçiş yapmayı göz önünde bulundurun. Kitaplık, bu kitaplıklardan gelen senaryoları kapsayacak şekilde geliştirilmiştir ve daha iyi performans ve destek sağlar. Geçiş kılavuzu için bkz. geçiş kılavuzu.