Skip to content

[Model][Last/4] Automatic conversion of CrossEncoding model #19675

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Jul 7, 2025

Conversation

noooop
Copy link
Contributor

@noooop noooop commented Jun 16, 2025

TL;DR

  • New Models
    • no_post_processing
      • GemmaForCausalLM
        • BAAI/bge-reranker-v2-gemma
    • from_2_way_softmax
      • Qwen3ForCausalLM
        • Qwen/Qwen3-Reranker-0.6B
        • Qwen/Qwen3-Reranker-4B
        • Qwen/Qwen3-Reranker-8B
      • Qwen2ForCausalLM
        • mixedbread-ai/mxbai-rerank-base-v2
        • mixedbread-ai/mxbai-rerank-large-v2

Hope that after merging this pr, vllm can support more llms using the relevance generation method as classifiers and rerankers.

Usage

  1. Offline convert ForCausalLM into ForSequenceClassification model.
  • for BAAI/bge-reranker-v2-gemma

Caution

"Yes" and "yes" are two different tokens

python convert_model_to_seq_cls.py --model_name BAAI/bge-reranker-v2-gemma --classifier_from_tokens '["Yes"]' --method no_post_processing --path ./bge-reranker-v2-gemma-seq-cls
  • for mxbai-rerank-v2
python convert_model_to_seq_cls.py --model_name mixedbread-ai/mxbai-rerank-base-v2 --classifier_from_tokens '["0", "1"]' --method from_2_way_softmax --path ./mxbai-rerank-base-v2-seq-cls
  • for Qwen3-Reranker
python convert_model_to_seq_cls.py --model_name Qwen/Qwen3-Reranker-0.6B --classifier_from_tokens '["no", "yes"]' --method from_2_way_softmax --path ./Qwen3-Reranker-0.6B-seq-cls
  1. Online convert ForCausalLM into ForSequenceClassification model.
  • for BAAI/bge-reranker-v2-gemma
# v1 temporarily will report an error
VLLM_USE_V1=0 vllm serve BAAI/bge-reranker-v2-gemma --hf_overrides '{"architectures": ["GemmaForSequenceClassification"],"classifier_from_token": ["Yes"],"method": "no_post_processing"}'
  • for mxbai-rerank-v2
vllm serve mixedbread-ai/mxbai-rerank-base-v2 --hf_overrides '{"architectures": ["Qwen2ForSequenceClassification"],"classifier_from_token": ["0", "1"],"method": "from_2_way_softmax"}'
  • for Qwen3-Reranker
vllm serve Qwen/Qwen3-Reranker-0.6B --hf_overrides '{"architectures": ["Qwen3ForSequenceClassification"],"classifier_from_token": ["no", "yes"],"is_original_qwen3_reranker": true}'
  1. Load offline converted model
  • for BAAI/bge-reranker-v2-gemma
# v1 temporarily will report an error
VLLM_USE_V1=0 vllm serve ./bge-reranker-v2-gemma-seq-cls --served-model-name BAAI/bge-reranker-v2-gemma
  • for mxbai-rerank-v2
vllm serve ./mxbai-rerank-base-v2-seq-cls --served-model-name mixedbread-ai/mxbai-rerank-base-v2
  • for Qwen3-Reranker
vllm serve ./Qwen3-Reranker-0.6B-seq-cls --served-model-name Qwen/Qwen3-Reranker-0.6B
  1. Requests demo + formating query & document

Caution

Please use the query_template and document_template to format the query and document for better reranker results.
without template, the results are almost as random. PTAL #19344

  • for BAAI/bge-reranker-v2-gemma
import requests

url = "http://127.0.0.1:8000/score"
MODEL_NAME = "BAAI/bge-reranker-v2-gemma"

# Please use the query_template and document_template to format the query and
# document for better reranker results.

prompt = "Given a query A and a passage B, determine whether the passage contains an answer to the query by providing a prediction of either 'Yes' or 'No'."
query_template = "A: {query}\n"
document_template = "B: {doc}\n{prompt}"

queries = [
    "What is the capital of China?",
    "Explain gravity",
]

documents = [
    "The capital of China is Beijing.",
    "Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun.",
]

queries= [query_template.format(query=query) for query in queries ]
documents= [
    document_template.format(doc=doc, prompt=prompt)
    for doc in documents 
]

response = requests.post(url,
                         json={
                             "model": MODEL_NAME,
                             "text_1": queries,
                             "text_2": documents,
                             "truncate_prompt_tokens": -1,
                         }).json()

print(response)

expected output

{'id': 'score-30d577279e674c98ad1b0ee12f978b67', 'object': 'list', 'created': 1750361179, 'model': 'BAAI/bge-reranker-v2-gemma', 'data': [{'index': 0, 'object': 'score', 'score': 0.9998812675476074}, {'index': 1, 'object': 'score', 'score': 0.9997507929801941}], 'usage': {'prompt_tokens': 126, 'total_tokens': 126, 'completion_tokens': 0, 'prompt_tokens_details': None}}
  • for mxbai-rerank-v2
import requests

url = "http://127.0.0.1:8000/score"
MODEL_NAME = "mixedbread-ai/mxbai-rerank-base-v2"

# Please use the query_template and document_template to format the query and
# document for better reranker results.

prefix = "<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n<|im_start|>user\n"
suffix = "<|im_end|>\n<|im_start|>assistant\n"

query_template = "{prefix}query: {query}\n"
document_template = "document: {doc}\n{instruction}{suffix}"

instruction = "You are a search relevance expert who evaluates how well documents match search queries. For each query-document pair, carefully analyze the semantic relationship between them, then provide your binary relevance judgment (0 for not relevant, 1 for relevant).\nRelevance:"

queries = [
    "What is the capital of China?",
    "Explain gravity",
]

documents = [
    "The capital of China is Beijing.",
    "Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun.",
]

queries = [
    query_template.format(prefix=prefix, query=query)
    for query in queries
]
documents = [
    document_template.format(doc=doc, suffix=suffix, instruction=instruction) for doc in documents
]

response = requests.post(url,
                         json={
                             "model": MODEL_NAME,
                             "text_1": queries,
                             "text_2": documents,
                             "truncate_prompt_tokens": -1,
                         }).json()

print(response)

expected output

{'id': 'score-da38975e56e34ec3aa1ad48008477491', 'object': 'list', 'created': 1751278496, 'model': 'mixedbread-ai/mxbai-rerank-base-v2', 'data': [{'index': 0, 'object': 'score', 'score': 0.9998867511749268}, {'index': 1, 'object': 'score', 'score': 0.9997918009757996}], 'usage': {'prompt_tokens': 211, 'total_tokens': 211, 'completion_tokens': 0, 'prompt_tokens_details': None}}
  • for Qwen3-Reranker
import requests

url = "http://127.0.0.1:8000/score"
MODEL_NAME = "Qwen/Qwen3-Reranker-0.6B"

# Please use the query_template and document_template to format the query and
# document for better reranker results.

prefix = '<|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be "yes" or "no".<|im_end|>\n<|im_start|>user\n'
suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"

query_template = "{prefix}<Instruct>: {instruction}\n<Query>: {query}\n"
document_template = "<Document>: {doc}{suffix}"

instruction = (
    "Given a web search query, retrieve relevant passages that answer the query"
)

queries = [
    "What is the capital of China?",
    "Explain gravity",
]

documents = [
    "The capital of China is Beijing.",
    "Gravity is a force that attracts two bodies towards each other. It gives weight to physical objects and is responsible for the movement of planets around the sun.",
]

queries = [
    query_template.format(prefix=prefix, instruction=instruction, query=query)
    for query in queries
]
documents = [
    document_template.format(doc=doc, suffix=suffix) for doc in documents
]

response = requests.post(url,
                         json={
                             "model": MODEL_NAME,
                             "text_1": queries,
                             "text_2": documents,
                             "truncate_prompt_tokens": -1,
                         }).json()

print(response)

expected output

{'id': 'score-14f698f021b9434482ec3d94a5757e11', 'object': 'list', 'created': 1749786173, 'model': 'Qwen/Qwen3-Reranker-0.6B', 'data': [{'index': 0, 'object': 'score', 'score': 0.99951171875}, {'index': 1, 'object': 'score', 'score': 0.99951171875}], 'usage': {'prompt_tokens': 189, 'total_tokens': 189, 'completion_tokens': 0, 'prompt_tokens_details': None}}

