In Sentence Transformers, how does SentenceTransformerTrainer decide which dataset column is the anchor, which is the positive and which is the label?
answer
- position beats naming
- four reserved label names
- stray metadata columns
- Dataset.select_columns
- the loss used when none is passed
basics
~20 sBy position. A column named label, labels, score or scores becomes the label; every other column is an input in dataset order, so the first is the anchor and the second the positive, whatever they are called.
solid answer
~40 sThe trainer's data collator first looks for a column named `label`, `labels`, `score` or `scores` and turns it into the label tensor. Every other column is an input, taken in the dataset's column order: the names are ignored, only the position counts. So a dataset ordered `["answer", "question"]` trains `MultipleNegativesRankingLoss` with the answer as the anchor, and a leftover `source` column is fed to the model as one more input, which that loss reads as a hard negative. Before training I fix the shape with `Dataset.select_columns(["question", "answer"])`, which keeps and orders the columns, or `remove_columns`. The number of input columns must match what the loss accepts, and I always pass `loss=` explicitly: without it the trainer falls back to `CoSENTLoss`, which expects a float score label.
code
python · 19 linesfrom datasets import Dataset
from sentence_transformers import SentenceTransformer, SentenceTransformerTrainer
from sentence_transformers.sentence_transformer.losses import MultipleNegativesRankingLoss
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
raw = Dataset.from_dict({
"ticket_id": ["T-1", "T-2"],
"answer": ["Reset it under Settings, Security.", "Invoices are listed under Billing."],
"question": ["How do I reset two-factor login?", "Where do I find my invoice?"],
})
# Names are ignored, order is not: keep the inputs and put the anchor first.
train_dataset = raw.select_columns(["question", "answer"])
trainer = SentenceTransformerTrainer(
model=model,
train_dataset=train_dataset,
loss=MultipleNegativesRankingLoss(model), # omitted, the trainer would use CoSENTLoss
)
trainer.train()go deeper
Recall that inputs are read by position and that only label, labels, score or scores count as a label. Say how you would put the question first.
Explain how the collator splits label from inputs, why an extra column silently becomes another input, and why select_columns, not rename_column, fixes order.
Show the habit of asserting column_names before every run, passing the loss explicitly, and reading the collator's order and ID warnings as real defects, not noise.
Treat the column order as an interface between data and training code: own a shared dataset schema and a pre-training check so a reordered export cannot quietly retrain a production model.
## What the trainer is handed `SentenceTransformerTrainer` takes a `model` (a `SentenceTransformer`), optional `args` (`SentenceTransformerTrainingArguments`), a `train_dataset` (a Hugging Face `datasets.Dataset`, or a dict of them), an optional `eval_dataset`, a `loss` and an optional `evaluator`. Nothing in that list says which column is a query and which is a document. The **dataset format contract** is implicit, and it is enforced by the trainer's data collator rather than by any schema you declare. ## The column contract, step by step For every batch the collator does the following: 1. It looks for a **label column**, checking the names `label`, `labels`, `score` and `scores` in that order, and takes the first one present as the label tensor passed to the loss. 2. It treats **every remaining column as an input**, in the order the dataset stores them. The column names are irrelevant; only the position matters. 3. It tokenizes each input column and hands the loss one feature batch per column. The loss then interprets them positionally: for `MultipleNegativesRankingLoss` the first column is the anchor, the second the positive, and any further columns are hard negatives. So the number of non-label columns must match what the chosen loss accepts, and their order must match what the loss assumes. ## What goes wrong when the shape is off | Dataset columns | Loss | What the loss actually sees | |---|---|---| | `question, answer` | `MultipleNegativesRankingLoss` | anchor = question, positive = answer: correct | | `answer, question` | `MultipleNegativesRankingLoss` | anchor = answer, positive = question: the direction is reversed | | `question, answer, source` | `MultipleNegativesRankingLoss` | `source` becomes a hard negative for every row | | `question, answer, ticket_id` | `MultipleNegativesRankingLoss` | the ID is tokenized and trained on as text | | `sentence1, sentence2, score` | `CoSENTLoss` | two inputs plus a float label: correct | The library helps a little. The collator warns once when a familiar name sits at an unusual index (a `question` column that is not first, an `answer` that is not second, `anchor` / `positive` / `negative` out of order), and it warns when a column called `id` or ending in `_id` is about to be tokenized as text. Those are **warnings, not errors**: training still runs on the wrong shape, and the only symptom may be a dev metric that refuses to move. ## Fixing the shape before training - **`Dataset.select_columns([...])`** keeps only the listed columns, in the listed order. It is the one call that both drops extras and reorders. - **`Dataset.remove_columns([...])`** drops metadata such as sample IDs, sources or types without touching the order of the rest. - **`Dataset.rename_column`** makes the intent readable, but renaming does **not** reorder: an `answer` column renamed to `positive` is still the anchor if it comes first. - Print `train_dataset.column_names` right before building the trainer; it is the cheapest check in the whole run. - Keep the label column under one of the four reserved names. A float column called `similarity` is not a label: it becomes a third input. ## Several datasets, several contracts The trainer also accepts a dict of datasets (or a `DatasetDict`) as `train_dataset`, together with an optional dict of losses keyed by the same dataset names. The column contract then applies **per dataset**: a `(question, answer)` set can feed `MultipleNegativesRankingLoss` while a `(sentence1, sentence2, score)` set feeds `CoSENTLoss`, and neither needs to be reshaped into the other's format. Each batch is drawn from a single dataset, so the shapes never mix inside one loss call. Which dataset the next batch comes from is set by `multi_dataset_batch_sampler`; the default, `MultiDatasetBatchSamplers.PROPORTIONAL`, samples in proportion to dataset size and uses every row, while `ROUND_ROBIN` alternates evenly and may leave rows of the larger datasets unused. ## Always pass the loss If `loss` is omitted, the trainer builds `CoSENTLoss(model)` and logs that it did so. It does **not** inspect the data and pick a loss for you. `CoSENTLoss` expects pairs with a float score, so a label-less `(question, answer)` dataset is the wrong match for it. Choose the loss from the shape of the data and pass it explicitly. ## Where column names do matter Names are ignored for the input/label split, but a few training arguments are keyed by name. The `prompts` argument of `SentenceTransformerTrainingArguments` can map a column name to a prompt string (for example a query prefix on the `question` column only), and `router_mapping` maps columns to routes for asymmetric models. When you use those, the names you chose must match the ones in the mapping, while the order still decides the anchor and the positive.
- Your dataset stores a float relevance column called similarity. What does the trainer do with it?It treats it as an input, not a label, because only `label`, `labels`, `score` and `scores` are recognised as label columns. A three-input dataset then reaches a loss such as `CoSENTLoss` that expects two inputs and a label, which fails or trains on nonsense. Rename it with `rename_column("similarity", "score")`.
- Does renaming answer to anchor and question to positive fix a dataset stored as answer, question?No. Renaming changes the names, not the positions, and positions are what the collator uses, so the answer is still the first input and still the anchor. Reorder with `select_columns(["question", "answer"])`; renaming afterwards is only for readability.
- The trainer matches columns by name, so they must be called anchor and positive.
- Extra metadata columns are ignored by SentenceTransformerTrainer.
- Leaving out the loss makes the trainer choose one from the data shape.
- Any numeric column is picked up as the label automatically.
- Renaming the columns to anchor and positive fixes a wrong column order.