Skip to main content

BertTokenizer

Struct BertTokenizer 

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

Wrapper around HuggingFace tokenizer configured for BERT-style encoding.

Implementations§

Source§

impl BertTokenizer

Source

pub fn from_dir(dir: &Path, max_length: usize) -> Result<Self>

Load tokenizer from a model directory containing:

  • tokenizer.json
  • config.json
  • special_tokens_map.json
  • tokenizer_config.json
Examples found in repository?
examples/semantic_check.rs (line 26)
15fn main() -> anyhow::Result<()> {
16    let dir = std::env::args()
17        .nth(1)
18        .expect("usage: semantic_check <model_dir>");
19    let dir = Path::new(&dir);
20    let pooling = if dir.to_string_lossy().to_lowercase().contains("bge") {
21        Pooling::Cls
22    } else {
23        Pooling::Mean
24    };
25
26    let tok = BertTokenizer::from_dir(dir, 64)?;
27    let mut model = RlxBertModel::load(
28        &dir.join("config.json"),
29        dir.join("model.safetensors").to_str().unwrap(),
30    )?;
31
32    let texts = [
33        "A man is playing a guitar.",                  // 0
34        "Someone is strumming an acoustic guitar.",    // 1  ~ 0
35        "It is freezing outside and snow is falling.", // 2
36        "The weather is cold and it is snowing.",      // 3  ~ 2
37    ];
38    let vecs = embed_with_rlx(&mut model, &tok, &texts, pooling)?;
39    println!("dim={} pooling={:?}", vecs[0].len(), pooling);
40
41    println!("\ncosine matrix:");
42    print!("      ");
43    for j in 0..texts.len() {
44        print!("  s{j:<5}");
45    }
46    println!();
47    for i in 0..texts.len() {
48        print!("s{i}  ");
49        for j in 0..texts.len() {
50            print!("  {:.3} ", cosine(&vecs[i], &vecs[j]));
51        }
52        println!();
53    }
54
55    let sim_related = (cosine(&vecs[0], &vecs[1]) + cosine(&vecs[2], &vecs[3])) / 2.0;
56    let sim_unrelated = (cosine(&vecs[0], &vecs[2])
57        + cosine(&vecs[0], &vecs[3])
58        + cosine(&vecs[1], &vecs[2])
59        + cosine(&vecs[1], &vecs[3]))
60        / 4.0;
61    println!("\nmean related  (0-1, 2-3): {sim_related:.3}");
62    println!("mean unrelated (cross)  : {sim_unrelated:.3}");
63    if sim_related > sim_unrelated + 0.05 {
64        println!("PASS: related pairs are clearly more similar than unrelated pairs.");
65    } else {
66        println!("FAIL: semantic ordering not observed.");
67        std::process::exit(1);
68    }
69    Ok(())
70}
Source

pub fn from_bytes( tokenizer_json: &[u8], config_json: &[u8], special_tokens_map_json: &[u8], tokenizer_config_json: &[u8], max_length: usize, ) -> Result<Self>

Load tokenizer from raw file bytes.

Source

pub fn encode_batch(&self, texts: &[&str]) -> Result<TokenizedBatch>

Tokenize a batch of texts.

Returns input_ids, attention_mask, and token_type_ids for each text, all padded to the same length (longest in batch).

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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