data_collator.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. from __future__ import annotations
  2. import logging
  3. from dataclasses import dataclass, field
  4. from typing import Any, Callable
  5. import torch
  6. logger = logging.getLogger(__name__)
  7. @dataclass
  8. class SentenceTransformerDataCollator:
  9. """Collator for a SentenceTransformers model.
  10. This encodes the text columns to {column}_input_ids and {column}_attention_mask columns.
  11. This works with the two text dataset that is used as the example in the training overview:
  12. https://www.sbert.net/docs/sentence_transformer/training_overview.html
  13. It is important that the columns are in the expected order. For example, if your dataset has columns
  14. "answer", "question" in that order, then the MultipleNegativesRankingLoss will consider
  15. "answer" as the anchor and "question" as the positive, and it will (unexpectedly) optimize for
  16. "given the answer, what is the question?".
  17. """
  18. tokenize_fn: Callable
  19. valid_label_columns: list[str] = field(default_factory=lambda: ["label", "score"])
  20. _warned_columns: set[tuple[str]] = field(default_factory=set, init=False, repr=False)
  21. def __call__(self, features: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
  22. column_names = list(features[0].keys())
  23. # We should always be able to return a loss, label or not:
  24. batch = {}
  25. if "dataset_name" in column_names:
  26. column_names.remove("dataset_name")
  27. batch["dataset_name"] = features[0]["dataset_name"]
  28. if tuple(column_names) not in self._warned_columns:
  29. self.maybe_warn_about_column_order(column_names)
  30. # Extract the label column if it exists
  31. for label_column in self.valid_label_columns:
  32. if label_column in column_names:
  33. batch["label"] = torch.tensor([row[label_column] for row in features])
  34. column_names.remove(label_column)
  35. break
  36. # Extract the feature columns
  37. for column_name in column_names:
  38. tokenized = self.tokenize_fn([row[column_name] for row in features])
  39. for key, value in tokenized.items():
  40. batch[f"{column_name}_{key}"] = value
  41. return batch
  42. def maybe_warn_about_column_order(self, column_names: list[str]) -> None:
  43. """Warn the user if the columns are likely not in the expected order."""
  44. # A mapping from common column names to the expected index in the dataset
  45. column_name_to_expected_idx = {
  46. "anchor": 0,
  47. "positive": 1,
  48. "negative": 2,
  49. "question": 0,
  50. "answer": 1,
  51. "query": 0,
  52. "response": 1,
  53. "hypothesis": 0,
  54. "entailment": 1,
  55. "contradiction": 2,
  56. }
  57. for column_name, expected_idx in column_name_to_expected_idx.items():
  58. if column_name in column_names and column_names.index(column_name) != expected_idx:
  59. if column_name in ("anchor", "positive", "negative"):
  60. proposed_fix_columns = ["anchor", "positive", "negative"]
  61. elif column_name in ("question", "answer"):
  62. proposed_fix_columns = ["question", "answer"]
  63. elif column_name in ("query", "response"):
  64. proposed_fix_columns = ["query", "response"]
  65. elif column_name in ("hypothesis", "entailment", "contradiction"):
  66. proposed_fix_columns = ["hypothesis", "entailment", "contradiction"]
  67. logger.warning(
  68. f"Column {column_name!r} is at index {column_names.index(column_name)}, whereas "
  69. f"a column with this name is usually expected at index {expected_idx}. Note that the column "
  70. "order can be important for some losses, e.g. MultipleNegativesRankingLoss will always "
  71. "consider the first column as the anchor and the second as the positive, regardless of "
  72. "the dataset column names. Consider renaming the columns to match the expected order, e.g.:\n"
  73. f"dataset = dataset.select_columns({proposed_fix_columns})"
  74. )
  75. # We only need to warn once per list of column names to prevent spamming the user
  76. break
  77. self._warned_columns.add(tuple(column_names))