Chiquitin commited on
Commit
242bd10
·
1 Parent(s): a6416c8

docstrings on tokenizer

Browse files
Files changed (1) hide show
  1. src/tokenizer.py +105 -17
src/tokenizer.py CHANGED
@@ -21,31 +21,62 @@ from transformers import PreTrainedTokenizerFast
21
 
22
 
23
  class SegmentationTokenizer:
24
- def __init__(
25
- self,
26
- vocab_size=32_768,
27
- min_frequency=2,
28
- max_length=1024
29
- ):
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  self.max_length = max_length
31
 
32
- # Raw tokenizer (training)
33
  self.raw_tokenizer = tokenizers.Tokenizer(
34
  BPE(unk_token="[UNK]")
35
  )
36
  self.raw_tokenizer.normalizer = NFKC()
37
  self.raw_tokenizer.pre_tokenizer = Whitespace()
38
 
 
39
  self.trainer = BpeTrainer(
40
  vocab_size=vocab_size,
41
  min_frequency=min_frequency,
42
  special_tokens=["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"]
43
  )
44
 
45
- self._hf_tokenizer = None # created after training
 
46
 
47
- # ---------- TRAINING ----------
48
- def build_iterator(self, dataset, batch_size=1024):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  batch = []
50
  for item in dataset:
51
  batch.append("\n".join(item["text"]).replace("\n\n", "\n"))
@@ -56,15 +87,39 @@ class SegmentationTokenizer:
56
  yield batch
57
 
58
  def train_from_iterator(self, iterator):
 
 
 
 
 
 
59
  self.raw_tokenizer.train_from_iterator(
60
- iterator, trainer=self.trainer
 
61
  )
62
 
63
- # ---------- IO ----------
 
 
64
  def save(self, path):
 
 
 
 
 
 
65
  self.raw_tokenizer.save(path)
66
 
67
  def load(self, tokenizer_path):
 
 
 
 
 
 
 
 
 
68
  self._hf_tokenizer = PreTrainedTokenizerFast(
69
  tokenizer_file=tokenizer_path,
70
  unk_token="[UNK]",
@@ -75,8 +130,19 @@ class SegmentationTokenizer:
75
  )
76
  return self
77
 
78
- # ---------- TOKENIZATION ----------
 
 
79
  def compute_unk_rate(self, corpus):
 
 
 
 
 
 
 
 
 
80
  unk_id = self._hf_tokenizer.convert_tokens_to_ids("[UNK]")
81
 
82
  total_tokens = 0
@@ -101,8 +167,18 @@ class SegmentationTokenizer:
101
  truncation=True
102
  ):
103
  """
104
- text: str or List[str]
105
- returns: dict with input_ids and attention_mask (torch.long)
 
 
 
 
 
 
 
 
 
 
106
  """
107
  if self._hf_tokenizer is None:
108
  raise RuntimeError("Tokenizer not loaded. Call .load() first.")
@@ -116,17 +192,29 @@ class SegmentationTokenizer:
116
  )
117
 
118
  return {
119
- "input_ids": enc["input_ids"], # torch.LongTensor
120
- "attention_mask": enc["attention_mask"] # torch.LongTensor
121
  }
122
 
 
 
 
123
  @property
124
  def vocab_size(self):
 
 
 
 
 
 
125
  if self._hf_tokenizer is None:
126
  raise RuntimeError("Tokenizer not loaded.")
127
  return self._hf_tokenizer.vocab_size
128
 
129
  def __repr__(self):
 
 
 
130
  return f"<SegmentationTokenizer vocab_size={self.trainer.vocab_size}>"
131
 
132
 
 
21
 
22
 
23
  class SegmentationTokenizer:
24
+ """
25
+ Wrapper class for training and using a BPE-based tokenizer for text segmentation.
26
+
27
+ This class supports:
28
+ - Training a Byte Pair Encoding (BPE) tokenizer from an iterator
29
+ - Saving and loading the tokenizer
30
+ - Tokenizing text with padding and truncation
31
+ - Computing the unknown-token (UNK) rate over a corpus
32
+ """
33
+
34
+ def __init__(self, vocab_size=32_768, min_frequency=2, max_length=1024):
35
+ """
36
+ Initialize the segmentation tokenizer.
37
+
38
+ Args:
39
+ vocab_size (int): Maximum vocabulary size for the BPE tokenizer.
40
+ min_frequency (int): Minimum token frequency to be included in the vocabulary.
41
+ max_length (int): Maximum sequence length for tokenization.
42
+ """
43
  self.max_length = max_length
44
 
45
+ # Raw tokenizer used only during training
46
  self.raw_tokenizer = tokenizers.Tokenizer(
47
  BPE(unk_token="[UNK]")
48
  )
