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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions model2vec/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,7 @@ def _encode_dispatch(
total_batches = math.ceil(len(sentences) / batch_size)

self._set_max_length_in_tokenizer(max_length)
previous_parallelism = os.environ.get("TOKENIZERS_PARALLELISM")
try:
if use_multiprocessing and len(sentences) > multiprocessing_threshold:
# Disable parallelism for tokenizers
Expand All @@ -291,6 +292,10 @@ def _encode_dispatch(
]
finally:
self._set_max_length_in_tokenizer(self.max_length)
if previous_parallelism is None:
os.environ.pop("TOKENIZERS_PARALLELISM", None)
else:
os.environ["TOKENIZERS_PARALLELISM"] = previous_parallelism
Comment thread
stephantul marked this conversation as resolved.
Resolved

return results, was_single

Expand Down
19 changes: 19 additions & 0 deletions tests/test_model.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
from pathlib import Path

import numpy as np
Expand Down Expand Up @@ -112,6 +113,24 @@ def test_encode_multiprocessing(
assert encoded.shape == (15000, 2)


@pytest.mark.parametrize("previous", [None, "true"])
def test_encode_multiprocessing_restores_tokenizers_parallelism(
mock_vectors: np.ndarray,
mock_tokenizer: Tokenizer,
mock_config: dict[str, str],
monkeypatch: pytest.MonkeyPatch,
previous: str | None,
) -> None:
"""Test that multiprocessing encoding restores TOKENIZERS_PARALLELISM."""
if previous is None:
monkeypatch.delenv("TOKENIZERS_PARALLELISM", raising=False)
else:
monkeypatch.setenv("TOKENIZERS_PARALLELISM", previous)
model = StaticModel(vectors=mock_vectors, tokenizer=mock_tokenizer, config=mock_config)
model.encode(["word1 word2"] * 15_000, use_multiprocessing=True)
assert os.environ.get("TOKENIZERS_PARALLELISM") == previous
Comment on lines +130 to +131

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Failed calls lack cleanup coverage

The new test checks restoration only after a successful encode. Add a case where a batch raises, then check that the original environment value is restored and the exception still reaches the caller. Otherwise, moving cleanup outside finally would pass this test while leaving parallelism disabled after failed requests.



def test_encode_as_sequence_max_length(
mock_vectors: np.ndarray, mock_tokenizer: Tokenizer, mock_config: dict[str, str]
) -> None:
Expand Down
Loading