Source file saga_tokenizers.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
(** Main tokenizers module that aggregates all tokenization functionality *)
module Either = struct
type ('a, 'b) t = Left of 'a | Right of 'b
end
module Models = Models
(** Re-export all the submodules *)
module Normalizers = Normalizers
module Pre_tokenizers = Pre_tokenizers
module Processors = Processors
module Decoders = Decoders
module Trainers = Trainers
module Unicode = Unicode
module Encoding = Encoding
module Bpe = Bpe
module Wordpiece = Wordpiece
type split_delimiter_behavior =
[ `Removed
| `Isolated
| `Merged_with_previous
| `Merged_with_next
| `Contiguous ]
(** Type definitions *)
type strategy = [ `Longest_first | `Only_first | `Only_second ]
type prepend_scheme = [ `Always | `Never | `First ]
(** Added token type *)
module Added_token = struct
type t = {
content : string;
single_word : bool;
lstrip : bool;
rstrip : bool;
normalized : bool;
special : bool;
}
let create ?(content = "") ?(single_word = false) ?(lstrip = false)
?(rstrip = false) ?(normalized = true) ?(special = false) () =
{ content; single_word; lstrip; rstrip; normalized; special }
let content t = t.content
let lstrip t = t.lstrip
let normalized t = t.normalized
let rstrip t = t.rstrip
let single_word t = t.single_word
let special t = t.special
let _ = special
end
type direction = [ `Left | `Right ]
(** Direction type for padding *)
(** Main Tokenizer module *)
module Tokenizer = struct
type padding_config = {
direction : direction;
pad_id : int;
pad_type_id : int;
pad_token : string;
length : int option;
pad_to_multiple_of : int option;
}
type truncation_config = {
max_length : int;
stride : int;
strategy : strategy;
direction : direction;
}
type t = {
mutable model : Models.t;
mutable normalizer : Normalizers.t option;
mutable pre_tokenizer : Pre_tokenizers.t option;
mutable post_processor : Processors.t option;
mutable decoder : Decoders.t option;
mutable padding : padding_config option;
mutable truncation : truncation_config option;
added_tokens : (string, Added_token.t) Hashtbl.t;
special_tokens : (string, int) Hashtbl.t;
}
let create ~model =
{
model;
normalizer = None;
pre_tokenizer = None;
post_processor = None;
decoder = None;
padding = None;
truncation = None;
added_tokens = Hashtbl.create 16;
special_tokens = Hashtbl.create 16;
}
let from_file path =
try
let json = Yojson.Basic.from_file path in
let t =
match json with
| `Assoc fields ->
let model =
match List.assoc_opt "model" fields with
| Some model_json -> Models.of_json model_json
| None -> Models.word_level ()
in
let tok = create ~model in
(match List.assoc_opt "normalizer" fields with
| Some `Null | None -> ()
| Some njson -> tok.normalizer <- Some (Normalizers.of_json njson));
(match List.assoc_opt "post_processor" fields with
| Some `Null | None -> ()
| Some pjson ->
tok.post_processor <- Some (Processors.of_json pjson));
(match List.assoc_opt "truncation" fields with
| Some (`Assoc tfs) ->
let max_length =
match List.assoc_opt "max_length" tfs with
| Some (`Int i) -> i
| _ -> 0
in
let stride =
match List.assoc_opt "stride" tfs with
| Some (`Int i) -> i
| _ -> 0
in
let direction =
match List.assoc_opt "direction" tfs with
| Some (`String "Left") -> `Left
| _ -> `Right
in
let strategy =
match List.assoc_opt "strategy" tfs with
| Some (`String "OnlyFirst") -> `Only_first
| Some (`String "OnlySecond") -> `Only_second
| _ -> `Longest_first
in
tok.truncation <-
Some { max_length; stride; strategy; direction }
| _ -> ());
(match List.assoc_opt "padding" fields with
| Some (`Assoc pfs) ->
let direction =
match List.assoc_opt "direction" pfs with
| Some (`String "Left") -> `Left
| _ -> `Right
in
let pad_id =
match List.assoc_opt "pad_id" pfs with
| Some (`Int i) -> i
| _ -> 0
in
let pad_type_id =
match List.assoc_opt "pad_type_id" pfs with
| Some (`Int i) -> i
| _ -> 0
in
let pad_token =
match List.assoc_opt "pad_token" pfs with
| Some (`String s) -> s
| _ -> "<pad>"
in
let length =
match List.assoc_opt "length" pfs with
| Some (`Int i) -> Some i
| _ -> None
in
let pad_to_multiple_of =
match List.assoc_opt "pad_to_multiple_of" pfs with
| Some (`Int i) -> Some i
| _ -> None
in
tok.padding <-
Some
{
direction;
pad_id;
pad_type_id;
pad_token;
length;
pad_to_multiple_of;
}
| _ -> ());
tok
| _ -> create ~model:(Models.word_level ())
in
Ok t
with e -> Error e
let from_str str =
try
let bytes = Bytes.of_string str in
let tmp = Filename.temp_file "saga_tokenizer" ".json" in
let oc = open_out tmp in
output_string oc (Bytes.to_string bytes);
close_out oc;
let res = from_file tmp in
(try Sys.remove tmp with _ -> ());
res
with e -> Error e
let from_pretrained identifier ?revision ?token () =
let _ = (identifier, revision, token) in
let model = Models.word_level () in
Ok (create ~model)
let from_buffer bytes = from_str (Bytes.to_string bytes)
let save t ~path ?pretty () =
let _ = pretty in
let json =
`Assoc
[
("version", `String "1.0");
("truncation", `Null);
("padding", `Null);
("added_tokens", `List []);
("normalizer", `Null);
("pre_tokenizer", `Null);
("post_processor", `Null);
("decoder", `Null);
("model", Models.to_json t.model);
]
in
let oc = open_out path in
Yojson.Basic.to_channel oc json;
close_out oc
let to_str t ?pretty () =
let int_opt = function None -> `Null | Some i -> `Int i in
let json =
`Assoc
[
("version", `String "1.0");
( "truncation",
match t.truncation with
| None -> `Null
| Some cfg ->
`Assoc
[
("max_length", `Int cfg.max_length);
("stride", `Int cfg.stride);
( "strategy",
`String
(match cfg.strategy with
| `Longest_first -> "LongestFirst"
| `Only_first -> "OnlyFirst"
| `Only_second -> "OnlySecond") );
( "direction",
`String
(match cfg.direction with
| `Left -> "Left"
| `Right -> "Right") );
] );
( "padding",
match t.padding with
| None -> `Null
| Some cfg ->
`Assoc
[
( "direction",
`String
(match cfg.direction with
| `Left -> "Left"
| `Right -> "Right") );
("pad_id", `Int cfg.pad_id);
("pad_type_id", `Int cfg.pad_type_id);
("pad_token", `String cfg.pad_token);
("length", int_opt cfg.length);
("pad_to_multiple_of", int_opt cfg.pad_to_multiple_of);
] );
( "added_tokens",
`List
(Hashtbl.fold
(fun _ tok acc ->
`Assoc
[
("content", `String (Added_token.content tok));
("single_word", `Bool (Added_token.single_word tok));
("lstrip", `Bool (Added_token.lstrip tok));
("rstrip", `Bool (Added_token.rstrip tok));
("normalized", `Bool (Added_token.normalized tok));
("special", `Bool (Added_token.special tok));
]
:: acc)
t.added_tokens []) );
( "normalizer",
match t.normalizer with
| None -> `Null
| Some n -> Normalizers.to_json n );
( "pre_tokenizer",
match t.pre_tokenizer with
| None -> `Null
| Some _ ->
`Assoc [ ("type", `String "Custom") ] );
( "post_processor",
match t.post_processor with
| None -> `Null
| Some p -> Processors.to_json p );
( "decoder",
match t.decoder with
| None -> `Null
| Some _ -> `Assoc [ ("type", `String "Custom") ] );
("model", Models.to_json t.model);
]
in
match pretty with
| Some true -> Yojson.Basic.pretty_to_string json
| _ -> Yojson.Basic.to_string json
let get_model t = t.model
let set_model t model = t.model <- model
let get_normalizer t = t.normalizer
let set_normalizer t normalizer = t.normalizer <- normalizer
let get_pre_tokenizer t = t.pre_tokenizer
let set_pre_tokenizer t pre_tokenizer = t.pre_tokenizer <- pre_tokenizer
let get_post_processor t = t.post_processor
let set_post_processor t post_processor = t.post_processor <- post_processor
let get_decoder t = t.decoder
let set_decoder t decoder = t.decoder <- decoder
let get_padding t = t.padding
let _set_padding t padding = t.padding <- Some padding
let no_padding t = t.padding <- None
let get_truncation t = t.truncation
let _set_truncation t truncation = t.truncation <- Some truncation
let no_truncation t = t.truncation <- None
let add_special_tokens t tokens =
let count = ref 0 in
let token_strings = ref [] in
List.iter
(fun token_either ->
let added_token =
match token_either with
| Either.Left str -> Added_token.create ~content:str ~special:true ()
| Either.Right tok -> tok
in
if not (Hashtbl.mem t.added_tokens (Added_token.content added_token))
then (
Hashtbl.add t.added_tokens
(Added_token.content added_token)
added_token;
Hashtbl.add t.special_tokens
(Added_token.content added_token)
(Hashtbl.length t.special_tokens);
token_strings := Added_token.content added_token :: !token_strings;
incr count))
tokens;
let model_count = Models.add_tokens t.model (List.rev !token_strings) in
let _ = model_count in
!count
let add_tokens t tokens =
let count = ref 0 in
let token_strings = ref [] in
List.iter
(fun token_either ->
let added_token =
match token_either with
| Either.Left str -> Added_token.create ~content:str ()
| Either.Right tok -> tok
in
if not (Hashtbl.mem t.added_tokens (Added_token.content added_token))
then (
Hashtbl.add t.added_tokens
(Added_token.content added_token)
added_token;
token_strings := Added_token.content added_token :: !token_strings;
incr count))
tokens;
let model_count = Models.add_tokens t.model (List.rev !token_strings) in
let _ = model_count in
!count
let get_vocab t ?with_added_tokens () =
let _with_added = Option.value with_added_tokens ~default:true in
Models.get_vocab t.model
let get_vocab_size t ?with_added_tokens () =
let with_added = Option.value with_added_tokens ~default:true in
let base_size = Models.get_vocab_size t.model in
if with_added then
base_size
+ Hashtbl.length t.added_tokens
+ Hashtbl.length t.special_tokens
else base_size
let enable_padding t config = t.padding <- Some config
let enable_truncation t config = t.truncation <- Some config
let encoding_to_processor (e : Encoding.t) : Processors.encoding =
{
ids = Encoding.get_ids e;
type_ids = Encoding.get_type_ids e;
tokens = Encoding.get_tokens e;
offsets = Encoding.get_offsets e;
special_tokens_mask = Encoding.get_special_tokens_mask e;
attention_mask = Encoding.get_attention_mask e;
overflowing = [];
sequence_ranges = [];
}
let processor_to_encoding (pe : Processors.encoding) : Encoding.t =
let len = Array.length pe.ids in
let words = Array.make len None in
let seq = Hashtbl.create 1 in
Encoding.create ~ids:pe.ids ~type_ids:pe.type_ids ~tokens:pe.tokens ~words
~offsets:pe.offsets ~special_tokens_mask:pe.special_tokens_mask
~attention_mask:pe.attention_mask ~overflowing:[] ~sequence_ranges:seq
let encode t ~sequence ?pair ?is_pretokenized ?add_special_tokens () =
let is_pretokenized = Option.value is_pretokenized ~default:false in
let add_special_tokens = Option.value add_special_tokens ~default:true in
let _ = (pair, is_pretokenized, add_special_tokens) in
let text =
match sequence with
| Either.Left s -> s
| Either.Right lst -> String.concat " " lst
in
let normalized =
match t.normalizer with
| Some n -> Normalizers.normalize_str n text
| None -> text
in
let pre_tokens =
match t.pre_tokenizer with
| Some pt -> pt normalized
| None -> [ (normalized, (0, String.length normalized)) ]
in
let tokens =
List.concat_map (fun (text, _) -> Models.tokenize t.model text) pre_tokens
in
let token_list =
List.map
(fun (tok : Models.token) -> (tok.id, tok.value, tok.offsets))
tokens
in
let enc = Encoding.from_tokens token_list ~type_id:0 in
let enc =
match t.post_processor with
| None -> enc
| Some proc -> (
let proc_enc = encoding_to_processor enc in
let outs = Processors.process proc [ proc_enc ] ~add_special_tokens in
match outs with [] -> enc | x :: _ -> processor_to_encoding x)
in
let enc =
match t.truncation with
| None -> enc
| Some cfg ->
let t_dir : Encoding.truncation_direction =
match cfg.direction with
| `Left -> Encoding.Left
| `Right -> Encoding.Right
in
Encoding.truncate enc ~max_length:cfg.max_length ~stride:cfg.stride
~direction:t_dir
in
let enc =
match t.padding with
| None -> enc
| Some cfg -> (
let p_dir : Encoding.padding_direction =
match cfg.direction with
| `Left -> Encoding.Left
| `Right -> Encoding.Right
in
match (cfg.length, cfg.pad_to_multiple_of) with
| Some target, _ ->
Encoding.pad enc ~target_length:target ~pad_id:cfg.pad_id
~pad_type_id:cfg.pad_type_id ~pad_token:cfg.pad_token
~direction:p_dir
| None, Some m when m > 0 ->
let cur = Encoding.length enc in
let target = (cur + m - 1) / m * m in
Encoding.pad enc ~target_length:target ~pad_id:cfg.pad_id
~pad_type_id:cfg.pad_type_id ~pad_token:cfg.pad_token
~direction:p_dir
| None, _ -> enc)
in
enc
let encode_batch t ~input ?is_pretokenized ?add_special_tokens () =
let encs =
List.map
(fun item ->
match item with
| Either.Left sequence ->
encode t ~sequence ?pair:None ?is_pretokenized ?add_special_tokens
()
| Either.Right (seq1, seq2) ->
encode t ~sequence:seq1 ~pair:seq2 ?is_pretokenized
?add_special_tokens ())
input
in
match t.padding with
| None -> encs
| Some cfg ->
let p_dir : Encoding.padding_direction =
match cfg.direction with
| `Left -> Encoding.Left
| `Right -> Encoding.Right
in
let max_len =
List.fold_left (fun acc e -> max acc (Encoding.length e)) 0 encs
in
let target =
match (cfg.length, cfg.pad_to_multiple_of) with
| Some l, _ -> l
| None, Some m when m > 0 -> (max_len + m - 1) / m * m
| _ -> max_len
in
List.map
(fun e ->
if Encoding.length e >= target then e
else
Encoding.pad e ~target_length:target ~pad_id:cfg.pad_id
~pad_type_id:cfg.pad_type_id ~pad_token:cfg.pad_token
~direction:p_dir)
encs
let decode t ids ?skip_special_tokens ?clean_up_tokenization_spaces () =
let skip_special_tokens = Option.value skip_special_tokens ~default:false in
let clean_up_tokenization_spaces =
Option.value clean_up_tokenization_spaces ~default:true
in
let _ = clean_up_tokenization_spaces in
let tokens =
List.filter_map
(fun id ->
match Models.id_to_token t.model id with
| Some token
when skip_special_tokens && Hashtbl.mem t.special_tokens token ->
None
| Some token -> Some token
| None -> None)
ids
in
match t.decoder with
| Some d -> Decoders.decode d tokens
| None -> (
match t.model with
| Models.WordLevel _ ->
String.concat " " tokens
| Models.WordPiece _ ->
String.concat "" tokens
| _ ->
String.concat "" tokens)
let decode_batch t id_lists ?skip_special_tokens ?clean_up_tokenization_spaces
() =
List.map
(fun ids ->
decode t ids ?skip_special_tokens ?clean_up_tokenization_spaces ())
id_lists
let token_to_id t token = Models.token_to_id t.model token
let id_to_token t id = Models.id_to_token t.model id
let get_added_tokens_decoder t =
Hashtbl.fold
(fun _ tok acc ->
match Models.token_to_id t.model (Added_token.content tok) with
| Some id -> (id, tok) :: acc
| None -> acc)
t.added_tokens []
let train t ~files ?trainer () =
let trainer =
match trainer with Some tr -> tr | None -> Trainers.word_level ()
in
let res = Trainers.train trainer ~files ?model:(Some t.model) () in
t.model <- res.model;
let _ =
if res.special_tokens <> [] then
add_special_tokens t
(List.map (fun s -> Either.Left s) res.special_tokens)
else 0
in
()
let train_from_iterator t (seq : string Seq.t) ?trainer ?length () =
let _ = length in
let trainer =
match trainer with Some tr -> tr | None -> Trainers.word_level ()
in
let state = ref seq in
let iterator () =
match !state () with
| Seq.Nil -> None
| Seq.Cons (x, next) ->
state := next;
Some x
in
let res =
Trainers.train_from_iterator trainer ~iterator ?model:(Some t.model) ()
in
t.model <- res.model;
let _ =
if res.special_tokens <> [] then
add_special_tokens t
(List.map (fun s -> Either.Left s) res.special_tokens)
else 0
in
()
let post_process _t ~encoding ?pair ?add_special_tokens () =
let _add_special_tokens = Option.value add_special_tokens ~default:true in
let _ = pair in
encoding
let num_special_tokens_to_add t ~is_pair =
match t.post_processor with
| None -> 0
| Some p -> Processors.added_tokens p ~is_pair
let save_pretrained t ~path =
let tok_file = Filename.concat path "tokenizer.json" in
let oc = open_out tok_file in
output_string oc (to_str t ~pretty:true ());
close_out oc;
let _files = Models.save t.model ~folder:path () in
()
end