Skip to main content

BertTokenizer

Struct BertTokenizer 

Source
pub struct BertTokenizer { /* private fields */ }
Expand description

BERT-style tokenizer combining basic tokenization and WordPiece subword segmentation.

Special tokens:

  • [CLS] (classification): prepended to every encoded sequence
  • [SEP] (separator): appended after each segment
  • [MASK] (masking): placeholder for masked-language-model pre-training
  • [PAD] (padding): used to fill sequences to a target length
  • [UNK] (unknown): substituted for tokens not present in the vocabulary

§Example

use std::collections::HashMap;
use scirs2_text::tokenizers::bert::BertTokenizer;

let mut vocab: HashMap<String, u32> = HashMap::new();
for (i, tok) in ["[PAD]","[UNK]","[CLS]","[SEP]","[MASK]",
                  "hello","world","##ing","play","##ed"].iter().enumerate() {
    vocab.insert(tok.to_string(), i as u32);
}
let tokenizer = BertTokenizer::new(vocab, true);
let ids = tokenizer.encode("Hello World").unwrap();
assert_eq!(ids[0], tokenizer.cls_token_id());

Implementations§

Source§

impl BertTokenizer

Source

pub fn new(vocab: HashMap<String, u32>, lowercase: bool) -> Self

Build a BertTokenizer from a token → id vocabulary map.

All five special tokens ([PAD], [UNK], [CLS], [SEP], [MASK]) are inserted into the vocabulary if absent.

Source

pub fn from_vocab_file(path: &str) -> Result<Self>

Load a tokenizer from a vocab.txt file (one token per line; line index = token ID, 0-based).

Returns an error if the file cannot be read or if the resulting vocabulary is missing required special tokens after auto-insertion.

Source

pub fn with_max_len(self, max_len: usize) -> Self

Override the maximum sequence length (default 512).

Source

pub fn cls_token_id(&self) -> u32

Returns the [CLS] token ID.

Source

pub fn sep_token_id(&self) -> u32

Returns the [SEP] token ID.

Source

pub fn pad_token_id(&self) -> u32

Returns the [PAD] token ID.

Source

pub fn mask_token_id(&self) -> u32

Returns the [MASK] token ID.

Source

pub fn unk_token_id(&self) -> u32

Returns the [UNK] token ID.

Source

pub fn vocab_size(&self) -> usize

Vocabulary size.

Source

pub fn vocab(&self) -> &HashMap<String, u32>

Return a reference to the full token → id vocabulary map.

Source

pub fn lowercase(&self) -> bool

Return whether this tokenizer lowercases input text.

Source

pub fn tokenize(&self, text: &str) -> Vec<String>

Tokenize text into a list of subword strings.

Applies basic tokenization (whitespace + punctuation split, optional lowercasing) followed by WordPiece subword segmentation. Unknown characters/words map to "[UNK]".

Source

pub fn encode(&self, text: &str) -> Result<Vec<u32>>

Encode a single text segment as [CLS] tokens [SEP].

Returns the flat sequence of token IDs. Use encode_pair for two-segment inputs (e.g. question + context).

Source

pub fn encode_pair( &self, text_a: &str, text_b: &str, ) -> Result<(Vec<u32>, Vec<u32>)>

Encode a pair of text segments (e.g. sentence A and sentence B).

Layout: [CLS] A-tokens [SEP] B-tokens [SEP]

Returns (token_ids, token_type_ids) where token_type_ids[i] is 0 for the first segment and 1 for the second.

Source

pub fn encode_single( &self, text: &str, max_length: usize, padding: bool, truncation: bool, ) -> Result<BertEncoding>

Build a single BertEncoding for text, with optional padding and truncation to max_length.

If padding is true, short sequences are padded with [PAD] to reach max_length. If truncation is true, long sequences are trimmed (preserving [CLS] and [SEP]).

Source

pub fn encode_batch( &self, texts: &[&str], max_length: usize, padding: bool, truncation: bool, ) -> Result<BatchEncoding>

Encode a batch of texts with consistent sequence length.

When padding is true, all sequences in the batch are padded to the longest (or to max_length, whichever is smaller). When truncation is true, sequences exceeding max_length are truncated.

Source

pub fn decode(&self, ids: &[u32]) -> String

Decode a sequence of token IDs back to a human-readable string.

Special tokens ([CLS], [SEP], [PAD], [MASK]) are skipped. WordPiece continuation tokens (prefixed with ##) are merged directly onto the preceding piece without a space.

Source

pub fn convert_token_to_id(&self, token: &str) -> Option<u32>

Convert token string to its ID (exposed for testing / downstream use).

Source

pub fn convert_id_to_token(&self, id: u32) -> Option<&str>

Convert token ID to its string representation.

Trait Implementations§

Source§

impl Clone for BertTokenizer

Source§

fn clone(&self) -> BertTokenizer

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for BertTokenizer

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V