49
  self.raw_tokenizer.normalizer = NFKC()
50
  self.raw_tokenizer.pre_tokenizer = Whitespace()
51
 
52
+ # Trainer configuration for BPE
53
  self.trainer = BpeTrainer(
54
  vocab_size=vocab_size,
55
  min_frequency=min_frequency,
56
  special_tokens=["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]"]
57
  )
58
 
59
+ # Hugging Face fast tokenizer (created after loading)
60
+ self._hf_tokenizer = None
61
 
62
+ # ------------------------------------------------------------------
63
+ # Training utilities
64
+ # ------------------------------------------------------------------
65
+ @staticmethod
66
+ def build_iterator(dataset, batch_size=1024):
67
+ """
68
+ Build a batched text iterator from a dataset.
69
+
70
+ Each dataset item is expected to contain a "text" field,
71
+ which is a list of strings.
72
+
73
+ Args:
74
+ dataset (Iterable[dict]): Dataset containing text entries.
75
+ batch_size (int): Number of samples per batch.
76
+
77
+ Yields:
78
+ List[str]: A batch of concatenated text samples.
79
+ """
80
  batch = []
81
  for item in dataset:
82
  batch.append("\n".join(item["text"]).replace("\n\n", "\n"))
 
87
  yield batch
88
 
89
  def train_from_iterator(self, iterator):
90
+ """
91
+ Train the raw tokenizer from an iterator of text batches.
92
+
93
+ Args:
94
+ iterator (Iterable[List[str]]): Iterator yielding batches of text.
95
+ """
96
  self.raw_tokenizer.train_from_iterator(
97
+ iterator,
98
+ trainer=self.trainer
99
  )
100
 
101
+ # ------------------------------------------------------------------
102
+ # I/O
103
+ # ------------------------------------------------------------------
104
  def save(self, path):
105
+ """
106
+ Save the trained raw tokenizer to disk.
107
+
108
+ Args:
109
+ path (str): Path where the tokenizer file will be saved.
110
+ """
111
  self.raw_tokenizer.save(path)
112
 
113
  def load(self, tokenizer_path):
114
+ """
115
+ Load a tokenizer from disk as a Hugging Face fast tokenizer.
116
+
117
+ Args:
118
+ tokenizer_path (str): Path to the saved tokenizer file.
119
+
120
+ Returns:
121
+ SegmentationTokenizer: Self, for chaining.
122
+ """
123
  self._hf_tokenizer = PreTrainedTokenizerFast(
124
  tokenizer_file=tokenizer_path,
125
  unk_token="[UNK]",
 
130
  )
131
  return self
132
 
133
+ # ------------------------------------------------------------------
134
+ # Tokenization utilities
135
+ # ------------------------------------------------------------------
136
  def compute_unk_rate(self, corpus):
137
+ """
138
+ Compute the proportion of unknown tokens ([UNK]) in a corpus.
139
+
140
+ Args:
141
+ corpus (Iterable[str]): Collection of input texts.
142
+
143
+ Returns:
144
+ float: UNK token rate in the corpus.
145
+ """
146
  unk_id = self._hf_tokenizer.convert_tokens_to_ids("[UNK]")
147
 
148
  total_tokens = 0
 
167
  truncation=True
168
  ):
169
  """
170
+ Tokenize input text.
171
+
172
+ Args:
173
+ text (str or List[str]): Input text or batch of texts.
174
+ return_tensors (str): Tensor type to return (e.g., "pt").
175
+ padding (bool): Whether to pad sequences to max_length.
176
+ truncation (bool): Whether to truncate sequences to max_length.
177
+
178
+ Returns:
179
+ dict: Dictionary containing:
180
+ - input_ids (torch.LongTensor)
181
+ - attention_mask (torch.LongTensor)
182
  """
183
  if self._hf_tokenizer is None:
184
  raise RuntimeError("Tokenizer not loaded. Call .load() first.")
 
192
  )
193
 
194
  return {
195
+ "input_ids": enc["input_ids"],
196
+ "attention_mask": enc["attention_mask"]
197
  }
198
 
199
+ # ------------------------------------------------------------------
200
+ # Properties and representations
201
+ # ------------------------------------------------------------------
202
  @property
203
  def vocab_size(self):
204
+ """
205
+ Get the vocabulary size of the loaded tokenizer.
206
+
207
+ Returns:
208
+ int: Vocabulary size.
209
+ """
210
  if self._hf_tokenizer is None:
211
  raise RuntimeError("Tokenizer not loaded.")
212
  return self._hf_tokenizer.vocab_size
213
 
214
  def __repr__(self):
215
+ """
216
+ String representation of the tokenizer.
217
+ """
218
  return f"<SegmentationTokenizer vocab_size={self.trainer.vocab_size}>"
219
 
220