Skip to content
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

[Frontend] Support OpenAI batch file format #4794

Merged
merged 34 commits into from
May 15, 2024

Conversation

wuisawesome
Copy link
Contributor

This PR adds basic support for the OpenAI batch file format (for chat endpoints).

The following help page summarizes the usage options:

# python -m vllm.entrypoints.openai.run_batch --help
usage: run_batch.py [-h] -i INPUT_FILE -o OUTPUT_FILE [--response-role RESPONSE_ROLE] [--model MODEL] [--tokenizer TOKENIZER] [--skip-tokenizer-init] [--revision REVISION]
                    [--code-revision CODE_REVISION] [--tokenizer-revision TOKENIZER_REVISION] [--tokenizer-mode {auto,slow}] [--trust-remote-code] [--download-dir DOWNLOAD_DIR]
                    [--load-format {auto,pt,safetensors,npcache,dummy,tensorizer}] [--dtype {auto,half,float16,bfloat16,float,float32}] [--kv-cache-dtype {auto,fp8}]
                    [--quantization-param-path QUANTIZATION_PARAM_PATH] [--max-model-len MAX_MODEL_LEN] [--guided-decoding-backend {outlines,lm-format-enforcer}] [--worker-use-ray]
                    [--pipeline-parallel-size PIPELINE_PARALLEL_SIZE] [--tensor-parallel-size TENSOR_PARALLEL_SIZE] [--max-parallel-loading-workers MAX_PARALLEL_LOADING_WORKERS]
                    [--ray-workers-use-nsight] [--block-size {8,16,32}] [--enable-prefix-caching] [--use-v2-block-manager] [--num-lookahead-slots NUM_LOOKAHEAD_SLOTS] [--seed SEED]
                    [--swap-space SWAP_SPACE] [--gpu-memory-utilization GPU_MEMORY_UTILIZATION] [--num-gpu-blocks-override NUM_GPU_BLOCKS_OVERRIDE]
                    [--max-num-batched-tokens MAX_NUM_BATCHED_TOKENS] [--max-num-seqs MAX_NUM_SEQS] [--max-logprobs MAX_LOGPROBS] [--disable-log-stats]
                    [--quantization {aqlm,awq,fp8,gptq,squeezellm,gptq_marlin,marlin,deepspeedfp,None}] [--enforce-eager] [--max-context-len-to-capture MAX_CONTEXT_LEN_TO_CAPTURE]
                    [--max-seq_len-to-capture MAX_SEQ_LEN_TO_CAPTURE] [--disable-custom-all-reduce] [--tokenizer-pool-size TOKENIZER_POOL_SIZE]
                    [--tokenizer-pool-type TOKENIZER_POOL_TYPE] [--tokenizer-pool-extra-config TOKENIZER_POOL_EXTRA_CONFIG] [--enable-lora] [--max-loras MAX_LORAS]
                    [--max-lora-rank MAX_LORA_RANK] [--lora-extra-vocab-size LORA_EXTRA_VOCAB_SIZE] [--lora-dtype {auto,float16,bfloat16,float32}] [--max-cpu-loras MAX_CPU_LORAS]
                    [--fully-sharded-loras] [--device {auto,cuda,neuron,cpu}] [--image-input-type {pixel_values,image_features}] [--image-token-id IMAGE_TOKEN_ID]
                    [--image-input-shape IMAGE_INPUT_SHAPE] [--image-feature-size IMAGE_FEATURE_SIZE] [--scheduler-delay-factor SCHEDULER_DELAY_FACTOR] [--enable-chunked-prefill]
                    [--speculative-model SPECULATIVE_MODEL] [--num-speculative-tokens NUM_SPECULATIVE_TOKENS] [--speculative-max-model-len SPECULATIVE_MAX_MODEL_LEN]
                    [--speculative-disable-by-batch-size SPECULATIVE_DISABLE_BY_BATCH_SIZE] [--ngram-prompt-lookup-max NGRAM_PROMPT_LOOKUP_MAX]
                    [--ngram-prompt-lookup-min NGRAM_PROMPT_LOOKUP_MIN] [--model-loader-extra-config MODEL_LOADER_EXTRA_CONFIG]
                    [--served-model-name SERVED_MODEL_NAME [SERVED_MODEL_NAME ...]] [--engine-use-ray] [--disable-log-requests] [--max-log-len MAX_LOG_LEN]

vLLM OpenAI-Compatible batch runner.

options:
  -h, --help            show this help message and exit
  -i INPUT_FILE, --input-file INPUT_FILE
                        The path or url to a single input file. Currently supports local file paths, or the http protocol (http or https). If a URL is specified, the file should be
                        available via HTTP GET.
  -o OUTPUT_FILE, --output-file OUTPUT_FILE
                        The path or url to a single output file. Currently supports local file paths, or web (http or https) urls. If a URL is specified, the file should be
                        available via HTTP PUT.
  --response-role RESPONSE_ROLE
                        The role name to return if `request.add_generation_prompt=true`.
  --model MODEL         Name or path of the huggingface model to use.
