Recursive AI

Tokenize a question and passage for BERT 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.

Call Encode(question, passage) to make one BERT input. Segment IDs tell you which text each token came from.

Terminal
dotnet add package RecursiveAI.OneNlp

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

C#
using RecursiveAI.OneNlp.Tokenizers;
 
// vocab.txt is in the zip and shown below.
var tokenizer = Tokenizer
    .FromWordPieceVocabulary("vocab.txt",
        new() { LowerCase = true });
var pair = tokenizer.Encode("Where?", "Paris");
for (int i = 0; i < pair.Length; i++)
{
    var (start, end) = pair.Offsets[i];
    Console.WriteLine($"{pair.Tokens[i]} " +
        $"{pair.Ids[i]} {pair.TypeIds[i]} " +
        $"[{start}, {end})");
}

Prints:

Text
[CLS] 2 0 [0, 0)
where 5 0 [0, 5)
? 6 0 [5, 6)
[SEP] 3 0 [0, 0)
paris 7 1 [0, 5)
[SEP] 3 1 [0, 0)

The columns are token, vocabulary ID, segment ID, and [start, end) in the original string. ? starts at index 5 in Where?, but paris starts back at 0 in Paris. If the tokenizer family doesn’t support pairs, Encode throws NotSupportedException.

Paste the code above into Program.cs of a new dotnet new console project and dotnet run, or unzip the example and dotnet run.

The zip’s vocab.txt is shown below. Save it alongside the project if you’re pasting the snippet.

Text
[PAD]
[UNK]
[CLS]
[SEP]
[MASK]
where
?
paris

Variations

Recover the original passage text. Add this after encoding the pair. Skip special tokens before slicing, even if their segment ID is 1.

C#
string passage = "Paris";
for (int i = 0; i < pair.Length; i++)
{
    if (pair.SpecialTokensMask[i] ||
        pair.TypeIds[i] != 1) continue;
    var (start, end) = pair.Offsets[i];
    Console.WriteLine(passage[start..end]);
}
Text
Paris

The short answer

Call tokenizer.Encode(question, passage) on a BERT WordPiece tokenizer. You get one sequence in the order [CLS] question [SEP] passage [SEP]. The question tokens have type ID 0 and the passage tokens have type ID 1. Use the tokenizer files and casing settings that came with your model (see how to load a BERT vocab.txt); the toy vocabulary here demonstrates the encoding but isn’t a model vocabulary. If the pair is too long for your model, set tokenizer.Truncation to a TruncationOptions with the model’s token limit as MaxLength: with the default LongestFirst strategy, Encode shortens the longer text first and counts special tokens toward the limit; without truncation configured, it leaves the pair uncut.

What are token type IDs in BERT?

In BERT, token IDs and segment IDs serve different roles. pair.Ids selects vocabulary entries; pair.TypeIds gives the segment IDs, and pair.AttentionMask tells the model which positions are not padding. All three arrays are in the same token order. The two [SEP] entries in the example have the same vocabulary ID, 3, but different segment IDs. Segment IDs are not a mask for extracting answers: the final [SEP] is in segment 1 too.

Tokenize the two strings as a pair, not as a single interpolated string. The single-text call would not know where your question ends, so it wouldn’t assign passage type IDs or provide offsets relative to the passage. Encoding the strings separately would give each string its own [CLS] and [SEP], rather than the special-token layout for a pair.

How do BERT token offsets map back to the passage?

For OneNLP’s string pair overload, offsets count UTF-16 code units, the same units C# string slicing uses. The end index is exclusive. Look up the segment before applying the offset: [0, 5) is Where in the question and Paris in the passage. Even though the tokenizer emits lowercase paris, slicing the original passage gives Paris. Check SpecialTokensMask before slicing: the inserted markers don’t represent spans in either string.

For an extractive answer, the model gives you token positions, not character offsets. Once both endpoints are known to be real passage tokens, use the start offset of the first token and the end offset of the last to slice the passage. A span in the question or on a separator isn’t an answer in the passage. This recipe prepares the input and shows that index mapping; it doesn’t run a question-answering model.

All onenlp recipes