Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wordpiece Decoder cleanup #147

Merged
merged 4 commits into from
Feb 14, 2020
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
4 changes: 3 additions & 1 deletion bindings/node/lib/bindings/decoders.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ export function byteLevelDecoder(): Decoder;
/**
* Instantiate a new WordPiece Decoder
* @param [prefix='##'] The prefix to use for subwords that are not a beginning-of-word
* @param [cleanup=true] Whether to cleanup some tokenization artifacts.
* Mainly spaces before punctuation, and some abbreviated english forms.
*/
export function wordPieceDecoder(prefix?: string): Decoder;
export function wordPieceDecoder(prefix?: string, cleanup?: boolean): Decoder;

/**
* Instantiate a new Metaspace
Expand Down
10 changes: 8 additions & 2 deletions bindings/node/native/src/decoders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,25 @@ fn byte_level(mut cx: FunctionContext) -> JsResult<JsDecoder> {
Ok(decoder)
}

/// wordpiece(prefix: String = "##")
/// wordpiece(prefix: String = "##", cleanup: bool)
fn wordpiece(mut cx: FunctionContext) -> JsResult<JsDecoder> {
let mut prefix = String::from("##");
if let Some(args) = cx.argument_opt(0) {
prefix = args.downcast::<JsString>().or_throw(&mut cx)?.value() as String;
}
let mut cleanup = true;
if let Some(args) = cx.argument_opt(1) {
cleanup = args.downcast::<JsBoolean>().or_throw(&mut cx)?.value();
}

let mut decoder = JsDecoder::new::<_, JsDecoder, _>(&mut cx, vec![])?;
let guard = cx.lock();
decoder
.borrow_mut(&guard)
.decoder
.to_owned(Box::new(tk::decoders::wordpiece::WordPiece::new(prefix)));
.to_owned(Box::new(tk::decoders::wordpiece::WordPiece::new(
prefix, cleanup,
)));
Ok(decoder)
}

Expand Down
10 changes: 8 additions & 2 deletions bindings/python/src/decoders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,24 @@ pub struct WordPiece {}
#[pymethods]
impl WordPiece {
#[new]
#[args(kwargs="**")]
#[args(kwargs = "**")]
fn new(obj: &PyRawObject, kwargs: Option<&PyDict>) -> PyResult<()> {
let mut prefix = String::from("##");
let mut cleanup = true;

if let Some(kwargs) = kwargs {
if let Some(p) = kwargs.get_item("prefix") {
prefix = p.extract()?;
}
if let Some(c) = kwargs.get_item("cleanup") {
cleanup = c.extract()?;
}
}

Ok(obj.init(Decoder {
decoder: Container::Owned(Box::new(tk::decoders::wordpiece::WordPiece::new(prefix))),
decoder: Container::Owned(Box::new(tk::decoders::wordpiece::WordPiece::new(
prefix, cleanup,
))),
}))
}
}
Expand Down
5 changes: 4 additions & 1 deletion bindings/python/tokenizers/decoders/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,15 @@ class WordPiece(Decoder):
""" WordPiece Decoder """

@staticmethod
def __init__(self, prefix: str = "##") -> Decoder:
def __init__(self, prefix: str = "##", cleanup: bool = True) -> Decoder:
""" Instantiate a new WordPiece Decoder

Args:
prefix: str:
The prefix to use for subwords that are not a beginning-of-word
cleanup: bool:
Whether to cleanup some tokenization artifacts. Mainly spaces before punctuation,
and some abbreviated english forms.
"""
pass

Expand Down
28 changes: 25 additions & 3 deletions tokenizers/src/decoders/wordpiece.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,47 @@
use crate::tokenizer::{Decoder, Result};

/// The WordPiece decoder takes care of decoding a list of wordpiece tokens
/// back into a readable string.
pub struct WordPiece {
/// The prefix to be used for continuing subwords
prefix: String,
/// Whether to cleanup some tokenization artifacts (spaces before punctuation, ...)
cleanup: bool,
}

impl WordPiece {
pub fn new(prefix: String) -> Self {
Self { prefix }
pub fn new(prefix: String, cleanup: bool) -> Self {
Self { prefix, cleanup }
}
}

impl Default for WordPiece {
fn default() -> Self {
Self {
prefix: String::from("##"),
cleanup: true,
}
}
}

impl Decoder for WordPiece {
fn decode(&self, tokens: Vec<String>) -> Result<String> {
Ok(tokens.join(" ").replace(&format!(" {}", self.prefix), ""))
let mut output = tokens.join(" ").replace(&format!(" {}", self.prefix), "");
if self.cleanup {
output = output
.replace(" .", ".")
.replace(" ?", "?")
.replace(" !", "!")
.replace(" ,", ",")
.replace(" ' ", "'")
.replace(" n't", "n't")
.replace(" 'm", "'m")
.replace(" do not", " don't")
.replace(" 's", "'s")
.replace(" 've", "'ve")
.replace(" 're", "'re");
}

Ok(output)
}
}