...

Assuming the following file exists:

# cat ../batch.jsonl 
{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "meta-llama/Meta-Llama-3-8B-Instruct", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}
{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "meta-llama/Meta-Llama-3-8B-Instruct", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}

The program is run as python -m vllm.entrypoints.openai.run_batch -i ../batch.jsonl -o ../results.jsonl --model meta-llama/Meta-Llama-3-8B-Instruct (this produces the typical logging from the async engine, which I've omitted).

Finally, the resulting file produced is:

# cat ../results.jsonl
{"id":"vllm-383d1c59835645aeb2e07d004d62a826","custom_id":"request-1","response":{"id":"cmpl-61c020e54b964d5a98fa7527bfcdd378","object":"chat.completion","created":1715633336,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"message":{"role":"assistant","content":"Hello! It's great to meet you! I'm here to help with any questions or tasks you may have. What's on your mind today?"},"logprobs":null,"finish_reason":"stop","stop_reason":null}],"usage":{"prompt_tokens":25,"total_tokens":56,"completion_tokens":31}},"error":null}
{"id":"vllm-42e3d09b14b04568afa3f1797751a267","custom_id":"request-2","response":{"id":"cmpl-f44d049f6b3a42d4b2d7850bb1e31bcc","object":"chat.completion","created":1715633336,"model":"meta-llama/Meta-Llama-3-8B-Instruct","choices":[{"index":0,"message":{"role":"assistant","content":"*silence*"},"logprobs":null,"finish_reason":"stop","stop_reason":null}],"usage":{"prompt_tokens":27,"total_tokens":32,"completion_tokens":5}},"error":null}

FIX #4777

BEFORE SUBMITTING, PLEASE READ THE CHECKLIST BELOW AND FILL IN THE DESCRIPTION ABOVE


PR Checklist (Click to Expand)

Thank you for your contribution to vLLM! Before submitting the pull request, please ensure the PR meets the following criteria. This helps vLLM maintain the code quality and improve the efficiency of the review process.

PR Title and Classification

Only specific types of PRs will be reviewed. The PR title is prefixed appropriately to indicate the type of change. Please use one of the following:

  • [Bugfix] for bug fixes.
  • [CI/Build] for build or continuous integration improvements.
  • [Doc] for documentation fixes and improvements.
  • [Model] for adding a new model or improving an existing model. Model name should appear in the title.
  • [Frontend] For changes on the vLLM frontend (e.g., OpenAI API server, LLM class, etc.)
  • [Kernel] for changes affecting CUDA kernels or other compute kernels.
  • [Core] for changes in the core vLLM logic (e.g., LLMEngine, AsyncLLMEngine, Scheduler, etc.)
  • [Hardware][Vendor] for hardware-specific changes. Vendor name should appear in the prefix (e.g., [Hardware][AMD]).
  • [Misc] for PRs that do not fit the above categories. Please use this sparingly.

Note: If the PR spans more than one category, please include all relevant prefixes.

Code Quality

The PR need to meet the following code quality standards:

  • We adhere to Google Python style guide and Google C++ style guide.
  • Pass all linter checks. Please use format.sh to format your code.
  • The code need to be well-documented to ensure future contributors can easily understand the code.
  • Include sufficient tests to ensure the project to stay correct and robust. This includes both unit tests and integration tests.
  • Please add documentation to docs/source/ if the PR modifies the user-facing behaviors of vLLM. It helps vLLM user understand and utilize the new features or changes.

Notes for Large Changes

Please keep the changes as concise as possible. For major architectural changes (>500 LOC excluding kernel/data/config/test), we would expect a GitHub issue (RFC) discussing the technical design and justification. Otherwise, we will tag it with rfc-required and might not go through the PR.

What to Expect for the Reviews

The goal of the vLLM team is to be a transparent reviewing machine. We would like to make the review process transparent and efficient and make sure no contributor feel confused or frustrated. However, the vLLM team is small, so we need to prioritize some PRs over others. Here is what you can expect from the review process:

  • After the PR is submitted, the PR will be assigned to a reviewer. Every reviewer will pick up the PRs based on their expertise and availability.
  • After the PR is assigned, the reviewer will provide status update every 2-3 days. If the PR is not reviewed within 7 days, please feel free to ping the reviewer or the vLLM team.
  • After the review, the reviewer will put an action-required label on the PR if there are changes required. The contributor should address the comments and ping the reviewer to re-review the PR.
  • Please respond to all comments within a reasonable time frame. If a comment isn't clear or you disagree with a suggestion, feel free to ask for clarification or discuss the suggestion.

Thank You

Finally, thank you for taking the time to read these guidelines and for your interest in contributing to vLLM. Your contributions make vLLM a great tool for everyone!

@@ -101,7 +101,7 @@ async def show_version():
async def create_chat_completion(request: ChatCompletionRequest,
raw_request: Request):
generator = await openai_serving_chat.create_chat_completion(
request, raw_request)
request, raw_request.is_disconnected)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I would prefer if this PR did not touch this file

method: str

# The OpenAI API relative URL to be used for the request. Currently
# /v1/chat/completions is supported.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is there a reason we cannot support /v1/embeddings?

https://platform.openai.com/docs/guides/batch

Copy link
Collaborator

Choose a reason for hiding this comment

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

[ This could be done in a follow up PR ]

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, we can support the other 2 endpoints in follow ups.

request = BatchRequestInput.model_validate_json(request_json)
response_futures.append(run_request(openai_serving_chat, request))

responses = await asyncio.gather(*response_futures)
Copy link
Collaborator

Choose a reason for hiding this comment

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

I assume this lets each request run concurrently right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yep, that way the async engine can decide how to queue/batch things.

{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "NousResearch/Meta-Llama-3-8B-Instruct", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 1000}}"""


def test_e2e():
Copy link
Collaborator

Choose a reason for hiding this comment

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

It there any way we can add a test that the input / output formats conform to the openai api

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sure

Copy link
Collaborator

@robertgshaw2-neuralmagic robertgshaw2-neuralmagic left a comment

Choose a reason for hiding this comment

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

I think this is a useful feature. Thanks for doing it!

My only concern is that this is not really an OpenAI-compatible API - but rather an OpenAI-compatible file format. I think this is fine, but perhaps we should make this explicit in the documentation ...

See comments in code - my biggest feedback is around the is_aborted - I would rather this PR not touch that function signature.

We should add embedding models as a follow up

@wuisawesome
Copy link
Contributor Author

wuisawesome commented May 14, 2024

My only concern is that this is not really an OpenAI-compatible API - but rather an OpenAI-compatible file format. I think this is fine, but perhaps we should make this explicit in the documentation ...

Yes I agree, I tried to use the wording "batch file format" everywhere but when writing the documentation I can be even more explicit. I alluded to it in the ticket (and I think you noticed it too on slack), but the actual openai api is tightly coupled to its file concept and opens up a whole can of worms around life cycle management/long lived state.

See comments in code - my biggest feedback is around the is_aborted - I would rather this PR not touch that function signature.

Updated to maintain backwards compatibility in the signature, but let me know if you have something specific in mind.

We should add embedding models as a follow up

Yup, agreed

@robertgshaw2-neuralmagic
Copy link
Collaborator

This looks great.

Can you just add a short example of run_batch.py in /examples


The OpenAI batch file format consists of a series of json objects on new lines.

[See here for an example file.](https://github.com/vllm-project/vllm/blob/main/examples/openai_example_batch.jsonl)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

These examples links point to master, so they don't work now, but should work once merged.

@wuisawesome
Copy link
Contributor Author

Example/docs are in. Let me know what you think.

@robertgshaw2-neuralmagic
Copy link
Collaborator

LGTM. Waiting for the CI to pass

@robertgshaw2-neuralmagic
Copy link
Collaborator

Thanks for the good work here

@robertgshaw2-neuralmagic robertgshaw2-neuralmagic merged commit 52f8107 into vllm-project:main May 15, 2024
55 checks passed
@AllenDou
Copy link
Contributor

openi_example_batch.jsonl -> openai_example_batch.jsonl ?

@wuisawesome
Copy link
Contributor Author

🤦yes, thanks for catching that.

@robertgshaw2-neuralmagic
Copy link
Collaborator

@wuisawesome ping me on slack and ill merge it

@wuisawesome
Copy link
Contributor Author

I think we're good here, Sang merged it already

robertgshaw2-neuralmagic added a commit to neuralmagic/nm-vllm that referenced this pull request May 19, 2024
Co-authored-by: Robert Shaw <114415538+robertgshaw2-neuralmagic@users.noreply.github.com>
dtrifiro pushed a commit to dtrifiro/vllm that referenced this pull request May 21, 2024
Co-authored-by: Robert Shaw <114415538+robertgshaw2-neuralmagic@users.noreply.github.com>
tybalex pushed a commit to tybalex/vllm-function-call that referenced this pull request May 25, 2024
Co-authored-by: Robert Shaw <114415538+robertgshaw2-neuralmagic@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature]: Support the OpenAI Batch Chat Completions file format
3 participants