DecodeStream

Struct DecodeStream 

Source
pub struct DecodeStream<'tok, M, N, PT, PP, D> { /* private fields */ }
Expand description

DecodeStream will keep the state necessary to produce individual chunks of strings given an input stream of token_ids.

This is necessary because decoding in general cannot achieve that since strings depend on surrounding ids to provide a valid string. Typically stripping extra spaces

Example:

use tokenizers::Tokenizer;
let tokenizer = Tokenizer::from_file("data/roberta.json").unwrap();

let mut decode_stream = tokenizer.decode_stream(false);
assert_eq!(decode_stream.step(713).unwrap(), Some("This".to_string()));
assert_eq!(decode_stream.step(16).unwrap(), Some(" is".to_string()));
assert_eq!(decode_stream.step(41).unwrap(), Some(" an".to_string()));
assert_eq!(
    decode_stream.step(1246).unwrap(),
    Some(" example".to_string())
);

Returning None means the given id is not enough to produce a chunk. This typically happens with byte_fallback options where some tokens do not represent valid utf-8, and only follow-up token_ids will help produce a valid chunk.

use tokenizers::{Tokenizer, TokenizerBuilder, models::bpe::BPE, decoders::byte_fallback::ByteFallback, pre_tokenizers::byte_level::ByteLevel, normalizers::unicode::NFC};
use std::collections::HashMap;
use std::iter::FromIterator;

let vocab = HashMap::from_iter([
    ("<0x20>".to_string(), 0),
    ("<0xC3>".to_string(), 1),
    ("<0xA9>".to_string(), 2),
    (" This".to_string(), 3),
]);
let merges = vec![];
let bpe = BPE::builder()
    .vocab_and_merges(vocab, merges)
    .byte_fallback(true)
    .build()
    .unwrap();
let tokenizer = TokenizerBuilder::default()
    .with_model(bpe)
    .with_decoder(Some(ByteFallback::default()))
    .with_normalizer(Some(NFC))
    .with_pre_tokenizer(Some(ByteLevel::default()))
    .with_post_processor(Some(ByteLevel::default()))
    .build().unwrap();

let mut decode_stream = tokenizer.decode_stream(false);
// Single byte_fallback is valid utf-8
assert_eq!(decode_stream.step(0).unwrap(), Some(" ".to_string()));
// Invalid utf-8
assert_eq!(decode_stream.step(1).unwrap(), None);
// Valid utf-8 again, this corresponds to both tokens: [1, 2]
assert_eq!(decode_stream.step(2).unwrap(), Some("é".to_string()));

To see how DecodeStream is necessary, let’s show how using raw TokenizerImpl::decode would fail.

use tokenizers::{Tokenizer, TokenizerBuilder, models::bpe::BPE, pre_tokenizers::{byte_level::ByteLevel, metaspace::Metaspace}, normalizers::unicode::NFC};
use std::collections::HashMap;
use std::iter::FromIterator;

let vocab = HashMap::from_iter([
    ("▁This".to_string(), 0),
]);
let merges = vec![];
let bpe = BPE::builder()
    .vocab_and_merges(vocab, merges)
    .byte_fallback(true)
    .build()
    .unwrap();
let tokenizer = TokenizerBuilder::new()
    .with_model(bpe)
    .with_decoder(Some(Metaspace::default()))
    .with_normalizer(Some(NFC))
    .with_pre_tokenizer(Some(ByteLevel::default()))
    .with_post_processor(Some(ByteLevel::default()))
    .build()
    .unwrap();

// Strip decoder removes the extra initial space
assert_eq!(tokenizer.decode(&[0, 0], false).unwrap(), "This This");
// Decoding one token at a time would produce "ThisThis"
assert_eq!(tokenizer.decode(&[0], false).unwrap(), "This");

// Using a stream fixes it by keeping the necessary state.
let mut decode_stream = tokenizer.decode_stream(false);
assert_eq!(decode_stream.step(0).unwrap(), Some("This".to_string()));
assert_eq!(decode_stream.step(0).unwrap(), Some(" This".to_string()));

Implementations§

Source§

impl<'tok, M, N, PT, PP, D> DecodeStream<'tok, M, N, PT, PP, D>
where M: Model, N: Normalizer, PT: PreTokenizer, PP: PostProcessor, D: Decoder,

Source

pub fn step(&mut self, id: u32) -> Result<Option<String>>

Auto Trait Implementations§

§

impl<'tok, M, N, PT, PP, D> Freeze for DecodeStream<'tok, M, N, PT, PP, D>

§

impl<'tok, M, N, PT, PP, D> RefUnwindSafe for DecodeStream<'tok, M, N, PT, PP, D>

§

impl<'tok, M, N, PT, PP, D> Send for DecodeStream<'tok, M, N, PT, PP, D>
where M: Sync, N: Sync, PT: Sync, PP: Sync, D: Sync,

§

impl<'tok, M, N, PT, PP, D> Sync for DecodeStream<'tok, M, N, PT, PP, D>
where M: Sync, N: Sync, PT: Sync, PP: Sync, D: Sync,

§

impl<'tok, M, N, PT, PP, D> Unpin for DecodeStream<'tok, M, N, PT, PP, D>

§

impl<'tok, M, N, PT, PP, D> UnwindSafe for DecodeStream<'tok, M, N, PT, PP, D>

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> 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, 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