RepoPeft-data / oracle_context_cache /MinishLab__model2vec.json
nanigock's picture
Upload folder using huggingface_hub
cd15502 verified
{"repo": "MinishLab/model2vec", "n_pairs": 58, "version": "v2_function_scoped", "contexts": {"tests/test_trainable.py::154": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification"], "enclosing_function": "test_train_test_split", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_model.py::201": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["Path", "StaticModel", "Tokenizer"], "enclosing_function": "test_load_pretrained_quantized", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_distillation.py::210": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["MagicMock", "PreTrainedModel", "StaticModel", "distill", "import_module", "patch", "pytest"], "enclosing_function": "test_distill", "extracted_code": "# Source: model2vec/distill/distillation.py\ndef distill(\n model_name: str,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n trust_remote_code: bool = False,\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model_name: The model name to use. Any sentencetransformer compatible model works.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimenionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming\n from `transformers`. If this is True, we will load all components.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel\n\n \"\"\"\n model: PreTrainedModel = AutoModel.from_pretrained(model_name, trust_remote_code=trust_remote_code)\n tokenizer = cast(\n PreTrainedTokenizerFast,\n AutoTokenizer.from_pretrained(model_name, trust_remote_code=trust_remote_code, use_fast=True),\n )\n\n return distill_from_model(\n model=model,\n tokenizer=tokenizer,\n vocabulary=vocabulary,\n device=device,\n pca_dims=pca_dims,\n token_remove_pattern=token_remove_pattern,\n sif_coefficient=sif_coefficient,\n quantize_to=quantize_to,\n vocabulary_quantization=vocabulary_quantization,\n pooling=pooling,\n )\n\n\n# Source: model2vec/model.py\nclass StaticModel:\n def __init__(\n self,\n vectors: np.ndarray,\n tokenizer: Tokenizer,\n config: dict[str, Any] | None = None,\n normalize: bool | None = None,\n base_model_name: str | None = None,\n language: list[str] | None = None,\n weights: np.ndarray | None = None,\n token_mapping: np.ndarray | None = None,\n ) -> None:\n \"\"\"\n Initialize the StaticModel.\n\n :param vectors: The vectors to use.\n :param tokenizer: The Transformers tokenizer to use.\n :param config: Any metadata config.\n :param normalize: Whether to normalize the embeddings.\n :param base_model_name: The used base model name. Used for creating a model card.\n :param language: The language of the model. Used for creating a model card.\n :param weights: The weights to use for the embeddings. If None, no weights are used.\n We always assume the norm of the embeddings is an implicit weight anyway.\n This is only used for models that have undergone vocabulary quantization.\n :param token_mapping: A mapping from token ids to indices in the vectors.\n If None, we don't remap the tokens during inference.\n This is only used for models that have undergone vocabulary quantization.\n :raises: ValueError if the number of tokens does not match the number of vectors.\n \"\"\"\n super().__init__()\n tokens, _ = zip(*sorted(tokenizer.get_vocab().items(), key=lambda x: x[1]))\n self.tokens = tokens\n\n if token_mapping is None and len(vectors) != len(tokens):\n raise ValueError(\n f\"Number of tokens ({len(tokens)}) does not match number of vectors ({len(vectors)}). \"\n \"Please provide a token mapping or ensure the number of tokens matches the number of vectors.\"\n )\n\n self.embedding = vectors\n self.weights = weights\n # Convert to an array for fast lookups\n # We can't use or short circuit here because np.ndarray as booleans are ambiguous.\n self.token_mapping: np.ndarray | None = token_mapping\n\n self.tokenizer = tokenizer\n self.unk_token_id: int | None\n if hasattr(self.tokenizer.model, \"unk_token\") and self.tokenizer.model.unk_token is not None:\n self.unk_token_id = tokenizer.get_vocab()[self.tokenizer.model.unk_token]\n else:\n self.unk_token_id = None # pragma: no cover # Doesn't actually happen, but can happen.\n\n self.median_token_length = int(np.median([len(token) for token in self.tokens]))\n self.config = config or {}\n self.base_model_name = base_model_name\n self.language = language\n if hasattr(self.tokenizer, \"encode_batch_fast\"):\n self._can_encode_fast = True\n else:\n self._can_encode_fast = False\n\n if normalize is not None:\n self.normalize = normalize\n else:\n self.normalize = self.config.get(\"normalize\", False)\n\n @property\n def dim(self) -> int:\n \"\"\"Get the dimension of the model.\"\"\"\n return self.embedding.shape[1]\n\n @property\n def normalize(self) -> bool:\n \"\"\"\n Get the normalize value.\n\n :return: The normalize value.\n \"\"\"\n return self._normalize\n\n @normalize.setter\n def normalize(self, value: bool) -> None:\n \"\"\"Update the config if the value of normalize changes.\"\"\"\n config_normalize = self.config.get(\"normalize\")\n self._normalize = value\n if config_normalize is not None and value != config_normalize:\n logger.warning(\n f\"Set normalization to `{value}`, which does not match config value `{config_normalize}`. Updating config.\"\n )\n self.config[\"normalize\"] = value\n\n @property\n def embedding_dtype(self) -> str:\n \"\"\"Get the dtype (precision) of the embedding matrix.\"\"\"\n return np.dtype(self.embedding.dtype).name\n\n @property\n def vocabulary_quantization(self) -> int | None:\n \"\"\"Get the number of clusters used for vocabulary quantization, if applicable.\"\"\"\n is_quantized = (self.token_mapping is not None) or (len(self.embedding) != len(self.tokens))\n return int(self.embedding.shape[0]) if is_quantized else None\n\n def save_pretrained(self, path: PathLike, model_name: str | None = None, subfolder: str | None = None) -> None:\n \"\"\"\n Save the pretrained model.\n\n :param path: The path to save to.\n :param model_name: The model name to use in the Model Card.\n :param subfolder: The subfolder to save to.\n \"\"\"\n from model2vec.hf_utils import save_pretrained\n\n save_pretrained(\n folder_path=Path(path),\n embeddings=self.embedding,\n tokenizer=self.tokenizer,\n config=self.config,\n base_model_name=self.base_model_name,\n language=self.language,\n model_name=model_name,\n subfolder=subfolder,\n weights=self.weights,\n mapping=self.token_mapping,\n )\n\n def tokenize(self, sentences: Sequence[str], max_length: int | None = None) -> list[list[int]]:\n \"\"\"\n Tokenize a list of sentences.\n\n :param sentences: The sentences to tokenize.\n :param max_length: The maximum length of the sentences in tokens. If this is None, sequences\n are not truncated.\n :return: A list of list of tokens.\n \"\"\"\n if max_length is not None:\n m = max_length * self.median_token_length\n sentences = [sentence[:m] for sentence in sentences]\n\n if self._can_encode_fast:\n encodings: list[Encoding] = self.tokenizer.encode_batch_fast(sentences, add_special_tokens=False)\n else:\n encodings = self.tokenizer.encode_batch(sentences, add_special_tokens=False)\n\n encodings_ids = [encoding.ids for encoding in encodings]\n\n if self.unk_token_id is not None:\n # NOTE: Remove the unknown token: necessary for word-level models.\n encodings_ids = [\n [token_id for token_id in token_ids if token_id != self.unk_token_id] for token_ids in encodings_ids\n ]\n if max_length is not None:\n encodings_ids = [token_ids[:max_length] for token_ids in encodings_ids]\n\n return encodings_ids\n\n @classmethod\n def from_pretrained(\n cls: type[StaticModel],\n path: PathLike,\n token: str | None = None,\n normalize: bool | None = None,\n subfolder: str | None = None,\n quantize_to: str | DType | None = None,\n dimensionality: int | None = None,\n vocabulary_quantization: int | None = None,\n force_download: bool = True,\n ) -> StaticModel:\n \"\"\"\n Load a StaticModel from a local path or huggingface hub path.\n\n NOTE: if you load a private model from the huggingface hub, you need to pass a token.\n\n :param path: The path to load your static model from.\n :param token: The huggingface token to use.\n :param normalize: Whether to normalize the embeddings.\n :param subfolder: The subfolder to load from.\n :param quantize_to: The dtype to quantize the model to. If None, no quantization is done.\n If a string is passed, it is converted to a DType.\n :param dimensionality: The dimensionality of the model. If this is None, use the dimensionality of the model.\n This is useful if you want to load a model with a lower dimensionality.\n Note that this only applies if you have trained your model using mrl or PCA.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization.\n :param force_download: Whether to force the download of the model. If False, the model is only downloaded if it is not\n already present in the cache.\n :return: A StaticModel.\n \"\"\"\n return _loading_helper(\n cls=cls,\n path=path,\n token=token,\n vocabulary_quantization=vocabulary_quantization,\n quantize_to=quantize_to,\n dimensionality=dimensionality,\n from_sentence_transformers=False,\n normalize=normalize,\n subfolder=subfolder,\n force_download=force_download,\n )\n\n @classmethod\n def from_sentence_transformers(\n cls: type[StaticModel],\n path: PathLike,\n token: str | None = None,\n normalize: bool | None = None,\n quantize_to: str | DType | None = None,\n dimensionality: int | None = None,\n vocabulary_quantization: int | None = None,\n force_download: bool = True,\n ) -> StaticModel:\n \"\"\"\n Load a StaticModel trained with sentence transformers from a local path or huggingface hub path.\n\n NOTE: if you load a private model from the huggingface hub, you need to pass a token.\n\n :param path: The path to load your static model from.\n :param token: The huggingface token to use.\n :param normalize: Whether to normalize the embeddings.\n :param quantize_to: The dtype to quantize the model to. If None, no quantization is done.\n If a string is passed, it is converted to a DType.\n :param dimensionality: The dimensionality of the model. If this is None, use the dimensionality of the model.\n This is useful if you want to load a model with a lower dimensionality.\n Note that this only applies if you have trained your model using mrl or PCA.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization.\n :param force_download: Whether to force the download of the model. If False, the model is only downloaded if it is not\n already present in the cache.\n :return: A StaticModel.\n \"\"\"\n return _loading_helper(\n cls=cls,\n path=path,\n token=token,\n vocabulary_quantization=vocabulary_quantization,\n quantize_to=quantize_to,\n dimensionality=dimensionality,\n from_sentence_transformers=True,\n normalize=normalize,\n subfolder=None,\n force_download=force_download,\n )\n\n @overload\n def encode_as_sequence(\n self,\n sentences: str,\n max_length: int | None = None,\n batch_size: int = 1024,\n show_progress_bar: bool = False,\n use_multiprocessing: bool = True,\n multiprocessing_threshold: int = 10_000,\n ) -> np.ndarray: ...\n\n @overload\n def encode_as_sequence(\n self,\n sentences: list[str],\n max_length: int | None = None,\n batch_size: int = 1024,\n show_progress_bar: bool = False,\n use_multiprocessing: bool = True,\n multiprocessing_threshold: int = 10_000,\n ) -> list[np.ndarray]: ...\n\n def encode_as_sequence(\n self,\n sentences: str | list[str],\n max_length: int | None = None,\n batch_size: int = 1024,\n show_progress_bar: bool = False,\n use_multiprocessing: bool = True,\n multiprocessing_threshold: int = 10_000,\n ) -> list[np.ndarray] | np.ndarray:\n \"\"\"\n Encode a list of sentences as a list of numpy arrays of tokens.\n\n This is useful if you want to use the tokens for further processing, or if you want to do sequence\n modeling.\n Note that if you just want the mean, you should use the `encode` method.\n This is about twice as slow.\n Sentences that do not contain any tokens will be turned into an empty array.\n\n NOTE: the input type is currently underspecified. The actual input type is `Sequence[str] | str`, but this\n is not possible to implement in python typing currently.\n\n :param sentences: The list of sentences to encode.\n :param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated.\n If this is None, no truncation is done.\n :param batch_size: The batch size to use.\n :param show_progress_bar: Whether to show the progress bar.\n :param use_multiprocessing: Whether to use multiprocessing.\n By default, this is enabled for inputs > multiprocessing_threshold sentences and disabled otherwise.\n :param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing.\n :return: The encoded sentences with an embedding per token.\n \"\"\"\n was_single = False\n if isinstance(sentences, str):\n sentences = [sentences]\n was_single = True\n\n # Prepare all batches\n sentence_batches = list(self._batch(sentences, batch_size))\n total_batches = math.ceil(len(sentences) / batch_size)\n\n # Use joblib for multiprocessing if requested, and if we have enough sentences\n if use_multiprocessing and len(sentences) > multiprocessing_threshold:\n # Disable parallelism for tokenizers\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\n results = ProgressParallel(n_jobs=-1, use_tqdm=show_progress_bar, total=total_batches)(\n delayed(self._encode_batch_as_sequence)(batch, max_length) for batch in sentence_batches\n )\n out_array: list[np.ndarray] = []\n for r in results:\n out_array.extend(r)\n else:\n out_array = []\n for batch in tqdm(\n sentence_batches,\n total=total_batches,\n disable=not show_progress_bar,\n ):\n out_array.extend(self._encode_batch_as_sequence(batch, max_length))\n\n if was_single:\n return out_array[0]\n return out_array\n\n def _encode_batch_as_sequence(self, sentences: Sequence[str], max_length: int | None) -> list[np.ndarray]:\n \"\"\"Encode a batch of sentences as a sequence.\"\"\"\n ids = self.tokenize(sentences=sentences, max_length=max_length)\n out: list[np.ndarray] = []\n for id_list in ids:\n if id_list:\n out.append(self._encode_helper(id_list))\n else:\n out.append(np.zeros((0, self.dim)))\n\n return out\n\n def encode(\n self,\n sentences: Sequence[str],\n show_progress_bar: bool = False,\n max_length: int | None = 512,\n batch_size: int = 1024,\n use_multiprocessing: bool = True,\n multiprocessing_threshold: int = 10_000,\n **kwargs: Any,\n ) -> np.ndarray:\n \"\"\"\n Encode a list of sentences.\n\n This function encodes a list of sentences by averaging the word embeddings of the tokens in the sentence.\n For ease of use, we don't batch sentences together.\n\n NOTE: the return type is currently underspecified. In the case of a single string, this returns a 1D array,\n but in the case of a list of strings, this returns a 2D array. Not possible to implement in numpy currently.\n\n :param sentences: The list of sentences to encode. You can also pass a single sentence.\n :param show_progress_bar: Whether to show the progress bar.\n :param max_length: The maximum length of the sentences. Any tokens beyond this length will be truncated.\n If this is None, no truncation is done.\n :param batch_size: The batch size to use.\n :param use_multiprocessing: Whether to use multiprocessing.\n By default, this is enabled for inputs > multiprocessing_threshold sentences and disabled otherwise.\n :param multiprocessing_threshold: The threshold in number of sentences for using multiprocessing.\n :param **kwargs: Any additional arguments. These are ignored.\n :return: The encoded sentences. If a single sentence was passed, a vector is returned.\n \"\"\"\n was_single = False\n if isinstance(sentences, str):\n sentences = [sentences]\n was_single = True\n\n # Prepare all batches\n sentence_batches = list(self._batch(sentences, batch_size))\n total_batches = math.ceil(len(sentences) / batch_size)\n\n # Use joblib for multiprocessing if requested, and if we have enough sentences\n if use_multiprocessing and len(sentences) > multiprocessing_threshold:\n # Disable parallelism for tokenizers\n os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\n results = ProgressParallel(n_jobs=-1, use_tqdm=show_progress_bar, total=total_batches)(\n delayed(self._encode_batch)(batch, max_length) for batch in sentence_batches\n )\n out_array = np.concatenate(results, axis=0)\n else:\n # Don't use multiprocessing\n out_arrays: list[np.ndarray] = []\n for batch in tqdm(\n sentence_batches,\n total=total_batches,\n disable=not show_progress_bar,\n ):\n out_arrays.append(self._encode_batch(batch, max_length))\n out_array = np.concatenate(out_arrays, axis=0)\n\n if was_single:\n return out_array[0]\n return out_array\n\n def _encode_helper(self, id_list: list[int]) -> np.ndarray:\n \"\"\"\n Helper function to encode a list of ids.\n\n This function is used to deduplicate the logic in `encode` and `encode_as_sequence`.\n It retrieves the embeddings for the given list of ids, applying weights if available.\n\n :param id_list: A list of token ids.\n :return: The embeddings for the given ids, as a sequence of vectors.\n \"\"\"\n id_list_remapped: list[int] | np.ndarray\n if self.token_mapping is None:\n id_list_remapped = id_list\n else:\n id_list_remapped = self.token_mapping[id_list]\n emb = self.embedding[id_list_remapped]\n if self.weights is not None:\n emb = emb * self.weights[id_list][:, None]\n\n return emb\n\n def _encode_batch(self, sentences: Sequence[str], max_length: int | None) -> np.ndarray:\n \"\"\"Encode a batch of sentences.\"\"\"\n ids = self.tokenize(sentences=sentences, max_length=max_length)\n out: list[np.ndarray] = []\n for id_list in ids:\n if id_list:\n emb = self._encode_helper(id_list)\n out.append(emb.mean(axis=0))\n else:\n out.append(np.zeros(self.dim))\n\n out_array = np.stack(out)\n if self.normalize:\n norm = np.linalg.norm(out_array, axis=1, keepdims=True) + 1e-32\n out_array = out_array / norm\n\n return out_array\n\n @staticmethod\n def _batch(sentences: Sequence[str], batch_size: int) -> Iterator[Sequence[str]]:\n \"\"\"Batch the sentences into equal-sized.\"\"\"\n return (sentences[i : i + batch_size] for i in range(0, len(sentences), batch_size))\n\n def push_to_hub(\n self, repo_id: str, private: bool = False, token: str | None = None, subfolder: str | None = None\n ) -> None:\n \"\"\"\n Push the model to the huggingface hub.\n\n NOTE: you need to pass a token if you are pushing a private model.\n\n :param repo_id: The repo id to push to.\n :param private: Whether the repo, if created is set to private.\n If the repo already exists, this doesn't change the visibility.\n :param token: The huggingface token to use.\n :param subfolder: The subfolder to push to.\n \"\"\"\n from model2vec.hf_utils import push_folder_to_hub\n\n with TemporaryDirectory() as temp_dir:\n self.save_pretrained(temp_dir, model_name=repo_id)\n push_folder_to_hub(Path(temp_dir), subfolder=subfolder, repo_id=repo_id, private=private, token=token)", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 23268}, "tests/test_model.py::211": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["Path", "StaticModel", "Tokenizer"], "enclosing_function": "test_load_pretrained_quantized", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_model.py::15": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["StaticModel", "Tokenizer"], "enclosing_function": "test_initialization", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_distillation.py::251": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["post_process_embeddings", "pytest"], "enclosing_function": "test__post_process_embeddings", "extracted_code": "# Source: model2vec/distill/inference.py\ndef post_process_embeddings(\n embeddings: np.ndarray, pca_dims: PCADimType, sif_coefficient: float | None = 1e-4\n) -> tuple[np.ndarray, np.ndarray]:\n \"\"\"Post process embeddings by applying PCA and SIF weighting by estimating the frequencies through Zipf's law.\"\"\"\n if pca_dims is not None:\n if pca_dims == \"auto\":\n pca_dims = embeddings.shape[1]\n if pca_dims > embeddings.shape[1]:\n logger.warning(\n f\"PCA dimension ({pca_dims}) is larger than the number of dimensions in the embeddings ({embeddings.shape[1]}). \"\n \"Applying PCA, but not reducing dimensionality. Is this is not desired, please set `pca_dims` to None. \"\n \"Applying PCA will probably improve performance, so consider just leaving it.\"\n )\n pca_dims = embeddings.shape[1]\n if pca_dims >= embeddings.shape[0]:\n logger.warning(\n f\"PCA dimension ({pca_dims}) is larger than the number of tokens in the vocabulary ({embeddings.shape[0]}). Not applying PCA.\"\n )\n elif pca_dims <= embeddings.shape[1]:\n if isinstance(pca_dims, float):\n logger.info(f\"Applying PCA with {pca_dims} explained variance.\")\n else:\n logger.info(f\"Applying PCA with n_components {pca_dims}\")\n\n orig_dims = embeddings.shape[1]\n p = PCA(n_components=pca_dims, svd_solver=\"full\")\n embeddings = p.fit_transform(embeddings)\n\n if embeddings.shape[1] < orig_dims:\n explained_variance_ratio = np.sum(p.explained_variance_ratio_)\n explained_variance = np.sum(p.explained_variance_)\n logger.info(f\"Reduced dimensionality from {orig_dims} to {embeddings.shape[1]}.\")\n logger.info(f\"Explained variance ratio: {explained_variance_ratio:.3f}.\")\n logger.info(f\"Explained variance: {explained_variance:.3f}.\")\n\n if sif_coefficient is not None:\n logger.info(\"Estimating word frequencies using Zipf's law, and then applying SIF.\")\n inv_rank = 1 / (np.arange(2, embeddings.shape[0] + 2))\n proba = inv_rank / np.sum(inv_rank)\n weight = sif_coefficient / (sif_coefficient + proba)\n else:\n weight = np.ones(embeddings.shape[0])\n\n return embeddings, weight", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 2384}, "tests/test_trainable.py::22": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification", "Tokenizer", "pytest", "torch"], "enclosing_function": "test_init_predict", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_quantization.py::60": {"resolved_imports": ["model2vec/quantization.py", "model2vec/vocabulary_quantization.py"], "used_names": ["quantize_vocabulary"], "enclosing_function": "test_quantize_vocabulary", "extracted_code": "# Source: model2vec/vocabulary_quantization.py\ndef quantize_vocabulary(\n n_clusters: int, weights: np.ndarray | None, embeddings: np.ndarray\n) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Quantize the vocabulary of embeddings using KMeans clustering.\"\"\"\n logger.info(f\"Quantizing vocabulary to {n_clusters} clusters.\")\n # If the model does not have weights, we assume the norm to be informative.\n if weights is None:\n weights = cast(np.ndarray, np.linalg.norm(embeddings, axis=1) + 1e-32)\n # Divide by the norm to normalize the embeddings, so we don't bias the clustering.\n embeddings = embeddings / weights[:, None]\n\n # Ensure the embeddings are in float32 for KMeans\n # Store the original dtype to restore it later\n orig_dtype = embeddings.dtype\n\n kmeans = KMeans(n_clusters=n_clusters, random_state=42, init=\"random\")\n cast_embeddings = embeddings.astype(np.float32)\n # Fit KMeans to the embeddings\n kmeans.fit(cast_embeddings)\n # Create a mapping from the original token index to the cluster index\n token_mapping = kmeans.predict(cast_embeddings)\n # The cluster centers are the new embeddings.\n # Convert them back to the original dtype\n embeddings = kmeans.cluster_centers_.astype(orig_dtype)\n\n return embeddings, token_mapping, weights", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1321}, "tests/test_utils.py::32": {"resolved_imports": ["model2vec/distill/utils.py", "model2vec/hf_utils.py", "model2vec/utils.py"], "used_names": ["NamedTemporaryFile", "Path", "_get_metadata_from_readme"], "enclosing_function": "test__get_metadata_from_readme_mocked_file_keys", "extracted_code": "# Source: model2vec/hf_utils.py\ndef _get_metadata_from_readme(readme_path: Path) -> dict[str, Any]:\n \"\"\"Get metadata from a README file.\"\"\"\n if not readme_path.exists():\n logger.info(f\"README file not found in {readme_path}. No model card loaded.\")\n return {}\n model_card = ModelCard.load(readme_path)\n data: dict[str, Any] = model_card.data.to_dict()\n if not data:\n logger.info(\"File README.md exists, but was empty. No model card loaded.\")\n return data", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 493}, "tests/test_quantization.py::61": {"resolved_imports": ["model2vec/quantization.py", "model2vec/vocabulary_quantization.py"], "used_names": ["quantize_vocabulary"], "enclosing_function": "test_quantize_vocabulary", "extracted_code": "# Source: model2vec/vocabulary_quantization.py\ndef quantize_vocabulary(\n n_clusters: int, weights: np.ndarray | None, embeddings: np.ndarray\n) -> tuple[np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Quantize the vocabulary of embeddings using KMeans clustering.\"\"\"\n logger.info(f\"Quantizing vocabulary to {n_clusters} clusters.\")\n # If the model does not have weights, we assume the norm to be informative.\n if weights is None:\n weights = cast(np.ndarray, np.linalg.norm(embeddings, axis=1) + 1e-32)\n # Divide by the norm to normalize the embeddings, so we don't bias the clustering.\n embeddings = embeddings / weights[:, None]\n\n # Ensure the embeddings are in float32 for KMeans\n # Store the original dtype to restore it later\n orig_dtype = embeddings.dtype\n\n kmeans = KMeans(n_clusters=n_clusters, random_state=42, init=\"random\")\n cast_embeddings = embeddings.astype(np.float32)\n # Fit KMeans to the embeddings\n kmeans.fit(cast_embeddings)\n # Create a mapping from the original token index to the cluster index\n token_mapping = kmeans.predict(cast_embeddings)\n # The cluster centers are the new embeddings.\n # Convert them back to the original dtype\n embeddings = kmeans.cluster_centers_.astype(orig_dtype)\n\n return embeddings, token_mapping, weights", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1321}, "tests/test_trainable.py::120": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification"], "enclosing_function": "test_predict", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_utils.py::24": {"resolved_imports": ["model2vec/distill/utils.py", "model2vec/hf_utils.py", "model2vec/utils.py"], "used_names": ["NamedTemporaryFile", "Path", "_get_metadata_from_readme"], "enclosing_function": "test__get_metadata_from_readme_mocked_file", "extracted_code": "# Source: model2vec/hf_utils.py\ndef _get_metadata_from_readme(readme_path: Path) -> dict[str, Any]:\n \"\"\"Get metadata from a README file.\"\"\"\n if not readme_path.exists():\n logger.info(f\"README file not found in {readme_path}. No model card loaded.\")\n return {}\n model_card = ModelCard.load(readme_path)\n data: dict[str, Any] = model_card.data.to_dict()\n if not data:\n logger.info(\"File README.md exists, but was empty. No model card loaded.\")\n return data", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 493}, "tests/test_distillation.py::79": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["MagicMock", "PreTrainedModel", "PreTrainedTokenizerFast", "distill", "distill_from_model", "import_module", "json", "patch", "pytest"], "enclosing_function": "test_distill_from_model", "extracted_code": "# Source: model2vec/distill/distillation.py\ndef distill_from_model(\n model: PreTrainedModel,\n tokenizer: PreTrainedTokenizerFast,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model: The model to use.\n :param tokenizer: The tokenizer to use.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimensionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled\n into a valid regex, we also throw an error.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel.\n :raises: ValueError if the vocabulary is empty after preprocessing.\n\n \"\"\"\n quantize_to = DType(quantize_to)\n sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)\n\n if vocabulary is None:\n vocabulary = []\n\n device = select_optimal_device(device)\n original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)\n\n # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.\n # Copy the original tokenizer model.\n tokenizer_model = original_tokenizer_model.model_copy(deep=True)\n if tokenizer_model.adds_prefix_space is not None:\n tokenizer_model.adds_prefix_space = True\n\n # Create the vocabulary in the new tokenizer.\n tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)\n # Remove the post processor, this is not necessary.\n tokenizer_model.post_processor = None\n\n # All tokens in a single list.\n all_tokens = tokenizer_model.sorted_vocabulary\n if not all_tokens:\n raise ValueError(\"The vocabulary is empty after preprocessing. Please check your token_remove_pattern.\")\n\n # Turn all _new_ tokens into ids using the original tokenizer\n token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)\n\n # Create the embeddings using the ids from the original tokenizer.\n embeddings = create_embeddings(\n tokenized=token_ids,\n model=model,\n device=device,\n pad_token_id=tokenizer_model.pad_token_id or 0,\n pooling=pooling,\n )\n\n # Maybe apply quantization\n if vocabulary_quantization is not None:\n _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)\n embeddings, token_mapping, weights = quantize_vocabulary(\n n_clusters=vocabulary_quantization, weights=weights, embeddings=np.asarray(embeddings)\n )\n embeddings, _ = post_process_embeddings(embeddings, pca_dims, sif_coefficient=sif_coefficient)\n else:\n # Post-process the embeddings.\n embeddings, weights = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)\n token_mapping = None\n # Quantize the embeddings.\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n model_name = getattr(model, \"name_or_path\", \"\")\n\n config = {\n \"model_type\": \"model2vec\",\n \"architectures\": [\"StaticModel\"],\n \"tokenizer_name\": model_name,\n \"apply_pca\": pca_dims,\n \"sif_coefficient\": sif_coefficient,\n \"hidden_dim\": embeddings.shape[1],\n \"seq_length\": 1000000, # Set this to a high value since we don't have a sequence length limit.\n \"normalize\": True,\n \"pooling\": pooling,\n }\n\n if os.path.exists(model_name):\n # Using a local model. Get the model name from the path.\n model_name = os.path.basename(model_name)\n language = None\n else:\n # Get the language from the model card.\n try:\n info = model_info(model_name)\n language = info.cardData.get(\"language\", None) if info.cardData is not None else None\n except Exception as e:\n # NOTE: bare except because there's many reasons this can fail.\n logger.warning(f\"Couldn't get the model info from the Hugging Face Hub: {e}. Setting language to None.\")\n language = None\n\n return StaticModel(\n vectors=embeddings,\n weights=weights,\n token_mapping=token_mapping,\n tokenizer=tokenizer_model.to_tokenizer(),\n config=config,\n base_model_name=model_name,\n language=language,\n normalize=True,\n )\n\ndef distill(\n model_name: str,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n trust_remote_code: bool = False,\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model_name: The model name to use. Any sentencetransformer compatible model works.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimenionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming\n from `transformers`. If this is True, we will load all components.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel\n\n \"\"\"\n model: PreTrainedModel = AutoModel.from_pretrained(model_name, trust_remote_code=trust_remote_code)\n tokenizer = cast(\n PreTrainedTokenizerFast,\n AutoTokenizer.from_pretrained(model_name, trust_remote_code=trust_remote_code, use_fast=True),\n )\n\n return distill_from_model(\n model=model,\n tokenizer=tokenizer,\n vocabulary=vocabulary,\n device=device,\n pca_dims=pca_dims,\n token_remove_pattern=token_remove_pattern,\n sif_coefficient=sif_coefficient,\n quantize_to=quantize_to,\n vocabulary_quantization=vocabulary_quantization,\n pooling=pooling,\n )", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 9727}, "tests/test_trainable.py::109": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["TextDataset", "pytest", "torch"], "enclosing_function": "test_textdataset_init_incorrect", "extracted_code": "# Source: model2vec/train/base.py\nclass TextDataset(Dataset):\n def __init__(self, tokenized_texts: list[list[int]], targets: torch.Tensor) -> None:\n \"\"\"\n A dataset of texts.\n\n :param tokenized_texts: The tokenized texts. Each text is a list of token ids.\n :param targets: The targets.\n :raises ValueError: If the number of labels does not match the number of texts.\n \"\"\"\n if len(targets) != len(tokenized_texts):\n raise ValueError(\"Number of labels does not match number of texts.\")\n self.tokenized_texts = tokenized_texts\n self.targets = targets\n\n def __len__(self) -> int:\n \"\"\"Return the length of the dataset.\"\"\"\n return len(self.tokenized_texts)\n\n def __getitem__(self, index: int) -> tuple[list[int], torch.Tensor]:\n \"\"\"Gets an item.\"\"\"\n return self.tokenized_texts[index], self.targets[index]\n\n @staticmethod\n def collate_fn(batch: list[tuple[list[list[int]], int]]) -> tuple[torch.Tensor, torch.Tensor]:\n \"\"\"Collate function.\"\"\"\n texts, targets = zip(*batch)\n\n tensors: list[torch.Tensor] = [torch.LongTensor(x) for x in texts]\n padded = pad_sequence(tensors, batch_first=True, padding_value=0)\n\n return padded, torch.stack(targets)\n\n def to_dataloader(self, shuffle: bool, batch_size: int = 32) -> DataLoader:\n \"\"\"Convert the dataset to a DataLoader.\"\"\"\n return DataLoader(self, collate_fn=self.collate_fn, shuffle=shuffle, batch_size=batch_size)", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 1523}, "tests/test_trainable.py::21": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification", "Tokenizer", "pytest", "torch"], "enclosing_function": "test_init_predict", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_trainable.py::81": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification", "torch"], "enclosing_function": "test_tokenize", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_distillation.py::146": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["MagicMock", "PreTrainedModel", "PreTrainedTokenizerFast", "distill_from_model", "import_module", "patch", "pytest"], "enclosing_function": "test_distill_removal_pattern", "extracted_code": "# Source: model2vec/distill/distillation.py\ndef distill_from_model(\n model: PreTrainedModel,\n tokenizer: PreTrainedTokenizerFast,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model: The model to use.\n :param tokenizer: The tokenizer to use.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimensionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled\n into a valid regex, we also throw an error.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel.\n :raises: ValueError if the vocabulary is empty after preprocessing.\n\n \"\"\"\n quantize_to = DType(quantize_to)\n sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)\n\n if vocabulary is None:\n vocabulary = []\n\n device = select_optimal_device(device)\n original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)\n\n # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.\n # Copy the original tokenizer model.\n tokenizer_model = original_tokenizer_model.model_copy(deep=True)\n if tokenizer_model.adds_prefix_space is not None:\n tokenizer_model.adds_prefix_space = True\n\n # Create the vocabulary in the new tokenizer.\n tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)\n # Remove the post processor, this is not necessary.\n tokenizer_model.post_processor = None\n\n # All tokens in a single list.\n all_tokens = tokenizer_model.sorted_vocabulary\n if not all_tokens:\n raise ValueError(\"The vocabulary is empty after preprocessing. Please check your token_remove_pattern.\")\n\n # Turn all _new_ tokens into ids using the original tokenizer\n token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)\n\n # Create the embeddings using the ids from the original tokenizer.\n embeddings = create_embeddings(\n tokenized=token_ids,\n model=model,\n device=device,\n pad_token_id=tokenizer_model.pad_token_id or 0,\n pooling=pooling,\n )\n\n # Maybe apply quantization\n if vocabulary_quantization is not None:\n _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)\n embeddings, token_mapping, weights = quantize_vocabulary(\n n_clusters=vocabulary_quantization, weights=weights, embeddings=np.asarray(embeddings)\n )\n embeddings, _ = post_process_embeddings(embeddings, pca_dims, sif_coefficient=sif_coefficient)\n else:\n # Post-process the embeddings.\n embeddings, weights = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)\n token_mapping = None\n # Quantize the embeddings.\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n model_name = getattr(model, \"name_or_path\", \"\")\n\n config = {\n \"model_type\": \"model2vec\",\n \"architectures\": [\"StaticModel\"],\n \"tokenizer_name\": model_name,\n \"apply_pca\": pca_dims,\n \"sif_coefficient\": sif_coefficient,\n \"hidden_dim\": embeddings.shape[1],\n \"seq_length\": 1000000, # Set this to a high value since we don't have a sequence length limit.\n \"normalize\": True,\n \"pooling\": pooling,\n }\n\n if os.path.exists(model_name):\n # Using a local model. Get the model name from the path.\n model_name = os.path.basename(model_name)\n language = None\n else:\n # Get the language from the model card.\n try:\n info = model_info(model_name)\n language = info.cardData.get(\"language\", None) if info.cardData is not None else None\n except Exception as e:\n # NOTE: bare except because there's many reasons this can fail.\n logger.warning(f\"Couldn't get the model info from the Hugging Face Hub: {e}. Setting language to None.\")\n language = None\n\n return StaticModel(\n vectors=embeddings,\n weights=weights,\n token_mapping=token_mapping,\n tokenizer=tokenizer_model.to_tokenizer(),\n config=config,\n base_model_name=model_name,\n language=language,\n normalize=True,\n )", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 6430}, "tests/test_trainable.py::28": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification", "Tokenizer", "pytest", "torch"], "enclosing_function": "test_init_predict", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_distillation.py::330": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["PoolingMode", "PreTrainedModel", "create_embeddings", "pytest"], "enclosing_function": "test_pooler_raises_without_pooler_output", "extracted_code": "# Source: model2vec/distill/inference.py\nclass PoolingMode(str, Enum):\n \"\"\"\n Pooling modes for embedding creation.\n\n - MEAN: masked mean over all tokens.\n - LAST: last non-padding token (often EOS, common in decoder-style models).\n - FIRST: first token hidden state (position 0). In BERT-style encoders,\n this corresponds to the [CLS] token representation.\n - POOLER: use the model's `pooler_output`. In BERT-like models this is\n computed as the hidden state at [CLS], passed through a learned\n dense layer + activation. Not all models provide this.\n \"\"\"\n\n MEAN = \"mean\"\n LAST = \"last\"\n FIRST = \"first\"\n POOLER = \"pooler\"\n\ndef create_embeddings(\n model: PreTrainedModel,\n tokenized: list[list[int]],\n device: str,\n pad_token_id: int,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> np.ndarray:\n \"\"\"\n Create output embeddings for a bunch of tokens using a pretrained model.\n\n It does a forward pass for all tokens passed in `tokens`.\n\n :param model: The model to use.\n This should be a transformers model.\n :param tokenized: All tokenized tokens.\n :param device: The torch device to use.\n :param pad_token_id: The pad token id. Used to pad sequences.\n :param pooling: The pooling mode to use.\n :return: The output embeddings.\n :raises ValueError: If the pooling mode is unknown.\n \"\"\"\n model = model.to(device).eval() # type: ignore # Transformers error\n\n out_weights: np.ndarray\n intermediate_weights: list[np.ndarray] = []\n\n # Add token_type_ids only if the model supports it\n add_token_type_ids = \"token_type_ids\" in inspect.getfullargspec(model.forward).args\n\n lengths = np.asarray([len(sequence) for sequence in tokenized])\n sort_order = np.argsort(lengths)\n\n sorted_tokenized = [tokenized[i] for i in sort_order]\n\n pbar = tqdm(total=len(sorted_tokenized), desc=\"Encoding tokens\", unit=\" tokens\")\n\n for batch_idx in range(0, len(sorted_tokenized), _DEFAULT_BATCH_SIZE):\n batch_list = sorted_tokenized[batch_idx : batch_idx + _DEFAULT_BATCH_SIZE]\n batch = [torch.tensor(x, dtype=torch.long) for x in batch_list]\n\n encoded = {}\n encoded[\"input_ids\"] = pad_sequence(batch, batch_first=True, padding_value=pad_token_id)\n\n # Create attention mask by using the lengths of each sequence\n seq_len = encoded[\"input_ids\"].size(1)\n batch_lengths = torch.tensor([len(x) for x in batch_list], device=encoded[\"input_ids\"].device)\n token_positions = torch.arange(seq_len, device=encoded[\"input_ids\"].device)\n # Mark padding tokens with 0, and non-padding tokens with 1\n attention_mask = token_positions.unsqueeze(0) < batch_lengths.unsqueeze(1)\n encoded[\"attention_mask\"] = attention_mask.to(dtype=torch.long)\n\n if add_token_type_ids:\n # Add token_type_ids for models that support it\n encoded[\"token_type_ids\"] = torch.zeros_like(encoded[\"input_ids\"])\n\n if pooling == PoolingMode.MEAN:\n out = _encode_mean_with_model(model, encoded)\n elif pooling == PoolingMode.LAST:\n out = _encode_last_with_model(model, encoded)\n elif pooling == PoolingMode.FIRST:\n out = _encode_first_with_model(model, encoded)\n elif pooling == PoolingMode.POOLER:\n out = _encode_pooler_with_model(model, encoded)\n else:\n raise ValueError(f\"Unknown pooling: {pooling}\")\n\n intermediate_weights.extend(out.numpy())\n pbar.update(len(batch))\n\n # Sort the output back to the original order\n intermediate_weights = [intermediate_weights[i] for i in np.argsort(sort_order)]\n out_weights = np.stack(intermediate_weights)\n out_weights = np.nan_to_num(out_weights)\n\n return out_weights", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 3826}, "tests/test_model.py::203": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["Path", "StaticModel", "Tokenizer"], "enclosing_function": "test_load_pretrained_quantized", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_trainable.py::123": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification"], "enclosing_function": "test_predict", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_quantization.py::48": {"resolved_imports": ["model2vec/quantization.py", "model2vec/vocabulary_quantization.py"], "used_names": ["DType", "quantize_and_reduce_dim"], "enclosing_function": "test_quantize_and_reduce_dim", "extracted_code": "# Source: model2vec/quantization.py\nclass DType(str, Enum):\n Float16 = \"float16\"\n Float32 = \"float32\"\n Float64 = \"float64\"\n Int8 = \"int8\"\n\ndef quantize_and_reduce_dim(\n embeddings: np.ndarray, quantize_to: str | DType | None, dimensionality: int | None\n) -> np.ndarray:\n \"\"\"\n Quantize embeddings to a datatype and reduce dimensionality.\n\n :param embeddings: The embeddings to quantize and reduce, as a numpy array.\n :param quantize_to: The data type to quantize to. If None, no quantization is performed.\n :param dimensionality: The number of dimensions to keep. If None, no dimensionality reduction is performed.\n :return: The quantized and reduced embeddings.\n :raises ValueError: If the passed dimensionality is not None and greater than the model dimensionality.\n \"\"\"\n if quantize_to is not None:\n quantize_to = DType(quantize_to)\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n if dimensionality is not None:\n if dimensionality > embeddings.shape[1]:\n raise ValueError(\n f\"Dimensionality {dimensionality} is greater than the model dimensionality {embeddings.shape[1]}\"\n )\n embeddings = embeddings[:, :dimensionality]\n\n return embeddings", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1267}, "tests/test_model.py::85": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["StaticModel", "Tokenizer"], "enclosing_function": "test_encode_as_sequence", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_distillation.py::78": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["MagicMock", "PreTrainedModel", "PreTrainedTokenizerFast", "distill", "distill_from_model", "import_module", "json", "patch", "pytest"], "enclosing_function": "test_distill_from_model", "extracted_code": "# Source: model2vec/distill/distillation.py\ndef distill_from_model(\n model: PreTrainedModel,\n tokenizer: PreTrainedTokenizerFast,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model: The model to use.\n :param tokenizer: The tokenizer to use.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimensionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled\n into a valid regex, we also throw an error.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel.\n :raises: ValueError if the vocabulary is empty after preprocessing.\n\n \"\"\"\n quantize_to = DType(quantize_to)\n sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)\n\n if vocabulary is None:\n vocabulary = []\n\n device = select_optimal_device(device)\n original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)\n\n # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.\n # Copy the original tokenizer model.\n tokenizer_model = original_tokenizer_model.model_copy(deep=True)\n if tokenizer_model.adds_prefix_space is not None:\n tokenizer_model.adds_prefix_space = True\n\n # Create the vocabulary in the new tokenizer.\n tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)\n # Remove the post processor, this is not necessary.\n tokenizer_model.post_processor = None\n\n # All tokens in a single list.\n all_tokens = tokenizer_model.sorted_vocabulary\n if not all_tokens:\n raise ValueError(\"The vocabulary is empty after preprocessing. Please check your token_remove_pattern.\")\n\n # Turn all _new_ tokens into ids using the original tokenizer\n token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)\n\n # Create the embeddings using the ids from the original tokenizer.\n embeddings = create_embeddings(\n tokenized=token_ids,\n model=model,\n device=device,\n pad_token_id=tokenizer_model.pad_token_id or 0,\n pooling=pooling,\n )\n\n # Maybe apply quantization\n if vocabulary_quantization is not None:\n _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)\n embeddings, token_mapping, weights = quantize_vocabulary(\n n_clusters=vocabulary_quantization, weights=weights, embeddings=np.asarray(embeddings)\n )\n embeddings, _ = post_process_embeddings(embeddings, pca_dims, sif_coefficient=sif_coefficient)\n else:\n # Post-process the embeddings.\n embeddings, weights = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)\n token_mapping = None\n # Quantize the embeddings.\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n model_name = getattr(model, \"name_or_path\", \"\")\n\n config = {\n \"model_type\": \"model2vec\",\n \"architectures\": [\"StaticModel\"],\n \"tokenizer_name\": model_name,\n \"apply_pca\": pca_dims,\n \"sif_coefficient\": sif_coefficient,\n \"hidden_dim\": embeddings.shape[1],\n \"seq_length\": 1000000, # Set this to a high value since we don't have a sequence length limit.\n \"normalize\": True,\n \"pooling\": pooling,\n }\n\n if os.path.exists(model_name):\n # Using a local model. Get the model name from the path.\n model_name = os.path.basename(model_name)\n language = None\n else:\n # Get the language from the model card.\n try:\n info = model_info(model_name)\n language = info.cardData.get(\"language\", None) if info.cardData is not None else None\n except Exception as e:\n # NOTE: bare except because there's many reasons this can fail.\n logger.warning(f\"Couldn't get the model info from the Hugging Face Hub: {e}. Setting language to None.\")\n language = None\n\n return StaticModel(\n vectors=embeddings,\n weights=weights,\n token_mapping=token_mapping,\n tokenizer=tokenizer_model.to_tokenizer(),\n config=config,\n base_model_name=model_name,\n language=language,\n normalize=True,\n )\n\ndef distill(\n model_name: str,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n trust_remote_code: bool = False,\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model_name: The model name to use. Any sentencetransformer compatible model works.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimenionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming\n from `transformers`. If this is True, we will load all components.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel\n\n \"\"\"\n model: PreTrainedModel = AutoModel.from_pretrained(model_name, trust_remote_code=trust_remote_code)\n tokenizer = cast(\n PreTrainedTokenizerFast,\n AutoTokenizer.from_pretrained(model_name, trust_remote_code=trust_remote_code, use_fast=True),\n )\n\n return distill_from_model(\n model=model,\n tokenizer=tokenizer,\n vocabulary=vocabulary,\n device=device,\n pca_dims=pca_dims,\n token_remove_pattern=token_remove_pattern,\n sif_coefficient=sif_coefficient,\n quantize_to=quantize_to,\n vocabulary_quantization=vocabulary_quantization,\n pooling=pooling,\n )", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 9727}, "tests/test_model.py::277": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["Path", "StaticModel", "Tokenizer"], "enclosing_function": "test_load_pretrained_vocabulary_quantized", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_distillation.py::225": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["MagicMock", "PreTrainedModel", "PreTrainedTokenizerFast", "distill_from_model", "import_module", "patch"], "enclosing_function": "test_missing_modelinfo", "extracted_code": "# Source: model2vec/distill/distillation.py\ndef distill_from_model(\n model: PreTrainedModel,\n tokenizer: PreTrainedTokenizerFast,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model: The model to use.\n :param tokenizer: The tokenizer to use.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimensionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled\n into a valid regex, we also throw an error.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel.\n :raises: ValueError if the vocabulary is empty after preprocessing.\n\n \"\"\"\n quantize_to = DType(quantize_to)\n sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)\n\n if vocabulary is None:\n vocabulary = []\n\n device = select_optimal_device(device)\n original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)\n\n # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.\n # Copy the original tokenizer model.\n tokenizer_model = original_tokenizer_model.model_copy(deep=True)\n if tokenizer_model.adds_prefix_space is not None:\n tokenizer_model.adds_prefix_space = True\n\n # Create the vocabulary in the new tokenizer.\n tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)\n # Remove the post processor, this is not necessary.\n tokenizer_model.post_processor = None\n\n # All tokens in a single list.\n all_tokens = tokenizer_model.sorted_vocabulary\n if not all_tokens:\n raise ValueError(\"The vocabulary is empty after preprocessing. Please check your token_remove_pattern.\")\n\n # Turn all _new_ tokens into ids using the original tokenizer\n token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)\n\n # Create the embeddings using the ids from the original tokenizer.\n embeddings = create_embeddings(\n tokenized=token_ids,\n model=model,\n device=device,\n pad_token_id=tokenizer_model.pad_token_id or 0,\n pooling=pooling,\n )\n\n # Maybe apply quantization\n if vocabulary_quantization is not None:\n _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)\n embeddings, token_mapping, weights = quantize_vocabulary(\n n_clusters=vocabulary_quantization, weights=weights, embeddings=np.asarray(embeddings)\n )\n embeddings, _ = post_process_embeddings(embeddings, pca_dims, sif_coefficient=sif_coefficient)\n else:\n # Post-process the embeddings.\n embeddings, weights = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)\n token_mapping = None\n # Quantize the embeddings.\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n model_name = getattr(model, \"name_or_path\", \"\")\n\n config = {\n \"model_type\": \"model2vec\",\n \"architectures\": [\"StaticModel\"],\n \"tokenizer_name\": model_name,\n \"apply_pca\": pca_dims,\n \"sif_coefficient\": sif_coefficient,\n \"hidden_dim\": embeddings.shape[1],\n \"seq_length\": 1000000, # Set this to a high value since we don't have a sequence length limit.\n \"normalize\": True,\n \"pooling\": pooling,\n }\n\n if os.path.exists(model_name):\n # Using a local model. Get the model name from the path.\n model_name = os.path.basename(model_name)\n language = None\n else:\n # Get the language from the model card.\n try:\n info = model_info(model_name)\n language = info.cardData.get(\"language\", None) if info.cardData is not None else None\n except Exception as e:\n # NOTE: bare except because there's many reasons this can fail.\n logger.warning(f\"Couldn't get the model info from the Hugging Face Hub: {e}. Setting language to None.\")\n language = None\n\n return StaticModel(\n vectors=embeddings,\n weights=weights,\n token_mapping=token_mapping,\n tokenizer=tokenizer_model.to_tokenizer(),\n config=config,\n base_model_name=model_name,\n language=language,\n normalize=True,\n )", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 6430}, "tests/test_model.py::146": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["StaticModel", "Tokenizer"], "enclosing_function": "test_normalize", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_trainable.py::131": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification"], "enclosing_function": "test_predict_proba", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_trainable.py::125": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification"], "enclosing_function": "test_predict", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_utils.py::70": {"resolved_imports": ["model2vec/distill/utils.py", "model2vec/hf_utils.py", "model2vec/utils.py"], "used_names": ["importable", "pytest"], "enclosing_function": "test_importable", "extracted_code": "# Source: model2vec/utils.py\ndef importable(module: str, extra: str) -> None:\n \"\"\"Check if a module is importable.\"\"\"\n module = dict(_MODULE_MAP).get(module, module)\n try:\n import_module(module)\n except ImportError:\n raise ImportError(\n f\"`{module}`, is required. Please reinstall model2vec with the `{extra}` extra. `pip install model2vec[{extra}]`\"\n )", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 397}, "tests/test_utils.py::79": {"resolved_imports": ["model2vec/distill/utils.py", "model2vec/hf_utils.py", "model2vec/utils.py"], "used_names": ["get_package_extras"], "enclosing_function": "test_get_package_extras", "extracted_code": "# Source: model2vec/utils.py\ndef get_package_extras(package: str, extra: str) -> Iterator[str]:\n \"\"\"Get the extras of the package.\"\"\"\n try:\n message = metadata(package)\n except Exception as e:\n raise ImportError(f\"Could not retrieve metadata for package '{package}': {e}\")\n\n all_packages = message.get_all(\"Requires-Dist\") or []\n for package in all_packages:\n name, *rest = package.split(\";\", maxsplit=1)\n if rest:\n # Extract and clean the extra requirement\n found_extra = rest[0].split(\"==\")[-1].strip(\" \\\"'\")\n if found_extra == extra:\n prefix, *_ = _DIVIDERS.split(name)\n yield prefix.strip()", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 700}, "tests/test_distillation.py::149": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["MagicMock", "PreTrainedModel", "PreTrainedTokenizerFast", "distill_from_model", "import_module", "patch", "pytest"], "enclosing_function": "test_distill_removal_pattern", "extracted_code": "# Source: model2vec/distill/distillation.py\ndef distill_from_model(\n model: PreTrainedModel,\n tokenizer: PreTrainedTokenizerFast,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model: The model to use.\n :param tokenizer: The tokenizer to use.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimensionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled\n into a valid regex, we also throw an error.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel.\n :raises: ValueError if the vocabulary is empty after preprocessing.\n\n \"\"\"\n quantize_to = DType(quantize_to)\n sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)\n\n if vocabulary is None:\n vocabulary = []\n\n device = select_optimal_device(device)\n original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)\n\n # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.\n # Copy the original tokenizer model.\n tokenizer_model = original_tokenizer_model.model_copy(deep=True)\n if tokenizer_model.adds_prefix_space is not None:\n tokenizer_model.adds_prefix_space = True\n\n # Create the vocabulary in the new tokenizer.\n tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)\n # Remove the post processor, this is not necessary.\n tokenizer_model.post_processor = None\n\n # All tokens in a single list.\n all_tokens = tokenizer_model.sorted_vocabulary\n if not all_tokens:\n raise ValueError(\"The vocabulary is empty after preprocessing. Please check your token_remove_pattern.\")\n\n # Turn all _new_ tokens into ids using the original tokenizer\n token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)\n\n # Create the embeddings using the ids from the original tokenizer.\n embeddings = create_embeddings(\n tokenized=token_ids,\n model=model,\n device=device,\n pad_token_id=tokenizer_model.pad_token_id or 0,\n pooling=pooling,\n )\n\n # Maybe apply quantization\n if vocabulary_quantization is not None:\n _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)\n embeddings, token_mapping, weights = quantize_vocabulary(\n n_clusters=vocabulary_quantization, weights=weights, embeddings=np.asarray(embeddings)\n )\n embeddings, _ = post_process_embeddings(embeddings, pca_dims, sif_coefficient=sif_coefficient)\n else:\n # Post-process the embeddings.\n embeddings, weights = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)\n token_mapping = None\n # Quantize the embeddings.\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n model_name = getattr(model, \"name_or_path\", \"\")\n\n config = {\n \"model_type\": \"model2vec\",\n \"architectures\": [\"StaticModel\"],\n \"tokenizer_name\": model_name,\n \"apply_pca\": pca_dims,\n \"sif_coefficient\": sif_coefficient,\n \"hidden_dim\": embeddings.shape[1],\n \"seq_length\": 1000000, # Set this to a high value since we don't have a sequence length limit.\n \"normalize\": True,\n \"pooling\": pooling,\n }\n\n if os.path.exists(model_name):\n # Using a local model. Get the model name from the path.\n model_name = os.path.basename(model_name)\n language = None\n else:\n # Get the language from the model card.\n try:\n info = model_info(model_name)\n language = info.cardData.get(\"language\", None) if info.cardData is not None else None\n except Exception as e:\n # NOTE: bare except because there's many reasons this can fail.\n logger.warning(f\"Couldn't get the model info from the Hugging Face Hub: {e}. Setting language to None.\")\n language = None\n\n return StaticModel(\n vectors=embeddings,\n weights=weights,\n token_mapping=token_mapping,\n tokenizer=tokenizer_model.to_tokenizer(),\n config=config,\n base_model_name=model_name,\n language=language,\n normalize=True,\n )", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 6430}, "tests/test_utils.py::65": {"resolved_imports": ["model2vec/distill/utils.py", "model2vec/hf_utils.py", "model2vec/utils.py"], "used_names": ["patch", "pytest", "select_optimal_device"], "enclosing_function": "test_select_optimal_device", "extracted_code": "# Source: model2vec/distill/utils.py\ndef select_optimal_device(device: str | None) -> str:\n \"\"\"\n Get the optimal device to use based on backend availability.\n\n For Torch versions >= 2.8.0, MPS is disabled due to known performance regressions.\n\n :param device: The device to use. If this is None, the device is automatically selected.\n :return: The selected device.\n :raises RuntimeError: If MPS is requested on a PyTorch version where it is disabled.\n \"\"\"\n # Get the torch version and check if MPS is broken\n torch_version = version.parse(torch.__version__.split(\"+\")[0])\n mps_broken = torch_version >= version.parse(\"2.8.0\")\n\n if device:\n if device == \"mps\" and mps_broken:\n raise RuntimeError(\n f\"MPS is disabled for PyTorch {torch.__version__} due to known performance regressions. \"\n \"Please use CPU or CUDA instead, or use a PyTorch version < 2.8.0.\"\n )\n else:\n return device\n\n if torch.cuda.is_available():\n device = \"cuda\"\n elif torch.backends.mps.is_available():\n if mps_broken:\n logger.warning(\n f\"MPS is available but PyTorch {torch.__version__} has known performance regressions. \"\n \"Falling back to CPU. Please use a PyTorch version < 2.8.0 to enable MPS support.\"\n )\n device = \"cpu\"\n else:\n device = \"mps\"\n else:\n device = \"cpu\"\n\n logger.info(f\"Automatically selected device: {device}\")\n return device", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1541}, "tests/test_trainable.py::143": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification", "numpy"], "enclosing_function": "test_convert_to_pipeline", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_quantization.py::40": {"resolved_imports": ["model2vec/quantization.py", "model2vec/vocabulary_quantization.py"], "used_names": ["DType", "quantize_and_reduce_dim"], "enclosing_function": "test_quantize_and_reduce_dim", "extracted_code": "# Source: model2vec/quantization.py\nclass DType(str, Enum):\n Float16 = \"float16\"\n Float32 = \"float32\"\n Float64 = \"float64\"\n Int8 = \"int8\"\n\ndef quantize_and_reduce_dim(\n embeddings: np.ndarray, quantize_to: str | DType | None, dimensionality: int | None\n) -> np.ndarray:\n \"\"\"\n Quantize embeddings to a datatype and reduce dimensionality.\n\n :param embeddings: The embeddings to quantize and reduce, as a numpy array.\n :param quantize_to: The data type to quantize to. If None, no quantization is performed.\n :param dimensionality: The number of dimensions to keep. If None, no dimensionality reduction is performed.\n :return: The quantized and reduced embeddings.\n :raises ValueError: If the passed dimensionality is not None and greater than the model dimensionality.\n \"\"\"\n if quantize_to is not None:\n quantize_to = DType(quantize_to)\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n if dimensionality is not None:\n if dimensionality > embeddings.shape[1]:\n raise ValueError(\n f\"Dimensionality {dimensionality} is greater than the model dimensionality {embeddings.shape[1]}\"\n )\n embeddings = embeddings[:, :dimensionality]\n\n return embeddings", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1267}, "tests/test_distillation.py::77": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["MagicMock", "PreTrainedModel", "PreTrainedTokenizerFast", "distill", "distill_from_model", "import_module", "json", "patch", "pytest"], "enclosing_function": "test_distill_from_model", "extracted_code": "# Source: model2vec/distill/distillation.py\ndef distill_from_model(\n model: PreTrainedModel,\n tokenizer: PreTrainedTokenizerFast,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model: The model to use.\n :param tokenizer: The tokenizer to use.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimensionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled\n into a valid regex, we also throw an error.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel.\n :raises: ValueError if the vocabulary is empty after preprocessing.\n\n \"\"\"\n quantize_to = DType(quantize_to)\n sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)\n\n if vocabulary is None:\n vocabulary = []\n\n device = select_optimal_device(device)\n original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)\n\n # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.\n # Copy the original tokenizer model.\n tokenizer_model = original_tokenizer_model.model_copy(deep=True)\n if tokenizer_model.adds_prefix_space is not None:\n tokenizer_model.adds_prefix_space = True\n\n # Create the vocabulary in the new tokenizer.\n tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)\n # Remove the post processor, this is not necessary.\n tokenizer_model.post_processor = None\n\n # All tokens in a single list.\n all_tokens = tokenizer_model.sorted_vocabulary\n if not all_tokens:\n raise ValueError(\"The vocabulary is empty after preprocessing. Please check your token_remove_pattern.\")\n\n # Turn all _new_ tokens into ids using the original tokenizer\n token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)\n\n # Create the embeddings using the ids from the original tokenizer.\n embeddings = create_embeddings(\n tokenized=token_ids,\n model=model,\n device=device,\n pad_token_id=tokenizer_model.pad_token_id or 0,\n pooling=pooling,\n )\n\n # Maybe apply quantization\n if vocabulary_quantization is not None:\n _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)\n embeddings, token_mapping, weights = quantize_vocabulary(\n n_clusters=vocabulary_quantization, weights=weights, embeddings=np.asarray(embeddings)\n )\n embeddings, _ = post_process_embeddings(embeddings, pca_dims, sif_coefficient=sif_coefficient)\n else:\n # Post-process the embeddings.\n embeddings, weights = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)\n token_mapping = None\n # Quantize the embeddings.\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n model_name = getattr(model, \"name_or_path\", \"\")\n\n config = {\n \"model_type\": \"model2vec\",\n \"architectures\": [\"StaticModel\"],\n \"tokenizer_name\": model_name,\n \"apply_pca\": pca_dims,\n \"sif_coefficient\": sif_coefficient,\n \"hidden_dim\": embeddings.shape[1],\n \"seq_length\": 1000000, # Set this to a high value since we don't have a sequence length limit.\n \"normalize\": True,\n \"pooling\": pooling,\n }\n\n if os.path.exists(model_name):\n # Using a local model. Get the model name from the path.\n model_name = os.path.basename(model_name)\n language = None\n else:\n # Get the language from the model card.\n try:\n info = model_info(model_name)\n language = info.cardData.get(\"language\", None) if info.cardData is not None else None\n except Exception as e:\n # NOTE: bare except because there's many reasons this can fail.\n logger.warning(f\"Couldn't get the model info from the Hugging Face Hub: {e}. Setting language to None.\")\n language = None\n\n return StaticModel(\n vectors=embeddings,\n weights=weights,\n token_mapping=token_mapping,\n tokenizer=tokenizer_model.to_tokenizer(),\n config=config,\n base_model_name=model_name,\n language=language,\n normalize=True,\n )\n\ndef distill(\n model_name: str,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n trust_remote_code: bool = False,\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model_name: The model name to use. Any sentencetransformer compatible model works.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimenionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming\n from `transformers`. If this is True, we will load all components.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel\n\n \"\"\"\n model: PreTrainedModel = AutoModel.from_pretrained(model_name, trust_remote_code=trust_remote_code)\n tokenizer = cast(\n PreTrainedTokenizerFast,\n AutoTokenizer.from_pretrained(model_name, trust_remote_code=trust_remote_code, use_fast=True),\n )\n\n return distill_from_model(\n model=model,\n tokenizer=tokenizer,\n vocabulary=vocabulary,\n device=device,\n pca_dims=pca_dims,\n token_remove_pattern=token_remove_pattern,\n sif_coefficient=sif_coefficient,\n quantize_to=quantize_to,\n vocabulary_quantization=vocabulary_quantization,\n pooling=pooling,\n )", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 9727}, "tests/test_model.py::279": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["Path", "StaticModel", "Tokenizer"], "enclosing_function": "test_load_pretrained_vocabulary_quantized", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_inference.py::30": {"resolved_imports": ["model2vec/inference/__init__.py"], "used_names": ["StaticModelPipeline"], "enclosing_function": "test_init_predict_proba", "extracted_code": "# Source: model2vec/inference/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 411}, "tests/test_utils.py::16": {"resolved_imports": ["model2vec/distill/utils.py", "model2vec/hf_utils.py", "model2vec/utils.py"], "used_names": ["Path", "_get_metadata_from_readme"], "enclosing_function": "test__get_metadata_from_readme_not_exists", "extracted_code": "# Source: model2vec/hf_utils.py\ndef _get_metadata_from_readme(readme_path: Path) -> dict[str, Any]:\n \"\"\"Get metadata from a README file.\"\"\"\n if not readme_path.exists():\n logger.info(f\"README file not found in {readme_path}. No model card loaded.\")\n return {}\n model_card = ModelCard.load(readme_path)\n data: dict[str, Any] = model_card.data.to_dict()\n if not data:\n logger.info(\"File README.md exists, but was empty. No model card loaded.\")\n return data", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 493}, "tests/test_distillation.py::291": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["LogCaptureFixture", "TokenizerModel", "clean_and_create_vocabulary", "pytest"], "enclosing_function": "test_clean_and_create_vocabulary", "extracted_code": "# Source: model2vec/tokenizer/__init__.py\n\nfrom model2vec.tokenizer.tokenizer import ( # noqa: E402\n clean_and_create_vocabulary,\n turn_tokens_into_ids,\n)\n\n__all__ = [\"clean_and_create_vocabulary\", \"turn_tokens_into_ids\"]\n\n)\n\n__all__ = [\"clean_and_create_vocabulary\", \"turn_tokens_into_ids\"]", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 298}, "tests/test_inference.py::24": {"resolved_imports": ["model2vec/inference/__init__.py"], "used_names": ["StaticModelPipeline"], "enclosing_function": "test_init_predict", "extracted_code": "# Source: model2vec/inference/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 411}, "tests/test_model.py::16": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["StaticModel", "Tokenizer"], "enclosing_function": "test_initialization", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_inference.py::87": {"resolved_imports": ["model2vec/inference/__init__.py"], "used_names": ["StaticModelPipeline", "TemporaryDirectory", "os", "pytest"], "enclosing_function": "test_roundtrip_save_file_gone", "extracted_code": "# Source: model2vec/inference/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 411}, "tests/test_trainable.py::155": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification"], "enclosing_function": "test_train_test_split", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_utils.py::62": {"resolved_imports": ["model2vec/distill/utils.py", "model2vec/hf_utils.py", "model2vec/utils.py"], "used_names": ["patch", "pytest", "select_optimal_device"], "enclosing_function": "test_select_optimal_device", "extracted_code": "# Source: model2vec/distill/utils.py\ndef select_optimal_device(device: str | None) -> str:\n \"\"\"\n Get the optimal device to use based on backend availability.\n\n For Torch versions >= 2.8.0, MPS is disabled due to known performance regressions.\n\n :param device: The device to use. If this is None, the device is automatically selected.\n :return: The selected device.\n :raises RuntimeError: If MPS is requested on a PyTorch version where it is disabled.\n \"\"\"\n # Get the torch version and check if MPS is broken\n torch_version = version.parse(torch.__version__.split(\"+\")[0])\n mps_broken = torch_version >= version.parse(\"2.8.0\")\n\n if device:\n if device == \"mps\" and mps_broken:\n raise RuntimeError(\n f\"MPS is disabled for PyTorch {torch.__version__} due to known performance regressions. \"\n \"Please use CPU or CUDA instead, or use a PyTorch version < 2.8.0.\"\n )\n else:\n return device\n\n if torch.cuda.is_available():\n device = \"cuda\"\n elif torch.backends.mps.is_available():\n if mps_broken:\n logger.warning(\n f\"MPS is available but PyTorch {torch.__version__} has known performance regressions. \"\n \"Falling back to CPU. Please use a PyTorch version < 2.8.0 to enable MPS support.\"\n )\n device = \"cpu\"\n else:\n device = \"mps\"\n else:\n device = \"cpu\"\n\n logger.info(f\"Automatically selected device: {device}\")\n return device", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 1541}, "tests/test_quantization.py::44": {"resolved_imports": ["model2vec/quantization.py", "model2vec/vocabulary_quantization.py"], "used_names": ["DType", "quantize_and_reduce_dim"], "enclosing_function": "test_quantize_and_reduce_dim", "extracted_code": "# Source: model2vec/quantization.py\nclass DType(str, Enum):\n Float16 = \"float16\"\n Float32 = \"float32\"\n Float64 = \"float64\"\n Int8 = \"int8\"\n\ndef quantize_and_reduce_dim(\n embeddings: np.ndarray, quantize_to: str | DType | None, dimensionality: int | None\n) -> np.ndarray:\n \"\"\"\n Quantize embeddings to a datatype and reduce dimensionality.\n\n :param embeddings: The embeddings to quantize and reduce, as a numpy array.\n :param quantize_to: The data type to quantize to. If None, no quantization is performed.\n :param dimensionality: The number of dimensions to keep. If None, no dimensionality reduction is performed.\n :return: The quantized and reduced embeddings.\n :raises ValueError: If the passed dimensionality is not None and greater than the model dimensionality.\n \"\"\"\n if quantize_to is not None:\n quantize_to = DType(quantize_to)\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n if dimensionality is not None:\n if dimensionality > embeddings.shape[1]:\n raise ValueError(\n f\"Dimensionality {dimensionality} is greater than the model dimensionality {embeddings.shape[1]}\"\n )\n embeddings = embeddings[:, :dimensionality]\n\n return embeddings", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1267}, "tests/test_trainable.py::73": {"resolved_imports": ["model2vec/model.py", "model2vec/train/__init__.py", "model2vec/train/base.py"], "used_names": ["StaticModelForClassification", "torch"], "enclosing_function": "test_encode", "extracted_code": "# Source: model2vec/train/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]\n\nfrom model2vec.train.classifier import StaticModelForClassification\n\n__all__ = [\"StaticModelForClassification\"]", "n_imports_parsed": 9, "n_files_resolved": 3, "n_chars_extracted": 313}, "tests/test_model.py::218": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["Path", "StaticModel", "Tokenizer"], "enclosing_function": "test_load_pretrained_quantized", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_inference.py::77": {"resolved_imports": ["model2vec/inference/__init__.py"], "used_names": ["StaticModelPipeline", "TemporaryDirectory", "patch", "pytest", "re"], "enclosing_function": "test_roundtrip_save_mock_trust_pattern", "extracted_code": "# Source: model2vec/inference/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 411}, "tests/test_model.py::276": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["Path", "StaticModel", "Tokenizer"], "enclosing_function": "test_load_pretrained_vocabulary_quantized", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_quantization.py::25": {"resolved_imports": ["model2vec/quantization.py", "model2vec/vocabulary_quantization.py"], "used_names": ["DType", "pytest", "quantize_embeddings"], "enclosing_function": "test_quantize_embeddings", "extracted_code": "# Source: model2vec/quantization.py\nclass DType(str, Enum):\n Float16 = \"float16\"\n Float32 = \"float32\"\n Float64 = \"float64\"\n Int8 = \"int8\"\n\ndef quantize_embeddings(embeddings: np.ndarray, quantize_to: DType) -> np.ndarray:\n \"\"\"\n Quantize embeddings to a specified data type to reduce memory usage.\n\n :param embeddings: The embeddings to quantize, as a numpy array.\n :param quantize_to: The data type to quantize to.\n :return: The quantized embeddings.\n :raises ValueError: If the quantization type is not valid.\n \"\"\"\n mapped_dtype = dtype_map[quantize_to]\n if embeddings.dtype == mapped_dtype:\n # Don't do anything if they match\n return embeddings\n\n # Handle float types\n if quantize_to in {DType.Float16, DType.Float32, DType.Float64}:\n return embeddings.astype(mapped_dtype)\n elif quantize_to == DType.Int8:\n # Normalize to [-128, 127] range for int8\n # We normalize to -127 to 127 to keep symmetry.\n scale = np.max(np.abs(embeddings)) / 127.0\n # Turn into float16 to minimize memory usage during computation\n # we copy once.\n buf = embeddings.astype(np.float16, copy=True)\n # Divide by the scale\n np.divide(buf, scale, out=buf)\n # Round to int, copy to the buffer\n np.rint(buf, out=buf)\n # Clip to int8 range and convert to int8\n np.clip(buf, -127, 127, out=buf)\n quantized = buf.astype(np.int8)\n return quantized\n else:\n raise ValueError(\"Not a valid enum member of DType.\")", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1554}, "tests/test_model.py::184": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["Path", "StaticModel", "Tokenizer"], "enclosing_function": "test_load_pretrained", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_model.py::75": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["StaticModel", "Tokenizer"], "enclosing_function": "test_encode_multiple_sentences", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_inference.py::31": {"resolved_imports": ["model2vec/inference/__init__.py"], "used_names": ["StaticModelPipeline"], "enclosing_function": "test_init_predict_proba", "extracted_code": "# Source: model2vec/inference/__init__.py\n importable(extra_dependency, _REQUIRED_EXTRA)\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]\n\nfrom model2vec.inference.model import StaticModelPipeline, evaluate_single_or_multi_label\n\n__all__ = [\"StaticModelPipeline\", \"evaluate_single_or_multi_label\"]", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 411}, "tests/test_model.py::55": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["StaticModel", "Tokenizer"], "enclosing_function": "test_encode_single_sentence", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_distillation.py::80": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["MagicMock", "PreTrainedModel", "PreTrainedTokenizerFast", "distill", "distill_from_model", "import_module", "json", "patch", "pytest"], "enclosing_function": "test_distill_from_model", "extracted_code": "# Source: model2vec/distill/distillation.py\ndef distill_from_model(\n model: PreTrainedModel,\n tokenizer: PreTrainedTokenizerFast,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model: The model to use.\n :param tokenizer: The tokenizer to use.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimensionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled\n into a valid regex, we also throw an error.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel.\n :raises: ValueError if the vocabulary is empty after preprocessing.\n\n \"\"\"\n quantize_to = DType(quantize_to)\n sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)\n\n if vocabulary is None:\n vocabulary = []\n\n device = select_optimal_device(device)\n original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)\n\n # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.\n # Copy the original tokenizer model.\n tokenizer_model = original_tokenizer_model.model_copy(deep=True)\n if tokenizer_model.adds_prefix_space is not None:\n tokenizer_model.adds_prefix_space = True\n\n # Create the vocabulary in the new tokenizer.\n tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)\n # Remove the post processor, this is not necessary.\n tokenizer_model.post_processor = None\n\n # All tokens in a single list.\n all_tokens = tokenizer_model.sorted_vocabulary\n if not all_tokens:\n raise ValueError(\"The vocabulary is empty after preprocessing. Please check your token_remove_pattern.\")\n\n # Turn all _new_ tokens into ids using the original tokenizer\n token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)\n\n # Create the embeddings using the ids from the original tokenizer.\n embeddings = create_embeddings(\n tokenized=token_ids,\n model=model,\n device=device,\n pad_token_id=tokenizer_model.pad_token_id or 0,\n pooling=pooling,\n )\n\n # Maybe apply quantization\n if vocabulary_quantization is not None:\n _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)\n embeddings, token_mapping, weights = quantize_vocabulary(\n n_clusters=vocabulary_quantization, weights=weights, embeddings=np.asarray(embeddings)\n )\n embeddings, _ = post_process_embeddings(embeddings, pca_dims, sif_coefficient=sif_coefficient)\n else:\n # Post-process the embeddings.\n embeddings, weights = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)\n token_mapping = None\n # Quantize the embeddings.\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n model_name = getattr(model, \"name_or_path\", \"\")\n\n config = {\n \"model_type\": \"model2vec\",\n \"architectures\": [\"StaticModel\"],\n \"tokenizer_name\": model_name,\n \"apply_pca\": pca_dims,\n \"sif_coefficient\": sif_coefficient,\n \"hidden_dim\": embeddings.shape[1],\n \"seq_length\": 1000000, # Set this to a high value since we don't have a sequence length limit.\n \"normalize\": True,\n \"pooling\": pooling,\n }\n\n if os.path.exists(model_name):\n # Using a local model. Get the model name from the path.\n model_name = os.path.basename(model_name)\n language = None\n else:\n # Get the language from the model card.\n try:\n info = model_info(model_name)\n language = info.cardData.get(\"language\", None) if info.cardData is not None else None\n except Exception as e:\n # NOTE: bare except because there's many reasons this can fail.\n logger.warning(f\"Couldn't get the model info from the Hugging Face Hub: {e}. Setting language to None.\")\n language = None\n\n return StaticModel(\n vectors=embeddings,\n weights=weights,\n token_mapping=token_mapping,\n tokenizer=tokenizer_model.to_tokenizer(),\n config=config,\n base_model_name=model_name,\n language=language,\n normalize=True,\n )\n\ndef distill(\n model_name: str,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n trust_remote_code: bool = False,\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model_name: The model name to use. Any sentencetransformer compatible model works.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimenionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value >= 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n :param trust_remote_code: Whether to trust the remote code. If this is False, we will only load components coming\n from `transformers`. If this is True, we will load all components.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel\n\n \"\"\"\n model: PreTrainedModel = AutoModel.from_pretrained(model_name, trust_remote_code=trust_remote_code)\n tokenizer = cast(\n PreTrainedTokenizerFast,\n AutoTokenizer.from_pretrained(model_name, trust_remote_code=trust_remote_code, use_fast=True),\n )\n\n return distill_from_model(\n model=model,\n tokenizer=tokenizer,\n vocabulary=vocabulary,\n device=device,\n pca_dims=pca_dims,\n token_remove_pattern=token_remove_pattern,\n sif_coefficient=sif_coefficient,\n quantize_to=quantize_to,\n vocabulary_quantization=vocabulary_quantization,\n pooling=pooling,\n )", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 9727}, "tests/test_model.py::110": {"resolved_imports": ["model2vec/__init__.py"], "used_names": ["StaticModel", "Tokenizer"], "enclosing_function": "test_encode_as_sequence_multiprocessing", "extracted_code": "# Source: model2vec/__init__.py\nfrom model2vec.model import StaticModel, quantize_model\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]\n\nfrom model2vec.version import __version__\n\n__all__ = [\"StaticModel\", \"quantize_model\", \"__version__\"]", "n_imports_parsed": 7, "n_files_resolved": 1, "n_chars_extracted": 292}, "tests/test_distillation.py::126": {"resolved_imports": ["model2vec/distill/distillation.py", "model2vec/distill/inference.py", "model2vec/model.py", "model2vec/tokenizer/__init__.py"], "used_names": ["MagicMock", "PreTrainedModel", "PreTrainedTokenizerFast", "distill_from_model", "import_module", "patch", "pytest"], "enclosing_function": "test_distill_removal_pattern", "extracted_code": "# Source: model2vec/distill/distillation.py\ndef distill_from_model(\n model: PreTrainedModel,\n tokenizer: PreTrainedTokenizerFast,\n vocabulary: list[str] | None = None,\n device: str | None = None,\n pca_dims: PCADimType = 256,\n sif_coefficient: float | None = 1e-4,\n token_remove_pattern: str | None = r\"\\[unused\\d+\\]\",\n quantize_to: DType | str = DType.Float16,\n vocabulary_quantization: int | None = None,\n pooling: PoolingMode | str = PoolingMode.MEAN,\n) -> StaticModel:\n \"\"\"\n Distill a staticmodel from a sentence transformer.\n\n This function creates a set of embeddings from a sentence transformer. It does this by doing either\n a forward pass for all subword tokens in the tokenizer, or by doing a forward pass for all tokens in a passed\n vocabulary.\n\n If you pass through a vocabulary, we create a custom word tokenizer for that vocabulary.\n If you don't pass a vocabulary, we use the model's tokenizer directly.\n\n :param model: The model to use.\n :param tokenizer: The tokenizer to use.\n :param vocabulary: The vocabulary to use. If this is None, we use the model's vocabulary.\n :param device: The device to use.\n :param pca_dims: The number of components to use for PCA.\n If this is None, we don't apply PCA.\n If this is 'auto', we don't reduce dimensionality, but still apply PCA.\n :param sif_coefficient: The SIF coefficient to use. If this is None, no weighting is applied.\n Should be a value > 0 and < 1.0. A value of 1e-4 is a good default.\n :param token_remove_pattern: If this is set to a string, we compile this into a regex. Any tokens that conform to\n this regex pattern will be removed from the vocabulary.\n If the pattern is so general that it removes all tokens, we throw an error. If the pattern can't be compiled\n into a valid regex, we also throw an error.\n :param quantize_to: The data type to quantize to. Can be any of the DType enum members or their string equivalents.\n :param vocabulary_quantization: The number of clusters to use for vocabulary quantization. If this is None, no\n quantization is performed.\n :param pooling: The pooling mode to use for creating embeddings. Can be one of:\n 'mean' (default): mean over all tokens. Robust and works well in most cases.\n 'last': use the last token's hidden state (often the [EOS] token). Common for decoder-style models.\n 'first': use the first token's hidden state ([CLS] token in BERT-style models).\n 'pooler': use the pooler output (if available). This is often a non-linear projection of the [CLS] token.\n :return: A StaticModel.\n :raises: ValueError if the vocabulary is empty after preprocessing.\n\n \"\"\"\n quantize_to = DType(quantize_to)\n sif_coefficient, token_remove_regex = _validate_parameters(sif_coefficient, token_remove_pattern)\n\n if vocabulary is None:\n vocabulary = []\n\n device = select_optimal_device(device)\n original_tokenizer_model = TokenizerModel.from_transformers_tokenizer(tokenizer)\n\n # Clean the vocabulary by removing duplicate tokens and tokens that are in the internal vocabulary.\n # Copy the original tokenizer model.\n tokenizer_model = original_tokenizer_model.model_copy(deep=True)\n if tokenizer_model.adds_prefix_space is not None:\n tokenizer_model.adds_prefix_space = True\n\n # Create the vocabulary in the new tokenizer.\n tokenizer_model = clean_and_create_vocabulary(tokenizer_model, vocabulary, token_remove_regex=token_remove_regex)\n # Remove the post processor, this is not necessary.\n tokenizer_model.post_processor = None\n\n # All tokens in a single list.\n all_tokens = tokenizer_model.sorted_vocabulary\n if not all_tokens:\n raise ValueError(\"The vocabulary is empty after preprocessing. Please check your token_remove_pattern.\")\n\n # Turn all _new_ tokens into ids using the original tokenizer\n token_ids = turn_tokens_into_ids(all_tokens, original_tokenizer_model)\n\n # Create the embeddings using the ids from the original tokenizer.\n embeddings = create_embeddings(\n tokenized=token_ids,\n model=model,\n device=device,\n pad_token_id=tokenizer_model.pad_token_id or 0,\n pooling=pooling,\n )\n\n # Maybe apply quantization\n if vocabulary_quantization is not None:\n _, weights = post_process_embeddings(np.asarray(embeddings), None, sif_coefficient=sif_coefficient)\n embeddings, token_mapping, weights = quantize_vocabulary(\n n_clusters=vocabulary_quantization, weights=weights, embeddings=np.asarray(embeddings)\n )\n embeddings, _ = post_process_embeddings(embeddings, pca_dims, sif_coefficient=sif_coefficient)\n else:\n # Post-process the embeddings.\n embeddings, weights = post_process_embeddings(np.asarray(embeddings), pca_dims, sif_coefficient=sif_coefficient)\n token_mapping = None\n # Quantize the embeddings.\n embeddings = quantize_embeddings(embeddings, quantize_to)\n\n model_name = getattr(model, \"name_or_path\", \"\")\n\n config = {\n \"model_type\": \"model2vec\",\n \"architectures\": [\"StaticModel\"],\n \"tokenizer_name\": model_name,\n \"apply_pca\": pca_dims,\n \"sif_coefficient\": sif_coefficient,\n \"hidden_dim\": embeddings.shape[1],\n \"seq_length\": 1000000, # Set this to a high value since we don't have a sequence length limit.\n \"normalize\": True,\n \"pooling\": pooling,\n }\n\n if os.path.exists(model_name):\n # Using a local model. Get the model name from the path.\n model_name = os.path.basename(model_name)\n language = None\n else:\n # Get the language from the model card.\n try:\n info = model_info(model_name)\n language = info.cardData.get(\"language\", None) if info.cardData is not None else None\n except Exception as e:\n # NOTE: bare except because there's many reasons this can fail.\n logger.warning(f\"Couldn't get the model info from the Hugging Face Hub: {e}. Setting language to None.\")\n language = None\n\n return StaticModel(\n vectors=embeddings,\n weights=weights,\n token_mapping=token_mapping,\n tokenizer=tokenizer_model.to_tokenizer(),\n config=config,\n base_model_name=model_name,\n language=language,\n normalize=True,\n )", "n_imports_parsed": 15, "n_files_resolved": 4, "n_chars_extracted": 6430}}}