Skip to content

Add LFM2.5 embedding model support - #28691

Merged
JustinTong0323 merged 7 commits into
sgl-project:mainfrom
vincentzed:vincent/lfm25-embedding-support
Jul 29, 2026
Merged

JustinTong0323 merged 7 commits into
sgl-project:mainfrom
vincentzed:vincent/lfm25-embedding-support

Conversation

@vincentzed

@vincentzed vincentzed commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add native support for LiquidAI/LFM2.5-Embedding-350M by routing Lfm2BidirectionalModel through SGLang's prefill-only embedding path.
  • The bidirectional variant uses encoder-only attention, non-causal same-padding short conv, CLS pooling, and L2 normalization.
  • Register Lfm2BidirectionalModel as non-generation so /v1/embeddings works without --is-embedding on FlashInfer.

How To Run

The model is auto-detected as an embedding model from its architecture, so --is-embedding is not required.

import json
import math
import subprocess
import time
import urllib.request


model = "LiquidAI/LFM2.5-Embedding-350M"
port = 30000

server = subprocess.Popen(
    [
        "python",
        "-m",
        "sglang.launch_server",
        "--model-path",
        model,
        "--host",
        "127.0.0.1",
        "--port",
        str(port),
        "--attention-backend",
        "flashinfer",
        "--dtype",
        "bfloat16",
    ]
)


def get(path):
    with urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=10) as r:
        return r.read()


def post(path, payload):
    req = urllib.request.Request(
        f"http://127.0.0.1:{port}{path}",
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=120) as r:
        return json.loads(r.read().decode("utf-8"))


try:
    deadline = time.time() + 300
    while True:
        try:
            get("/health")
            break
        except Exception:
            if time.time() > deadline:
                raise
            time.sleep(2)

    # Match the model card's asymmetric prompts.
    inputs = [
        "query: What is the capital of France?",
        "document: Paris is the capital and largest city of France.",
        "document: Tokyo is the capital of Japan.",
    ]
    response = post("/v1/embeddings", {"model": model, "input": inputs})
    embeddings = [item["embedding"] for item in sorted(response["data"], key=lambda x: x["index"])]

    query = embeddings[0]
    docs = embeddings[1:]

    def cosine(a, b):
        dot = sum(x * y for x, y in zip(a, b))
        return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))

    scores = [cosine(query, doc) for doc in docs]
    print(scores)
finally:
    server.terminate()
    server.wait(timeout=30)

Motivation

LiquidAI/LFM2.5-Embedding-350M is a dense bi-encoder built from the LFM2.5 bidirectional architecture. The Hugging Face checkpoint exposes Lfm2BidirectionalModel, but SGLang previously only had the causal LFM2 path. This PR adds the minimum model-side support needed for /v1/embeddings to return the model's CLS-pooled, normalized vectors through the existing prefill-only embedding flow.

Modifications

  • Add Lfm2BidirectionalModel in python/sglang/srt/models/lfm2.py.
  • Let LFM2 attention layers select AttentionType.ENCODER_ONLY for the bidirectional embedding architecture.
  • Add a non-causal same-padding short-conv path for the bidirectional model.
  • Reuse the existing LFM2 weight-loading shape; Lfm2ForCausalLM.load_weights remains inline with the original conv renaming, QKV stacking, and tied lm_head handling.
  • Add "Lfm2BidirectionalModel" to the non-generation architecture set in is_generation_model.

Accuracy Tests

Compile and registry checks:

PYTHONPATH=python python -m py_compile python/sglang/srt/models/lfm2.py python/sglang/srt/configs/model_config.py

PYTHONPATH=python python - <<'PY'
from sglang.srt.configs.model_config import is_generation_model
from sglang.srt.models.registry import ModelRegistry

print(is_generation_model(["Lfm2BidirectionalModel"]))
model_cls, arch = ModelRegistry.resolve_model_cls(["Lfm2BidirectionalModel"])
print(arch, model_cls.__name__)
PY

Output:

False
Lfm2BidirectionalModel Lfm2BidirectionalModel

FlashInfer default serving check against the PyLate/SentenceTransformers reference:

