Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion ext/tiktoken_ruby/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ crate-type = ["cdylib"]
[dependencies]
magnus = { version = "0.8.2" }
rb-sys = { version = "0.9.127", features = ["stable-api-compiled-fallback"] }
tiktoken-rs = { version = "0.11.0" }
tiktoken-rs = { version = "0.12.0" }
14 changes: 10 additions & 4 deletions ext/tiktoken_ruby/src/core_bpe_wrapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ struct EncodeData {
core_bpe: *const tiktoken_rs::CoreBPE,
text: String,
allowed_special: HashSet<String>,
result: Vec<Rank>,
result: Result<Vec<Rank>, String>,
}

struct EncodeSpecialData {
Expand All @@ -46,7 +46,11 @@ unsafe extern "C" fn encode_without_gvl(data: *mut c_void) -> *mut c_void {
let data = &mut *(data as *mut EncodeData);
let core_bpe = &*data.core_bpe;
let allowed_special: HashSet<&str> = data.allowed_special.iter().map(|s| s.as_str()).collect();
data.result = core_bpe.encode(&data.text, &allowed_special).0;
// Keep only the token vector and surface any tokenization failure to Ruby.
data.result = core_bpe
.encode(&data.text, &allowed_special)
.map(|(tokens, _last_piece_token_len)| tokens)
.map_err(|e| e.to_string());
std::ptr::null_mut()
}

Expand Down Expand Up @@ -99,7 +103,7 @@ impl CoreBPEWrapper {
core_bpe: &self.core_bpe as *const _,
text,
allowed_special: HashSet::from_iter(allowed_special),
result: Vec::new(),
result: Ok(Vec::new()),
};

unsafe {
Expand All @@ -111,7 +115,9 @@ impl CoreBPEWrapper {
);
}

Ok(data.result)
data.result.map_err(|e| {
magnus::Error::new(magnus::Ruby::get().unwrap().exception_runtime_error(), e)
})
}

pub fn encode_with_special_tokens(&self, text: String) -> Vec<Rank> {
Expand Down
Loading