An embedding training job can divide its batches between processes while keeping one synchronized model. Sentence Transformers uses distributed data parallel training through PyTorch, and a two-process CPU job on Linux can exercise training, distributed evaluation, and saving without a GPU.

Each process, called a rank, holds a model replica and contributes gradients to the same optimizer updates. Starting with Sentence Transformers 6.2.0, an evaluator attached to the trainer also shares its embedding work between ranks. Rank zero assembles the predictions, computes one set of metrics, and broadcasts those metrics to the other ranks.

The small public MiniLM checkpoint and synthetic sentence pairs keep the CPU workload bounded. Two optimizer updates demonstrate the distributed lifecycle; they do not establish embedding quality or GPU speedup. Gloo handles CPU communication, while measuring NCCL performance requires a separate multi-GPU workload and a single-GPU baseline.

Steps to run distributed training in Sentence Transformers:

  1. Create a fresh Python virtual environment in your project directory.
    $ python3 -m venv .venv

    A Linux shell, internet access for public package and model downloads, and Python 3.10 or newer are required. On Ubuntu or Debian, the matching python3-venv package supplies environment creation.
    Related: Install Python on Ubuntu or Debian
    Related: Create a Python virtual environment

  2. Activate the project environment.
    $ source .venv/bin/activate
  3. Install CPU PyTorch in the environment.
    $ python -m pip install torch --index-url https://download.pytorch.org/whl/cpu

    The CPU wheel is sufficient for this Linux job. It does not provide a CUDA runtime.
    Related: Install Sentence Transformers with pip

  4. Install the Sentence Transformers training extra at version 6.2.0.
    $ python -m pip install "sentence-transformers[train]==6.2.0"

    The training extra supplies datasets and accelerate. The version pin includes distributed evaluator inference; older releases can evaluate on rank zero alone.

  5. Create train_distributed.py in your text editor with the initial imports and checkpoint loader below.
    train_distributed.py
    from datasets import Dataset
    from sentence_transformers import (
        SentenceTransformer,
        SentenceTransformerTrainer,
        SentenceTransformerTrainingArguments,
    )
    from sentence_transformers.sentence_transformer import losses
    from sentence_transformers.sentence_transformer.evaluation import (
        EmbeddingSimilarityEvaluator,
    )
     
     
    def main():
        model = SentenceTransformer("sentence-transformers/paraphrase-MiniLM-L3-v2")

    The public checkpoint needs no sign-in or custom model code. The main() function keeps training behind the process entry point added below.

  6. Append the training pairs inside main() immediately after model initialization.
        pairs = [
            ("A cat sits on a mat.", "A cat is resting on the rug.", 0.9),
            ("A dog runs outside.", "A dog is running outdoors.", 0.9),
            ("Someone cooks dinner.", "A person prepares a meal.", 0.8),
            ("The train has arrived.", "The train is at the station.", 0.8),
            ("A cat sits on a mat.", "An airplane is taking off.", 0.0),
            ("A dog runs outside.", "Someone reads a book.", 0.1),
            ("Someone cooks dinner.", "The road is covered in snow.", 0.0),
            ("The train has arrived.", "A child paints a picture.", 0.1),
        ]
        train_dataset = Dataset.from_dict({
            "sentence1": [a for a, b, score in pairs],
            "sentence2": [b for a, b, score in pairs],
            "label": [score for a, b, score in pairs],
        })

    Each row contains two texts and a similarity label between zero and one. CosineSimilarityLoss will fit their embedding cosine similarity to that label. These eight synthetic rows supply two batches per rank at a batch size of two.

  7. Append the held-out similarity evaluator after the training dataset.
        evaluator = EmbeddingSimilarityEvaluator(
            sentences1=[
                "A person rides a bicycle.", "A woman plays the piano.",
                "It is raining outside.", "Two people are talking.",
            ],
            sentences2=[
                "Someone cycles down the street.", "Someone plays music.",
                "A man repairs a computer.", "A plane crosses the sky.",
            ],
            scores=[0.9, 0.7, 0.1, 0.0],
            name="demo",
            similarity_fn_names=["cosine"],
        )

    The evaluator compares predicted similarities with four held-out labels. No explicit device or pool is passed, allowing the trainer to distribute its inference calls. Calling evaluator(model) directly would keep normal single-process evaluation.

  8. Append the CPU distributed training configuration after the evaluator.
        args = SentenceTransformerTrainingArguments(
            output_dir="distributed-output",
            use_cpu=True,
            ddp_backend="gloo",
            per_device_train_batch_size=2,
            max_steps=2,
            learning_rate=2e-5,
            optim="adamw_torch",
            logging_steps=1,
            save_strategy="no",
            dataloader_pin_memory=False,
            disable_tqdm=True,
            report_to="none",
        )
        trainer = SentenceTransformerTrainer(
            model=model,
            args=args,
            train_dataset=train_dataset,
            loss=losses.CosineSimilarityLoss(model),
            evaluator=evaluator,
        )

    Two ranks with two rows per device produce a global batch of four. max_steps=2 bounds the optimizer work. CPU execution uses unfused AdamW and does not need pinned CUDA transfer memory. Automatic intermediate checkpoint saving is disabled because the final model is saved explicitly.

    The output paths distributed-output and distributed-model should be unused for a new experiment. A rerun can replace an earlier saved model and metrics at those paths.

  9. Append training, evaluation, saving, and the process entry point after the trainer.
        trainer.train()
        metrics = trainer.evaluate()
        trainer.save_model("distributed-model")
        trainer.accelerator.wait_for_everyone()
        print(
            f"rank={args.process_index} world_size={args.world_size} "
            f"steps={trainer.state.global_step} completed",
            flush=True,
        )
        if trainer.is_world_process_zero():
            trainer.save_metrics("eval", metrics)
            print(f"eval_demo_spearman_cosine={metrics['eval_demo_spearman_cosine']}")
     
     
    if __name__ == "__main__":
        main()

    Every rank enters trainer.evaluate() so the shared inference calls can finish. SentenceTransformerTrainer restricts model writes to the saving rank; the explicit rank-zero branch writes one metrics JSON file and prints its correlation. The barrier waits for all ranks before they report completion.

  10. Save train_distributed.py in your editor.
  11. Launch the script as one job with two local CPU ranks.
    $ OMP_NUM_THREADS=2 torchrun --standalone --nnodes=1 --nproc-per-node=2 train_distributed.py
    ##### snipped #####
    rank=1 world_size=2 steps=2 completed
    rank=0 world_size=2 steps=2 completed
    eval_demo_spearman_cosine=0.7999999999999999

    torchrun assigns the ranks and starts a local rendezvous. Two CPU threads per process avoid oversubscribing a four-core machine. Both rank=0 world_size=2 steps=2 completed and rank=1 world_size=2 steps=2 completed should appear; their order can vary. The preceding output includes model downloads and training statistics. Unauthenticated Hub warnings concern download rate limits; no token is needed for this public model. The trainer enables last-batch dropping for DDP, and a PyTorch buffer deprecation warning can appear with current Accelerate. A child-process error or a missing completion line means the job has not finished successfully. The upstream distributed training documentation covers GPU launch choices; CPU completion does not measure GPU performance.

  12. Read the saved evaluation metrics. Example output:
    $ python -m json.tool distributed-output/eval_results.json
    {
        "epoch": 1.0,
        "eval_demo_pearson_cosine": 0.9567006552100051,
        "eval_demo_spearman_cosine": 0.7999999999999999,
        "eval_runtime": 0.0237,
        "eval_samples_per_second": 0.0,
        "eval_steps_per_second": 0.0
    }

    The correlation values and timing vary. This is one metrics object for all four evaluation pairs, rather than one score file per rank. Four synthetic pairs are too few to estimate production quality.

  13. Create reload_distributed.py with a local model reload and embedding call.
    reload_distributed.py
    import numpy as np
    from sentence_transformers import SentenceTransformer
     
    model = SentenceTransformer("distributed-model", local_files_only=True)
    embeddings = model.encode([
        "A person rides a bicycle.",
        "Someone cycles down the street.",
    ])
    print("embedding shape:", embeddings.shape)
    print("finite embeddings:", bool(np.isfinite(embeddings).all()))
  14. Save reload_distributed.py in your editor.
  15. Verify that the saved trained model generates finite embeddings.
    $ python reload_distributed.py
    ##### snipped #####
    embedding shape: (2, 384)
    finite embeddings: True

    The local-only load must succeed without downloading another checkpoint. A missing model directory, incompatible saved files, a different shape, or non-finite values requires investigation before using the trained model.

Share this guide