uv run --no-project --python scratch/lfm25_embed_validation/.venv-pylate/bin/python \
  python scratch/lfm25_embed_validation/large_batch_match_pylate.py \
  --reference-batch-size 64 \
  --assert-reference unpadded \
  --request-batch-sizes 1 8 32 96 \
  --port 32193 \
  --server-log scratch/lfm25_embed_validation/server_flashinfer_large_batch_unpadded_pass.log \
  --results-file scratch/lfm25_embed_validation/sglang_flashinfer_large_batch_match_pylate_unpadded_pass.json

Results:

n_queries=32
n_documents=64
combined_request_size=96
request_batch_sizes=[1, 8, 32, 96]
min_cos_vs_pylate_unpadded=0.9999272227
max_score_abs_diff_vs_pylate_unpadded=0.0032193363
max_top_doc_mismatches_vs_pylate_unpadded=0
min_cos_vs_request_batch_1=0.9999198914

The default server path was confirmed in the log:

attention_backend='flashinfer'
is_embedding=False
disable_radix_cache=False
chunked_prefill_size=16384

Note: SGLang's prefill path is packed/unpadded. The HF remote model comments describe FlashAttention-2 behavior as equivalent to the unpadded forward, while eager/sdpa preserves padded training-time behavior. For that reason the vector-level serving check asserts against the unpadded PyLate/SentenceTransformers reference.

Speed Tests and Profiling

No dedicated speed benchmark in this PR. The validation above exercises the default FlashInfer serving path with one 96-item embeddings request.

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

CI States

Latest PR Test (Base): ⏳ Run #30426507975
Latest PR Test (Extra): ❌ Run #30426507842

Add native support for LiquidAI/LFM2.5-Embedding-350M by routing Lfm2BidirectionalModel through the prefill-only embedding path. The bidirectional variant uses encoder-only attention, non-causal same-padding short conv, CLS pooling, and L2 normalization.

Keep Lfm2ForCausalLM.load_weights inline with the original conv renaming, QKV stacking, and tied lm_head handling. Lfm2BidirectionalModel uses the same conv/QKV loading shape without the tied lm_head path because the embedding checkpoint has no lm_head.

Register Lfm2BidirectionalModel as non-generation so /v1/embeddings works without --is-embedding on FlashInfer.

Validation:
- PYTHONPATH=python python -m py_compile python/sglang/srt/models/lfm2.py python/sglang/srt/configs/model_config.py
- PYTHONPATH=python python - <<'PY'
from sglang.srt.configs.model_config import is_generation_model
from sglang.srt.models.registry import ModelRegistry
print(is_generation_model(['Lfm2BidirectionalModel']))
model_cls, arch = ModelRegistry.resolve_model_cls(['Lfm2BidirectionalModel'])
print(arch, model_cls.__name__)
PY
  False
  Lfm2BidirectionalModel Lfm2BidirectionalModel
- PYTHONPATH=python python scratch/lfm25_embed_validation/sglang_backend_cosine.py --backends flashinfer --launch-preset default --base-port 32171 --results-file scratch/lfm25_embed_validation/sglang_flashinfer_default_after_simplify_results.json
  top_docs=[0, 1], query_pair_cosine=[0.9999523, 0.9999496], document_pair_cosine=[0.9999526, 0.9999406, 0.9999533], score_max_abs_diff_vs_reference=0.0013513
  server_args included is_embedding=False, disable_radix_cache=False, chunked_prefill_size=16384, attention_backend='flashinfer'.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@vincentzed

Copy link
Copy Markdown
Contributor Author

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Jun 19, 2026
@vincentzed

Copy link
Copy Markdown
Contributor Author

/tag-and-rerun-ci

@JustinTong0323 JustinTong0323 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, very clean

@vincentzed

Copy link
Copy Markdown
Contributor Author

/tag-and-rerun-ci

@tugot17

tugot17 commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

@JustinTong0323 could we merge it now?

@vincentzed

Copy link
Copy Markdown
Contributor Author

/tag-and-rerun-ci

@JustinTong0323
JustinTong0323 merged commit d254ec9 into sgl-project:main Jul 29, 2026
135 of 147 checks passed
saturn-acc pushed a commit to saturn-acc/sglang that referenced this pull request Aug 16, 2026
Atituiset pushed a commit to Atituiset/sglang that referenced this pull request Sep 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants