all-MiniLM-L6-v2 / code /tt_minilm /tokenizer.py
changh95's picture
tt-model push all-minilm-l6-v2 (container)
1e8fbed verified
Raw History Blame Contribute Delete
2.41 kB
# SPDX-License-Identifier: Apache-2.0
"""The model's BERT WordPiece tokenizer (HF ``tokenizers``, the snapshot's ``tokenizer.json``) with the official
sentence-transformers framing: ``[CLS] + word pieces + [SEP]``, truncated to ``max_length`` (256), no padding.
Truncation policies: ``right`` (official ``longest_first`` for one text: keep the first ``max_length - 2`` pieces),
``left`` (keep the last ones) and ``error`` (:class:`TooLong`)."""
from __future__ import annotations
import os
from typing import List, Sequence
from .weights import CLS_ID, SEP_ID
TRUNCATE = ("right", "left", "error")
class TooLong(ValueError):
pass
class Tokenizer:
def __init__(self, model_dir: str, max_length: int = 256):
from tokenizers import Tokenizer as _T
self._tok = _T.from_file(os.path.join(model_dir, "tokenizer.json"))
self._tok.no_truncation() # the snapshot's tokenizer.json bakes truncation 128 / padding 128 in
self._tok.no_padding()
self.max_length = int(max_length)
if self._tok.token_to_id("[CLS]") != CLS_ID or self._tok.token_to_id("[SEP]") != SEP_ID:
raise ValueError("tokenizer.json special ids differ from [CLS]=101 / [SEP]=102")
def pieces(self, texts: Sequence[str]) -> List[List[int]]:
encs = self._tok.encode_batch(list(texts), add_special_tokens=False)
return [list(e.ids) for e in encs]
def encode(self, texts: Sequence[str], max_length: int = None, truncate: str = "right") -> List[List[int]]:
"""ids per text incl. [CLS] / [SEP]; ``2 <= len <= max_length``."""
ml = self.max_length if max_length is None else int(max_length)
if not 2 <= ml <= self.max_length:
raise ValueError(f"max_length {ml} outside [2, {self.max_length}]")
if truncate not in TRUNCATE:
raise ValueError(f"truncate {truncate!r} not in {TRUNCATE}")
out = []
keep = ml - 2
for i, wp in enumerate(self.pieces(texts)):
if len(wp) > keep:
if truncate == "error":
raise TooLong(f"text {i} has {len(wp) + 2} tokens > max_length {ml}")
wp = wp[:keep] if truncate == "right" else wp[len(wp) - keep:]
out.append([CLS_ID] + wp + [SEP_ID])
return out
def count(self, texts: Sequence[str]) -> List[int]:
return [len(w) + 2 for w in self.pieces(texts)]