package saga
Text processing and NLP extensions for Nx
Install
dune-project
Dependency
Authors
Maintainers
Sources
raven-1.0.0.alpha1.tbz
sha256=8e277ed56615d388bc69c4333e43d1acd112b5f2d5d352e2453aef223ff59867
sha512=369eda6df6b84b08f92c8957954d107058fb8d3d8374082e074b56f3a139351b3ae6e3a99f2d4a4a2930dd950fd609593467e502368a13ad6217b571382da28c
doc/src/saga.tokenizers/wordpiece.ml.html
Source file wordpiece.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
(** WordPiece tokenization implementation *) exception Error of string type vocab = (string, int) Hashtbl.t type vocab_r = (int, string) Hashtbl.t type token = { id : int; value : string; offsets : int * int } type config = { vocab : vocab; unk_token : string; continuing_subword_prefix : string; max_input_chars_per_word : int; } type t = { mutable vocab : vocab; mutable vocab_r : vocab_r; unk_token : string; mutable continuing_subword_prefix : string; max_input_chars_per_word : int; } let create_internal vocab unk_token continuing_subword_prefix max_input_chars_per_word = let vocab_r = Hashtbl.create (Hashtbl.length vocab) in Hashtbl.iter (fun k v -> Hashtbl.add vocab_r v k) vocab; (* Only raise error if vocabulary is non-empty but missing UNK token *) if Hashtbl.length vocab > 0 && not (Hashtbl.mem vocab unk_token) then raise (Error "WordPiece error: Missing [UNK] token from the vocabulary"); { vocab; vocab_r; unk_token; continuing_subword_prefix; max_input_chars_per_word; } let create (cfg : config) = create_internal cfg.vocab cfg.unk_token cfg.continuing_subword_prefix cfg.max_input_chars_per_word let default () = create_internal (Hashtbl.create 0) "[UNK]" "##" 100 let read_file ~vocab_file = let vocab = Hashtbl.create 10000 in let ic = open_in vocab_file in let index = ref 0 in (try while true do let line = input_line ic in let token = String.trim line in if token <> "" then ( Hashtbl.add vocab token !index; incr index) done with End_of_file -> ()); close_in ic; vocab let read_bytes bytes = let vocab = Hashtbl.create 10000 in let str = Bytes.to_string bytes in let lines = String.split_on_char '\n' str in List.iteri (fun index line -> let token = String.trim line in if token <> "" then Hashtbl.add vocab token index) lines; vocab let from_file ~vocab_file = let vocab = read_file ~vocab_file in (* Use default values for BERT-style WordPiece *) create_internal vocab "[UNK]" "##" 100 let from_file_with_config ~vocab_file ~unk_token ~continuing_subword_prefix ~max_input_chars_per_word = let vocab = read_file ~vocab_file in create_internal vocab unk_token continuing_subword_prefix max_input_chars_per_word let tokenize model sequence = (* Handle empty vocabulary case *) if Hashtbl.length model.vocab = 0 then [] else let char_count = let decoder = Uutf.decoder (`String sequence) in let count = ref 0 in let rec loop () = match Uutf.decode decoder with | `Uchar _ -> incr count; loop () | `End -> !count | `Malformed _ -> incr count; loop () | `Await -> assert false in loop () in if char_count > model.max_input_chars_per_word then let id = Hashtbl.find model.vocab model.unk_token in [ { id; value = model.unk_token; offsets = (0, String.length sequence) } ] else let rec tokenize_greedy start acc = if start >= String.length sequence then List.rev acc else let rec find_longest_match end_pos = if end_pos <= start then None else let substr = String.sub sequence start (end_pos - start) in let token_str = if start > 0 then model.continuing_subword_prefix ^ substr else substr in match Hashtbl.find_opt model.vocab token_str with | Some id -> Some { id; value = token_str; offsets = (start, end_pos) } | None -> let new_end = let rec find_char_start pos = if pos <= start then start else if Char.code sequence.[pos - 1] land 0xC0 <> 0x80 then pos - 1 else find_char_start (pos - 1) in find_char_start end_pos in if new_end <= start then None else find_longest_match new_end in match find_longest_match (String.length sequence) with | Some token -> tokenize_greedy (snd token.offsets) (token :: acc) | None -> let id = Hashtbl.find model.vocab model.unk_token in [ { id; value = model.unk_token; offsets = (0, String.length sequence); }; ] in tokenize_greedy 0 [] let token_to_id model token = Hashtbl.find_opt model.vocab token let id_to_token model id = Hashtbl.find_opt model.vocab_r id let get_vocab model = Hashtbl.fold (fun k v acc -> (k, v) :: acc) model.vocab [] let get_vocab_size model = Hashtbl.length model.vocab let get_unk_token model = model.unk_token let get_continuing_subword_prefix model = model.continuing_subword_prefix let get_max_input_chars_per_word model = model.max_input_chars_per_word let save model ~path ?name () = let vocab_file = match name with | Some n -> Filename.concat path (n ^ "-vocab.txt") | None -> Filename.concat path "vocab.txt" in let vocab_list = Hashtbl.fold (fun k v acc -> (v, k) :: acc) model.vocab [] |> List.sort compare |> List.map (fun (_, k) -> k) in let oc = open_out vocab_file in List.iter (fun token -> output_string oc token; output_char oc '\n') vocab_list; close_out oc; vocab_file let from_bpe bpe = let vocab = Hashtbl.create (Bpe.get_vocab_size bpe) in List.iter (fun (k, id) -> Hashtbl.add vocab k id) (Bpe.get_vocab bpe); let unk_token = match Bpe.get_unk_token bpe with Some u -> u | None -> "[UNK]" in let continuing_subword_prefix = match Bpe.get_continuing_subword_prefix bpe with | Some p -> p | None -> "##" in create_internal vocab unk_token continuing_subword_prefix 100 (* Save reference to internal create before Builder shadows it *) let create_wordpiece = create_internal (** Builder module *) module Builder = struct type builder = { mutable files : string option; mutable vocab : vocab; mutable unk_token : string; mutable continuing_subword_prefix : string; mutable max_input_chars_per_word : int; } let create () = { files = None; vocab = Hashtbl.create 0; unk_token = "[UNK]"; continuing_subword_prefix = "##"; max_input_chars_per_word = 100; } let files builder f = builder.files <- Some f; builder let vocab builder v = builder.vocab <- v; builder let unk_token builder token = builder.unk_token <- token; builder let continuing_subword_prefix builder prefix = builder.continuing_subword_prefix <- prefix; builder let max_input_chars_per_word builder max = builder.max_input_chars_per_word <- max; builder let build builder = let vocab = match builder.files with | None -> builder.vocab | Some f -> read_file ~vocab_file:f in create_wordpiece vocab builder.unk_token builder.continuing_subword_prefix builder.max_input_chars_per_word end (** Serialization *) let to_yojson model = let vocab_list = Hashtbl.fold (fun k v acc -> (v, k) :: acc) model.vocab [] |> List.sort compare |> List.map (fun (_, k) -> (k, `Int (Hashtbl.find model.vocab k))) in `Assoc [ ("type", `String "WordPiece"); ("unk_token", `String model.unk_token); ("continuing_subword_prefix", `String model.continuing_subword_prefix); ("max_input_chars_per_word", `Int model.max_input_chars_per_word); ("vocab", `Assoc vocab_list); ] let of_yojson json = match json with | `Assoc fields -> let get_field name = List.assoc_opt name fields |> function | Some v -> v | None -> raise (Error ("Missing field: " ^ name)) in let () = match get_field "type" with | `String "WordPiece" -> () | _ -> raise (Error "Invalid type") | exception _ -> () in let unk_token = match get_field "unk_token" with | `String s -> s | _ -> raise (Error "Invalid unk_token") in let continuing_subword_prefix = match get_field "continuing_subword_prefix" with | `String s -> s | _ -> raise (Error "Invalid continuing_subword_prefix") in let max_input_chars_per_word = match get_field "max_input_chars_per_word" with | `Int i -> i | _ -> raise (Error "Invalid max_input_chars_per_word") in let vocab_json = get_field "vocab" in let vocab = match vocab_json with | `Assoc pairs -> let h = Hashtbl.create (List.length pairs) in List.iter (fun (k, v) -> match v with | `Int id -> Hashtbl.add h k id | _ -> raise (Error "Invalid vocab entry")) pairs; h | _ -> raise (Error "Invalid vocab") in create_internal vocab unk_token continuing_subword_prefix max_input_chars_per_word | _ -> raise (Error "Invalid JSON structure") let from_bytes bytes = let str = Bytes.to_string bytes in of_yojson (Yojson.Basic.from_string str) (** Trainer module *) module Trainer = struct type trainer_config = { min_frequency : int; vocab_size : int; show_progress : bool; special_tokens : string list; limit_alphabet : int option; initial_alphabet : char list; continuing_subword_prefix : string; end_of_word_suffix : string option; } type trainer = { config : trainer_config; [@warning "-69"] bpe_config : Bpe.Trainer.trainer_config; [@warning "-69"] bpe_trainer : Bpe.Trainer.trainer; } let default_config = { min_frequency = 0; vocab_size = 30000; show_progress = true; special_tokens = [ "[UNK]"; "[CLS]"; "[SEP]"; "[PAD]"; "[MASK]" ]; limit_alphabet = None; initial_alphabet = []; continuing_subword_prefix = "##"; end_of_word_suffix = None; } let create config = let bpe_config = { Bpe.Trainer.min_frequency = config.min_frequency; vocab_size = config.vocab_size; show_progress = config.show_progress; special_tokens = config.special_tokens; limit_alphabet = config.limit_alphabet; initial_alphabet = config.initial_alphabet; continuing_subword_prefix = Some config.continuing_subword_prefix; end_of_word_suffix = config.end_of_word_suffix; max_token_length = None; } in { config; bpe_config; bpe_trainer = Bpe.Trainer.create bpe_config } let feed trainer texts = Bpe.Trainer.feed trainer.bpe_trainer texts let train trainer model = let bpe_model = Bpe.default () in let special_tokens = Bpe.Trainer.train trainer.bpe_trainer bpe_model in let new_model = from_bpe bpe_model in model.vocab <- new_model.vocab; model.vocab_r <- new_model.vocab_r; model.continuing_subword_prefix <- new_model.continuing_subword_prefix; special_tokens end
sectionYPositions = computeSectionYPositions($el), 10)"
x-init="setTimeout(() => sectionYPositions = computeSectionYPositions($el), 10)"
>