https://huggingface.co/docs/tokenizers/quicktour
| 8 | |
| 9 | # https://huggingface.co/docs/tokenizers/quicktour |
| 10 | def test_works |
| 11 | tokenizer = Tokenizers::Tokenizer.new(Tokenizers::Models::BPE.new(unk_token: "[UNK]")) |
| 12 | |
| 13 | trainer = Tokenizers::Trainers::BpeTrainer.new(special_tokens: ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"]) |
| 14 | |
| 15 | tokenizer.pre_tokenizer = Tokenizers::PreTokenizers::Whitespace.new |
| 16 | |
| 17 | files = ["test", "train", "valid"].map { |split| "#{data_path}/wikitext-103-raw/wiki.#{split}.raw" } |
| 18 | tokenizer.train(files, trainer) |
| 19 | |
| 20 | tokenizer.save("/tmp/tokenizer-wiki.json") |
| 21 | |
| 22 | tokenizer = Tokenizers::Tokenizer.from_file("/tmp/tokenizer-wiki.json") |
| 23 | |
| 24 | output = tokenizer.encode("Hello, y'all! How are you 😁 ?") |
| 25 | |
| 26 | assert_equal ["Hello", ",", "y", "'", "all", "!", "How", "are", "you", "[UNK]", "?"], output.tokens |
| 27 | |
| 28 | assert_equal [27253, 16, 93, 11, 5097, 5, 7961, 5112, 6218, 0, 35], output.ids |
| 29 | |
| 30 | assert_equal [26, 27], output.offsets[9] |
| 31 | |
| 32 | sentence = "Hello, y'all! How are you 😁 ?" |
| 33 | assert_equal "😁", sentence[26...27] |
| 34 | |
| 35 | assert_equal 2, tokenizer.token_to_id("[SEP]") |
| 36 | |
| 37 | tokenizer.post_processor = |
| 38 | Tokenizers::Processors::TemplateProcessing.new( |
| 39 | single: "[CLS] $A [SEP]", |
| 40 | pair: "[CLS] $A [SEP] $B:1 [SEP]:1", |
| 41 | special_tokens: [ |
| 42 | ["[CLS]", tokenizer.token_to_id("[CLS]")], |
| 43 | ["[SEP]", tokenizer.token_to_id("[SEP]")] |
| 44 | ] |
| 45 | ) |
| 46 | |
| 47 | output = tokenizer.encode("Hello, y'all! How are you 😁 ?") |
| 48 | assert_equal ["[CLS]", "Hello", ",", "y", "'", "all", "!", "How", "are", "you", "[UNK]", "?", "[SEP]"], output.tokens |
| 49 | |
| 50 | output = tokenizer.encode("Hello, y'all!", "How are you 😁 ?") |
| 51 | assert_equal ["[CLS]", "Hello", ",", "y", "'", "all", "!", "[SEP]", "How", "are", "you", "[UNK]", "?", "[SEP]"], output.tokens |
| 52 | |
| 53 | assert_equal [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1], output.type_ids |
| 54 | |
| 55 | output = tokenizer.encode_batch(["Hello, y'all!", "How are you 😁 ?"]) |
| 56 | |
| 57 | output = |
| 58 | tokenizer.encode_batch( |
| 59 | [["Hello, y'all!", "How are you 😁 ?"], ["Hello to you too!", "I'm fine, thank you!"]] |
| 60 | ) |
| 61 | |
| 62 | tokenizer.enable_padding(pad_id: 3, pad_token: "[PAD]") |
| 63 | |
| 64 | output = tokenizer.encode_batch(["Hello, y'all!", "How are you 😁 ?"]) |
| 65 | assert_equal ["[CLS]", "How", "are", "you", "[UNK]", "?", "[SEP]", "[PAD]"], output[1].tokens |
| 66 | |
| 67 | assert_equal [1, 1, 1, 1, 1, 1, 1, 0], output[1].attention_mask |
nothing calls this directly
no test coverage detected