Nexuss0781 commited on
Commit
bbb716d
·
verified ·
1 Parent(s): 6611338

Upload scripts/train_tokenizer.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/train_tokenizer.py +129 -7
scripts/train_tokenizer.py CHANGED
@@ -3,7 +3,7 @@
3
  Command-line interface for training BBPE tokenizers.
4
 
5
  Usage:
6
- python train_tokenizer.py --data_dir ./data --vocab_size 30000 --model_name my_tokenizer
7
  """
8
 
9
  import argparse
@@ -13,7 +13,7 @@ from pathlib import Path
13
  # Add parent directory to path for imports
14
  sys.path.insert(0, str(Path(__file__).parent))
15
 
16
- from bbpe_trainer import BBPETrainer, BBPEConfig
17
 
18
 
19
  def parse_args():
@@ -100,7 +100,7 @@ def parse_args():
100
  parser.add_argument(
101
  "--model_name",
102
  type=str,
103
- default="bbpe_tokenizer",
104
  help="Name for the saved tokenizer model",
105
  )
106
 
@@ -119,6 +119,88 @@ def parse_args():
119
  help="Path to save the configuration JSON file",
120
  )
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  return parser.parse_args()
123
 
124
 
@@ -137,11 +219,18 @@ def main():
137
  min_frequency=args.min_frequency,
138
  special_tokens=args.special_tokens,
139
  lowercase=args.lowercase,
140
- add_prefix_space=not args.no_prefix_space,
141
  show_progress=args.show_progress,
142
  data_dir=args.data_dir,
143
  model_save_dir=args.model_save_dir,
144
  model_name=args.model_name,
 
 
 
 
 
 
 
 
145
  )
146
 
147
  # Save config if requested
@@ -150,7 +239,7 @@ def main():
150
  print(f"Configuration saved to {args.save_config}")
151
 
152
  # Initialize trainer
153
- trainer = BBPETrainer(config)
154
 
155
  # Get training files
156
  if args.files:
@@ -171,7 +260,21 @@ def main():
171
  sys.exit(1)
172
 
173
  # Save the tokenizer
174
- save_path = trainer.save()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
  # Test the tokenizer
177
  print("\n" + "="*60)
@@ -180,7 +283,7 @@ def main():
180
 
181
  test_texts = [
182
  "Hello, world!",
183
- "This is a test of the BBPE tokenizer.",
184
  "Special characters: @#$%^&*()",
185
  "Numbers: 12345 and words mixed together.",
186
  ]
@@ -198,6 +301,25 @@ def main():
198
  print("\n" + "="*60)
199
  print(f"Tokenizer training complete!")
200
  print(f"Model saved to: {save_path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  print("="*60)
202
 
203
 
 
3
  Command-line interface for training BBPE tokenizers.
4
 
5
  Usage:
6
+ python train_tokenizer.py --data_dir ./data --vocab_size 30000 --model_name EthioBBPE
7
  """
8
 
9
  import argparse
 
13
  # Add parent directory to path for imports
14
  sys.path.insert(0, str(Path(__file__).parent))
15
 
16
+ from bbpe_trainer import EthioBBPETrainer, BBPEConfig
17
 
18
 
19
  def parse_args():
 
100
  parser.add_argument(
101
  "--model_name",
102
  type=str,
103
+ default="EthioBBPE",
104
  help="Name for the saved tokenizer model",
105
  )
106
 
 
119
  help="Path to save the configuration JSON file",
120
  )
121
 
122
+ # Advanced production features
123
+ parser.add_argument(
124
+ "--use_checkpoint",
125
+ action="store_true",
126
+ default=True,
127
+ help="Enable checkpointing during training",
128
+ )
129
+
130
+ parser.add_argument(
131
+ "--no_checkpoint",
132
+ action="store_false",
133
+ dest="use_checkpoint",
134
+ help="Disable checkpointing",
135
+ )
136
+
137
+ parser.add_argument(
138
+ "--checkpoint_dir",
139
+ type=str,
140
+ default="./models/checkpoints",
141
+ help="Directory to save checkpoints",
142
+ )
143
+
144
+ parser.add_argument(
145
+ "--max_checkpoints",
146
+ type=int,
147
+ default=5,
148
+ help="Maximum number of checkpoints to keep (0 = unlimited)",
149
+ )
150
+
151
+ parser.add_argument(
152
+ "--save_compressed",
153
+ action="store_true",
154
+ default=True,
155
+ help="Save tokenizer files in compressed format (.gz, .bz2, .xz)",
156
+ )
157
+
158
+ parser.add_argument(
159
+ "--no_compression",
160
+ action="store_false",
161
+ dest="save_compressed",
162
+ help="Disable compression",
163
+ )
164
+
165
+ parser.add_argument(
166
+ "--compression_format",
167
+ type=str,
168
+ choices=['gzip', 'bz2', 'lzma'],
169
+ default='gzip',
170
+ help="Compression format to use",
171
+ )
172
+
173
+ parser.add_argument(
174
+ "--compression_level",
175
+ type=int,
176
+ choices=range(1, 10),
177
+ default=9,
178
+ help="Compression level (1-9, higher = better compression but slower)",
179
+ )
180
+
181
+ parser.add_argument(
182
+ "--enable_quantization",
183
+ action="store_true",
184
+ default=False,
185
+ help="Enable model quantization for deployment",
186
+ )
187
+
188
+ parser.add_argument(
189
+ "--quantization_bits",
190
+ type=int,
191
+ choices=[4, 8],
192
+ default=8,
193
+ help="Quantization bits (4 or 8)",
194
+ )
195
+
196
+ parser.add_argument(
197
+ "--export_formats",
198
+ type=str,
199
+ nargs='+',
200
+ default=['tokenizer.json', 'vocab_compressed', 'hf_export'],
201
+ help="Export formats to generate",
202
+ )
203
+
204
  return parser.parse_args()
