Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 201 additions & 0 deletions model2vec/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
from __future__ import annotations

import copy
import json
from abc import ABC, abstractmethod
from collections.abc import Sequence
from logging import getLogger
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any, Generic, TypeVar, cast

import numpy as np
from tokenizers import Encoding, Tokenizer

from model2vec.types import StaticModelConfig

PathLike = Path | str

logger = getLogger(__name__)

DEFAULT_MAX_LENGTH = 512
_DEFAULT_NORMALIZE = False


ConfigT = TypeVar("ConfigT", bound=StaticModelConfig)


class BaseStaticModel(ABC, Generic[ConfigT]):
def __init__(
self,
tokenizer: Tokenizer,
config: ConfigT | None = None,
normalize: bool = _DEFAULT_NORMALIZE,
base_model_name: str | None = None,
language: list[str] | None = None,
max_length: int | None = DEFAULT_MAX_LENGTH,
) -> None:
"""Initialize the tokenizer, config and settings shared by dense and sparse static models.

:param tokenizer: The tokenizer to use. Stored as a copy. If you change `model.tokenizer`
in place, assign it again (`model.tokenizer = model.tokenizer`) for `encode` to use the changes.
:param config: Any metadata config. Stored as a copy, so mutating it afterwards does not affect
the model, and vice versa.
:param normalize: Whether to normalize the embeddings. Defaults to False. This value is authoritative:
it is written to `config["normalize"]`, and any conflicting value already in `config` is overridden.
:param base_model_name: The used base model name. Used for creating a model card.
:param language: The language of the model. Used for creating a model card.
:param max_length: The default maximum sequence length (in tokens) used by `encode` when its own
`max_length` argument is not passed. Defaults to 512; pass None to disable truncation. This value
is authoritative: it is written to `config["max_length"]`, and any conflicting value already in
`config` is overridden.
"""
super().__init__()
tokens, _ = zip(*sorted(tokenizer.get_vocab().items(), key=lambda x: x[1]))
self.tokens = tokens

self.tokenizer = copy.deepcopy(tokenizer)
_disable_padding(self.tokenizer)
self.unk_token_id = _get_unk_token_id(self.tokenizer)

self.median_token_length = int(np.median([len(token) for token in self.tokens]))
self.config: ConfigT = cast(ConfigT, {**config} if config is not None else {})
self.base_model_name = base_model_name
self.language = language
self.max_length = max_length
self.normalize = normalize

@property
def tokenizer(self) -> Tokenizer:
"""The tokenizer."""
return self._tokenizer

@tokenizer.setter
def tokenizer(self, value: Tokenizer) -> None:
self._tokenizer = value

@property
def normalize(self) -> bool:
"""Get the normalize value.

:return: The normalize value.
"""
return self._normalize

@normalize.setter
def normalize(self, value: bool) -> None:
"""Update the config."""
self._normalize = value
self._update_config("normalize", value)

@property
def max_length(self) -> int | None:
"""Get the max_length value.

:return: The max_length value.
"""
return self._max_length

@max_length.setter
def max_length(self, value: int | None) -> None:
"""Update the config."""
self._max_length = value
self._update_config("max_length", value)
self._set_max_length_in_tokenizer(value)

def _update_config(self, key: str, value: Any) -> None:
"""Write a value to the config, warning if it conflicts with the value already there."""
config = cast(dict[str, Any], self.config)
config_value = config.get(key)
if config_value is not None and value != config_value:
logger.warning(
f"Set {key} to `{value}`, which does not match config value `{config_value}`. Updating config."
)
config[key] = value

@abstractmethod
def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None:
"""Save the pretrained model.

:param path: The path to save to.
:param model_name: The model name to use in the Model Card.
:param subfolder: The subfolder to save to.
"""

def tokenize(self, sentences: Sequence[str]) -> list[list[int]]:
"""Tokenize a list of sentences.

:param sentences: The sentences to tokenize.
:return: A list of list of tokens.
"""
encodings: list[Encoding] = self.tokenizer.encode_batch_fast(sentences, add_special_tokens=False)

encodings_ids = [encoding.ids for encoding in encodings]

if self.unk_token_id is not None:
# NOTE: Remove the unknown token: necessary for word-level models.
encodings_ids = [
[token_id for token_id in token_ids if token_id != self.unk_token_id] for token_ids in encodings_ids
]

return encodings_ids

def _tokenize_truncated(self, sentences: list[str], max_length: int | None) -> list[list[int]]:
"""Tokenize sentences, truncated to `max_length` tokens, or not truncated if `max_length` is None."""
if max_length is not None:
m = max_length * self.median_token_length
sentences = [sentence[:m] for sentence in sentences]

self._set_max_length_in_tokenizer(max_length)
try:
return self.tokenize(sentences)
finally:
self._set_max_length_in_tokenizer(self.max_length)

def _set_max_length_in_tokenizer(self, max_length: int | None) -> None:
"""Sets the max length in the tokenizer."""
if max_length is None:
self.tokenizer.no_truncation()
else:
self.tokenizer.enable_truncation(max_length)

def push_to_hub(
self, repo_id: str, private: bool = False, token: str | None = None, subfolder: str | None = None
) -> None:
"""Push the model to the huggingface hub.

NOTE: you need to pass a token if you are pushing a private model.

:param repo_id: The repo id to push to.
:param private: Whether the repo, if created is set to private.
If the repo already exists, this doesn't change the visibility.
:param token: The huggingface token to use.
:param subfolder: The subfolder to push to.
"""
from model2vec.persistence import push_folder_to_hub

with TemporaryDirectory() as temp_dir:
self.save_pretrained(temp_dir, model_name=repo_id)
push_folder_to_hub(Path(temp_dir), subfolder=subfolder, repo_id=repo_id, private=private, token=token)


def _disable_padding(tokenizer: Tokenizer) -> None:
"""Stop the tokenizer from padding, while keeping its pad token."""
padding = tokenizer.padding
if padding is not None:
tokenizer.enable_padding(
pad_id=padding["pad_id"], pad_token=padding["pad_token"], pad_type_id=padding["pad_type_id"], length=0
)


def _get_unk_token_id(tokenizer: Tokenizer) -> int | None:
"""Get the unk token id."""
model = tokenizer.model
# Wordpiece + BPE + Word level
if hasattr(model, "unk_token"):
token = model.unk_token
if token is None:
return None
return tokenizer.token_to_id(token)
# Unigram
return json.loads(tokenizer.to_str())["model"].get("unk_id")
Loading
Loading