model2vec 0.1.2__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. model2vec-0.2.0/.github/workflows/ci.yaml +58 -0
  2. {model2vec-0.1.2 → model2vec-0.2.0}/.gitignore +0 -2
  3. {model2vec-0.1.2 → model2vec-0.2.0}/.pre-commit-config.yaml +2 -0
  4. {model2vec-0.1.2 → model2vec-0.2.0}/PKG-INFO +38 -9
  5. {model2vec-0.1.2 → model2vec-0.2.0}/README.md +38 -9
  6. model2vec-0.2.0/assets/images/logo.png +0 -0
  7. model2vec-0.2.0/assets/images/model2vec_model_diagram.png +0 -0
  8. model2vec-0.2.0/assets/images/tutorial_ezlo.png +0 -0
  9. model2vec-0.2.0/model2vec/distill/__main__.py +53 -0
  10. model2vec-0.2.0/model2vec/distill/distillation.py +171 -0
  11. model2vec-0.2.0/model2vec/distill/inference.py +130 -0
  12. model2vec-0.2.0/model2vec/distill/tokenizer.py +80 -0
  13. {model2vec-0.1.2 → model2vec-0.2.0}/model2vec/model.py +34 -19
  14. model2vec-0.2.0/model2vec/model_card_template.md +70 -0
  15. model2vec-0.2.0/model2vec/utils.py +215 -0
  16. {model2vec-0.1.2 → model2vec-0.2.0}/model2vec.egg-info/PKG-INFO +38 -9
  17. {model2vec-0.1.2 → model2vec-0.2.0}/model2vec.egg-info/SOURCES.txt +14 -1
  18. {model2vec-0.1.2 → model2vec-0.2.0}/model2vec.egg-info/requires.txt +1 -1
  19. {model2vec-0.1.2 → model2vec-0.2.0}/pyproject.toml +7 -2
  20. model2vec-0.2.0/tests/conftest.py +71 -0
  21. model2vec-0.2.0/tests/data/test_tokenizer/special_tokens_map.json +7 -0
  22. model2vec-0.2.0/tests/data/test_tokenizer/tokenizer.json +30684 -0
  23. model2vec-0.2.0/tests/data/test_tokenizer/tokenizer_config.json +57 -0
  24. model2vec-0.2.0/tests/test_distillation.py +152 -0
  25. {model2vec-0.1.2 → model2vec-0.2.0}/tests/test_model.py +2 -1
  26. model2vec-0.2.0/tests/test_utils.py +25 -0
  27. model2vec-0.2.0/tutorials/README.md +14 -0
  28. model2vec-0.2.0/tutorials/recipe_search.ipynb +500 -0
  29. {model2vec-0.1.2 → model2vec-0.2.0}/uv.lock +7 -76
  30. model2vec-0.1.2/model2vec/distill/__main__.py +0 -133
  31. model2vec-0.1.2/model2vec/distill/inference.py +0 -124
  32. model2vec-0.1.2/model2vec/distill/tokenizer.py +0 -73
  33. model2vec-0.1.2/model2vec/utils.py +0 -114
  34. model2vec-0.1.2/tests/conftest.py +0 -29
  35. {model2vec-0.1.2 → model2vec-0.2.0}/LICENSE +0 -0
  36. {model2vec-0.1.2 → model2vec-0.2.0}/Makefile +0 -0
  37. {model2vec-0.1.2 → model2vec-0.2.0}/assets/images/sentences_per_second_vs_average_score.png +0 -0
  38. {model2vec-0.1.2 → model2vec-0.2.0}/assets/images/speed_vs_accuracy.png +0 -0
  39. {model2vec-0.1.2 → model2vec-0.2.0}/model2vec/__init__.py +0 -0
  40. {model2vec-0.1.2 → model2vec-0.2.0}/model2vec/distill/__init__.py +0 -0
  41. {model2vec-0.1.2 → model2vec-0.2.0}/model2vec.egg-info/dependency_links.txt +0 -0
  42. {model2vec-0.1.2 → model2vec-0.2.0}/model2vec.egg-info/top_level.txt +0 -0
  43. {model2vec-0.1.2 → model2vec-0.2.0}/setup.cfg +0 -0
  44. {model2vec-0.1.2 → model2vec-0.2.0}/tests/__init__.py +0 -0
@@ -0,0 +1,58 @@
1
+ name: Run tests and upload coverage
2
+
3
+ on:
4
+ push
5
+
6
+ jobs:
7
+ test:
8
+ name: Run tests with pytest
9
+ runs-on: ${{ matrix.os }}
10
+ strategy:
11
+ matrix:
12
+ os: ["ubuntu-latest", "windows-latest"]
13
+ python-version: ["3.10"]
14
+ fail-fast: false
15
+
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }}
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: ${{ matrix.python-version }}
23
+ allow-prereleases: true
24
+
25
+ # Step for Windows: Create and activate a virtual environment
26
+ - name: Create and activate a virtual environment (Windows)
27
+ if: ${{ runner.os == 'Windows' }}
28
+ run: |
29
+ irm https://astral.sh/uv/install.ps1 | iex
30
+ uv venv .venv
31
+ "VIRTUAL_ENV=.venv" | Out-File -FilePath $env:GITHUB_ENV -Append
32
+ "$PWD/.venv/Scripts" | Out-File -FilePath $env:GITHUB_PATH -Append
33
+
34
+ # Step for Unix: Create and activate a virtual environment
35
+ - name: Create and activate a virtual environment (Unix)
36
+ if: ${{ runner.os != 'Windows' }}
37
+ run: |
38
+ curl -LsSf https://astral.sh/uv/install.sh | sh
39
+ uv venv .venv
40
+ echo "VIRTUAL_ENV=.venv" >> $GITHUB_ENV
41
+ echo "$PWD/.venv/bin" >> $GITHUB_PATH
42
+
43
+ # Install dependencies using uv pip
44
+ - name: Install dependencies
45
+ run: make install
46
+ # run: uv pip install -e ".[pytest]"
47
+
48
+ # Run tests with coverage
49
+ - name: Run tests under coverage
50
+ run: |
51
+ coverage run -m pytest
52
+ coverage report
53
+
54
+ # Upload results to Codecov
55
+ - name: Upload results to Codecov
56
+ uses: codecov/codecov-action@v4
57
+ with:
58
+ token: ${{ secrets.CODECOV_TOKEN }}
@@ -1,5 +1,3 @@
1
- local/*
2
-
3
1
  # Byte-compiled / optimized / DLL files
4
2
  __pycache__/
5
3
  *.py[cod]
@@ -15,6 +15,8 @@ repos:
15
15
  description: Prevent giant files from being committed.
16
16
  - id: check-case-conflict
17
17
  description: Check for files with names that would conflict on case-insensitive filesystems like MacOS/Windows.
18
+ - id: check-yaml
19
+ description: Check yaml files for syntax errors.
18
20
  - repo: https://github.com/jsh9/pydoclint
19
21
  rev: 0.5.3
20
22
  hooks:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: model2vec
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: Distill a Small Fast Model from any Sentence Transformer
5
5
  Author-email: Stéphan Tulkens <stephantul@gmail.com>, Thomas van Dongen <thomas123@live.nl>
6
6
  License: MIT License
@@ -49,9 +49,9 @@ Requires-Dist: tqdm
49
49
  Requires-Dist: typer
50
50
  Requires-Dist: transformers
51
51
  Requires-Dist: torch
52
- Requires-Dist: sentence_transformers
53
52
  Requires-Dist: tokenizers
54
53
  Requires-Dist: scikit-learn
54
+ Requires-Dist: setuptools
55
55
  Provides-Extra: dev
56
56
  Requires-Dist: black; extra == "dev"
57
57
  Requires-Dist: ipython; extra == "dev"
@@ -61,14 +61,43 @@ Requires-Dist: pytest; extra == "dev"
61
61
  Requires-Dist: pytest-coverage; extra == "dev"
62
62
  Requires-Dist: ruff; extra == "dev"
63
63
 
64
- # Model2Vec: Distill a Small Fast Model from any Sentence Transformer
65
64
 
66
- **Model2Vec** is a method to distill a small, fast model from any Sentence Transformer model.
65
+ <div align="center">
66
+ <picture>
67
+ <img width="50%" alt="Model2Vec logo" src="assets/images/logo.png">
68
+ </picture>
69
+ </a>
70
+ </div>
67
71
 
68
- | ![Description](assets/images/speed_vs_accuracy.png) |
69
- |:--:|
70
- |*Model2vec allows you to create really fast small models that still perform well.*|
72
+ <div align="center">
73
+ <h2>Distill a Small Fast Model from any Sentence Transformer</h2>
74
+ </div>
75
+
76
+ <div align="center">
77
+ <h2>
78
+ <a href="https://huggingface.co/minishlab"><strong>🤗 Models</strong></a> |
79
+ <a href="https://github.com/MinishLab/model2vec/tree/main/tutorials"><strong>📚 Tutorials</strong></a> |
80
+ <a href="https://github.com/MinishLab"><strong>📖 Website </strong></a>
81
+ </h2>
82
+ </div>
83
+
84
+ <div align="center">
85
+ <h2>
86
+ <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/v/model2vec?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
87
+ <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/pyversions/model2vec" alt="Supported Python versions"></a>
88
+ <a href="https://pepy.tech/project/model2vec">
89
+ <img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
90
+ </a>
91
+ <a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
92
+ </h2>
93
+ </div>
94
+
95
+
96
+ <p align="center">
97
+ <img width="75%", src="assets/images/model2vec_model_diagram.png" alt="Model2Vec">
98
+ </p>
71
99
 
100
+ Model2Vec is a technique to turn any sentence transformer into a really small fast model, reducing model size by 15x and making the models up to 500x faster, with a small drop in performance. See our results [here](#classification-and-speed-benchmarks), or dive in to see how it works.
72
101
 
73
102
  ## Table of Contents
74
103
  - [Quickstart](#quickstart)
@@ -104,7 +133,7 @@ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to ever
104
133
 
105
134
  And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
106
135
 
107
- Instead of using on of our models, you can distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
136
+ Instead of using one of our models, you can distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
108
137
  ```python
109
138
  from model2vec.distill import distill
110
139
 
@@ -324,7 +353,7 @@ MIT
324
353
 
325
354
  If you use Model2Vec in your research, please cite the following:
326
355
  ```bibtex
327
- @software{minishlab2024word2vec,
356
+ @software{minishlab2024model2vec,
328
357
  authors = {Stephan Tulkens, Thomas van Dongen},
329
358
  title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
330
359
  year = {2024},
@@ -1,11 +1,40 @@
1
- # Model2Vec: Distill a Small Fast Model from any Sentence Transformer
2
-
3
- **Model2Vec** is a method to distill a small, fast model from any Sentence Transformer model.
4
-
5
- | ![Description](assets/images/speed_vs_accuracy.png) |
6
- |:--:|
7
- |*Model2vec allows you to create really fast small models that still perform well.*|
8
1
 
2
+ <div align="center">
3
+ <picture>
4
+ <img width="50%" alt="Model2Vec logo" src="assets/images/logo.png">
5
+ </picture>
6
+ </a>
7
+ </div>
8
+
9
+ <div align="center">
10
+ <h2>Distill a Small Fast Model from any Sentence Transformer</h2>
11
+ </div>
12
+
13
+ <div align="center">
14
+ <h2>
15
+ <a href="https://huggingface.co/minishlab"><strong>🤗 Models</strong></a> |
16
+ <a href="https://github.com/MinishLab/model2vec/tree/main/tutorials"><strong>📚 Tutorials</strong></a> |
17
+ <a href="https://github.com/MinishLab"><strong>📖 Website </strong></a>
18
+ </h2>
19
+ </div>
20
+
21
+ <div align="center">
22
+ <h2>
23
+ <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/v/model2vec?color=%23007ec6&label=pypi%20package" alt="Package version"></a>
24
+ <a href="https://pypi.org/project/model2vec/"><img src="https://img.shields.io/pypi/pyversions/model2vec" alt="Supported Python versions"></a>
25
+ <a href="https://pepy.tech/project/model2vec">
26
+ <img src="https://static.pepy.tech/badge/model2vec" alt="Downloads">
27
+ </a>
28
+ <a href="https://github.com/MinishLab/model2vec/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License - MIT"></a>
29
+ </h2>
30
+ </div>
31
+
32
+
33
+ <p align="center">
34
+ <img width="75%", src="assets/images/model2vec_model_diagram.png" alt="Model2Vec">
35
+ </p>
36
+
37
+ Model2Vec is a technique to turn any sentence transformer into a really small fast model, reducing model size by 15x and making the models up to 500x faster, with a small drop in performance. See our results [here](#classification-and-speed-benchmarks), or dive in to see how it works.
9
38
 
10
39
  ## Table of Contents
11
40
  - [Quickstart](#quickstart)
@@ -41,7 +70,7 @@ embeddings = model.encode(["It's dangerous to go alone!", "It's a secret to ever
41
70
 
42
71
  And that's it. You can use the model to classify texts, to cluster, or to build a RAG system.
43
72
 
44
- Instead of using on of our models, you can distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
73
+ Instead of using one of our models, you can distill your own Model2Vec model from a Sentence Transformer model. The following code snippet shows how to distill a model:
45
74
  ```python
46
75
  from model2vec.distill import distill
47
76
 
@@ -261,7 +290,7 @@ MIT
261
290
 
262
291
  If you use Model2Vec in your research, please cite the following:
263
292
  ```bibtex
264
- @software{minishlab2024word2vec,
293
+ @software{minishlab2024model2vec,
265
294
  authors = {Stephan Tulkens, Thomas van Dongen},
266
295
  title = {Model2Vec: Turn any Sentence Transformer into a Small Fast Model},
267
296
  year = {2024},
Binary file
@@ -0,0 +1,53 @@
1
+ import logging
2
+ from pathlib import Path
3
+ from typing import Annotated, Optional
4
+
5
+ import typer
6
+
7
+ from model2vec.distill.distillation import distill
8
+ from model2vec.utils import setup_logging
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ app = typer.Typer()
13
+
14
+
15
+ @app.command()
16
+ def main(
17
+ model_name: Annotated[str, typer.Option(help="The model name to initialize the embedder model with.")],
18
+ save_path: Annotated[str, typer.Option(help="The folder to save the model to.")],
19
+ vocabulary_path: Annotated[
20
+ Optional[str],
21
+ typer.Option(
22
+ help="The path to the vocabulary file, which is a .txt file with one word per line. If this is not passed, we use the model's vocabulary."
23
+ ),
24
+ ] = None,
25
+ device: Annotated[str, typer.Option(help="The device to train the model on.")] = "cpu",
26
+ pca_dims: Annotated[
27
+ int | None, typer.Option(help="The PCA dimensionality to use. If this is None, no PCA is applied.")
28
+ ] = 256,
29
+ apply_zipf: Annotated[bool, typer.Option(help="Whether to apply Zipf weighting.")] = True,
30
+ use_subword: Annotated[
31
+ bool, typer.Option(help="Whether to use subword tokenization. If this is False, you must pass a vocabulary.")
32
+ ] = True,
33
+ ) -> None:
34
+ """Creates output embeddings for a sentencetransformer."""
35
+ if vocabulary_path is not None:
36
+ vocabulary = open(vocabulary_path).read().splitlines()
37
+ else:
38
+ vocabulary = None
39
+
40
+ model = distill(
41
+ model_name=model_name,
42
+ vocabulary=vocabulary,
43
+ device=device,
44
+ pca_dims=pca_dims,
45
+ apply_zipf=apply_zipf,
46
+ use_subword=use_subword,
47
+ )
48
+ model.save_pretrained(Path(save_path))
49
+
50
+
51
+ if __name__ == "__main__":
52
+ setup_logging()
53
+ typer.run(main)
@@ -0,0 +1,171 @@
1
+ import logging
2
+
3
+ import numpy as np
4
+ from huggingface_hub import model_info
5
+ from sklearn.decomposition import PCA
6
+ from transformers import AutoModel, AutoTokenizer, PreTrainedModel, PreTrainedTokenizerFast
7
+
8
+ from model2vec.distill.inference import (
9
+ create_output_embeddings_from_model_name,
10
+ create_output_embeddings_from_model_name_and_tokens,
11
+ )
12
+ from model2vec.distill.tokenizer import add_tokens, preprocess_vocabulary, remove_tokens
13
+ from model2vec.model import StaticModel
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def distill(
19
+ model_name: str,
20
+ vocabulary: list[str] | None = None,
21
+ device: str = "cpu",
22
+ pca_dims: int | None = 256,
23
+ apply_zipf: bool = True,
24
+ use_subword: bool = True,
25
+ ) -> StaticModel:
26
+ """
27
+ Distill a staticmodel from a sentence transformer.
28
+
29
+ This function creates a set of embeddings from a sentence transformer. It does this by doing either
30
+ a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed vocabulary.
31
+
32
+ If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.
33
+ If you don't pass a vocabulary, we use the model's tokenizer directly.
34
+
35
+ :param model_name: The model name to use. Any sentencetransformer compatible model works.
36
+ :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.
37
+ :param device: The device to use.
38
+ :param pca_dims: The number of components to use for PCA. If this is None, we don't apply PCA.
39
+ :param apply_zipf: Whether to apply Zipf weighting to the embeddings.
40
+ :param use_subword: Whether to keep subword tokens in the vocabulary. If this is False, you must pass a vocabulary, and the returned tokenizer will only detect full words.
41
+ :raises: ValueError if the PCA dimension is larger than the number of dimensions in the embeddings.
42
+ :raises: ValueError if the vocabulary contains duplicate tokens.
43
+ :return: A StaticModel
44
+
45
+ """
46
+ if not use_subword and vocabulary is None:
47
+ raise ValueError(
48
+ "You must pass a vocabulary if you don't use subword tokens. Either pass a vocabulary, or set use_subword to True."
49
+ )
50
+
51
+ # Load original tokenizer. We need to keep this to tokenize any tokens in the vocabulary.
52
+ original_tokenizer: PreTrainedTokenizerFast = AutoTokenizer.from_pretrained(model_name)
53
+ original_model: PreTrainedModel = AutoModel.from_pretrained(model_name)
54
+ # Make a base list of tokens.
55
+ tokens: list[str] = []
56
+ if use_subword:
57
+ # Create the subword embeddings.
58
+ tokens, embeddings = create_output_embeddings_from_model_name(
59
+ model=original_model, tokenizer=original_tokenizer, device=device
60
+ )
61
+
62
+ # Remove any unused tokens from the tokenizer and embeddings.
63
+ wrong_tokens = [x for x in tokens if x.startswith("[unused")]
64
+ vocab = original_tokenizer.get_vocab()
65
+ # Get the ids of the unused token.
66
+ wrong_token_ids = [vocab[token] for token in wrong_tokens]
67
+ # Remove the unused tokens from the tokenizer.
68
+ new_tokenizer = remove_tokens(original_tokenizer.backend_tokenizer, wrong_tokens)
69
+ # Remove the embeddings of the unused tokens.
70
+ embeddings = np.delete(embeddings, wrong_token_ids, axis=0)
71
+ logger.info(f"Removed {len(wrong_tokens)} unused tokens from the tokenizer and embeddings.")
72
+ else:
73
+ # We need to keep the unk token in the tokenizer.
74
+ unk_token = original_tokenizer.backend_tokenizer.model.unk_token
75
+ # Remove all tokens except the UNK token.
76
+ new_tokenizer = remove_tokens(
77
+ original_tokenizer.backend_tokenizer, list(set(original_tokenizer.get_vocab()) - {unk_token})
78
+ )
79
+ # We need to set embeddings to None because we don't know the dimensions of the embeddings yet.
80
+ embeddings = None
81
+
82
+ if vocabulary is not None:
83
+ # Preprocess the vocabulary with the original tokenizer.
84
+ preprocessed_vocabulary = preprocess_vocabulary(original_tokenizer.backend_tokenizer, vocabulary)
85
+ n_tokens_before = len(preprocessed_vocabulary)
86
+ # Clean the vocabulary by removing duplicate tokens and tokens that are in the subword vocabulary.
87
+ cleaned_vocabulary = _clean_vocabulary(preprocessed_vocabulary, tokens)
88
+ n_tokens_after = len(cleaned_vocabulary)
89
+ logger.info(
90
+ f"Adding {n_tokens_after} tokens to the vocabulary. Removed {n_tokens_before - n_tokens_after} tokens during preprocessing."
91
+ )
92
+ # Only create embeddings if we have tokens to add.
93
+ if cleaned_vocabulary:
94
+ # Create the embeddings.
95
+ _, token_embeddings = create_output_embeddings_from_model_name_and_tokens(
96
+ model=original_model,
97
+ tokenizer=original_tokenizer,
98
+ tokens=cleaned_vocabulary,
99
+ device=device,
100
+ )
101
+
102
+ # If we don't have subword tokens, we still need to create
103
+ # some embeddings for [UNK] and some other special tokens.
104
+ if embeddings is None:
105
+ embeddings = np.zeros((new_tokenizer.get_vocab_size(), token_embeddings.shape[1]))
106
+ embeddings = np.concatenate([embeddings, token_embeddings], axis=0)
107
+ # Add the cleaned vocabulary to the tokenizer.
108
+ new_tokenizer = add_tokens(new_tokenizer, cleaned_vocabulary)
109
+ else:
110
+ logger.warning("Didn't create any token embeddings as all tokens were duplicates or empty.")
111
+
112
+ # Post process the embeddings by applying PCA and Zipf weighting.
113
+ embeddings = _post_process_embeddings(np.asarray(embeddings), pca_dims, apply_zipf)
114
+
115
+ config = {"tokenizer_name": model_name, "apply_pca": pca_dims, "apply_zipf": apply_zipf}
116
+ # Get the language from the model card
117
+ info = model_info(model_name)
118
+ language = info.cardData.get("language")
119
+
120
+ return StaticModel(
121
+ vectors=embeddings, tokenizer=new_tokenizer, config=config, base_model_name=model_name, language=language
122
+ )
123
+
124
+
125
+ def _post_process_embeddings(embeddings: np.ndarray, pca_dims: int | None, apply_zipf: bool) -> np.ndarray:
126
+ """Post process embeddings by applying PCA and Zipf weighting."""
127
+ if pca_dims is not None:
128
+ if pca_dims >= embeddings.shape[1]:
129
+ raise ValueError(
130
+ f"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]})"
131
+ )
132
+ if pca_dims >= embeddings.shape[0]:
133
+ logger.warning(
134
+ f"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA."
135
+ )
136
+ elif pca_dims < embeddings.shape[1]:
137
+ logger.info(f"Applying PCA with n_components {pca_dims}")
138
+
139
+ p = PCA(n_components=pca_dims, whiten=False)
140
+ embeddings = p.fit_transform(embeddings)
141
+
142
+ if apply_zipf:
143
+ logger.info("Applying Zipf weighting")
144
+ embeddings *= np.log(1 + np.arange(embeddings.shape[0]))[:, None]
145
+
146
+ return embeddings
147
+
148
+
149
+ def _clean_vocabulary(preprocessed_vocabulary: list[str], added_tokens: list[str]) -> list[str]:
150
+ """Cleans a vocabulary by removing duplicates and tokens that were already in the vocabulary."""
151
+ added_tokens_set = set(added_tokens)
152
+ seen_tokens = set()
153
+ cleaned_vocabulary = []
154
+ n_empty = 0
155
+ n_duplicates = 0
156
+ for token in preprocessed_vocabulary:
157
+ if not token:
158
+ n_empty += 1
159
+ continue
160
+ if token in seen_tokens or token in added_tokens_set:
161
+ n_duplicates += 1
162
+ continue
163
+ seen_tokens.add(token)
164
+ cleaned_vocabulary.append(token)
165
+
166
+ if n_duplicates:
167
+ logger.warning(f"Removed {n_duplicates} duplicate tokens.")
168
+ if n_empty:
169
+ logger.warning(f"Removed {n_empty} empty tokens.")
170
+
171
+ return cleaned_vocabulary
@@ -0,0 +1,130 @@
1
+ # -*- coding: utf-8 -*-
2
+ import logging
3
+ from pathlib import Path
4
+ from typing import Protocol
5
+
6
+ import numpy as np
7
+ import torch
8
+ from tqdm import tqdm
9
+ from transformers import PreTrainedModel, PreTrainedTokenizer
10
+ from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ PathLike = str | Path
16
+
17
+ _DEFAULT_BATCH_SIZE = 1024
18
+
19
+
20
+ class ModulewithWeights(Protocol):
21
+ weight: torch.nn.Parameter
22
+
23
+
24
+ def create_output_embeddings_from_model_name_and_tokens(
25
+ model: PreTrainedModel,
26
+ tokenizer: PreTrainedTokenizer,
27
+ tokens: list[str],
28
+ device: str,
29
+ ) -> tuple[list[str], np.ndarray]:
30
+ """
31
+ Create output embeddings for a bunch of tokens from a model name.
32
+
33
+ It does a forward pass for all tokens passed in tokens.
34
+
35
+ :param model: The model name to use.
36
+ :param tokenizer: The tokenizer to use.
37
+ :param tokens: The tokens to use.
38
+ :param device: The torch device to use.
39
+ :return: The tokens and output embeddings.
40
+ """
41
+ model = model.to(device)
42
+
43
+ out_weights: np.ndarray
44
+ intermediate_weights: list[np.ndarray] = []
45
+
46
+ for batch_idx in tqdm(range(0, len(tokens), _DEFAULT_BATCH_SIZE)):
47
+ batch = tokens[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]
48
+ out = _encode_mean_using_model(model, tokenizer, batch)
49
+ intermediate_weights.append(out.numpy())
50
+ out_weights = np.concatenate(intermediate_weights)
51
+
52
+ return tokens, out_weights
53
+
54
+
55
+ @torch.no_grad()
56
+ def _encode_mean_using_model(model: PreTrainedModel, tokenizer: PreTrainedTokenizer, tokens: list[str]) -> torch.Tensor:
57
+ """
58
+ Encode a batch of tokens using a model.
59
+
60
+ Note that if a token in the input batch does not have any embeddings, it will be output as a vector of zeros.
61
+ So detection of these is necessary.
62
+
63
+ :param model: The model to use.
64
+ :param tokenizer: The tokenizer to use.
65
+ :param tokens: The tokens to encode.
66
+ :return: The mean of the output for each token.
67
+ """
68
+ encodings = tokenizer(tokens, return_tensors="pt", padding=True, truncation=True).to(model.device)
69
+ encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(**encodings)
70
+ out = encoded.last_hidden_state.cpu()
71
+
72
+ mask = encodings["attention_mask"].cpu()
73
+ # NOTE: evil hack. For any batch, there will be a mask vector
74
+ # which has all 1s, because we pad to max_length. argmin returns 0
75
+ # in this case, which is wrong. But because we end up subtracting 1
76
+ # from it, we use -1, which is correct.
77
+ last_nonzero_index = mask.argmin(1) - 1
78
+ # NOTE: do not change the order of these calls. If you do, the hack
79
+ # above will no longer be evil (it will turn good), and will no longer work.
80
+ mask[torch.arange(mask.shape[0]), last_nonzero_index] = 0
81
+ mask[:, 0] = 0
82
+
83
+ # We take the mean of embeddings by first summing
84
+ result = torch.bmm(mask[:, None, :].float(), out).squeeze(1)
85
+
86
+ # Divide by the number of non-padding tokens, non-cls, etc. tokens.
87
+ divisor = mask.sum(1)
88
+ # Account for the case where divisor is 0.
89
+ divisor[divisor == 0] = 1
90
+
91
+ return result / divisor[:, None]
92
+
93
+
94
+ def create_output_embeddings_from_model_name(
95
+ model: PreTrainedModel,
96
+ tokenizer: PreTrainedTokenizer,
97
+ device: str,
98
+ ) -> tuple[list[str], np.ndarray]:
99
+ """
100
+ Create output embeddings for a bunch of tokens from a model name.
101
+
102
+ It does a forward pass for all ids in the tokenizer.
103
+
104
+ :param model: The model name to use.
105
+ :param tokenizer: The tokenizer to use.
106
+ :param device: The torch device to use.
107
+ :return: The tokens and output embeddings.
108
+ """
109
+ model = model.to(device)
110
+ ids = torch.arange(tokenizer.vocab_size)
111
+
112
+ # Work-around to get the eos and bos token ids without having to go into tokenizer internals.
113
+ dummy_encoding = tokenizer.encode("A")
114
+ eos_token_id, bos_token_id = dummy_encoding[0], dummy_encoding[-1]
115
+
116
+ eos = torch.full([len(ids)], fill_value=eos_token_id)
117
+ bos = torch.full([len(ids)], fill_value=bos_token_id)
118
+
119
+ stacked = torch.stack([bos, ids, eos], dim=1)
120
+
121
+ intermediate_weights: list[np.ndarray] = []
122
+ for batch_idx in tqdm(range(0, len(stacked), _DEFAULT_BATCH_SIZE)):
123
+ batch = stacked[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE].to(model.device)
124
+ with torch.no_grad():
125
+ encoded: BaseModelOutputWithPoolingAndCrossAttentions = model(input_ids=batch.to(device))
126
+ out: torch.Tensor = encoded.last_hidden_state
127
+ intermediate_weights.append(out[:, 1].cpu().numpy())
128
+ out_weights = np.concatenate(intermediate_weights)
129
+
130
+ return tokenizer.convert_ids_to_tokens(ids), out_weights
@@ -0,0 +1,80 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+
6
+ from tokenizers import Tokenizer
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def preprocess_vocabulary(tokenizer: Tokenizer, vocabulary: list[str]) -> list[str]:
12
+ """Preprocess a vocabulary with a tokenizer by doing a roundtrip encode/decode."""
13
+ encoded_ids: list[list[int]] = [
14
+ encoding.ids for encoding in tokenizer.encode_batch(vocabulary, add_special_tokens=False)
15
+ ]
16
+ return tokenizer.decode_batch(encoded_ids)
17
+
18
+
19
+ def remove_tokens(tokenizer: Tokenizer, tokens_to_remove: list[str]) -> Tokenizer:
20
+ """
21
+ Remove tokens from a tokenizer.
22
+
23
+ :param tokenizer: The tokenizer to remove tokens from.
24
+ :param tokens_to_remove: The tokens to remove.
25
+ :return: The modified tokenizer.
26
+ """
27
+ tokenizer_data = json.loads(tokenizer.to_str())
28
+
29
+ # Find all added tokens
30
+ added_tokens = tokenizer_data["added_tokens"]
31
+ added_tokens_str = {token["content"] for token in added_tokens}
32
+
33
+ # Remove all added tokens from the list of tokens to remove.
34
+ # Things will go bad if we keep them.
35
+ tokens_to_remove = [token for token in tokens_to_remove if token not in added_tokens_str]
36
+
37
+ # Load the vocabulary.
38
+ vocab: dict[str, int] = tokenizer_data["model"]["vocab"]
39
+ n_tokens = len(vocab)
40
+
41
+ # Remove the tokens.
42
+ for token in tokens_to_remove:
43
+ if vocab.pop(token, None) is None:
44
+ logger.warning(f"Token {token} was not in the vocabulary.")
45
+
46
+ n_removed = n_tokens - len(vocab)
47
+ logger.info(f"Removed {n_removed} tokens from the vocabulary.")
48
+
49
+ # Reindex the vocabulary so that it is contiguous.
50
+ reindexed = {token: idx for idx, (token, _) in enumerate(sorted(vocab.items(), key=lambda x: x[1]))}
51
+ tokenizer_data["model"]["vocab"] = reindexed
52
+
53
+ # Reindex the special tokens (i.e., CLS and SEP for BertTokenizers.)
54
+ special_tokens_post_processor: dict[str, dict] = tokenizer_data["post_processor"]["special_tokens"]
55
+ for token, token_data in special_tokens_post_processor.items():
56
+ token_data["ids"] = [reindexed[token] for token in token_data["tokens"]]
57
+
58
+ # Reinitialize the tokenizer from the json.
59
+ tokenizer = Tokenizer.from_str(json.dumps(tokenizer_data))
60
+
61
+ return tokenizer
62
+
63
+
64
+ def add_tokens(tokenizer: Tokenizer, tokens_to_add: list[str]) -> Tokenizer:
65
+ """
66
+ Add tokens to a tokenizer.
67
+
68
+ :param tokenizer: The tokenizer to add tokens to.
69
+ :param tokens_to_add: The tokens to add.
70
+ :return: The modified tokenizer.
71
+ """
72
+ data = json.loads(tokenizer.to_str())
73
+
74
+ vocab: dict[str, int] = data["model"]["vocab"]
75
+ for token in tokens_to_add:
76
+ vocab[token] = len(vocab)
77
+
78
+ tokenizer = Tokenizer.from_str(json.dumps(data))
79
+
80
+ return tokenizer