205
 
206
 
 
219
  min_frequency=args.min_frequency,
220
  special_tokens=args.special_tokens,
221
  lowercase=args.lowercase,
 
222
  show_progress=args.show_progress,
223
  data_dir=args.data_dir,
224
  model_save_dir=args.model_save_dir,
225
  model_name=args.model_name,
226
+ use_checkpoint=args.use_checkpoint,
227
+ checkpoint_dir=args.checkpoint_dir,
228
+ save_compressed=args.save_compressed,
229
+ compression_format=args.compression_format,
230
+ compression_level=args.compression_level,
231
+ enable_quantization=args.enable_quantization,
232
+ quantization_bits=args.quantization_bits,
233
+ max_checkpoints=args.max_checkpoints,
234
  )
235
 
236
  # Save config if requested
 
239
  print(f"Configuration saved to {args.save_config}")
240
 
241
  # Initialize trainer
242
+ trainer = EthioBBPETrainer(config)
243
 
244
  # Get training files
245
  if args.files:
 
260
  sys.exit(1)
261
 
262
  # Save the tokenizer
263
+ save_path = trainer.save(export_formats=args.export_formats)
264
+
265
+ # List checkpoints
266
+ print("\n" + "="*60)
267
+ print("CHECKPOINTS")
268
+ print("="*60)
269
+ checkpoints = trainer.list_checkpoints()
270
+ if checkpoints:
271
+ for ckpt in checkpoints:
272
+ status = "✓" if trainer.validate_checkpoint(ckpt['path']) else "✗"
273
+ print(f"{status} {ckpt['name']} ({ckpt['size_kb']:.1f} KB)")
274
+ if 'vocab_size' in ckpt:
275
+ print(f" Vocab size: {ckpt['vocab_size']}, Final: {ckpt.get('is_final', False)}")
276
+ else:
277
+ print("No checkpoints found.")
278
 
279
  # Test the tokenizer
280
  print("\n" + "="*60)
 
283
 
284
  test_texts = [
285
  "Hello, world!",
286
+ "This is a test of the EthioBBPE tokenizer.",
287
  "Special characters: @#$%^&*()",
288
  "Numbers: 12345 and words mixed together.",
289
  ]
 
301
  print("\n" + "="*60)
302
  print(f"Tokenizer training complete!")
303
  print(f"Model saved to: {save_path}")
304
+ if args.save_compressed:
305
+ print(f"Compressed files saved (format: {args.compression_format}, level: {args.compression_level})")
306
+ if args.enable_quantization:
307
+ print(f"Quantized model saved ({args.quantization_bits}-bit)")
308
+ if args.use_checkpoint:
309
+ print(f"Checkpoints saved to: {args.checkpoint_dir} (max: {args.max_checkpoints})")
310
+
311
+ # Print training metrics
312
+ print("\n" + "="*60)
313
+ print("TRAINING METRICS")
314
+ print("="*60)
315
+ metrics = trainer.get_training_metrics()
316
+ if 'initial' in metrics:
317
+ print(f"Files processed: {metrics['initial'].get('num_files', 'N/A')}")
318
+ print(f"Total data size: {metrics['initial'].get('total_bytes', 0) / 1024:.2f} KB")
319
+ if 'final' in metrics:
320
+ print(f"Final vocab size: {metrics['final'].get('vocab_size', 'N/A')}")
321
+ print(f"Training duration: {metrics['final'].get('training_duration_sec', 0):.2f} seconds")
322
+
323
  print("="*60)
324
 
325