-
Notifications
You must be signed in to change notification settings - Fork 970
feat: add cli for tokenizer and training #1842
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
Open
b00f
wants to merge
1
commit into
huggingface:main
Choose a base branch
from
b00f:feat/cli
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
use clap::{Parser, Subcommand}; | ||
use tokenizers::tokenizer::Tokenizer; | ||
|
||
#[derive(Parser, Debug)] | ||
#[command(author, version, about, long_about = None)] | ||
struct Cli { | ||
#[command(subcommand)] | ||
command: Commands, | ||
} | ||
|
||
#[derive(Subcommand, Debug)] | ||
enum Commands { | ||
/// Tokenize input text using a model file | ||
Tokenize { | ||
/// Path to the tokenizer model file (e.g., tokenizer.json) | ||
#[arg(long)] | ||
model: String, | ||
/// Input text to tokenize | ||
#[arg(long)] | ||
text: String, | ||
}, | ||
/// Train a new BPE tokenizer model | ||
Train { | ||
/// Input text file(s) for training (comma-separated or repeated) | ||
#[arg(long, required = true)] | ||
files: Vec<String>, | ||
/// Vocabulary size | ||
#[arg(long, default_value_t = 30000)] | ||
vocab_size: usize, | ||
/// Output path for the trained model (e.g., model.json) | ||
#[arg(long)] | ||
output: String, | ||
}, | ||
} | ||
|
||
fn main() { | ||
let cli = Cli::parse(); | ||
match cli.command { | ||
Commands::Tokenize { model, text } => match Tokenizer::from_file(&model) { | ||
Ok(tokenizer) => match tokenizer.encode(text.as_str(), true) { | ||
Ok(encoding) => { | ||
println!("Token IDs: {:?}", encoding.get_ids()); | ||
} | ||
Err(e) => { | ||
eprintln!("Failed to encode text: {}", e); | ||
std::process::exit(1); | ||
} | ||
}, | ||
Err(e) => { | ||
eprintln!("Failed to load tokenizer model: {}", e); | ||
std::process::exit(1); | ||
} | ||
}, | ||
Commands::Train { | ||
files, | ||
vocab_size, | ||
output, | ||
} => { | ||
use tokenizers::models::bpe::{BpeTrainer, BPE}; | ||
use tokenizers::models::ModelWrapper; | ||
use tokenizers::models::TrainerWrapper; | ||
|
||
let mut tokenizer = Tokenizer::new(ModelWrapper::BPE(BPE::default())); | ||
let mut trainer = | ||
TrainerWrapper::BpeTrainer(BpeTrainer::builder().vocab_size(vocab_size).build()); | ||
if let Err(e) = tokenizer.train_from_files(&mut trainer, files.clone()) { | ||
eprintln!("Failed to train tokenizer: {}", e); | ||
std::process::exit(1); | ||
} | ||
if let Err(e) = tokenizer.save(&output, true) { | ||
eprintln!("Failed to save trained model: {}", e); | ||
std::process::exit(1); | ||
} | ||
println!("Model trained and saved to {}", output); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
use assert_cmd::Command; | ||
use predicates::prelude::*; | ||
use std::fs; | ||
use std::path::Path; | ||
|
||
const BIN_NAME: &str = "tokenize"; | ||
|
||
#[test] | ||
fn test_cli_tokenize_success() { | ||
// Prepare a minimal model file (assume one exists for test) | ||
let model_path = "./data/tokenizer.json"; | ||
let text = "Hello world!"; | ||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); | ||
cmd.arg("tokenize") | ||
.arg("--model") | ||
.arg(model_path) | ||
.arg("--text") | ||
.arg(text); | ||
cmd.assert() | ||
.success() | ||
.stdout(predicate::str::contains("Token IDs:")); | ||
} | ||
|
||
#[test] | ||
fn test_cli_tokenize_missing_model() { | ||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); | ||
cmd.arg("tokenize") | ||
.arg("--model") | ||
.arg("/nonexistent/model.json") | ||
.arg("--text") | ||
.arg("test"); | ||
cmd.assert() | ||
.failure() | ||
.stderr(predicate::str::contains("Failed to load tokenizer model")); | ||
} | ||
|
||
#[test] | ||
fn test_cli_tokenize_invalid_text() { | ||
// Should still succeed, but may return empty or error if model is bad | ||
let model_path = "./data/tokenizer.json"; | ||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); | ||
cmd.arg("tokenize") | ||
.arg("--model") | ||
.arg(model_path) | ||
.arg("--text") | ||
.arg(""); | ||
cmd.assert() | ||
.success() | ||
.stdout(predicate::str::contains("Token IDs:")); | ||
} | ||
|
||
#[test] | ||
fn test_cli_train_success() { | ||
// Prepare a small training file | ||
let train_file = "./data/small.txt"; | ||
let output_model = "./data/test-model.json"; | ||
if Path::new(output_model).exists() { | ||
fs::remove_file(output_model).unwrap(); | ||
} | ||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); | ||
cmd.arg("train") | ||
.arg("--files") | ||
.arg(train_file) | ||
.arg("--vocab-size") | ||
.arg("100") | ||
.arg("--output") | ||
.arg(output_model); | ||
cmd.assert() | ||
.success() | ||
.stdout(predicate::str::contains("Model trained and saved to")); | ||
assert!(Path::new(output_model).exists()); | ||
fs::remove_file(output_model).unwrap(); | ||
} | ||
|
||
#[test] | ||
fn test_cli_train_missing_file() { | ||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); | ||
cmd.arg("train") | ||
.arg("--files") | ||
.arg("/nonexistent/data.txt") | ||
.arg("--output") | ||
.arg("/tmp/should-not-exist.json"); | ||
cmd.assert() | ||
.failure() | ||
.stderr(predicate::str::contains("Failed to train tokenizer")); | ||
} | ||
|
||
#[test] | ||
fn test_cli_train_invalid_output() { | ||
// Output to a directory should fail | ||
let train_file = "./data/small.txt"; | ||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); | ||
cmd.arg("train") | ||
.arg("--files") | ||
.arg(train_file) | ||
.arg("--output") | ||
.arg("./data/"); | ||
cmd.assert() | ||
.failure() | ||
.stderr(predicate::str::contains("Failed to save trained model")); | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
probably want to add all flavors here no? Unigram etc
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not sure what do you mean, could you please explain more?