Repeated embedding requests can spend part of their time dispatching the same tensor operations. On Ubuntu, a Sentence Transformers model can use PyTorch CPU compilation to optimize its forward pass for inference, while retaining the usual embedding API. Compilation adds startup work, so its value depends on the latency of later requests.

Sentence Transformers applies compilation through model.compile(), which changes the existing model in place. Compilation is lazy, with much of the work deferred until the next embedding call. Dynamic shapes allow varying sequence lengths, although a new input pattern can still trigger additional compilation.

The CPU path on Ubuntu keeps both measurements on the same model, input batch, precision, and thread count. Embedding agreement within a numerical tolerance matters as much as timing, since a faster result is unusable if its values change too far. A small model can also remain faster without compilation because tokenization and Python overhead still contribute to each request.

Steps to compile a Sentence Transformers model for inference on Ubuntu:

  1. Activate a Python virtual environment containing Sentence Transformers 5.7 or later.
    $ source .venv/bin/activate

    The inference fix in Sentence Transformers 5.7 allows embedding calls to use compilation. The CPU commands use Ubuntu 26.04 with Python 3.14; the measured package versions are recorded beside the results.
    Related: Create a Python virtual environment, Activate a Python virtual environment, and install Sentence Transformers with pip.

  2. Refresh Ubuntu's package index for the compilation dependencies.
    $ sudo apt update
  3. Install the C++ toolchain and development headers for Ubuntu's default Python.
    $ sudo apt install build-essential python3-dev

    PyTorch's CPU compiler needs both the C++ toolchain and Python headers. Python dependencies remain in the project environment.

  4. Create a file named compile_embeddings.py in the project directory using your text editor.
  5. Enter the model setup and input batch in compile_embeddings.py.
    compile_embeddings.py
    from statistics import median
    from time import perf_counter
     
    import numpy as np
    import torch
    from sentence_transformers import SentenceTransformer
     
    torch.set_num_threads(2)
    model = SentenceTransformer(
        "sentence-transformers/all-MiniLM-L6-v2", device="cpu"
    )
    sentences = [
        "A compiler can optimize repeated model inference.",
        "Sentence embeddings represent the meaning of text.",
        "The first compiled call includes compilation work.",
        "Measure steady-state latency after warming up.",
    ]
    encode_options = dict(batch_size=4, show_progress_bar=False)

    The public pretrained model downloads on first use. The explicit CPU device and two inference threads keep the eager and compiled paths comparable; the model uses its default float32 precision.

  6. Append the eager baseline and timing function at the end of compile_embeddings.py.
    def median_latency():
        samples = []
        for _ in range(20):
            start = perf_counter()
            model.encode(sentences, **encode_options)
            samples.append(perf_counter() - start)
        return median(samples)
     
     
    eager = model.encode(sentences, **encode_options)
    model.encode(sentences, **encode_options)
    eager_seconds = median_latency()

    Two eager calls warm the model before timing. Each measured call includes tokenization, inference, pooling, and conversion to a NumPy array, matching an ordinary embedding request.

  7. Append compilation and the embedding parity assertion at the end of compile_embeddings.py.
    start = perf_counter()
    model.compile(dynamic=True)
    compiled = model.encode(sentences, **encode_options)
    first_call_seconds = perf_counter() - start
    np.testing.assert_allclose(
        compiled, eager, rtol=1e-4, atol=1e-5
    )
    max_error = np.max(np.abs(compiled - eager))

    The first measurement includes compilation setup and one embedding call, rather than isolating compiler time alone. The assertion rejects values outside a relative tolerance of 0.0001 plus an absolute tolerance of 0.00001; a mismatch stops the script. The default compilation mode here does not use CUDA graphs.

  8. Append warmed timing and result reporting at the end of compile_embeddings.py.
    for _ in range(3):
        model.encode(sentences, **encode_options)
    compiled_seconds = median_latency()
    print(f"Shape: {compiled.shape}")
    print(f"Dtype: {compiled.dtype}")
    print("Parity: passed")
    print(f"Max error: {max_error:.2e}")
    print(f"First call: {first_call_seconds:.3f} s")
    print(f"Eager: {eager_seconds * 1000:.3f} ms")
    print(f"Compiled: {compiled_seconds * 1000:.3f} ms")
    print(f"Latency ratio: {eager_seconds / compiled_seconds:.2f}x")

    Three additional compiled calls precede the median of 20 calls. The latency ratio exceeds 1 when compiled inference is faster and falls below 1 when it is slower. Startup cost is excluded from that ratio.

  9. Save compile_embeddings.py.
  10. Run compile_embeddings.py to verify compiled inference. Example output:
    $ TORCHINDUCTOR_COMPILE_THREADS=1 python compile_embeddings.py
    ##### snipped #####
    Shape: (4, 384)
    Dtype: float32
    Parity: passed
    Max error: 1.66e-07
    First call: 9.971 s
    Eager: 81.654 ms
    Compiled: 74.324 ms
    Latency ratio: 1.10x

    The environment variable limits parallel compiler jobs. These measurements used Sentence Transformers 6.3.0, PyTorch 2.15.0+cpu, and Transformers 5.22.2 on an ARM64 CPU with two available cores. Timings vary with hardware and load. The first invocation also downloads model weights if they are not cached. A Hugging Face warning about unauthenticated requests concerns download rate limits and does not require a login for this public model.

Share this guide