|
| 1 | +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +import os |
| 17 | +import tempfile |
| 18 | +import unittest |
| 19 | +from unittest.mock import MagicMock |
| 20 | + |
| 21 | +import numpy as np |
| 22 | +import sentencepiece |
| 23 | +import torch |
| 24 | + |
| 25 | +from nemo.export.sentencepiece_tokenizer import SentencePieceTokenizer |
| 26 | + |
| 27 | + |
| 28 | +class TestSentencePieceTokenizer(unittest.TestCase): |
| 29 | + @classmethod |
| 30 | + def setUpClass(cls): |
| 31 | + # Create a temporary directory for test files |
| 32 | + cls.test_dir = tempfile.mkdtemp() |
| 33 | + |
| 34 | + # Create a simple sentencepiece model for testing |
| 35 | + with open(os.path.join(cls.test_dir, "test.txt"), "w") as f: |
| 36 | + f.write("Hello world\nThis is a test\n") |
| 37 | + |
| 38 | + # Train a simple sentencepiece model |
| 39 | + sentencepiece.SentencePieceTrainer.Train( |
| 40 | + f'--input={os.path.join(cls.test_dir, "test.txt")} ' |
| 41 | + f'--model_prefix={os.path.join(cls.test_dir, "test_model")} ' |
| 42 | + '--vocab_size=55 --model_type=bpe' |
| 43 | + ) |
| 44 | + |
| 45 | + cls.model_path = os.path.join(cls.test_dir, "test_model.model") |
| 46 | + |
| 47 | + @classmethod |
| 48 | + def tearDownClass(cls): |
| 49 | + # Clean up temporary files |
| 50 | + import shutil |
| 51 | + |
| 52 | + shutil.rmtree(cls.test_dir) |
| 53 | + |
| 54 | + def setUp(self): |
| 55 | + self.tokenizer = SentencePieceTokenizer(model_path=self.model_path) |
| 56 | + |
| 57 | + def test_initialization(self): |
| 58 | + # Test initialization with model path |
| 59 | + tokenizer = SentencePieceTokenizer(model_path=self.model_path) |
| 60 | + self.assertIsNotNone(tokenizer.tokenizer) |
| 61 | + self.assertEqual(tokenizer.original_vocab_size, tokenizer.vocab_size) |
| 62 | + |
| 63 | + # Test initialization with invalid model path |
| 64 | + with self.assertRaises(ValueError): |
| 65 | + SentencePieceTokenizer(model_path="nonexistent.model") |
| 66 | + |
| 67 | + # Test initialization with both model_path and tokenizer |
| 68 | + mock_tokenizer = MagicMock() |
| 69 | + with self.assertRaises(ValueError): |
| 70 | + SentencePieceTokenizer(model_path=self.model_path, tokenizer=mock_tokenizer) |
| 71 | + |
| 72 | + # Test initialization with neither model_path nor tokenizer |
| 73 | + with self.assertRaises(ValueError): |
| 74 | + SentencePieceTokenizer() |
| 75 | + |
| 76 | + def test_text_to_tokens(self): |
| 77 | + text = "Hello world" |
| 78 | + tokens = self.tokenizer.text_to_tokens(text) |
| 79 | + self.assertIsInstance(tokens, list) |
| 80 | + self.assertTrue(all(isinstance(t, str) for t in tokens)) |
| 81 | + |
| 82 | + def test_encode(self): |
| 83 | + text = "Hello world" |
| 84 | + ids = self.tokenizer.encode(text) |
| 85 | + self.assertIsInstance(ids, list) |
| 86 | + self.assertTrue(all(isinstance(i, int) for i in ids)) |
| 87 | + |
| 88 | + def test_tokens_to_text(self): |
| 89 | + text = "Hello world" |
| 90 | + tokens = self.tokenizer.text_to_tokens(text) |
| 91 | + reconstructed_text = self.tokenizer.tokens_to_text(tokens) |
| 92 | + self.assertIsInstance(reconstructed_text, str) |
| 93 | + self.assertNotEqual(reconstructed_text, "") # Should not be empty |
| 94 | + |
| 95 | + def test_batch_decode(self): |
| 96 | + text = "Hello world" |
| 97 | + ids = self.tokenizer.encode(text) |
| 98 | + |
| 99 | + # Test with list |
| 100 | + decoded_text = self.tokenizer.batch_decode(ids) |
| 101 | + self.assertIsInstance(decoded_text, str) |
| 102 | + |
| 103 | + # Test with numpy array |
| 104 | + ids_np = np.array(ids) |
| 105 | + decoded_text_np = self.tokenizer.batch_decode(ids_np) |
| 106 | + self.assertIsInstance(decoded_text_np, str) |
| 107 | + |
| 108 | + # Test with torch tensor |
| 109 | + ids_torch = torch.tensor(ids) |
| 110 | + decoded_text_torch = self.tokenizer.batch_decode(ids_torch) |
| 111 | + self.assertIsInstance(decoded_text_torch, str) |
| 112 | + |
| 113 | + def test_token_to_id(self): |
| 114 | + text = "Hello" |
| 115 | + tokens = self.tokenizer.text_to_tokens(text) |
| 116 | + token_id = self.tokenizer.token_to_id(tokens[0]) |
| 117 | + self.assertIsInstance(token_id, int) |
| 118 | + |
| 119 | + def test_ids_to_tokens(self): |
| 120 | + text = "Hello world" |
| 121 | + ids = self.tokenizer.encode(text) |
| 122 | + tokens = self.tokenizer.ids_to_tokens(ids) |
| 123 | + self.assertIsInstance(tokens, list) |
| 124 | + self.assertTrue(all(isinstance(t, str) for t in tokens)) |
| 125 | + |
| 126 | + def test_tokens_to_ids(self): |
| 127 | + text = "Hello" |
| 128 | + tokens = self.tokenizer.text_to_tokens(text) |
| 129 | + ids = self.tokenizer.tokens_to_ids(tokens) |
| 130 | + self.assertIsInstance(ids, list) |
| 131 | + self.assertTrue(all(isinstance(i, int) for i in ids)) |
| 132 | + |
| 133 | + def test_legacy_mode(self): |
| 134 | + special_tokens = ["[PAD]", "[BOS]", "[EOS]"] |
| 135 | + tokenizer = SentencePieceTokenizer(model_path=self.model_path, special_tokens=special_tokens, legacy=True) |
| 136 | + |
| 137 | + # Test adding special tokens |
| 138 | + self.assertGreater(tokenizer.vocab_size, tokenizer.original_vocab_size) |
| 139 | + |
| 140 | + # Test special token encoding |
| 141 | + text = "Hello [PAD] world" |
| 142 | + tokens = tokenizer.text_to_tokens(text) |
| 143 | + self.assertIn("[PAD]", tokens) |
| 144 | + |
| 145 | + # Test special token decoding |
| 146 | + ids = tokenizer.encode(text) |
| 147 | + decoded_text = tokenizer.batch_decode(ids) |
| 148 | + self.assertIn("[PAD]", decoded_text) |
| 149 | + |
| 150 | + def test_properties(self): |
| 151 | + # Test pad_id property |
| 152 | + self.assertIsInstance(self.tokenizer.pad_id, int) |
| 153 | + |
| 154 | + # Test bos_token_id property |
| 155 | + self.assertIsInstance(self.tokenizer.bos_token_id, int) |
| 156 | + |
| 157 | + # Test eos_token_id property |
| 158 | + self.assertIsInstance(self.tokenizer.eos_token_id, int) |
| 159 | + |
| 160 | + # Test unk_id property |
| 161 | + self.assertIsInstance(self.tokenizer.unk_id, int) |
| 162 | + |
| 163 | + def test_vocab_property(self): |
| 164 | + vocab = self.tokenizer.vocab |
| 165 | + self.assertIsInstance(vocab, list) |
| 166 | + self.assertTrue(all(isinstance(t, str) for t in vocab)) |
| 167 | + |
| 168 | + def test_convert_ids_to_tokens(self): |
| 169 | + text = "Hello world" |
| 170 | + ids = self.tokenizer.encode(text) |
| 171 | + tokens = self.tokenizer.convert_ids_to_tokens(ids) |
| 172 | + self.assertIsInstance(tokens, list) |
| 173 | + self.assertTrue(all(isinstance(t, str) for t in tokens)) |
| 174 | + |
| 175 | + def test_convert_tokens_to_string(self): |
| 176 | + text = "Hello world" |
| 177 | + tokens = self.tokenizer.text_to_tokens(text) |
| 178 | + string = self.tokenizer.convert_tokens_to_string(tokens) |
| 179 | + self.assertIsInstance(string, str) |
| 180 | + |
| 181 | + def test_len(self): |
| 182 | + self.assertEqual(len(self.tokenizer), self.tokenizer.vocab_size) |
| 183 | + |
| 184 | + def test_is_fast(self): |
| 185 | + self.assertTrue(self.tokenizer.is_fast) |
| 186 | + |
| 187 | + def test_get_added_vocab(self): |
| 188 | + self.assertIsNone(self.tokenizer.get_added_vocab()) |
| 189 | + |
| 190 | + |
| 191 | +if __name__ == '__main__': |
| 192 | + unittest.main() |
0 commit comments