Skip to content

embeddings: skip logits and lm head during inference - #25964

Closed
nanlongyu wants to merge 1 commit into
ggml-org:masterfrom
nanlongyu:embedding-no-logits
Closed

nanlongyu wants to merge 1 commit into
ggml-org:masterfrom
nanlongyu:embedding-no-logits

Conversation

@nanlongyu

Copy link
Copy Markdown

Overview

This PR adds the no-logits mode which is an optional optimization for embedding workloads. When a causal model is used only for embeddings, the request needs the hidden states and pooled embeddings, but the regular path may still run the vocabulary projection and copy the unused logits to host memory. Enabling this mode skips that extra work while leaving the embedding calculation itself unchanged.

Additional information

  • llama_context_params now includes a public no_logits_for_embeddings option, which is disabled by default.
  • The option is available through --no-logits-for-embeddings and LLAMA_ARG_NO_LOGITS_FOR_EMBEDDINGS.
  • The logits path is bypassed only for embedding requests that enable this option, use LLAMA_CONTEXT_TYPE_DEFAULT, and do not configure a backend sampler.
  • In that case, the computation graph is built from the embedding tensor rather than the logits tensor, leaving the vocabulary projection or LM head out of the graph.
  • Because no logits output is needed, the runtime also skips allocating and copying the host-side raw-logits buffer. On this path, llama_get_logits() and llama_get_logits_ith() return NULL.
  • Token-level and pooled embeddings continue to follow the same computation path as before.
  • Existing behavior is retained when the option is disabled, as well as for generation, non-embedding requests, and requests that use a backend sampler.
  • Graph-cache compatibility checks also take this option into account, so graphs with different output behavior are kept separate.

For example, a Qwen3 embedding request using LAST pooling would normally compute the hidden states and then run the LM head to produce a [tokens, vocabulary] logits tensor, even though those logits are not used afterward. With --no-logits-for-embeddings enabled, the graph ends at the embedding output instead. LAST pooling still uses the same embedding result, while the LM-head computation and host-side logits buffer are left out.

The tests cover the option from the CLI through to the runtime context. For Llama and Qwen3, they compare the enabled and disabled paths and expect both per-token and pooled embeddings to match exactly. There is also coverage for BERT and Llama Embed models, which do not have an LM head. Additional cases check that eligible embedding requests leave out the LM-head/logits branch, while text-generation and backend-sampler requests continue to produce logits.

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES. AI was used to review the implementation and assist with writing and running tests.

Add an opt-in no-logits mode for embedding contexts without backend samplers. This omits the vocabulary projection and raw logits output allocation and copy while preserving embedding outputs.
@ggml-gh-bot

ggml-gh-bot Bot commented Jul 21, 2026

Copy link
Copy Markdown

Hi @nanlongyu, thanks for your contribution!

Per our contribution guidelines, the automated PR checker found the following issue(s) that need your attention:

  • Large PR: Large changes require prior discussion (e.g. an issue or RFC) and maintainers may not be able to review this PR as-is. Consider splitting it into smaller, focused PRs.

Please note that maintainers reserve the right to make final decisions on PRs. If you believe there is a mistake, please comment below.

@github-actions github-actions Bot added documentation Improvements or additions to documentation model Model specific testing Everything test related server labels Jul 21, 2026
@m4zar

m4zar commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Glad to see someone tackling this. I hit the same thing a few months ago and wrote it up in #24713 (closed by the stale bot, no maintainer reply), with benches across 80 archs on CUDA / ROCm / Metal / CPU, so maybe that counts as the "prior discussion" the bot is asking for here.

Short version of what I measured with the same gate (!cparams.embeddings → skip lm_head + has_logits = false), llama-bench -embd 1 -p 512:

  • ROCm (RX 9070 XT): median +59.8%, up to +241.7% (38 archs)
  • CUDA (RTX PRO 6000): median +17.4%, up to +126.6% (80 archs, all positive)
  • Metal (M5 Max): median +9.9%, up to +48.3% (51 archs)
  • 0 regressions anywhere. Output is bit-identical / cosine 1.000000 across LAST/MEAN/CLS pooling; generation untouched.

One thought on the design: given the outputs are identical and nothing consumes the logits when embeddings && pooling != NONE, I'd lean towards making this the default on that path rather than an opt-in flag. A flag that is off by default means the ~100 model files still carry the wasted matmul for everyone who doesn't know about it. The only case I can think of that needs the logits in embedding mode is a backend sampler, and the PR already excludes that.

If it helps for parity checks, I have a public corpus (1023 Gutenberg chunks) I used for control vs patched: https://gist.github.com/m4zar/cf5f2f82c51233944bb9493efe2bf692

Happy to re-run the benches on top of this branch if useful.

@srflaherty

Copy link
Copy Markdown

Thanks for this — it covers most of what we hit running Qwen3-Embedding-8B and Qwen3-Reranker-8B (Q8_0, Vulkan, RTX 5060 Ti 16 GB). One piece it doesn't reach, in case it's useful here or as a follow-up:

The duplicated output tensor is still loaded, and placed with the output layer. Qwen3's embedding/reranker GGUFs carry no output.weight, so llama_model_qwen3::load_arch_tensors falls back to TENSOR_DUPLICATED of token_embd (still the case on master f2918ca, src/models/qwen3.cpp lines 22–26). With the output layer offloaded, that is a full second copy of the 151,665-token table on the GPU — 629 MiB at Q8_0 for the 8B models — which a pooling context never reads. Skipping the LM head at graph time (this PR) removes the compute and the logits, but the tensor is created at load time, before any context exists.

We've been carrying a small local patch for this since 2026-10-05, applied to llama-cpp-sys-2 0.1.156 (llama.cpp b10405): when output is missing and the file declares a pooling type (hparams.pooling_type > LLAMA_POOLING_TYPE_NONE), the duplicate isn't created; a pooling embedding context doesn't build the LM head; and a context that would want token scores from such a model is refused with an error rather than handed an empty buffer. Measured A·B·B·A against the unpatched build, same machine, same inputs — the embeddings came out identical (checksum over four runs matched exactly):

Qwen3-*-8B Q8_0, Vulkan unpatched patched
embedder: model on the GPU 7,668.64 MiB 7,039.18 MiB
embedder: compute buffer (n_ubatch 512) 312.73 MiB 96.51 MiB
reranker: model on the GPU 7,668.67 MiB 7,039.18 MiB
reranker: compute buffer 313.63 MiB 97.41 MiB
bulk embed, 64 sections 8,247 / 8,214 ms 6,942 / 7,008 ms (−15%)
one 10-pair rerank (1,685 tokens) 490 ms 425 ms (−13%)

The speed and compute-buffer gains are the same ones this PR gives (the LM head no longer runs on every token in embedding mode). The ~629 MiB of model memory is the part that needs the load-time check. Keying it on the file's declared pooling type kept it safe for us: generation GGUFs don't normally declare one, so nothing changed for our chat models, and the same file can't later be asked for logits without an explicit error.

Not proposing our exact patch — it's shaped around our use, and the opt-in route here is more conservative — just flagging the load-time half with numbers, in case it's worth folding in (or a separate PR, if the maintainers prefer). Happy to share the diff or test anything.

Related: #30255 frees the host logits buffer when the graph has no logits tensor; for Qwen3-based embedding models the graph still builds t_logits today, so that one doesn't apply to them unless the LM head is skipped first.

(Posted by Steve Flaherty; the investigation, measurements and this write-up were done with Claude.)

@ggerganov

Copy link
Copy Markdown
Member

Superseded by #30445

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation model Model specific server testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants