├── .gitignore ├── .pre-commit-config.yaml ├── .pylintrc ├── LICENSE ├── README.md ├── figures ├── parallel_tokenizer.gif └── tokenizer_speed.png ├── parallel_tokenizer ├── __init__.py ├── logger.py ├── parallel_tokenizer.py ├── sp_tokenizer.py ├── special_cases.py └── utils.py ├── setup.py ├── tests ├── __init__.py ├── test_interface.py ├── test_parallel_tokenizer.py └── utils.py └── version.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | .idea/ 161 | .vscode/ 162 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/psf/black 5 | rev: '22.8.0' 6 | hooks: 7 | - id: black 8 | args: 9 | - --line-length=120 10 | - repo: https://github.com/pycqa/isort 11 | rev: '5.12.0' 12 | hooks: 13 | - id: isort 14 | name: isort 15 | files: "\\.(py)$" 16 | args: 17 | - --profile=black 18 | - repo: https://github.com/PyCQA/flake8 19 | rev: '3.8.4' 20 | hooks: 21 | - id: flake8 22 | args: 23 | - --ignore=F403,F405,W504,W503,E203 24 | - --max-line-length=120 25 | - repo: https://github.com/pre-commit/pygrep-hooks 26 | rev: v1.9.0 27 | hooks: 28 | - id: python-check-blanket-noqa 29 | - repo: https://github.com/pre-commit/pre-commit-hooks 30 | rev: v4.3.0 31 | hooks: 32 | - id: trailing-whitespace 33 | - id: end-of-file-fixer 34 | - id: check-added-large-files 35 | args: ['--maxkb=2000',--enforce-all] 36 | - id: check-json 37 | - id: check-docstring-first 38 | - id: check-yaml 39 | - id: debug-statements 40 | - id: mixed-line-ending 41 | - repo: https://github.com/PyCQA/pylint/ 42 | rev: v2.17.2 43 | hooks: 44 | - id: pylint 45 | name: pylint 46 | entry: pylint 47 | language: system 48 | types: [python] 49 | args: 50 | [ 51 | '--rcfile=.pylintrc', 52 | '--disable=C0114,C0415,W0212,W0235,W0238,W0621,C0103,R1735,C2801,E0402,C0412,W0719,R1728,W1514,W0718,W0105,W0707,C0209,W0703,W1203' 53 | ] 54 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | # This Pylint rcfile contains a best-effort configuration to uphold the 2 | # best-practices and style described in the Google Python style guide: 3 | # https://google.github.io/styleguide/pyguide.html 4 | # 5 | # Its canonical open-source location is: 6 | # https://google.github.io/styleguide/pylintrc 7 | 8 | [MASTER] 9 | 10 | # Files or directories to be skipped. They should be base names, not paths. 11 | ignore=third_party,storage 12 | 13 | # Files or directories matching the regex patterns are skipped. The regex 14 | # matches against base names, not paths. 15 | ignore-patterns= 16 | 17 | # Pickle collected data for later comparisons. 18 | persistent=no 19 | 20 | # List of plugins (as comma separated values of python modules names) to load, 21 | # usually to register additional checkers. 22 | load-plugins= 23 | 24 | # Use multiple processes to speed up Pylint. 25 | jobs=4 26 | 27 | # Allow loading of arbitrary C extensions. Extensions are imported into the 28 | # active Python interpreter and may run arbitrary code. 29 | unsafe-load-any-extension=no 30 | 31 | 32 | [MESSAGES CONTROL] 33 | 34 | # Only show warnings with the listed confidence levels. Leave empty to show 35 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED 36 | confidence= 37 | 38 | # Enable the message, report, category or checker with the given id(s). You can 39 | # either give multiple identifier separated by comma (,) or put this option 40 | # multiple time (only on the command line, not in the configuration file where 41 | # it should appear only once). See also the "--disable" option for examples. 42 | #enable= 43 | 44 | # Disable the message, report, category or checker with the given id(s). You 45 | # can either give multiple identifiers separated by comma (,) or put this 46 | # option multiple times (only on the command line, not in the configuration 47 | # file where it should appear only once).You can also use "--disable=all" to 48 | # disable everything first and then reenable specific checks. For example, if 49 | # you want to run only the similarities checker, you can use "--disable=all 50 | # --enable=similarities". If you want to run only the classes checker, but have 51 | # no Warning level messages displayed, use"--disable=all --enable=classes 52 | # --disable=W" 53 | disable=abstract-method, 54 | apply-builtin, 55 | arguments-differ, 56 | attribute-defined-outside-init, 57 | backtick, 58 | bad-option-value, 59 | basestring-builtin, 60 | buffer-builtin, 61 | c-extension-no-member, 62 | consider-using-enumerate, 63 | cmp-builtin, 64 | cmp-method, 65 | coerce-builtin, 66 | coerce-method, 67 | delslice-method, 68 | div-method, 69 | duplicate-code, 70 | eq-without-hash, 71 | execfile-builtin, 72 | file-builtin, 73 | filter-builtin-not-iterating, 74 | fixme, 75 | getslice-method, 76 | global-statement, 77 | hex-method, 78 | idiv-method, 79 | implicit-str-concat, 80 | import-error, 81 | import-self, 82 | import-star-module-level, 83 | inconsistent-return-statements, 84 | input-builtin, 85 | intern-builtin, 86 | invalid-str-codec, 87 | locally-disabled, 88 | long-builtin, 89 | long-suffix, 90 | map-builtin-not-iterating, 91 | misplaced-comparison-constant, 92 | missing-function-docstring, 93 | metaclass-assignment, 94 | next-method-called, 95 | next-method-defined, 96 | no-absolute-import, 97 | no-else-break, 98 | no-else-continue, 99 | no-else-raise, 100 | no-else-return, 101 | no-init, # added 102 | no-member, 103 | no-name-in-module, 104 | no-self-use, 105 | nonzero-method, 106 | oct-method, 107 | old-division, 108 | old-ne-operator, 109 | old-octal-literal, 110 | old-raise-syntax, 111 | parameter-unpacking, 112 | print-statement, 113 | raising-string, 114 | range-builtin-not-iterating, 115 | raw_input-builtin, 116 | rdiv-method, 117 | reduce-builtin, 118 | relative-import, 119 | reload-builtin, 120 | round-builtin, 121 | setslice-method, 122 | signature-differs, 123 | standarderror-builtin, 124 | suppressed-message, 125 | sys-max-int, 126 | too-few-public-methods, 127 | too-many-ancestors, 128 | too-many-arguments, 129 | too-many-boolean-expressions, 130 | too-many-branches, 131 | too-many-instance-attributes, 132 | too-many-locals, 133 | too-many-nested-blocks, 134 | too-many-public-methods, 135 | too-many-return-statements, 136 | too-many-statements, 137 | trailing-newlines, 138 | unichr-builtin, 139 | unicode-builtin, 140 | unnecessary-pass, 141 | unpacking-in-except, 142 | useless-else-on-loop, 143 | useless-object-inheritance, 144 | useless-suppression, 145 | using-cmp-argument, 146 | wrong-import-order, 147 | xrange-builtin, 148 | zip-builtin-not-iterating, 149 | 150 | 151 | [REPORTS] 152 | 153 | # Set the output format. Available formats are text, parseable, colorized, msvs 154 | # (visual studio) and html. You can also give a reporter class, eg 155 | # mypackage.mymodule.MyReporterClass. 156 | output-format=colorized 157 | 158 | # Tells whether to display a full report or only the messages 159 | reports=no 160 | 161 | # Python expression which should return a note less than 10 (10 is the highest 162 | # note). You have access to the variables errors warning, statement which 163 | # respectively contain the number of errors / warnings messages and the total 164 | # number of statements analyzed. This is used by the global evaluation report 165 | # (RP0004). 166 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 167 | 168 | # Template used to display messages. This is a python new-style format string 169 | # used to format the message information. See doc for all details 170 | #msg-template= 171 | 172 | 173 | [BASIC] 174 | 175 | # Good variable names which should always be accepted, separated by a comma 176 | good-names=main,_ 177 | 178 | # Bad variable names which should always be refused, separated by a comma 179 | bad-names= 180 | 181 | # Colon-delimited sets of names that determine each other's naming style when 182 | # the name regexes allow several styles. 183 | name-group= 184 | 185 | # Include a hint for the correct naming format with invalid-name 186 | include-naming-hint=no 187 | 188 | # List of decorators that produce properties, such as abc.abstractproperty. Add 189 | # to this list to register other decorators that produce valid properties. 190 | property-classes=abc.abstractproperty,cached_property.cached_property,cached_property.threaded_cached_property,cached_property.cached_property_with_ttl,cached_property.threaded_cached_property_with_ttl 191 | 192 | # Regular expression matching correct function names 193 | function-rgx=^(?:(?PsetUp|tearDown|setUpModule|tearDownModule)|(?P_?[A-Z][a-zA-Z0-9]*)|(?P_?[a-z][a-z0-9_]*))$ 194 | 195 | # Regular expression matching correct variable names 196 | variable-rgx=^[a-z][a-z0-9_]*$ 197 | 198 | # Regular expression matching correct constant names 199 | const-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ 200 | 201 | # Regular expression matching correct attribute names 202 | attr-rgx=^_{0,2}[a-z][a-z0-9_]*$ 203 | 204 | # Regular expression matching correct argument names 205 | argument-rgx=^[a-z][a-z0-9_]*$ 206 | 207 | # Regular expression matching correct class attribute names 208 | class-attribute-rgx=^(_?[A-Z][A-Z0-9_]*|__[a-z0-9_]+__|_?[a-z][a-z0-9_]*)$ 209 | 210 | # Regular expression matching correct inline iteration names 211 | inlinevar-rgx=^[a-z][a-z0-9_]*$ 212 | 213 | # Regular expression matching correct class names 214 | class-rgx=^_?[A-Z][a-zA-Z0-9]*$ 215 | 216 | # Regular expression matching correct module names 217 | module-rgx=^(_?[a-z][a-z0-9_]*|__init__)$ 218 | 219 | # Regular expression matching correct method names 220 | method-rgx=(?x)^(?:(?P_[a-z0-9_]+__|runTest|setUp|tearDown|setUpTestCase|tearDownTestCase|setupSelf|tearDownClass|setUpClass|(test|assert)_*[A-Z0-9][a-zA-Z0-9_]*|next)|(?P_{0,2}[A-Z][a-zA-Z0-9_]*)|(?P_{0,2}[a-z][a-z0-9_]*))$ 221 | 222 | # Regular expression which should only match function or class names that do 223 | # not require a docstring. 224 | no-docstring-rgx=(__.*__|main|test.*|.*test|.*Test)$ 225 | 226 | # Minimum line length for functions/classes that require docstrings, shorter 227 | # ones are exempt. 228 | docstring-min-length=10 229 | 230 | 231 | [TYPECHECK] 232 | 233 | # List of decorators that produce context managers, such as 234 | # contextlib.contextmanager. Add to this list to register other decorators that 235 | # produce valid context managers. 236 | contextmanager-decorators=contextlib.contextmanager,contextlib2.contextmanager 237 | 238 | # Tells whether missing members accessed in mixin class should be ignored. A 239 | # mixin class is detected if its name ends with "mixin" (case insensitive). 240 | ignore-mixin-members=yes 241 | 242 | # List of module names for which member attributes should not be checked 243 | # (useful for modules/projects where namespaces are manipulated during runtime 244 | # and thus existing member attributes cannot be deduced by static analysis. It 245 | # supports qualified module names, as well as Unix pattern matching. 246 | ignored-modules= 247 | 248 | # List of class names for which member attributes should not be checked (useful 249 | # for classes with dynamically set attributes). This supports the use of 250 | # qualified names. 251 | ignored-classes=optparse.Values,thread._local,_thread._local 252 | 253 | # List of members which are set dynamically and missed by pylint inference 254 | # system, and so shouldn't trigger E1101 when accessed. Python regular 255 | # expressions are accepted. 256 | generated-members= 257 | 258 | 259 | [FORMAT] 260 | 261 | # Maximum number of characters on a single line. 262 | max-line-length=120 263 | 264 | # TODO(https://github.com/PyCQA/pylint/issues/3352): Direct pylint to exempt 265 | # lines made too long by directives to pytype. 266 | 267 | # Regexp for a line that is allowed to be longer than the limit. 268 | ignore-long-lines=(?x)( 269 | ^\s*(\#\ )??$| 270 | ^\s*(from\s+\S+\s+)?import\s+.+$) 271 | 272 | # Allow the body of an if to be on the same line as the test if there is no 273 | # else. 274 | single-line-if-stmt=yes 275 | 276 | # Maximum number of lines in a module 277 | max-module-lines=99999 278 | 279 | # String used as indentation unit. The internal Google style guide mandates 2 280 | # spaces. Google's externaly-published style guide says 4, consistent with 281 | # PEP 8. Here, we use 2 spaces, for conformity with many open-sourced Google 282 | # projects (like TensorFlow). 283 | indent-string=' ' 284 | 285 | # Number of spaces of indent required inside a hanging or continued line. 286 | indent-after-paren=4 287 | 288 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 289 | expected-line-ending-format= 290 | 291 | 292 | [MISCELLANEOUS] 293 | 294 | # List of note tags to take in consideration, separated by a comma. 295 | notes=TODO 296 | 297 | 298 | [STRING] 299 | 300 | # This flag controls whether inconsistent-quotes generates a warning when the 301 | # character used as a quote delimiter is used inconsistently within a module. 302 | check-quote-consistency=yes 303 | 304 | 305 | [VARIABLES] 306 | 307 | # Tells whether we should check for unused import in __init__ files. 308 | init-import=no 309 | 310 | # A regular expression matching the name of dummy variables (i.e. expectedly 311 | # not used). 312 | dummy-variables-rgx=^\*{0,2}(_$|unused_|dummy_) 313 | 314 | # List of additional names supposed to be defined in builtins. Remember that 315 | # you should avoid to define new builtins when possible. 316 | additional-builtins= 317 | 318 | # List of strings which can identify a callback function by name. A callback 319 | # name must start or end with one of those strings. 320 | callbacks=cb_,_cb 321 | 322 | # List of qualified module names which can have objects that can redefine 323 | # builtins. 324 | redefining-builtins-modules=six,six.moves,past.builtins,future.builtins,functools 325 | 326 | 327 | [LOGGING] 328 | 329 | # Logging modules to check that the string format arguments are in logging 330 | # function parameter format 331 | logging-modules=logging,absl.logging,tensorflow.io.logging 332 | 333 | 334 | [SIMILARITIES] 335 | 336 | # Minimum lines number of a similarity. 337 | min-similarity-lines=4 338 | 339 | # Ignore comments when computing similarities. 340 | ignore-comments=yes 341 | 342 | # Ignore docstrings when computing similarities. 343 | ignore-docstrings=yes 344 | 345 | # Ignore imports when computing similarities. 346 | ignore-imports=no 347 | 348 | 349 | [SPELLING] 350 | 351 | # Spelling dictionary name. Available dictionaries: none. To make it working 352 | # install python-enchant package. 353 | spelling-dict= 354 | 355 | # List of comma separated words that should not be checked. 356 | spelling-ignore-words= 357 | 358 | # A path to a file that contains private dictionary; one word per line. 359 | spelling-private-dict-file= 360 | 361 | # Tells whether to store unknown words to indicated private dictionary in 362 | # --spelling-private-dict-file option instead of raising a message. 363 | spelling-store-unknown-words=no 364 | 365 | 366 | [IMPORTS] 367 | 368 | # Deprecated modules which should not be used, separated by a comma 369 | deprecated-modules=regsub, 370 | TERMIOS, 371 | Bastion, 372 | rexec, 373 | sets 374 | 375 | # Create a graph of every (i.e. internal and external) dependencies in the 376 | # given file (report RP0402 must not be disabled) 377 | import-graph= 378 | 379 | # Create a graph of external dependencies in the given file (report RP0402 must 380 | # not be disabled) 381 | ext-import-graph= 382 | 383 | # Create a graph of internal dependencies in the given file (report RP0402 must 384 | # not be disabled) 385 | int-import-graph= 386 | 387 | # Force import order to recognize a module as part of the standard 388 | # compatibility libraries. 389 | known-standard-library= 390 | 391 | # Force import order to recognize a module as part of a third party library. 392 | known-third-party=enchant, absl 393 | 394 | # Analyse import fallback blocks. This can be used to support both Python 2 and 395 | # 3 compatible code, which means that the block might have code that exists 396 | # only in one or another interpreter, leading to false positives when analysed. 397 | analyse-fallback-blocks=no 398 | 399 | 400 | [CLASSES] 401 | 402 | # List of method names used to declare (i.e. assign) instance attributes. 403 | defining-attr-methods=__init__, 404 | __new__, 405 | setUp 406 | 407 | # List of member names, which should be excluded from the protected access 408 | # warning. 409 | exclude-protected=_asdict, 410 | _fields, 411 | _replace, 412 | _source, 413 | _make 414 | 415 | # List of valid names for the first argument in a class method. 416 | valid-classmethod-first-arg=cls, 417 | class_ 418 | 419 | # List of valid names for the first argument in a metaclass class method. 420 | valid-metaclass-classmethod-first-arg=mcs 421 | 422 | 423 | [EXCEPTIONS] 424 | 425 | # Exceptions that will emit a warning when being caught. Defaults to 426 | # "Exception" 427 | overgeneral-exceptions=builtins.BaseException, 428 | builtins.Exception 429 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ParallelTokenizer 2 | 3 | ### Latest News 🔥 4 | 5 | - 2024/03/21: Added compatibility with ChatGLM3 6 | 7 | 8 | ## Introduction 9 | 10 | ParallelTokenizer is an open-sourced efficient tokenization framework which aims to support the efficient tokenization of a context with thousands of or millions of tokens. The working principle of parallel tokenizer can be summarized as follows. 11 | 12 | 1. **Split**. ParallelTokenizer first splits the input text based on a pre-defined chunk_size. Different from regular chunking, in order to avoid the token at the cutting point being destroyed, a piece of overlap needs to be reserved for the two slices before and after. The size of this overlap should be no less than the longest token in the vocabulary measured in char. By default, ```chunk_size=40960``` and ```overlap=512```. 13 | 14 | 2. **Tokenize**. After the input text being split, ParallelTokenizer conducts tokenization of different segment in parallel and arquires the token lists of different segments. 15 | 16 | 3. **Merge**. ParallelTokenizer finally merge the token lists of different segments with the overlap being evicted to obtain the token list of the entire input. Importantly, the overlap part can be located with LCS algorithm. ParallelTokenizer concatenate the token list before the overlap part in the previous chunk, the token in the overlap, and the token list after the overlap part in the next chunk, thus obtaining the result of tokenizing the entire input content. 17 | 18 | 19 | 20 | Use ParallelTokenizer can help you achieve superior acceleration, compared with the common tokenization when you processing the tokenization of extremely long context. 21 | 22 | 23 | -------------------------------------------------------------------------------- /figures/parallel_tokenizer.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenLMLab/ParallelTokenizer/c1ba82bf6d028151dcaed49c193c141908da9715/figures/parallel_tokenizer.gif -------------------------------------------------------------------------------- /figures/tokenizer_speed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenLMLab/ParallelTokenizer/c1ba82bf6d028151dcaed49c193c141908da9715/figures/tokenizer_speed.png -------------------------------------------------------------------------------- /parallel_tokenizer/__init__.py: -------------------------------------------------------------------------------- 1 | from .logger import get_logger 2 | from .parallel_tokenizer import ParallelTokenizer, get_parallel_tokenizer 3 | from .sp_tokenizer import SentencePieceTokenizer 4 | from .special_cases import SPECIAL_KEYS_DICT, SPECIAL_TOKENIZERS_DICT 5 | 6 | __all__ = [ 7 | "get_parallel_tokenizer", 8 | "SentencePieceTokenizer", 9 | "ParallelTokenizer", 10 | "get_logger", 11 | "SPECIAL_KEYS_DICT", 12 | "SPECIAL_TOKENIZERS_DICT", 13 | ] 14 | -------------------------------------------------------------------------------- /parallel_tokenizer/logger.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- encoding: utf-8 -*- 3 | 4 | import logging 5 | 6 | LOGGER_NAME = "parallel_tokenizer" 7 | LOGGER_FORMAT = "%(asctime)s\t%(levelname)s %(filename)s:%(lineno)s in %(funcName)s -- %(message)s" 8 | LOGGER_LEVEL = "info" 9 | LOGGER_LEVEL_CHOICES = ["debug", "info", "warning", "error", "critical"] 10 | LOGGER_LEVEL_HELP = ( 11 | "The logging level threshold, choices=['debug', 'info', 'warning', 'error', 'critical'], default='info'" 12 | ) 13 | 14 | 15 | def get_logger(logger_name: str = LOGGER_NAME, logging_level: str = LOGGER_LEVEL) -> logging.Logger: 16 | """Configure the logger that is used for uniscale framework. 17 | 18 | Args: 19 | logger_name (str): used to create or get the correspoding logger in 20 | getLogger call. It will be "internlm" by default. 21 | logging_level (str, optional): Logging level in string or logging enum. 22 | 23 | Returns: 24 | logger (logging.Logger): the created or modified logger. 25 | 26 | """ 27 | 28 | logger = logging.getLogger(logger_name) 29 | 30 | if logging_level not in LOGGER_LEVEL_CHOICES: 31 | logging_level = LOGGER_LEVEL 32 | print(LOGGER_LEVEL_HELP) 33 | 34 | logging_level = logging.getLevelName(logging_level.upper()) 35 | 36 | handler = logging.StreamHandler() 37 | handler.setLevel(logging_level) 38 | logger.setLevel(logging_level) 39 | handler.setFormatter(logging.Formatter(LOGGER_FORMAT)) 40 | logger.addHandler(handler) 41 | 42 | return logger 43 | -------------------------------------------------------------------------------- /parallel_tokenizer/parallel_tokenizer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) OpenLMLab. All rights reserved. 2 | import multiprocessing as mp 3 | import os 4 | import time 5 | from functools import partial, reduce 6 | from typing import Any, Callable, List, Sequence, Tuple, Union 7 | 8 | import numpy as np 9 | import torch 10 | from transformers.tokenization_utils import BatchEncoding, PreTrainedTokenizer 11 | 12 | from .logger import get_logger 13 | from .sp_tokenizer import SentencePieceTokenizer 14 | from .special_cases import SPECIAL_KEYS_DICT 15 | from .utils import chunks, flatten, match, merge, pairs, to_list 16 | 17 | logger = get_logger(__name__) 18 | 19 | os.environ["TOKENIZERS_PARALLELISM"] = "false" 20 | 21 | 22 | class ParallelTokenizer: 23 | """ 24 | ParallelTokenizer is designed to accelerate the tokenization process by utilizing multiprocessing. 25 | It splits the input text into chunks, tokenizes them in parallel, and then merges the results. 26 | 27 | Parameters: 28 | - tokenizer (Union[SentencePieceTokenizer, PreTrainedTokenizer]): The tokenizer instance that will be 29 | used for tokenizing text. It can be either a SentencePieceTokenizer or a PreTrainedTokenizer. 30 | - num_processes (int, optional): The number of parallel processes to use for tokenizing. Defaults to 4. 31 | - chunk_size (int, optional): The size of each chunk of text to be tokenized in parallel. Defaults to 40960. 32 | - overlap_length (int, optional): The length of the overlapping parts of the text chunks to ensure continuity 33 | in the tokenization process. Defaults to 512. 34 | - concat_keys (List[str], optional): The keys of the tokenized outputs to be concatenated when merging results. 35 | Defaults to ["input_ids", "attention_mask"]. 36 | """ 37 | 38 | def __init__( 39 | self, 40 | tokenizer: Union[SentencePieceTokenizer, PreTrainedTokenizer], 41 | num_processes: int = 4, 42 | chunk_size: int = 40960, 43 | overlap_length: int = 512, 44 | concat_keys: Sequence[str] = ("input_ids", "attention_mask"), 45 | ) -> None: 46 | assert callable(tokenizer), "tokenizer should be callable" 47 | self.tokenizer = tokenizer 48 | self.num_processes = num_processes 49 | self.chunk_size = chunk_size 50 | self.overlap_length = overlap_length 51 | self.concat_keys = concat_keys 52 | self.pool = mp.Pool(num_processes) # pylint: disable=R1732 53 | 54 | def __call__(self, *args: Any, **kwargs: Any) -> Any: 55 | """ 56 | Tokenizes the input text in parallel by splitting it into chunks, tokenizing each chunk in a separate 57 | process, and then merging the results. 58 | 59 | Parameters: 60 | - *args: Positional arguments passed to the tokenizer. The first argument is expected to be the 61 | text to tokenize. 62 | - **kwargs: Keyword arguments passed to the tokenizer. If 'text' is not provided as a positional 63 | argument, it should be passed as a keyword argument with the key 'text'. 64 | 65 | Returns: 66 | - The tokenized output, which can be a list of token ids, a dictionary, or a BatchEncoding object, 67 | depending on the tokenizer's output format. 68 | """ 69 | if len(args) > 0: 70 | text = args[0] 71 | args = args[1:] 72 | else: 73 | text = kwargs.pop("text") 74 | assert isinstance(text, str), "Currently not support batch encoding. Please pass the text as a string." 75 | _tokenizer = partial(self.tokenizer, *args, **kwargs) 76 | shards = self.pool.map( 77 | partial(ParallelTokenizer.encode_handler, tokenizer=_tokenizer), 78 | chunks(text, self.chunk_size, self.overlap_length), 79 | ) 80 | 81 | if len(shards) == 1: 82 | return shards[0] 83 | 84 | if isinstance(shards[0], (dict, BatchEncoding)): 85 | tokens_shards = [flatten(shard["input_ids"]) for shard in shards] 86 | else: 87 | tokens_shards = [flatten(shard) for shard in shards] 88 | 89 | matches = self.pool.map(ParallelTokenizer.match_handler, pairs(tokens_shards)) 90 | matches = [0] + list(reduce(lambda x, y: x + y, matches)) + [0] 91 | 92 | if isinstance(shards[0], (dict, BatchEncoding)): 93 | result = shards[0].__class__() 94 | for key in shards[0].keys(): 95 | if key in SPECIAL_KEYS_DICT: 96 | result[key] = SPECIAL_KEYS_DICT[key]([shard[key] for shard in shards], matches=matches) 97 | elif key in self.concat_keys: 98 | result[key] = merge([shard[key] for shard in shards], matches) 99 | else: 100 | result[key] = [shard[key] for shard in shards] 101 | else: 102 | result = merge(shards, matches) 103 | return result 104 | 105 | def __del__(self): 106 | self.pool.close() 107 | self.pool.join() 108 | 109 | def __getattr__(self, __name: str) -> Any: 110 | """ 111 | Allows direct access to the tokenizer's attributes. 112 | 113 | Parameters: 114 | - __name (str): The attribute name to access from the tokenizer. 115 | 116 | Returns: 117 | - The value of the attribute named `__name` from the tokenizer. 118 | """ 119 | return getattr(self.tokenizer, __name) 120 | 121 | def benchmark(self, *args: Any, return_acc: bool = True, **kwargs: Any) -> float: 122 | """ 123 | Tests the efficiency and accuracy of the parallel tokenization process compared to the sequential process. 124 | 125 | Parameters: 126 | - *args: Positional arguments passed to the tokenizer for testing. 127 | - **kwargs: Keyword arguments passed to the tokenizer for testing. 128 | 129 | Returns: 130 | - A float representing the accuracy of the parallel tokenization process compared to the sequential process. 131 | """ 132 | start = time.time() 133 | raw_result = self.tokenizer(*args, **kwargs) 134 | raw_time = time.time() - start 135 | 136 | start = time.time() 137 | parallel_result = self(*args, **kwargs) 138 | parallel_time = time.time() - start 139 | 140 | if isinstance(raw_result, (dict, BatchEncoding)): 141 | raw_tokens = to_list(flatten(raw_result["input_ids"])) 142 | parallel_tokens = to_list(flatten(parallel_result["input_ids"])) 143 | else: 144 | raw_tokens = to_list(flatten(raw_result)) 145 | parallel_tokens = to_list(flatten(parallel_result)) 146 | 147 | if return_acc: 148 | acc = [raw_tokens[i] - parallel_tokens[i] for i in range(min(len(raw_tokens), len(parallel_tokens)))].count( 149 | 0 150 | ) / min(len(raw_tokens), len(parallel_tokens)) 151 | 152 | logger.info(f"raw_time: {raw_time:.4f} - parallel_time: {parallel_time:.4f} - acc: {acc:.4f}") 153 | 154 | return raw_time, parallel_time, acc 155 | else: 156 | logger.info(f"raw_time: {raw_time:.4f} - parallel_time: {parallel_time:.4f}") 157 | 158 | @staticmethod 159 | def encode_handler( 160 | chunk: Union[str, Sequence[str]], tokenizer: Callable 161 | ) -> Union[torch.Tensor, np.ndarray, List[int]]: 162 | """ 163 | A static method used as a handler for encoding a single chunk of text with the tokenizer. 164 | 165 | Parameters: 166 | - chunk (Union[str, Sequence[str]]): A single chunk of text or a sequence of texts to tokenize. 167 | - tokenizer (Callable): The tokenizer function to use for tokenizing the chunk. 168 | 169 | Returns: 170 | - The tokenized output for the chunk, which can be a torch.Tensor, np.ndarray, or List[int], 171 | depending on the tokenizer's output format. 172 | """ 173 | return tokenizer(chunk) 174 | 175 | @staticmethod 176 | def match_handler(chunks: List[Union[torch.Tensor, np.ndarray, List[int]]]) -> Tuple[int]: 177 | """ 178 | A static method used to handle matching and merging overlapping parts of tokenized chunks. 179 | 180 | Parameters: 181 | - chunks (List[Union[torch.Tensor, np.ndarray, List[int]]]): A list of tokenized outputs for consecutive chunks 182 | that need to be matched and merged. 183 | 184 | Returns: 185 | - A tuple of integers indicating the positions where chunks should be merged. 186 | """ 187 | return match(chunks) 188 | 189 | 190 | def get_parallel_tokenizer( # pylint: disable=W0102 191 | tokenizer: Union[SentencePieceTokenizer, PreTrainedTokenizer], 192 | num_processes: int = 4, 193 | chunk_size: int = 40960, 194 | overlap_length: int = 512, 195 | concat_keys: List[str] = ["input_ids", "attention_mask"], 196 | ) -> ParallelTokenizer: 197 | """ 198 | A convenience function to create a ParallelTokenizer instance with the specified configuration. 199 | 200 | Parameters: 201 | - tokenizer (Union[SentencePieceTokenizer, PreTrainedTokenizer]): The tokenizer to be used for parallel 202 | tokenization. 203 | - num_processes (int, optional): The number of processes to use for parallel tokenization. Defaults to 4. 204 | - chunk_size (int, optional): The size of text chunks to be tokenized in parallel. Defaults to 40960. 205 | - overlap_length (int, optional): The length of overlaps between text chunks to ensure continuity. Defaults to 512. 206 | - concat_keys (List[str], optional): The keys of the tokenization output to be concatenated. 207 | Defaults to ["input_ids", "attention_mask"]. 208 | 209 | Returns: 210 | - A ParallelTokenizer instance configured with the specified parameters. 211 | """ 212 | return ParallelTokenizer( 213 | tokenizer=tokenizer, 214 | num_processes=num_processes, 215 | chunk_size=chunk_size, 216 | overlap_length=overlap_length, 217 | concat_keys=concat_keys, 218 | ) 219 | -------------------------------------------------------------------------------- /parallel_tokenizer/sp_tokenizer.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) OpenLMLab. All rights reserved. 2 | import os 3 | from typing import Any, List 4 | 5 | from sentencepiece import SentencePieceProcessor 6 | 7 | from .logger import get_logger 8 | 9 | logger = get_logger(__name__) 10 | 11 | 12 | class SentencePieceTokenizer: 13 | """Wrapper for SentencePiece tokenizer.""" 14 | 15 | def __init__(self, model_path: str, use_logger: bool = True, use_bos: bool = True, use_eos: bool = True) -> None: 16 | # reload tokenizer 17 | if not os.path.isfile(model_path): 18 | raise ValueError(f"Got invalid `model_path={model_path}` for SentencePieceTokenizer.") 19 | self.sp_model = SentencePieceProcessor(model_file=model_path) # pylint: disable=unexpected-keyword-arg 20 | 21 | self.use_bos = use_bos 22 | self.use_eos = use_eos 23 | 24 | if use_logger: 25 | logger.info(f"Reloaded SentencePiece model from {model_path}") 26 | 27 | # BOS / EOS token IDs 28 | self.n_words: int = self.sp_model.vocab_size() 29 | self.bos_id: int = self.sp_model.bos_id() 30 | self.eos_id: int = self.sp_model.eos_id() 31 | self.pad_id: int = self.sp_model.pad_id() 32 | 33 | if use_logger: 34 | logger.info(f"#words: {self.n_words} - BOS ID: {self.bos_id} - EOS ID: {self.eos_id}") 35 | 36 | assert self.sp_model.vocab_size() == self.sp_model.get_piece_size(), ( 37 | f"The vocab size {self.sp_model.vocab_size()} of the model in {model_path} is not equal to " 38 | f"the piece size {self.sp_model.get_piece_size()} of the model." 39 | ) 40 | 41 | def encode(self, s: str, use_bos: bool | None = None, use_eos: bool | None = None) -> List[int]: 42 | assert isinstance(s, str), "tokenizer expect a string, but got a " + str(type(s)) 43 | t = self.sp_model.encode(s) 44 | if use_bos is None: 45 | use_bos = self.use_bos 46 | if use_bos: 47 | t = [self.bos_id] + t 48 | if use_eos is None: 49 | use_eos = self.use_eos 50 | if use_eos: 51 | t = t + [self.eos_id] 52 | return t 53 | 54 | def decode(self, t: List[int]) -> str: 55 | return self.sp_model.decode(t) 56 | 57 | def __call__(self, s: str, use_bos: bool | None = None, use_eos: bool | None = None) -> Any: 58 | return self.encode(s, use_bos=use_bos, use_eos=use_eos) 59 | 60 | def id_to_piece(self, token_id): 61 | """ 62 | This method is used by the scoring function module in the tools folder. 63 | """ 64 | return self.sp_model.id_to_piece(token_id) 65 | -------------------------------------------------------------------------------- /parallel_tokenizer/special_cases.py: -------------------------------------------------------------------------------- 1 | from typing import List, Tuple, Union 2 | 3 | import numpy as np 4 | import torch 5 | 6 | from .logger import get_logger 7 | from .utils import arange_like, get_size 8 | 9 | logger = get_logger(__name__) 10 | 11 | 12 | def position_ids(shards: List[Union[torch.Tensor, np.ndarray, List[int]]], matches: List[Tuple[int]]): 13 | seqlen = sum( 14 | [ 15 | get_size(x[0])[-1] - x[1][1] - ((get_size(x[0])[-1] - x[1][0]) % get_size(x[0])[-1]) 16 | for x in zip(shards, [matches[i : i + 2] for i in range(0, len(matches), 2)]) 17 | ] 18 | ) 19 | return arange_like(shards[0], start=0, end=seqlen) 20 | 21 | 22 | SPECIAL_KEYS_DICT = {"position_ids": position_ids} 23 | 24 | SPECIAL_TOKENIZERS_DICT = {} 25 | -------------------------------------------------------------------------------- /parallel_tokenizer/utils.py: -------------------------------------------------------------------------------- 1 | from difflib import SequenceMatcher 2 | from functools import reduce 3 | from typing import Iterable, List, Sequence, Tuple, Union 4 | 5 | import numpy as np 6 | import torch 7 | 8 | from .logger import get_logger 9 | 10 | logger = get_logger(__name__) 11 | 12 | 13 | def concat(*args: List[Union[torch.Tensor, np.ndarray, List[int]]], dim: int = -1): 14 | """ 15 | Concatenates a sequence of tensors, numpy arrays, or lists. 16 | 17 | Parameters: 18 | - *args: A variable number of lists, each containing torch.Tensors, 19 | numpy.ndarrays, or Python lists to be concatenated. 20 | 21 | Returns: 22 | - Union[torch.Tensor, np.ndarray, List[int]]: The concatenated result 23 | as the same type as the input. The concatenation is performed along 24 | the first axis for tensors and arrays, and by appending lists for lists. 25 | 26 | Raises: 27 | - ValueError: If the type of the input is not supported. 28 | """ 29 | if dim < 0: 30 | dim = get_ndim(args[0]) + dim 31 | assert dim < get_ndim(args[0]), "dim should be less than the number of dimensions of the input" 32 | if isinstance(args[0], torch.Tensor): 33 | return torch.cat(args, dim=dim) 34 | elif isinstance(args[0], np.ndarray): 35 | return np.concatenate(args, axis=dim) 36 | elif isinstance(args[0], List): 37 | if dim == 0: 38 | return list(reduce(lambda x, y: x + y, args)) 39 | else: 40 | return [concat(*items, dim=dim - 1) for items in zip(*args)] 41 | else: 42 | raise ValueError(f"Unsupported type {type(args[0])} for concat") 43 | 44 | 45 | def chunks(sentence: Union[str, Sequence[str]], chunk_size: int = 40960, overlap_length: int = 512): 46 | """ 47 | Splits a string or a sequence of strings into chunks with a specified size and overlap. 48 | 49 | Parameters: 50 | - sentence (Union[str, Sequence[str]]): The input text to be chunked. Can be a single 51 | string or a sequence of strings. 52 | - chunk_size (int, optional): The size of each chunk. Defaults to 40960. 53 | - overlap_length (int, optional): The length of the overlap between adjacent chunks. 54 | Defaults to 512. 55 | 56 | Yields: 57 | - Iterable[Union[str, List[str]]]: An iterable of chunks, each being a string 58 | or a list of strings, 59 | depending on the input type. 60 | 61 | Raises: 62 | - ValueError: If the input type is not a string or a sequence of strings. 63 | """ 64 | if isinstance(sentence, str): 65 | while sentence: 66 | yield sentence[: overlap_length + chunk_size] 67 | sentence = sentence[chunk_size:] 68 | elif isinstance(sentence, Sequence) and isinstance(sentence[0], str): 69 | while any(sentence): 70 | yield [s[: overlap_length + chunk_size] for s in sentence] 71 | sentence = [s[chunk_size:] for s in sentence] 72 | else: 73 | raise ValueError(f"Unsupported type {type(sentence)} for chunks") 74 | 75 | 76 | def pairs(chunks: List[List[int]]) -> Iterable[List[List[int]]]: 77 | """ 78 | Generates consecutive pairs of chunks for matching. 79 | 80 | Parameters: 81 | - chunks (List[List[int]]): A list of chunks, where each chunk is a list of integers. 82 | 83 | Yields: 84 | - Iterable[List[List[int]]]: An iterable of pairs of consecutive chunks. 85 | """ 86 | for i in range(0, len(chunks) - 1): 87 | yield (chunks[i], chunks[i + 1]) 88 | 89 | 90 | def match(chunks: List[Union[torch.Tensor, np.ndarray, List[int]]]) -> Tuple[int]: 91 | """ 92 | Finds the longest matching subsequence between the last part of the first chunk and the first 93 | part of the second chunk. 94 | 95 | Parameters: 96 | - chunks (List[Union[torch.Tensor, np.ndarray, List[int]]]): A list containing two chunks. 97 | Each chunk can be a torch.Tensor, a numpy.ndarray, or a list of integers. 98 | 99 | Returns: 100 | - Tuple[int]: A tuple containing the starting index of the match in the first chunk and the 101 | ending index of the match in the second chunk. 102 | 103 | Notes: 104 | - This function is primarily used for adjusting the boundaries between chunks that have been 105 | tokenized separately to ensure a seamless merge. 106 | """ 107 | _match = SequenceMatcher( 108 | None, to_list(reverse(chunks[0])), to_list(reverse(chunks[-1])), autojunk=False 109 | ).find_longest_match(0, len(chunks[0]), 0, len(chunks[-1])) 110 | if _match.size == 0: 111 | logger.warning( 112 | "It is detected that the text cannot be tokenized accurately, " 113 | "which is often caused by tokenizer_chunk being too small. " 114 | ) 115 | return _match.a, _match.b 116 | 117 | 118 | def flatten(item: Union[torch.Tensor, np.ndarray, List]): 119 | """ 120 | Flattens a nested sequence (torch.Tensor, numpy.ndarray, or List) into a single flat list. 121 | 122 | Parameters: 123 | - item (Union[torch.Tensor, np.ndarray, List]): The item to flatten, which can be either 124 | a torch.Tensor, a numpy.ndarray, or a nested list. 125 | 126 | Returns: 127 | - Union[torch.Tensor, np.ndarray, List[int]]: A flattened version of the input, as a 128 | torch.Tensor, a numpy.ndarray, or a list of integers. 129 | 130 | Raises: 131 | - ValueError: If the input type is not supported or if the flattening process fails. 132 | """ 133 | if isinstance(item, (torch.Tensor, np.ndarray)): 134 | return item.flatten() 135 | elif isinstance(item, List): 136 | while all(isinstance(i, Sequence) for i in item): 137 | item = [i for sublist in item for i in sublist] 138 | assert not any(isinstance(i, Sequence) for i in item), "flatten failed" 139 | return item 140 | else: 141 | raise ValueError(f"Unsupported type {type(item)} for flatten") 142 | 143 | 144 | def merge( 145 | shards: List[Union[torch.Tensor, np.ndarray, List[int]]], matches: List[Tuple[int]], merge_dim: int = -1 146 | ) -> Union[torch.Tensor, np.ndarray, List[int]]: 147 | """ 148 | Merges a list of tokenized shards, adjusting for overlaps using provided match indices. 149 | 150 | Parameters: 151 | - shards (List[Union[torch.Tensor, np.ndarray, List[int]]]): The tokenized shards to merge. 152 | Each shard can be a torch.Tensor, a numpy.ndarray, or a list of integers. 153 | - matches (List[Tuple[int]]): A list of tuples indicating the overlap indices for adjacent shards. 154 | 155 | Returns: 156 | - Union[torch.Tensor, np.ndarray, List[int]]: The merged result, in the same type as the shards. 157 | 158 | Raises: 159 | - AssertionError: If the length of the shards list is not twice the length of the matches list, 160 | indicating a mismatch in provided data. 161 | """ 162 | assert len(shards) * 2 == len(matches), "the length of shards should be twice the length of matches" 163 | result = map( 164 | lambda x: slicing( 165 | x[0], 166 | dim=merge_dim, 167 | start=(get_size(x[0])[-1] - x[1][0]) % get_size(x[0])[-1], 168 | end=get_size(x[0])[-1] - x[1][1], 169 | ), 170 | zip(shards, [matches[i : i + 2] for i in range(0, len(matches), 2)]), 171 | ) 172 | result = reduce(lambda x, y: concat(x, y, dim=merge_dim), result) 173 | return result 174 | 175 | 176 | def reverse(item: Union[torch.Tensor, np.ndarray, List[int]]): 177 | """ 178 | Reverses the order of elements in the input item. The input item can be a PyTorch tensor, a NumPy array, 179 | or a list of integers. This function is designed to work with these specific types to accommodate common 180 | data structures used in machine learning and data processing tasks. 181 | 182 | Parameters: 183 | - item (Union[torch.Tensor, np.ndarray, List[int]]): The item whose elements are to be reversed. It can be a 184 | PyTorch tensor, a NumPy array, or a list of integers. 185 | 186 | Returns: 187 | - The reversed item, maintaining the original type. For a PyTorch tensor, the function returns a tensor with 188 | elements in reverse order. For a NumPy array, it returns an array with elements in reverse order. For a list 189 | of integers, it returns a list with integers in reverse order. 190 | 191 | Raises: 192 | - ValueError: If the input `item` is not a PyTorch tensor, a NumPy array, or a list of integers, the function 193 | raises a ValueError indicating the unsupported type. 194 | """ 195 | if isinstance(item, (np.ndarray, list)): 196 | return item[::-1] 197 | elif isinstance(item, torch.Tensor): 198 | return torch.flip(item, [0]) 199 | else: 200 | raise ValueError(f"Unsupported type {type(item)} for reverse") 201 | 202 | 203 | def to_list(item: Union[torch.Tensor, np.ndarray, List[int]]) -> List[int]: 204 | """ 205 | Converts the input item to a list of integers. The function supports input items that are 206 | PyTorch tensors, NumPy arrays, or already lists of integers. 207 | 208 | Parameters: 209 | - item (Union[torch.Tensor, np.ndarray, List[int]]): The item to convert to a list. It can be a 210 | PyTorch tensor, a NumPy array, or a list of integers. 211 | 212 | Returns: 213 | - List[int]: A list of integers derived from the input item. 214 | 215 | Raises: 216 | - ValueError: If the input `item` is not a supported type (i.e., not a PyTorch tensor, a NumPy array, 217 | or a list of integers), the function raises a ValueError. 218 | """ 219 | if isinstance(item, torch.Tensor): 220 | return item.cpu().tolist() 221 | elif isinstance(item, np.ndarray): 222 | return item.tolist() 223 | elif isinstance(item, List): 224 | return item 225 | else: 226 | raise ValueError(f"Unsupported type {type(item)} for to_list") 227 | 228 | 229 | def get_ndim(item: Union[torch.Tensor, np.ndarray, List[int]]) -> int: 230 | """ 231 | Determines the number of dimensions of the input item. The function supports input items that 232 | are PyTorch tensors, NumPy arrays, or lists (potentially nested to represent higher dimensions). 233 | 234 | Parameters: 235 | - item (Union[torch.Tensor, np.ndarray, List[int]]): The item whose number of dimensions is to 236 | be determined. 237 | 238 | Returns: 239 | - int: The number of dimensions of the input item. 240 | 241 | Raises: 242 | - ValueError: If the input `item` is not a supported type (i.e., not a PyTorch tensor, a NumPy array, 243 | or a list), the function raises a ValueError. 244 | """ 245 | if isinstance(item, (torch.Tensor, np.ndarray)): 246 | return item.ndim 247 | elif isinstance(item, List): 248 | ndim = 1 249 | while isinstance(item[0], List): 250 | item = item[0] 251 | ndim += 1 252 | return ndim 253 | else: 254 | raise ValueError(f"Unsupported type {type(item)} for get_ndim") 255 | 256 | 257 | def slicing(item: Union[torch.Tensor, np.ndarray, List[int]], dim: int = -1, start: int = 0, end: int = None): 258 | """ 259 | Slices the input item along a specified dimension from a start index to an end index. 260 | The function supports input items that are PyTorch tensors, NumPy arrays, or lists 261 | (potentially nested to represent higher dimensions). 262 | 263 | Parameters: 264 | - item (Union[torch.Tensor, np.ndarray, List[int]]): The item to slice. 265 | - dim (int, optional): The dimension along which to slice. Defaults to -1, 266 | which typically means the last dimension. 267 | - start (int, optional): The start index of the slice. Defaults to 0. 268 | - end (int, optional): The end index of the slice. If None, slicing goes to the end of 269 | the dimension. Defaults to None. 270 | 271 | Returns: 272 | - The sliced portion of the input item, maintaining the original type. 273 | 274 | Raises: 275 | - ValueError: If the input `item` is not a supported type or the specified dimension 276 | is invalid. 277 | """ 278 | if dim < 0: 279 | dim = get_ndim(item) + dim 280 | assert dim < get_ndim(item), "dim should be less than the number of dimensions of the input" 281 | if isinstance(item, torch.Tensor): 282 | return item.narrow(dim, start, end - start) 283 | elif isinstance(item, np.ndarray): 284 | return item.take(range(start, end), axis=dim) 285 | elif isinstance(item, List): 286 | if dim == 0: 287 | return item[start:end] 288 | else: 289 | return [slicing(subitem, dim - 1, start, end) for subitem in item] 290 | 291 | 292 | def get_size(item: Union[torch.Tensor, np.ndarray, List[int]]) -> Tuple[int]: 293 | """ 294 | Returns the size (shape) of the input item. The function supports input items that are PyTorch tensors, 295 | NumPy arrays, or lists (potentially nested to represent higher dimensions). 296 | 297 | Parameters: 298 | - item (Union[torch.Tensor, np.ndarray, List[int]]): The item whose size is to be determined. 299 | 300 | Returns: 301 | - Tuple[int]: A tuple representing the size (shape) of the item. For tensors and arrays, it directly 302 | corresponds to their shape. For lists, it's the equivalent shape based on the nesting level and length 303 | of the lists. 304 | 305 | Raises: 306 | - ValueError: If the input `item` is not a supported type, the function raises a ValueError. 307 | """ 308 | if isinstance(item, torch.Tensor): 309 | return item.size() 310 | elif isinstance(item, np.ndarray): 311 | return item.shape 312 | elif isinstance(item, List): 313 | ndim = get_ndim(item) 314 | shape = [] 315 | for _ in range(ndim): 316 | shape.append(len(item)) 317 | item = item[0] 318 | return tuple(shape) 319 | else: 320 | raise ValueError(f"Unsupported type {type(item)} for get_size") 321 | 322 | 323 | def add_scalar( 324 | item: Union[torch.Tensor, np.ndarray, List[int]], scalar: int 325 | ) -> Union[torch.Tensor, np.ndarray, List[int]]: 326 | if isinstance(item, (torch.Tensor, np.ndarray)): 327 | return item + scalar 328 | elif isinstance(item, List): 329 | return [add_scalar(subitem, scalar) for subitem in item] 330 | elif isinstance(item, int): 331 | return item + scalar 332 | else: 333 | raise ValueError(f"Unsupported type {type(item)} for add_scalar") 334 | 335 | 336 | def arange_like( 337 | item: Union[torch.Tensor, np.ndarray, List[int]], start: int, end: int 338 | ) -> Union[torch.Tensor, np.ndarray, List[int]]: 339 | ndim = get_ndim(item) 340 | if isinstance(item, torch.Tensor): 341 | item = torch.arange(start, end, device=item.device, dtype=item.dtype) 342 | while get_ndim(item) < ndim: 343 | item = item.unsqueeze(0) 344 | elif isinstance(item, np.ndarray): 345 | item = np.arange(start, end) 346 | while get_ndim(item) < ndim: 347 | item = item[np.newaxis] 348 | elif isinstance(item, List): 349 | item = list(range(start, end)) 350 | while get_ndim(item) < ndim: 351 | item = [item] 352 | else: 353 | raise ValueError(f"Unsupported type {type(item)} for arange_like") 354 | return item 355 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) OpenLMLab. All rights reserved. 2 | import os 3 | 4 | from setuptools import find_packages, setup 5 | 6 | pwd = os.path.dirname(__file__) 7 | 8 | 9 | def readme(): 10 | with open(os.path.join(pwd, "README.md"), encoding="utf-8") as f: 11 | content = f.read() 12 | return content 13 | 14 | 15 | def get_version(): 16 | with open(os.path.join(pwd, "version.txt"), "r") as f: 17 | content = f.read() 18 | return content 19 | 20 | 21 | setup( 22 | name="ParallelTokenizer", 23 | version=get_version(), 24 | description="a tool that uses a parallel approach to tokenizer to achieve superior acceleration", 25 | long_description=readme(), 26 | long_description_content_type="text/markdown", 27 | packages=find_packages(), 28 | classifiers=[ 29 | "Programming Language :: Python :: 3.8", 30 | "Programming Language :: Python :: 3.9", 31 | "Programming Language :: Python :: 3.10", 32 | "Programming Language :: Python :: 3.11", 33 | "Intended Audience :: Developers", 34 | "Intended Audience :: Education", 35 | "Intended Audience :: Science/Research", 36 | ], 37 | ) 38 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OpenLMLab/ParallelTokenizer/c1ba82bf6d028151dcaed49c193c141908da9715/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_interface.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | import pytest 4 | import torch 5 | from transformers import AutoTokenizer 6 | from wonderwords import RandomWord 7 | 8 | from parallel_tokenizer import ParallelTokenizer 9 | 10 | TEST_MODELS = [ 11 | "internlm/internlm2-7b", 12 | "meta-llama/Llama-2-7b-chat-hf", 13 | "baichuan-inc/Baichuan2-7B-Chat", 14 | "mistralai/Mistral-7B-Instruct-v0.2", 15 | "google/gemma-7b-it", 16 | "Qwen/Qwen1.5-72B-Chat", 17 | "THUDM/chatglm3-6b", 18 | ] 19 | TEST_LENGTHS = [8192, 16384] 20 | 21 | 22 | @pytest.mark.parametrize("model_name_or_path", TEST_MODELS) 23 | @pytest.mark.parametrize("sentence_length", TEST_LENGTHS) 24 | @pytest.mark.parametrize("add_special_tokens", [True, False]) 25 | @pytest.mark.parametrize("return_tensors", [None, "pt"]) 26 | @pytest.mark.parametrize("batch", [False]) 27 | def test_call( 28 | model_name_or_path: str, sentence_length: int, add_special_tokens: bool, return_tensors: str or None, batch: bool 29 | ): 30 | random.seed(1024) 31 | r = RandomWord() 32 | 33 | tokenizer_hf = AutoTokenizer.from_pretrained(model_name_or_path, trust_remote_code=True) 34 | parallel_tokenizer = ParallelTokenizer( 35 | tokenizer=tokenizer_hf, 36 | num_processes=4, 37 | chunk_size=4096, 38 | overlap_length=128, 39 | concat_keys=["input_ids", "attention_mask"], 40 | ) 41 | 42 | if batch: 43 | input_text: list[str] = [" ".join([r.word() for _ in range(sentence_length)]) for _ in range(2)] 44 | else: 45 | input_text: str = " ".join([r.word() for _ in range(sentence_length)]) 46 | 47 | ret_hf = tokenizer_hf(input_text, add_special_tokens=add_special_tokens, return_tensors=return_tensors) 48 | ret_parallel = parallel_tokenizer(input_text, add_special_tokens=add_special_tokens, return_tensors=return_tensors) 49 | 50 | for k in ret_hf: 51 | 52 | if isinstance(ret_hf[k], list): 53 | assert ret_hf[k] == ret_parallel[k], f"{k} is not equal" 54 | elif isinstance(ret_hf[k], torch.Tensor): 55 | assert ret_hf[k].equal(ret_parallel[k]), f"{k} is not equal" 56 | else: 57 | assert f"{type(ret_hf[k])} is not supported" 58 | 59 | 60 | if __name__ == "__main__": 61 | test_call("THUDM/chatglm3-6b", 8192, True, "pt", False) 62 | -------------------------------------------------------------------------------- /tests/test_parallel_tokenizer.py: -------------------------------------------------------------------------------- 1 | import os 2 | from tempfile import TemporaryDirectory 3 | 4 | import pytest 5 | 6 | from parallel_tokenizer.parallel_tokenizer import ParallelTokenizer 7 | from tests.utils import download_file 8 | 9 | 10 | @pytest.mark.parametrize("sentence_length", [81920, 163840]) 11 | def test_sp_tokenizer_in_parallel(sentence_length: int): 12 | import math 13 | import random 14 | 15 | from wonderwords import RandomWord 16 | 17 | from parallel_tokenizer.sp_tokenizer import SentencePieceTokenizer 18 | 19 | random.seed(1024) 20 | r = RandomWord() 21 | 22 | with TemporaryDirectory() as tmp_dir: 23 | model_path = os.path.join(tmp_dir, "tokenizer.model") 24 | download_file("https://huggingface.co/internlm/internlm2-20b/resolve/main/tokenizer.model", model_path) 25 | tokenizer = SentencePieceTokenizer(model_path) 26 | 27 | parallel_tokenizer = ParallelTokenizer( 28 | tokenizer=tokenizer, 29 | num_processes=4, 30 | chunk_size=40960, 31 | overlap_length=512, 32 | concat_keys=["input_ids", "attention_mask"], 33 | ) 34 | sentence: str = " ".join([r.word() for _ in range(sentence_length)]) 35 | _, _, acc = parallel_tokenizer.benchmark(sentence) 36 | assert math.isclose(acc, 1.0, abs_tol=1e-5) 37 | 38 | 39 | @pytest.mark.parametrize("sentence_length", [81920]) 40 | @pytest.mark.parametrize("return_tensors", [None, "pt", "np"]) 41 | def test_hf_tokenizer_in_parallel(sentence_length: int, return_tensors: str): 42 | import math 43 | import random 44 | 45 | from transformers import AutoTokenizer 46 | from wonderwords import RandomWord 47 | 48 | random.seed(1024) 49 | r = RandomWord() 50 | 51 | tokenizer = AutoTokenizer.from_pretrained("internlm/internlm2-20b", trust_remote_code=True) 52 | parallel_tokenizer = ParallelTokenizer( 53 | tokenizer=tokenizer, 54 | num_processes=4, 55 | chunk_size=40960, 56 | overlap_length=512, 57 | concat_keys=["input_ids", "attention_mask"], 58 | ) 59 | sentence: str = " ".join([r.word() for _ in range(sentence_length)]) 60 | _, _, acc = parallel_tokenizer.benchmark(sentence, return_tensors=return_tensors) 61 | assert math.isclose(acc, 1.0, abs_tol=1e-5) 62 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | 4 | def download_file(url, filename): 5 | response = requests.get(url, timeout=10) 6 | with open(filename, "wb") as f: 7 | f.write(response.content) 8 | -------------------------------------------------------------------------------- /version.txt: -------------------------------------------------------------------------------- 1 | 0.1.0 2 | --------------------------------------------------------------------------------