다음을 통해 공유


텍스트 토큰화에 Microsoft.ML.Tokenizers 사용

Microsoft.ML.Tokenizers 라이브러리는 .NET 애플리케이션에서 텍스트를 토큰화하기 위한 포괄적인 도구 집합을 제공합니다. 토큰화는 AI 모델에 대한 토큰 개수, 예상 비용 및 전처리 텍스트를 관리할 수 있으므로 LLM(대규모 언어 모델)을 사용할 때 필수적입니다.

이 문서에서는 라이브러리의 주요 기능을 사용하고 다양한 토케나이저 모델에서 작업하는 방법을 보여 줍니다.

필수 조건

비고

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 라이브러리는 다음을 제공합니다.

  • 확장 가능한 토큰라이저 아키텍처: Normalizer, PreTokenizer, 모델/인코더 및 디코더 구성 요소를 특수화할 수 있습니다.
  • 여러 토큰화 알고리즘: BPE(바이트 쌍 인코딩), Tiktoken, Llama, CodeGen 등을 지원합니다.
  • 토큰 계산 및 예측: AI 서비스를 사용할 때 비용 및 컨텍스트 제한을 관리하는 데 도움이 됩니다.
  • 유연한 인코딩 옵션: 텍스트를 토큰 ID로 인코딩하고, 토큰 수를 계산하고, 토큰을 다시 텍스트로 디코딩하는 메서드를 제공합니다.

Tiktoken tokenizer 사용

Tiktoken tokenizer는 GPT-4와 같은 OpenAI 모델에서 일반적으로 사용됩니다. 다음 예제에서는 Tiktoken tokenizer를 초기화하고 일반적인 작업을 수행하는 방법을 보여 줍니다.

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

성능을 향상시키려면 앱 전체에서 tokenizer 인스턴스를 캐시하고 다시 사용해야 합니다.

LLM을 사용하는 경우 토큰 제한 내에서 텍스트를 관리해야 하는 경우가 많습니다. 다음 예제에서는 텍스트를 특정 토큰 수로 자르는 방법을 보여줍니다.

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 tokenizer 사용

라마 토케나이저는 라마 모델 제품군을 위해 설계되었습니다. 포옹 얼굴과 같은 모델 리포지토리에서 다운로드할 수 있는 토큰라이저 모델 파일이 필요합니다.

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

모든 tokenizer는 정규화 및 사전 토큰화 제어와 같은 고급 인코딩 옵션을 지원합니다.

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는 기본 클래스를 구현합니다 Tokenizer . 다음 표에서는 사용 가능한 메서드를 보여 줍니다.

메서드 Description
EncodeToIds 텍스트를 토큰 ID 목록으로 변환합니다.
Decode 토큰 ID를 다시 텍스트로 변환합니다.
CountTokens 텍스트 문자열의 토큰 수를 반환합니다.
EncodeToTokens 값 및 ID를 포함한 자세한 토큰 정보를 반환합니다.
GetIndexByTokenCount 처음부터 특정 토큰 수로부터 문자 인덱스를 찾습니다.
GetIndexByTokenCountFromEnd 끝에서 특정 토큰 수의 문자 인덱스를 찾습니다.

다른 라이브러리에서 마이그레이션

현재 DeepDev.TokenizerLib 또는 SharpToken를 사용 중이라면 Microsoft.ML.Tokenizers로의 마이그레이션을 고려해 보세요. 라이브러리는 해당 라이브러리의 시나리오를 포함하도록 향상되었으며 더 나은 성능과 지원을 제공합니다. 마이그레이션 지침은 마이그레이션 가이드를 참조하세요.