General-purpose embedding models often misread a trade's shorthand, ranking a sentence that shares its words above one that shares its meaning. A LoRA adapter from Hugging Face PEFT teaches a Sentence Transformers model that vocabulary and stores what it learned in files small enough to keep beside the unchanged base model, ready to reload whenever the application needs them.

LoRA adds small low-rank weight updates to chosen layers and freezes the rest of the network, so training touches only a fraction of the model's parameters. The result stays separate from the base, with adapter_model.safetensors holding the learned updates and adapter_config.json naming the model they apply to, so an application still needs access to that base model when it loads the adapter.

A small adapter also gives a small proof. Fourteen warehouse rows can correct a few jargon rankings on a CPU, but they do not make a production model, so judge any adapter on sentences it never saw during training and compare the scores with the base model's. Identical scores mean the adapter changed nothing.

Steps to train a LoRA adapter with Sentence Transformers:

  1. Create a project directory for the adapter.
    $ mkdir warehouse-adapter
  2. Change to the project directory.
    $ cd warehouse-adapter
  3. Create a Python virtual environment in the project directory.
    $ python3 -m venv .venv

    If Ubuntu reports that ensurepip is not available, the python3-venv package is missing, so install it with sudo apt install python3-venv and repeat this command.
    Related: Create a Python virtual environment

  4. Activate the virtual environment.
    $ source .venv/bin/activate
  5. Install the CPU build of PyTorch.
    $ python -m pip install torch \
        --index-url https://download.pytorch.org/whl/cpu
    Looking in indexes: https://download.pytorch.org/whl/cpu
    Collecting torch
    ##### snipped #####
    Successfully installed ##### snipped ##### torch-2.15.0+cpu

    On Linux for arm64, this build kept the environment near 1.6 GB, while the default wheel reached 6.2 GB. On a machine with a supported GPU, install the matching PyTorch build instead.
    Related: How to install Sentence Transformers with pip

  6. Install Sentence Transformers and PEFT in the same environment.
    $ python -m pip install "sentence-transformers[train]" peft
    Collecting sentence-transformers[train]
    ##### snipped #####
    Successfully installed ##### snipped ##### transformers-5.22.2

    The train extra adds datasets and accelerate for the trainer, but it does not include PEFT, so that package is named separately. Tested with Sentence Transformers 6.2.0, PEFT 0.21.2, Transformers 5.22.2 and PyTorch 2.15.0 on Python 3.14 and Ubuntu 26.04 for arm64.

  7. Create a file named train_adapter.py in the project directory using your text editor.
  8. Enter the imports and the base model name.
    train_adapter.py
    from datasets import Dataset
    from peft import LoraConfig, TaskType
    from sentence_transformers import (
        SentenceTransformer,
        SentenceTransformerTrainer,
        SentenceTransformerTrainingArguments,
    )
    from sentence_transformers.sentence_transformer.losses import (
        MultipleNegativesRankingLoss,
    )
     
    base_model = "sentence-transformers/all-MiniLM-L6-v2"

    all-MiniLM-L6-v2 is a small public model that downloads without a token.

  9. Add the training rows below the model name, using your own domain's sentences instead of these warehouse rows for a real adapter.
    anchors = [
        "We short shipped the Boston order",
        "The supplier short shipped twelve cartons",
        "A short shipment needs a claim",
        "The invoice shows a short ship",
        "Customers complain when we short ship",
        "That pallet was short shipped by two cases",
        "Cycle count zone B tonight",
        "The cycle count found a variance",
        "Schedule the weekly cycle counts",
        "Cycle count the fast movers first",
        "The carrier missed the dock appointment",
        "Move the dock appointment to Monday",
        "Every inbound load needs a dock appointment",
        "The dock appointment was confirmed",
    ]
    positives = [
        "The Boston order went out with items missing",
        "Twelve cartons were missing from the supplier delivery",
        "Report the delivery that came with too few units",
        "The invoice lists more goods than actually arrived",
        "Customers complain when boxes arrive with too few items",
        "The pallet arrived two cases below the ordered amount",
        "Count the inventory on the shelves in zone B tonight",
        "Counting the shelf stock showed a different quantity",
        "Plan the regular partial stock checks each week",
        "Check stock levels of the best selling items first",
        "The truck did not arrive for its unloading time slot",
        "Change the truck unloading slot to Monday",
        "Each arriving truck must reserve a time to unload",
        "The unloading slot for the delivery truck was approved",
    ]
    negatives = [
        "The Boston order shipped ahead of schedule",
        "The supplier shipped twelve cartons on time",
        "An early shipment needs no claim",
        "The invoice shows the order shipped quickly",
        "Customers complain when we ship late",
        "That pallet was shipped two days early",
        "Cycle through zone B on a bike tonight",
        "The cycling team found a variance in lap times",
        "Schedule the weekly cycling class",
        "Cycle the fast riders to the front first",
        "The carrier missed the dentist appointment",
        "Move the doctor appointment to Monday",
        "Every new patient needs a medical appointment",
        "The hospital appointment was confirmed",
    ]
    train_dataset = Dataset.from_dict(
        {
            "anchor": anchors,
            "positive": positives,
            "negative": negatives,
        }
    )

    Each row pairs a jargon sentence with a plain-language sentence of the same meaning. The negative column holds a sentence that shares the anchor's words but means something else, because that word overlap is the mistake the adapter has to unlearn.

  10. Add the LoRA configuration below the training rows.
    model = SentenceTransformer(base_model)
    peft_config = LoraConfig(
        task_type=TaskType.FEATURE_EXTRACTION,
        r=16,
        lora_alpha=32,
        lora_dropout=0.1,
    )
    model.add_adapter(peft_config)

    r sets the size of the low-rank update and lora_alpha scales its effect. The FEATURE_EXTRACTION task matches an embedding model. With no target_modules setting, PEFT chooses the layers from the architecture, which is query and value for this model. These settings train about 147,000 of its 22.9 million parameters.
    Related: Training with PEFT adapters

  11. Add the loss and trainer below the adapter call.
    args = SentenceTransformerTrainingArguments(
        output_dir="training-output",
        num_train_epochs=30,
        per_device_train_batch_size=6,
        learning_rate=1e-3,
        logging_strategy="no",
        save_strategy="no",
    )
    trainer = SentenceTransformerTrainer(
        model=model,
        args=args,
        train_dataset=train_dataset,
        loss=MultipleNegativesRankingLoss(model),
    )
    result = trainer.train()
    print(f"Training steps: {result.global_step}")
    print(f"Average loss: {result.training_loss:.4f}")

    Thirty epochs and a learning rate of 1e-3 suit these 14 rows. The upstream recipe trains on one million pairs for one epoch at 2e-5, so treat these values as a starting point for a small sample. Setting logging_strategy="no" and save_strategy="no" skips the periodic loss lines and intermediate checkpoints.
    Related: How to train with multiple negatives ranking loss in Sentence Transformers

  12. Add the save call at the end of the file.
    model.save_pretrained("adapter")

    The model still carries its adapter here, so save_pretrained() writes the adapter weights instead of a full copy of the base model.

  13. Save train_adapter.py.
  14. Run the training script.
    $ python train_adapter.py
    ##### snipped #####
    Training steps: 90
    Average loss: 0.3342

    The average loss describes only how well the adapter fits these 14 rows, so the held-out comparison below is the real test. The unauthenticated Hugging Face warning and the pin_memory warning on a CPU are harmless.

  15. List the saved adapter files with their sizes.
    $ du -h adapter/*
    8.0K	adapter/1_Pooling
    8.0K	adapter/2_Normalize
    16K	adapter/README.md
    4.0K	adapter/adapter_config.json
    580K	adapter/adapter_model.safetensors
    4.0K	adapter/config_sentence_transformers.json
    4.0K	adapter/modules.json
    4.0K	adapter/sentence_bert_config.json
    696K	adapter/tokenizer.json
    4.0K	adapter/tokenizer_config.json

    adapter_model.safetensors is the adapter's weights, and the directory has no model.safetensors because the base weights were not copied. At 580K it is under 1% of the base model's 87M file. adapter_config.json and adapter_model.safetensors are enough to reapply the adapter to the base model, and the other files hold the tokenizer and pipeline settings. The base_model_name_or_path entry in adapter_config.json names the base model.

  16. Create a file named check_adapter.py in the project directory using your text editor.
  17. Enter the held-out sentences and a scoring function, using your own domain's sentences for a real adapter.
    check_adapter.py
    from sentence_transformers import SentenceTransformer
     
    held_out = [
        (
            "short ship",
            "The order was short shipped",
            "The customer received fewer units than they ordered",
            "The order was shipped earlier than planned",
        ),
        (
            "cycle count",
            "Run a cycle count on aisle four",
            "Check stock quantities on a few shelves in aisle four",
            "Ride a bicycle around aisle four",
        ),
        (
            "dock slot",
            "Book a dock appointment for Friday",
            "Reserve a delivery unloading slot for Friday",
            "Book a doctor appointment for Friday",
        ),
    ]
     
     
    def print_scores(title, model):
        print(title)
        print(f"{'query':<12}{'related':<9}other")
        for label, query, related, unrelated in held_out:
            embeddings = model.encode([query, related, unrelated])
            scores = model.similarity(
                embeddings[:1], embeddings[1:]
            )[0]
            print(f"{label:<12}{scores[0]:<9.3f}{scores[1]:.3f}")

    None of these sentences appear in the training rows. Each tuple holds a short label, a jargon query, a sentence with the same meaning, and another sentence that only shares its words, which the output reports as other.

  18. Add the base model comparison at the end of the file.
    base_model = "sentence-transformers/all-MiniLM-L6-v2"
    model = SentenceTransformer(base_model)
    print_scores("Base model", model)
     
    model.load_adapter("adapter")
    print_scores("Base with adapter", model)

    load_adapter() applies the saved files to the base model from the line above, so one script can score both. Passing the adapter directory to SentenceTransformer() loads the base model and adapter in one call and gives the same scores.

  19. Save check_adapter.py.
  20. Run check_adapter.py to compare the base model with the reloaded adapter.
    $ python check_adapter.py
    ##### snipped #####
    Base model
    query       related  other
    short ship  0.447    0.748
    cycle count 0.476    0.691
    dock slot   0.415    0.613
    ##### snipped #####
    Base with adapter
    query       related  other
    short ship  0.651    0.446
    cycle count 0.665    0.572
    dock slot   0.787    0.458

    The related score should beat other in every row of the second table, reversing the base model's ranking. Scores shift a little between machines. A second table identical to the first means the adapter has no effect, as an untrained adapter produces.

Share this guide