Tip

If someone wants to implement an offline conversion from ForCausalLM to ForSequenceClassification support new methods or new models, please refer to
https://github.com/noooop/snippet/tree/main/converting2SequenceClassification
(I don't know where to place this code in vllm.)

Essential Elements of an Effective PR Description Checklist

  • The purpose of the PR, such as "Fix some issue (link existing issues this PR will resolve)".
  • The test plan, such as providing test command.
  • The test results, such as pasting the results comparison before and after, or e2e results
  • (Optional) The necessary documentation update, such as updating supported_models.md and examples for a new model.

Purpose

Follow-up #11469, Further improve #10674

  • Automatic conversion of CrossEncoding models

this pr:

  • support GemmaForSequenceClassification
  • use_pad_token: BAAI/bge-reranker-v2-gemma needs to directly concatenate the query and document without using pad_token to get exactly the same result as the official one.
  • examples/offline_inference/convert_model_to_seq_cls.py for offline convert ForCausalLM into ForSequenceClassification model.

Test Plan

tests/models/language/pooling/test_bge_reranker_v2_gemma.py

Test Result

pass

(Optional) Documentation Update

Known issues

  1. Template aware prompt truncation to avoid cutting off important instructions.
  2. default_softmax=True in conflict with what in documentation (default_softmax=False when the task is score).

Fix #19673
Fix #20051

Copy link

👋 Hi! Thank you for contributing to the vLLM project.

💬 Join our developer Slack at https://slack.vllm.ai to discuss your PR in #pr-reviews, coordinate on features in #feat- channels, or join special interest groups in #sig- channels.

Just a reminder: PRs would not trigger full CI run by default. Instead, it would only run fastcheck CI which starts running only a small and essential subset of CI tests to quickly catch errors. You can run other CI tests on top of those by going to your fastcheck build on Buildkite UI (linked in the PR checks section) and unblock them. If you do not have permission to unblock, ping simon-mo or khluu to add you in our Buildkite org.

Once the PR is approved and ready to go, your PR reviewer(s) can run CI to test the changes comprehensively before merging.

To run CI, PR reviewers can either: Add ready label to the PR or enable auto-merge.

🚀

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @noooop, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refactors the automatic model conversion mechanism to support both classification and scoring tasks under a unified as_seq_cls_model adapter. It updates the model loading utility to recognize the score task and applies the generic adapter. The adapter itself is refactored to handle pooling and scoring more flexibly, and the Qwen3 sequence classification model is updated to utilize this new generic adapter.

Highlights

  • Score Task Support: The automatic model conversion logic in the model loader (vllm/model_executor/model_loader/utils.py) is updated to use the as_seq_cls_model adapter for models specified with the score task, in addition to the existing classify task.
  • Adapter Refactoring: The as_seq_cls_model adapter in vllm/model_executor/models/adapters.py is refactored. The pooling and scoring logic is moved into a dedicated pooler method, allowing for more flexible handling of different pooling types within the adapter. It also adds a check to squeeze the output dimension for the score task.
  • Qwen3 Reranker Integration: The specific Qwen3ForSequenceClassification implementation is updated to inherit from the new generic as_seq_cls_model adapter, simplifying its structure and leveraging the shared adapter logic. Specific Qwen3 reranker configuration verification is moved into a new config_verify method.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configureGemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@mergify mergify bot added the documentation Improvements or additions to documentation label Jun 16, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request focuses on enabling automatic conversion of score models by adapting the sequence classification model functionality. Key changes include:

  • Renaming as_classification_model to as_seq_cls_model and updating its functionality to support both "classify" and "score" tasks. This is consistently applied across documentation, tests, and model loading utilities.
  • Refactoring Qwen3ForSequenceClassification to leverage the new as_seq_cls_model adapter. This promotes code reuse and centralizes the classification/scoring logic.
  • Introducing a config_verify method in the adapter pattern, allowing model-specific configurations, which is well-utilized by Qwen3ForSequenceClassification for its reranker variant.
  • Ensuring that for "score" tasks, the model expects num_labels == 1 and the output is appropriately processed (squeezed).

The changes appear robust and improve the model adaptation framework. One area for potential clarification is the behavior of PoolingType.ALL within the as_seq_cls_model adapter, as noted in the specific comment.

Please also consider filling out the checklist in the PR description (Purpose, Test Plan, Test Result) for completeness.

@noooop noooop changed the title [Model] Automatic conversion of score models [Model] Automatic conversion of score (CrossEncoding) models Jun 16, 2025
@noooop noooop force-pushed the as_score_model branch 4 times, most recently from 6dc55ba to 00d377b Compare June 18, 2025 08:33
@noooop noooop force-pushed the as_score_model branch 2 times, most recently from aa22cad to 71b1df4 Compare June 18, 2025 10:49
@mergify mergify bot added the qwen Related to Qwen models label Jun 18, 2025
Copy link

mergify bot commented Jun 19, 2025

This pull request has merge conflicts that must be resolved before it can be
merged. Please rebase the PR, @noooop.

https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork

@mergify mergify bot added the needs-rebase label Jun 19, 2025
@noooop noooop closed this Jun 19, 2025
@noooop noooop reopened this Jun 19, 2025
Copy link

mergify bot commented Jun 19, 2025

This pull request has merge conflicts that must be resolved before it can be
merged. Please rebase the PR, @noooop.

https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork

@mergify mergify bot removed the needs-rebase label Jun 19, 2025
@noooop noooop force-pushed the as_score_model branch 2 times, most recently from b588a67 to f905250 Compare June 19, 2025 08:39
@noooop noooop mentioned this pull request Jun 19, 2025
4 tasks
@noooop noooop marked this pull request as ready for review June 19, 2025 09:32
@noooop noooop requested a review from hmellor as a code owner June 19, 2025 09:32
Signed-off-by: wang.yuqi <noooop@126.com>
noooop added 3 commits July 7, 2025 17:03
Signed-off-by: wang.yuqi <noooop@126.com>
Signed-off-by: wang.yuqi <noooop@126.com>
Signed-off-by: wang.yuqi <noooop@126.com>
@DarkLight1337 DarkLight1337 enabled auto-merge (squash) July 7, 2025 10:31
@DarkLight1337
Copy link
Member

Thanks for working hard on this!

@DarkLight1337
Copy link
Member

Please fix pre-commit

Signed-off-by: wang.yuqi <noooop@126.com>
auto-merge was automatically disabled July 7, 2025 10:35

Head branch was pushed to by a user without write access

@noooop
Copy link
Contributor Author

noooop commented Jul 7, 2025

Thanks for reviewing

@noooop
Copy link
Contributor Author

noooop commented Jul 7, 2025

@DarkLight1337

As i said before in #20168 (comment)

now basically task=="classify"/ the architecture name is *ForSequenceClassification / is_cross_encoder is True are equal.
so task=="classify" naming is slightly inconsistent with actual usage

But it is too complex for me to implement, requiring a lot of code and documentation adjustments.

If you think it's necessary, Please implement it.

@DarkLight1337
Copy link
Member

I'm planning to update that after we implement hidden states processor

@DarkLight1337 DarkLight1337 enabled auto-merge (squash) July 7, 2025 14:40
@DarkLight1337 DarkLight1337 merged commit 110df74 into vllm-project:main Jul 7, 2025
72 checks passed
linzebing pushed a commit to linzebing/vllm that referenced this pull request Jul 7, 2025
linzebing pushed a commit to linzebing/vllm that referenced this pull request Jul 7, 2025
huydhn pushed a commit to huydhn/vllm that referenced this pull request Jul 8, 2025
@noooop noooop deleted the as_score_model branch July 10, 2025 04:48
Chen-zexi pushed a commit to Chen-zexi/vllm that referenced this pull request Jul 13, 2025
patrickvonplaten pushed a commit to patrickvonplaten/vllm that referenced this pull request Jul 15, 2025
…ject#19675)

Signed-off-by: wang.yuqi <noooop@126.com>
Signed-off-by: Patrick von Platen <patrick.v.platen@gmail.com>
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 frontend new-model Requests to new models qwen Related to Qwen models ready ONLY add when PR is ready to merge/full CI is needed
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[New Model]: mxbai-rerank-large-v2 [New Model]: Support BAAI/bge-reranker-v2-gemma model
3 participants