Skip to content

Commit 83b72b8

Browse files
authored
fix: add token dropout to pair trainer (#393)
1 parent f8523cd commit 83b72b8

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

‎model2vec/train/pairs.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,7 @@ def fit(
279279
validation_steps: int | None = None,
280280
random_seed: int = DEFAULT_RANDOM_SEED,
281281
temperature: float = 0.05,
282+
token_dropout: float = 0.0,
282283
) -> T:
283284
"""Fit a model that embeds paired texts close together.
284285
@@ -313,6 +314,8 @@ def fit(
313314
:param validation_steps: The number of steps to run validation for. If None, validation steps are estimated from the data.
314315
:param random_seed: The random seed to use. Defaults to 42.
315316
:param temperature: The temperature of the InfoNCE loss.
317+
:param token_dropout: The fraction of tokens to randomly drop from each training text.
318+
Has no effect during validation. Must be in the range [0, 1).
316319
:return: The fitted model.
317320
:raises ValueError: If `batch_size` is smaller than 2.
318321
"""
@@ -339,6 +342,7 @@ def fit(
339342
max_epochs=max_epochs,
340343
device=device,
341344
validation_steps=validation_steps,
345+
token_dropout=token_dropout,
342346
)
343347

344348
return self

‎tests/test_trainable.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -833,6 +833,19 @@ def test_pair_similarity_fit_rejects_invalid_temperature_and_batch_size(
833833
model.fit(text_a, text_b, test_size=0.5, batch_size=1)
834834

835835

836+
def test_pair_similarity_fit_token_dropout(mock_vectors: np.ndarray, mock_tokenizer: Tokenizer) -> None:
837+
"""fit() passes token_dropout to training and rejects values outside [0, 1)."""
838+
model = StaticModelForPairSimilarity(vectors=torch.from_numpy(mock_vectors).float(), tokenizer=mock_tokenizer)
839+
text_a, text_b = ["word1", "word2", "word3", "word1 word2"], ["word2", "word3", "word1", "word3"]
840+
with pytest.raises(ValueError, match="token_dropout"):
841+
model.fit(text_a, text_b, test_size=0.5, token_dropout=1.0)
842+
with pytest.raises(ValueError, match="token_dropout"):
843+
model.fit(text_a, text_b, test_size=0.5, token_dropout=-0.1)
844+
845+
model.fit(text_a, text_b, test_size=0.5, token_dropout=0.3, max_epochs=1)
846+
assert model.token_dropout == 0.3
847+
848+
836849
def test_pairdataset_drops_single_pair_batches() -> None:
837850
"""A final batch with a single pair is dropped, unless it is the only pair."""
838851
dataset = PairDataset(ColumnRows(text_a=[[1], [2], [3]], text_b=[[1], [2], [3]]), _pretokenized)

0 commit comments

Comments
 (0)