package saga
sectionYPositions = computeSectionYPositions($el), 10)"
x-init="setTimeout(() => sectionYPositions = computeSectionYPositions($el), 10)"
>
Text processing and NLP extensions for Nx
Install
dune-project
Dependency
Authors
Maintainers
Sources
raven-1.0.0.alpha2.tbz
sha256=93abc49d075a1754442ccf495645bc4fdc83e4c66391ec8aca8fa15d2b4f44d2
sha512=5eb958c51f30ae46abded4c96f48d1825f79c7ce03f975f9a6237cdfed0d62c0b4a0774296694def391573d849d1f869919c49008acffca95946b818ad325f6f
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(** 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 = { vocab : vocab; vocab_r : vocab_r; unk_token : string; 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 (** 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 *) let train ~min_frequency ~vocab_size ~show_progress ~special_tokens ~limit_alphabet ~initial_alphabet ~continuing_subword_prefix ~end_of_word_suffix texts existing = let _ = existing in (* WordPiece training uses BPE algorithm internally *) let bpe_trained, result_tokens = Bpe.train ~min_frequency ~vocab_size ~show_progress ~special_tokens ~limit_alphabet ~initial_alphabet ~continuing_subword_prefix:(Some continuing_subword_prefix) ~end_of_word_suffix ~max_token_length:None texts None in let wordpiece_model = from_bpe bpe_trained in (wordpiece_model, result_tokens)
sectionYPositions = computeSectionYPositions($el), 10)"
x-init="setTimeout(() => sectionYPositions = computeSectionYPositions($el), 10)"
>