Use tiktoken (#1044)

* use tiktoken==0.3.0

* formatting

* tuple should be safer

* Update whisper/tokenizer.py

Co-authored-by: Ruhollah Majdoddin <r.majdodin@gmail.com>

* use tiktoken 0.3.1

* reflecting suggestions

* cleanup

* bypassing load_tiktoken_bpe to avoid blobfile dep

---------

Co-authored-by: Ruhollah Majdoddin <r.majdodin@gmail.com>
This commit is contained in:
Jong Wook KimandRuhollah Majdoddin authored and GitHub committed 2023-03-13 02:34:16 -07:00
1 parent ad3250a846
commit 839639a223
15 files changed
+100601 -100096

No files matched your search

-2
View File
@@ -2,6 +2,4 @@ include requirements.txt
include README.md include README.md
include LICENSE include LICENSE
include whisper/assets/* include whisper/assets/*
include whisper/assets/gpt2/*
include whisper/assets/multilingual/*
include whisper/normalizers/english.json include whisper/normalizers/english.json
+1 -1
View File
@@ -3,5 +3,5 @@ numpy
torch torch
tqdm tqdm
more-itertools more-itertools
transformers>=4.19.0 tiktoken==0.3.1
ffmpeg-python==0.2.0 ffmpeg-python==0.2.0
+6 -1
View File
@@ -4,6 +4,7 @@ import pytest
import torch import torch
import whisper import whisper
from whisper.tokenizer import get_tokenizer
@pytest.mark.parametrize("model_name", whisper.available_models()) @pytest.mark.parametrize("model_name", whisper.available_models())
@@ -24,6 +25,11 @@ def test_transcribe(model_name: str):
assert "your country" in transcription assert "your country" in transcription
assert "do for you" in transcription assert "do for you" in transcription
tokenizer = get_tokenizer(model.is_multilingual)
all_tokens = [t for s in result["segments"] for t in s["tokens"]]
assert tokenizer.decode(all_tokens) == result["text"]
assert tokenizer.decode_with_timestamps(all_tokens).startswith("<|0.00|>")
timing_checked = False timing_checked = False
for segment in result["segments"]: for segment in result["segments"]:
for timing in segment["words"]: for timing in segment["words"]:
@@ -31,7 +37,6 @@ def test_transcribe(model_name: str):
if timing["word"].strip(" ,") == "Americans": if timing["word"].strip(" ,") == "Americans":
assert timing["start"] <= 1.8 assert timing["start"] <= 1.8
assert timing["end"] >= 1.8 assert timing["end"] >= 1.8
print(timing)
timing_checked = True timing_checked = True
assert timing_checked assert timing_checked
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1 +0,0 @@
{"bos_token": "<|endoftext|>", "eos_token": "<|endoftext|>", "unk_token": "<|endoftext|>"}
@@ -1 +0,0 @@
{"unk_token": "<|endoftext|>", "bos_token": "<|endoftext|>", "eos_token": "<|endoftext|>", "add_prefix_space": false, "model_max_length": 1024, "special_tokens_map_file": null, "name_or_path": "gpt2", "tokenizer_class": "GPT2Tokenizer"}
-1
View File
@@ -1 +0,0 @@
{"!":0,"\"":1,"#":2,"$":3,"%":4,"&":5,"'":6,"(":7,")":8,"*":9,"+":10,",":11,"-":12,".":13,"/":14,"0":15,"1":16,"2":17,"3":18,"4":19,"5":20,"6":21,"7":22,"8":23,"9":24,":":25,";":26,"<":27,"=":28,">":29,"?":30,"@":31,"A":32,"B":33,"C":34,"D":35,"E":36,"F":37,"G":38,"H":39,"I":40,"J":41,"K":42,"L":43,"M":44,"N":45,"O":46,"P":47,"Q":48,"R":49,"S":50,"T":51,"U":52,"V":53,"W":54,"X":55,"Y":56,"Z":57,"[":58,"\\":59,"]":60,"^":61,"_":62,"`":63,"a":64,"b":65,"c":66,"d":67,"e":68,"f":69,"g":70,"h":71,"i":72,"j":73,"k":74,"l":75,"m":76,"n":77,"o":78,"p":79,"q":80,"r":81,"s":82,"t":83,"u":84,"v":85,"w":86,"x":87,"y":88,"z":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,"IJ":238,"ij":239,"Ĵ":240,"ĵ":241,"Ķ":242,"ķ":243,"ĸ":244,"Ĺ":245,"ĺ":246,"Ļ":247,"ļ":248,"Ľ":249,"ľ":250,"Ŀ":251,"ŀ":252,"Ł":253,"ł":254,"Ń":255,"Ġt":256,"Ġa":257,"he":258,"in":259,"re":260,"on":261,"Ġthe":262,"er":263,"Ġs":264,"at":265,"Ġw":266,"Ġo":267,"en":268,"Ġc":269,"it":270,"is":271,"an":272,"or":273,"es":274,"Ġb":275,"ed":276,"Ġf":277,"ing":278,"Ġp":279,"ou":280,"Ġan":281,"al":282,"ar":283,"Ġto":284,"Ġm":285,"Ġof":286,"Ġin":287,"Ġd":288,"Ġh":289,"Ġand":290,"ic":291,"as":292,"le":293,"Ġth":294,"ion":295,"om":296,"ll":297,"ent":298,"Ġn":299,"Ġl":300,"st":301,"Ġre":302,"ve":303,"Ġe":304,"ro":305,"ly":306,"Ġbe":307,"Ġg":308,"ĠT":309,"ct":310,"ĠS":311,"id":312,"ot":313,"ĠI":314,"ut":315,"et":316,"ĠA":317,"Ġis":318,"Ġon":319,"im":320,"am":321,"ow":322,"ay":323,"ad":324,"se":325,"Ġthat":326,"ĠC":327,"ig":328,"Ġfor":329,"ac":330,"Ġy":331,"ver":332,"ur":333,"Ġu":334,"ld":335,"Ġst":336,"ĠM":337,"'s":338,"Ġhe":339,"Ġit":340,"ation":341,"ith":342,"ir":343,"ce":344,"Ġyou":345,"il":346,"ĠB":347,"Ġwh":348,"ol":349,"ĠP":350,"Ġwith":351,"Ġ1":352,"ter":353,"ch":354,"Ġas":355,"Ġwe":356,"Ġ(":357,"nd":358,"ill":359,"ĠD":360,"if":361,"Ġ2":362,"ag":363,"ers":364,"ke":365,"Ġ\"":366,"ĠH":367,"em":368,"Ġcon":369,"ĠW":370,"ĠR":371,"her":372,"Ġwas":373,"Ġr":374,"od":375,"ĠF":376,"ul":377,"ate":378,"Ġat":379,"ri":380,"pp":381,"ore":382,"ĠThe":383,"Ġse":384,"us":385,"Ġpro":386,"Ġha":387,"um":388,"Ġare":389,"Ġde":390,"ain":391,"and":392,"Ġor":393,"igh":394,"est":395,"ist":396,"ab":397,"rom":398,"ĠN":399,"th":400,"Ġcom":401,"ĠG":402,"un":403,"op":404,"00":405,"ĠL":406,"Ġnot":407,"ess":408,"Ġex":409,"Ġv":410,"res":411,"ĠE":412,"ew":413,"ity":414,"ant":415,"Ġby":416,"el":417,"os":418,"ort":419,"oc":420,"qu":421,"Ġfrom":422,"Ġhave":423,"Ġsu":424,"ive":425,"ould":426,"Ġsh":427,"Ġthis":428,"nt":429,"ra":430,"pe":431,"ight":432,"art":433,"ment":434,"Ġal":435,"ust":436,"end":437,"--":438,"all":439,"ĠO":440,"ack":441,"Ġch":442,"Ġle":443,"ies":444,"red":445,"ard":446,"âĢ":447,"out":448,"ĠJ":449,"Ġab":450,"ear":451,"iv":452,"ally":453,"our":454,"ost":455,"gh":456,"pt":457,"Ġpl":458,"ast":459,"Ġcan":460,"ak":461,"ome":462,"ud":463,"The":464,"Ġhis":465,"Ġdo":466,"Ġgo":467,"Ġhas":468,"ge":469,"'t":470,"ĠU":471,"rou":472,"Ġsa":473,"Ġj":474,"Ġbut":475,"Ġwor":476,"Ġall":477,"ect":478,"Ġk":479,"ame":480,"Ġwill":481,"ok":482,"Ġwhe":483,"Ġthey":484,"ide":485,"01":486,"ff":487,"ich":488,"pl":489,"ther":490,"Ġtr":491,"..":492,"Ġint":493,"ie":494,"ure":495,"age":496,"Ġne":497,"ial":498,"ap":499,"ine":500,"ice":501,"Ġme":502,"Ġout":503,"ans":504,"one":505,"ong":506,"ions":507,"Ġwho":508,"ĠK":509,"Ġup":510,"Ġtheir":511,"Ġad":512,"Ġ3":513,"Ġus":514,"ated":515,"ous":516,"Ġmore":517,"ue":518,"og":519,"ĠSt":520,"ind":521,"ike":522,"Ġso":523,"ime":524,"per":525,".\"":526,"ber":527,"iz":528,"act":529,"Ġone":530,"Ġsaid":531,"Ġ-":532,"are":533,"Ġyour":534,"cc":535,"ĠTh":536,"Ġcl":537,"ep":538,"ake":539,"able":540,"ip"Line truncated
File diff suppressed because it is too large. Load diff
@@ -1 +0,0 @@
{"<|endoftext|>": 50257}
File diff suppressed because it is too large. Load diff
@@ -1 +0,0 @@
{"bos_token": "<|endoftext|>", "eos_token": "<|endoftext|>", "unk_token": "<|endoftext|>"}
@@ -1 +0,0 @@
{"unk_token": {"content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "bos_token": {"content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "eos_token": {"content": "<|endoftext|>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true, "__type": "AddedToken"}, "add_prefix_space": false, "model_max_length": 1024, "special_tokens_map_file": null, "name_or_path": "multilingual", "errors": "replace", "tokenizer_class": "GPT2Tokenizer"}
-1
View File
@@ -1 +0,0 @@
{"!": 0, "\"": 1, "#": 2, "$": 3, "%": 4, "&": 5, "'": 6, "(": 7, ")": 8, "*": 9, "+": 10, ",": 11, "-": 12, ".": 13, "/": 14, "0": 15, "1": 16, "2": 17, "3": 18, "4": 19, "5": 20, "6": 21, "7": 22, "8": 23, "9": 24, ":": 25, ";": 26, "<": 27, "=": 28, ">": 29, "?": 30, "@": 31, "A": 32, "B": 33, "C": 34, "D": 35, "E": 36, "F": 37, "G": 38, "H": 39, "I": 40, "J": 41, "K": 42, "L": 43, "M": 44, "N": 45, "O": 46, "P": 47, "Q": 48, "R": 49, "S": 50, "T": 51, "U": 52, "V": 53, "W": 54, "X": 55, "Y": 56, "Z": 57, "[": 58, "\\": 59, "]": 60, "^": 61, "_": 62, "`": 63, "a": 64, "b": 65, "c": 66, "d": 67, "e": 68, "f": 69, "g": 70, "h": 71, "i": 72, "j": 73, "k": 74, "l": 75, "m": 76, "n": 77, "o": 78, "p": 79, "q": 80, "r": 81, "s": 82, "t": 83, "u": 84, "v": 85, "w": 86, "x": 87, "y": 88, "z": 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, "IJ": 238, "ij": 239, "Ĵ": 240, "ĵ": 241, "Ķ": 242, "ķ": 243, "ĸ": 244, "Ĺ": 245, "ĺ": 246, "Ļ": 247, "ļ": 248, "Ľ": 249, "ľ": 250, "Ŀ": 251, "ŀ": 252, "Ł": 253, "ł": 254, "Ń": 255, "Ġt": 256, "Ġa": 257, "Ġth": 258, "in": 259, "er": 260, "Ġw": 261, "Ġs": 262, "ou": 263, "Ġthe": 264, "re": 265, "on": 266, "at": 267, "en": 268, "Ġc": 269, "it": 270, "is": 271, "Ġb": 272, "nd": 273, "Ġd": 274, "Ġm": 275, "Ġh": 276, "Ġo": 277, "ing": 278, "es": 279, "Ġp": 280, "Ġto": 281, "an": 282, "Ġf": 283, "or": 284, "ll": 285, "ĠI": 286, "Ġl": 287, "Ġy": 288, "ar": 289, "Ġg": 290, "Ġyou": 291, "ed": 292, "Ġand": 293, "Ġin": 294, "Ġof": 295, "as": 296, "Ġn": 297, "om": 298, "ic": 299, "Ġthat": 300, "us": 301, "et": 302, "ve": 303, "al": 304, "ow": 305, "le": 306, "Ġis": 307, "Ġe": 308, "Ġit": 309, "ot": 310, "'s": 311, "Ġbe": 312, "ion": 313, "ĠT": 314, "Ġwh": 315, "ĠA": 316, "ent": 317, "ĠS": 318, "Ġre": 319, "ay": 320, "Ġwe": 321, "Ġon": 322, "ere": 323, "Ġha": 324, "ut": 325, "ac": 326, "id": 327, "ig": 328, "os": 329, "ke": 330, "ver": 331, "im": 332, "ĠÐ": 333, "ĠTh": 334, "am": 335, "all": 336, "Ġfor": 337, "el": 338, "ch": 339, "ro": 340, "Ġthis": 341, "Ġst": 342, "ĠW": 343, "Ġu": 344, "ad": 345, "out": 346, "ir": 347, "ld": 348, "ct": 349, "Ġk": 350, "if": 351, "Ġgo": 352, "..": 353, "о": 354, "ith": 355, "ly": 356, "ht": 357, "qu": 358, "Ġ-": 359, "Ġdo": 360, "Ġj": 361, "Ġhave": 362, "ĠB": 363, "Ġan": 364, "Ġwith": 365, "Ġare": 366, "Ġr": 367, "Ġde": 368, "Ġse": 369, "Ġso": 370, "Ġv": 371, "st": 372, "ill": 373, "ur": 374, "Ġli": 375, "ĠM": 376, "est": 377, "od": 378, "ally": 379, "'t": 380, "ust": 381, "Ġas": 382, "ĠC": 383, "ce": 384, "Ġme": 385, "а": 386, "е": 387, "il": 388, "ĠH": 389, "Ġwas": 390, "ter": 391, "th": 392, "Ġcan": 393, "ant": 394, "Ġcom": 395, "our": 396, "ight": 397, "ĠY": 398, "ation": 399, "ĠAnd": 400, "ol": 401, "Ġsh": 402, "ÑĤ": 403, "op": 404, "se": 405, "Ġnot": 406, "ĠSo": 407, "Ġne": 408, "un": 409, "Ġab": 410, "Ġlike": 411, "Ġat": 412, "ĠD": 413, "ie": 414, "Ġhe": 415, "Ġcon": 416, "Ġch": 417, "ore": 418, "Ġal": 419, "Ġor": 420, "Ġqu": 421, "ĠO": 422, "ome": 423, "ra": 424, "ul": 425, "ĠN": 426, "pp": 427, "Ġyour": 428, "ould": 429, "ĠP": 430, "Ġfr": 431, "ge": 432, "ers": 433, "'re": 434, "и": 435, "Ġthey": 436, "Ġwhat": 437, "use": 438, "Ġall": 439, "ĠThe": 440, "ĠL": 441, "ess": 442, "em": 443, "Ġkn": 444, "Ġjust": 445, "art": 446, "Ġpro": 447, "very": 448, "um": 449, "Ġlo": 450, "Ġì":Line truncated
+81 -84
View File
@@ -1,12 +1,12 @@
import base64
import os import os
import string import string
from dataclasses import dataclass from dataclasses import dataclass, field
from functools import cached_property, lru_cache from functools import cached_property, lru_cache
from typing import List, Optional, Tuple, Union from typing import Dict, List, Optional, Tuple
import numpy as np import tiktoken
import torch from tiktoken_ext.openai_public import gpt2
from transformers import GPT2TokenizerFast
LANGUAGES = { LANGUAGES = {
"en": "english", "en": "english",
@@ -127,74 +127,84 @@ TO_LANGUAGE_CODE = {
} }
@dataclass(frozen=True) @dataclass
class Tokenizer: class Tokenizer:
"""A thin wrapper around `GPT2TokenizerFast` providing quick access to special tokens""" """A thin wrapper around `tiktoken` providing quick access to special tokens"""
tokenizer: "GPT2TokenizerFast" encoding: tiktoken.Encoding
language: Optional[str] language: Optional[str] = None
sot_sequence: Tuple[int] task: Optional[str] = None
sot_sequence: Tuple[int] = ()
special_tokens: Dict[str, int] = field(default_factory=dict)
def __post_init__(self):
for special in self.encoding.special_tokens_set:
special_token = self.encoding.encode_single_token(special)
self.special_tokens[special] = special_token
sot: int = self.special_tokens["<|startoftranscript|>"]
translate: int = self.special_tokens["<|translate|>"]
transcribe: int = self.special_tokens["<|transcribe|>"]
langs = tuple(LANGUAGES.keys())
sot_sequence = [sot]
if self.language is not None:
sot_sequence.append(sot + 1 + langs.index(self.language))
if self.task is not None:
task_token: int = transcribe if self.task == "transcribe" else translate
sot_sequence.append(task_token)
self.sot_sequence = tuple(sot_sequence)
def encode(self, text, **kwargs): def encode(self, text, **kwargs):
return self.tokenizer.encode(text, **kwargs) return self.encoding.encode(text, **kwargs)
def decode( def decode(self, token_ids: List[int], **kwargs) -> str:
self, token_ids: Union[int, List[int], np.ndarray, torch.Tensor], **kwargs token_ids = [t for t in token_ids if t < self.timestamp_begin]
): return self.encoding.decode(token_ids, **kwargs)
return self.tokenizer.decode(token_ids, **kwargs)
def decode_with_timestamps(self, tokens) -> str: def decode_with_timestamps(self, token_ids: List[int], **kwargs) -> str:
""" """
Timestamp tokens are above the special tokens' id range and are ignored by `decode()`. Timestamp tokens are above other special tokens' id range and are ignored by `decode()`.
This method decodes given tokens with timestamps tokens annotated, e.g. "<|1.08|>". This method decodes given tokens with timestamps tokens annotated, e.g. "<|1.08|>".
""" """
outputs = [[]] return self.encoding.decode(token_ids, **kwargs)
for token in tokens:
if token >= self.timestamp_begin:
timestamp = f"<|{(token - self.timestamp_begin) * 0.02:.2f}|>"
outputs.append(timestamp)
outputs.append([])
else:
outputs[-1].append(token)
return "".join(
[s if isinstance(s, str) else self.tokenizer.decode(s) for s in outputs]
)
@cached_property @cached_property
def eot(self) -> int: def eot(self) -> int:
return self.tokenizer.eos_token_id return self.encoding.eot_token
@cached_property @cached_property
def transcribe(self) -> int: def transcribe(self) -> int:
return self._get_single_token_id("<|transcribe|>") return self.special_tokens["<|transcribe|>"]
@cached_property @cached_property
def translate(self) -> int: def translate(self) -> int:
return self._get_single_token_id("<|translate|>") return self.special_tokens["<|translate|>"]
@cached_property @cached_property
def sot(self) -> int: def sot(self) -> int:
return self._get_single_token_id("<|startoftranscript|>") return self.special_tokens["<|startoftranscript|>"]
@cached_property @cached_property
def sot_lm(self) -> int: def sot_lm(self) -> int:
return self._get_single_token_id("<|startoflm|>") return self.special_tokens["<|startoflm|>"]
@cached_property @cached_property
def sot_prev(self) -> int: def sot_prev(self) -> int:
return self._get_single_token_id("<|startofprev|>") return self.special_tokens["<|startofprev|>"]
@cached_property @cached_property
def no_speech(self) -> int: def no_speech(self) -> int:
return self._get_single_token_id("<|nospeech|>") return self.special_tokens["<|nospeech|>"]
@cached_property @cached_property
def no_timestamps(self) -> int: def no_timestamps(self) -> int:
return self._get_single_token_id("<|notimestamps|>") return self.special_tokens["<|notimestamps|>"]
@cached_property @cached_property
def timestamp_begin(self) -> int: def timestamp_begin(self) -> int:
return self.tokenizer.all_special_ids[-1] + 1 return self.special_tokens["<|0.00|>"]
@cached_property @cached_property
def language_token(self) -> int: def language_token(self) -> int:
@@ -202,25 +212,15 @@ class Tokenizer:
if self.language is None: if self.language is None:
raise ValueError("This tokenizer does not have language token configured") raise ValueError("This tokenizer does not have language token configured")
additional_tokens = dict( if token := self.special_tokens.get(f"<|{self.language}|>", None):
zip( return token
self.tokenizer.additional_special_tokens,
self.tokenizer.additional_special_tokens_ids,
)
)
candidate = f"<|{self.language}|>"
if candidate in additional_tokens:
return additional_tokens[candidate]
raise KeyError(f"Language {self.language} not found in tokenizer.") raise KeyError(f"Language {self.language} not found in tokenizer.")
@cached_property @cached_property
def all_language_tokens(self) -> Tuple[int]: def all_language_tokens(self) -> Tuple[int]:
result = [] result = []
for token, token_id in zip( for token, token_id in self.special_tokens.items():
self.tokenizer.additional_special_tokens,
self.tokenizer.additional_special_tokens_ids,
):
if token.strip("<|>") in LANGUAGES: if token.strip("<|>") in LANGUAGES:
result.append(token_id) result.append(token_id)
return tuple(result) return tuple(result)
@@ -258,22 +258,17 @@ class Tokenizer:
assert all(0x2640 <= ord(c) <= 0x267F for c in miscellaneous) assert all(0x2640 <= ord(c) <= 0x267F for c in miscellaneous)
# allow hyphens "-" and single quotes "'" between words, but not at the beginning of a word # allow hyphens "-" and single quotes "'" between words, but not at the beginning of a word
result = {self.tokenizer.encode(" -")[0], self.tokenizer.encode(" '")[0]} result = {self.encoding.encode(" -")[0], self.encoding.encode(" '")[0]}
for symbol in symbols + list(miscellaneous): for symbol in symbols + list(miscellaneous):
for tokens in [ for tokens in [
self.tokenizer.encode(symbol), self.encoding.encode(symbol),
self.tokenizer.encode(" " + symbol), self.encoding.encode(" " + symbol),
]: ]:
if len(tokens) == 1 or symbol in miscellaneous: if len(tokens) == 1 or symbol in miscellaneous:
result.add(tokens[0]) result.add(tokens[0])
return tuple(sorted(result)) return tuple(sorted(result))
def _get_single_token_id(self, text) -> int:
tokens = self.tokenizer.encode(text)
assert len(tokens) == 1, f"{text} is not encoded as a single token"
return tokens[0]
def split_to_word_tokens(self, tokens: List[int]): def split_to_word_tokens(self, tokens: List[int]):
if self.language in {"zh", "ja", "th", "lo", "my"}: if self.language in {"zh", "ja", "th", "lo", "my"}:
# These languages don't typically use spaces, so it is difficult to split words # These languages don't typically use spaces, so it is difficult to split words
@@ -318,12 +313,17 @@ class Tokenizer:
@lru_cache(maxsize=None) @lru_cache(maxsize=None)
def build_tokenizer(name: str = "gpt2"): def get_encoding(name: str = "gpt2"):
os.environ["TOKENIZERS_PARALLELISM"] = "false" vocab_path = os.path.join(os.path.dirname(__file__), "assets", f"{name}.tiktoken")
path = os.path.join(os.path.dirname(__file__), "assets", name) ranks = {
tokenizer = GPT2TokenizerFast.from_pretrained(path) base64.b64decode(token): int(rank)
for token, rank in (line.split() for line in open(vocab_path) if line)
}
n_vocab = len(ranks)
special_tokens = {}
specials = [ specials = [
"<|endoftext|>",
"<|startoftranscript|>", "<|startoftranscript|>",
*[f"<|{lang}|>" for lang in LANGUAGES.keys()], *[f"<|{lang}|>" for lang in LANGUAGES.keys()],
"<|translate|>", "<|translate|>",
@@ -332,18 +332,28 @@ def build_tokenizer(name: str = "gpt2"):
"<|startofprev|>", "<|startofprev|>",
"<|nospeech|>", "<|nospeech|>",
"<|notimestamps|>", "<|notimestamps|>",
*[f"<|{i * 0.02:.2f}|>" for i in range(1501)],
] ]
tokenizer.add_special_tokens(dict(additional_special_tokens=specials)) for token in specials:
return tokenizer special_tokens[token] = n_vocab
n_vocab += 1
return tiktoken.Encoding(
name=os.path.basename(vocab_path),
explicit_n_vocab=n_vocab,
pat_str=gpt2()["pat_str"],
mergeable_ranks=ranks,
special_tokens=special_tokens,
)
@lru_cache(maxsize=None) @lru_cache(maxsize=None)
def get_tokenizer( def get_tokenizer(
multilingual: bool, multilingual: bool,
*, *,
task: Optional[str] = None, # Literal["transcribe", "translate", None]
language: Optional[str] = None, language: Optional[str] = None,
task: Optional[str] = None, # Literal["transcribe", "translate", None]
) -> Tokenizer: ) -> Tokenizer:
if language is not None: if language is not None:
language = language.lower() language = language.lower()
@@ -354,27 +364,14 @@ def get_tokenizer(
raise ValueError(f"Unsupported language: {language}") raise ValueError(f"Unsupported language: {language}")
if multilingual: if multilingual:
tokenizer_name = "multilingual" encoding_name = "multilingual"
task = task or "transcribe"
language = language or "en" language = language or "en"
task = task or "transcribe"
else: else:
tokenizer_name = "gpt2" encoding_name = "gpt2"
task = None
language = None language = None
task = None
tokenizer = build_tokenizer(name=tokenizer_name) encoding = get_encoding(name=encoding_name)
all_special_ids: List[int] = tokenizer.all_special_ids
sot: int = all_special_ids[1]
translate: int = all_special_ids[-6]
transcribe: int = all_special_ids[-5]
langs = tuple(LANGUAGES.keys()) return Tokenizer(encoding=encoding, language=language, task=task)
sot_sequence = [sot]
if language is not None:
sot_sequence.append(sot + 1 + langs.index(language))
if task is not None:
sot_sequence.append(transcribe if task == "transcribe" else translate)
return Tokenizer(
tokenizer=tokenizer, language=language, sot_sequence=tuple(sot_sequence)
)