Recursive AI

Batch tokenize and pad text for transformers in C#

OneNLP is a free, open-source natural language processing library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Encode each string as its own row. Padding gives shorter rows the same length as the longest one.

The snippet needs vocab.txt (included in the zip and listed below).

Terminal
dotnet add package RecursiveAI.OneNlp

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneNlp.Tokenizers;
 
var tok = Tokenizer
    .FromFile("vocab.txt");
tok.Padding = new(0, "[PAD]");
var batch = tok.EncodeBatch(
    ["hello", "hello worlds"]);
foreach (var row in batch)
    Console.WriteLine(
        string.Join(" ", row.Ids));

Unzip the example, then dotnet run.

Prints two rows of token IDs:

Text
2 5 3 0 0
2 5 6 7 3

The full program

vocab.txt contains this tiny WordPiece vocabulary, one token per line. It demonstrates padding without downloading a transformer model. The full program prints the attention mask beside each row of IDs.

Text
[PAD]
[UNK]
[CLS]
[SEP]
[MASK]
hello
world
##s
C#
using RecursiveAI.OneNlp.Tokenizers;
 
var tok = Tokenizer
    .FromFile("vocab.txt");
tok.Padding = new(0, "[PAD]");
var batch = tok.EncodeBatch(
    ["hello", "hello worlds"]);
foreach (var row in batch)
{
    var ids = string.Join(" ", row.Ids);
    var mask = string.Join(" ",
        row.AttentionMask);
    Console.WriteLine($"IDs:  {ids}");
    Console.WriteLine($"Mask: {mask}");
}
Text
IDs:  2 5 3 0 0
Mask: 1 1 1 0 0
IDs:  2 5 6 7 3
Mask: 1 1 1 1 1

A padding length does not shorten an overlength input; set Truncation separately when the model has a length limit.

Variations

If your model needs exactly five positions per text, replace the padding line and add a truncation limit before calling EncodeBatch:

C#
tok.Padding = new(0, "[PAD]", Length: 5);
tok.Truncation = new(5);

With inputs "hello" and "hello worlds hello", the first row is padded and the last hello in the second row is removed. Both rows keep their end token:

Text
IDs:  2 5 3 0 0
Mask: 1 1 1 0 0
IDs:  2 5 6 7 3
Mask: 1 1 1 1 1

The short answer

Set Tokenizer.Padding to your model’s pad ID and token, then pass the independent strings to EncodeBatch. Read Ids and AttentionMask from each result in input order. If PaddingOptions.Length is unset, OneNlp pads to the longest encoding in that batch. CountTokens and EncodeToIds ignore padding and truncation; use EncodeBatch for the actual input rows, not a token count.

How is tokenization performed in transformers?

A tokenizer turns text into pieces and maps them to IDs in the model’s vocabulary. In this WordPiece example, “worlds” becomes world and ##s. The encoding also adds [CLS] at the start and [SEP] at the end. The two inputs stay separate: EncodeBatch produces a row per string, not one concatenated sequence. Adding the boundary tokens is part of encoding; adding [PAD] to the shorter row happens afterward.

The same word need not have the same ID in two different vocabularies. Use the files shipped with your model, and match its pad token, pad ID, and whether it pads on the left or the right. For a supported tokenizer.json, OneNlp loads padding and truncation settings from the file when present. The zero pad ID in the sample just means [PAD] is the first entry in this vocabulary.

What is the attention mask in transformers?

It marks the positions the model should treat as part of the sequence. OneNlp’s mask has 1 for tokens in the sequence, including boundary tokens, and 0 for padding. For the first row, the last two zeros in the mask line up with the two pad IDs. Pass the mask beside the IDs if the model expects it; token ID 0 is not a universal way to tell a model which positions to ignore.

When should I pad to the longest sequence or a fixed length?

Use the longest sequence in the current batch if the model accepts variable input shapes. The batch is rectangular, but its width can change on the next call. Use a fixed padding length when the model requires a fixed number of positions, and set a matching truncation limit if inputs may be longer. Padding and truncation solve different problems: padding fills short rows and truncation cuts long ones. The truncation limit includes special tokens, so a five-position row with two boundary tokens has room for only three other tokens.

All onenlp recipes