Compare commits

..
332 Commits
Author SHA1 Message Date
Owen Qwen 08c6ff7490 Bump vLLM to 0.17.0
CI | Update runpod package version / Check python requirements file and update (push) Canceled after 0s
2026-03-26 12:13:42 -05:00
chrisvelaandGitHub 9d1686960d Merge pull request #273 from runpod-workers/bug/hf-overides-rope-scaling
bug: fix rope scaling to be forward compatible from hf_overrides
2026-03-10 11:21:44 -05:00
velaraptor-runpod 45d1eeee47 bug: fix rope scaling to be forward compatible from hf_overrides 2026-03-06 15:34:11 -06:00
chrisvelaandGitHub 17efb0e7d0 Merge pull request #272 from runpod-workers/feat/vllm-0.16.0
Release / release (push) Waiting to run
feat: Update to 0.16.0
2026-03-05 13:06:45 -06:00
velaraptor-runpod 2b5f07df63 feat: Update to 0.16.0, remove NUM_GPU_BLOCKS_OVERRIDE in hub default since 0 will break 2026-03-04 16:38:40 -06:00
chrisvelaandGitHub 13fa71878e Merge pull request #269 from runpod-workers/feat/allow-engine-args-env
Release / release (push) Waiting to run
feat: allow all AsyncEngineArgs as env vars
2026-02-27 15:34:23 -06:00
velaraptor-runpod 8a9365bed4 remove DEFAULT_ARGS that are none, fix MAX_CONTEXT_LEN_TO_CAPTURE 2026-02-27 14:04:15 -06:00
velaraptor-runpod cd485a1af1 update readme 2026-02-25 22:57:17 -06:00
velaraptor-runpod b9043639e9 requested changes/refactor 2026-02-25 16:07:38 -06:00
chrisvelaandGitHub 407dbd7773 Merge pull request #270 from runpod-workers/feat/update-vllm-v0.15.1
feat: update vllm to 0.15.1
2026-02-25 15:35:58 -06:00
velaraptor-runpod f103c142c1 feat: update vllm to 0.15.1 2026-02-24 17:44:49 -06:00
velaraptor-runpod efb093e198 add as VLLM_RUNPOD prefix and update readme 2026-02-24 17:37:57 -06:00
velaraptor-runpod 42443f735e feat: allow engine args through VLLM_ and checks the engine args 2026-02-24 16:05:18 -06:00
chrisvelaandGitHub b7c6d4f9a2 feat: update dockerfile to 12.9.1 (#267)
Release / release (push) Waiting to run
* feat: update dockerfile to 12.9.1

* update readme on VLLM_NIGHTLY build arg
2026-02-19 10:13:14 +01:00
chrisvelaandGitHub d69cc021e8 Merge pull request #268 from runpod-workers/fix/spec-config-0-to-none
Release / release (push) Waiting to run
fix: spec config env vars should be none if zero
2026-02-18 15:51:51 -06:00
velaraptor-runpod 61faa8f137 fix: spec config env vars should be none if zero 2026-02-18 15:41:19 -06:00
chrisvelaandGitHub 1606cff557 Merge pull request #265 from runpod-workers/fix/zero-max-model-num_batches
Release / release (push) Waiting to run
fix: check for zero param and set to None
2026-02-13 15:26:06 -06:00
velaraptor-runpod e705c9494b fix: check for zero param and set to None 2026-02-13 15:23:54 -06:00
chrisvelaandGitHub b749aa5718 Merge pull request #264 from runpod-workers/fix/max_num_batched_tokens
Release / release (push) Waiting to run
fix: max num batched tokens
2026-02-13 12:38:01 -06:00
velaraptor-runpod 4705ba8a7c fix: check max_num_batched_tokenz if max_model_len not set 2026-02-13 03:29:52 -06:00
velaraptor-runpod 767c66c301 make minimal changes 2026-02-13 03:23:44 -06:00
velaraptor-runpod fefdbe21a9 update changes 2026-02-13 03:16:43 -06:00
velaraptor-runpod ee961ad28d Update hub.json 2026-02-13 03:08:19 -06:00
velaraptor-runpod 2e8c251447 Merge branch 'main' into feat/update-vllm-v0.15.0 2026-02-13 03:01:05 -06:00
velaraptor-runpod c3cf43b228 Update hub.json 2026-02-13 00:22:16 -06:00
velaraptor-runpod 7ec10b98cd Update utils.py 2026-02-12 15:28:31 -06:00
c45ac42acd vLLM Worker v0.15.0 — Upgrade from v0.11.x to v0.15.0 (#259)
Release / release (push) Waiting to run
* VLLM upgrade to 0.12.0 and compatibility fixes

* MAX_NUM_BATCHED_TOKENS fix and CUDA tester

* Sys kill worker instead of marking as failed

* upgrade to vllm 0.12.0

* Update to vllm 0.15.0 and lora fix

* Update for HUB and removal of deprected env variables

* reverted docker-bake changes

* removed leftovers

* Update src/handler.py

Co-authored-by: Dj Isaac <contact@dejaydev.com>

* Update src/utils.py

Co-authored-by: Dj Isaac <contact@dejaydev.com>

* Update src/handler.py

Co-authored-by: Dj Isaac <contact@dejaydev.com>

* Clean up of docs and comments in code

* nit: lowercase p

* nit: lowercase p

---------

Co-authored-by: Dj Isaac <contact@dejaydev.com>
Co-authored-by: chrisvela <chris.vela@runpod.io>
2026-02-12 21:50:34 +01:00
velaraptor-runpod 340bc0b3c6 fix: served model name 2026-02-10 21:42:58 -06:00
velaraptor-runpod e1e9ef74ad add changes from pr 2026-02-06 18:10:09 -06:00
velaraptor-runpod 461f89cea6 add torch-c-dlpack-ext requirement 2026-02-06 17:03:39 -06:00
velaraptor-runpod 8eb55b90c1 add changes for v0.15.0 2026-02-05 17:24:16 -06:00
Tim PietruskyandGitHub 6d6cbe7095 fix: deactivate RunPod tests to fix hub release (#253)
Release / release (push) Waiting to run
Rename tests.json to tests_json to temporarily disable automated
tests while fixing the release on the hub.
2026-01-22 18:06:36 +01:00
90c16b472d fix: update CUDA to 12.4.1 for Blackwell GPU support (#251)
Release / release (push) Waiting to run
* fix: update CUDA to 12.4.1 for Blackwell GPU support

- Update Dockerfile base image from CUDA 12.1.0 to 12.4.1
- Update ldconfig path to cuda-12.4
- Update FlashInfer installation to use flashinfer-python package
- Add NVIDIA B200 (Blackwell) to supported gpuIds in hub.json

This fixes the "imagePullAsync: failed to get self-hosted image registry auth"
error when deploying on Blackwell GPUs (RTX PRO 6000, B200) by aligning
the Docker image CUDA version with the allowedCudaVersions in hub.json.

Fixes: DR-1118

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* revert: remove NVIDIA B200 from default gpuIds

The gpuIds in hub.json controls default GPU selection for deployments,
not GPU compatibility. The CUDA 12.4 upgrade is sufficient to enable
Blackwell GPU support.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: remove FlashInfer to avoid JIT compilation errors

FlashInfer requires nvcc to JIT-compile CUDA kernels at runtime for
new GPU architectures (like Blackwell SM 10.0). Since we use the CUDA
base image without the toolkit, nvcc is not available.

vLLM will use its built-in fallback sampling methods instead.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-13 22:01:36 +01:00
Tim PietruskyandGitHub 6f2381a9a1 chore(deps): update runpod to latest version (#242)
Release / release (push) Waiting to run
2025-11-24 16:42:21 +01:00
chrisvelaandGitHub 3851d53f93 add ENABLE_EXPERT_PARALLEL engine arg for MoE models (#239)
Release / release (push) Waiting to run
* enable expert parallel arg for moe models

* add ENABLE_EXPERT_PARALLEL to hub config
2025-11-17 19:25:19 +01:00
Witold WydmańskiandGitHub c896438f21 feat: bump transformers to allow Qwen3-VL (#225)
Release / release (push) Waiting to run
2025-11-14 17:23:34 +01:00
Tim PietruskyandGitHub 912892f94e fix: remove space from gpuIds (#234) 2025-11-14 17:23:09 +01:00
Tim PietruskyandGitHub f8bf82469c fix(config): update allowed cuda versions in hub and tests config (#236)
remove unsupported cuda versions (12.1-12.3) from hub.json and tests.json
to fix compatibility issues with worker deployment

- hub.json: remove 12.1, 12.2, 12.3 from allowedCudaVersions
- tests.json: remove 12.1, 12.2, 12.3, 12.4 from allowedCudaVersions

refs: AE-1452
2025-11-14 17:22:43 +01:00
Hailong YangandGitHub ec1664902b Merge pull request #230 from runpod-workers/feat/cse-853-vllm-template-params
Feat/cse 853 vllm template params
2025-10-31 13:32:34 -04:00
Eugene Klitenik d09122de4a remove un-needed 2025-10-29 13:06:33 -04:00
Eugene Klitenik e27dc68dea remove uneeded 2025-10-29 13:05:26 -04:00
Eugene Klitenik 1ee18d06a9 determine num gpus in python 2025-10-29 11:31:42 -04:00
Eugene Klitenik 5c4edd15cc update entrypoint command 2025-10-28 18:07:18 -04:00
Eugene Klitenik b074d3a23b auto detect num GPUs 2025-10-28 14:39:55 -04:00
Eugene Klitenik 205847471c reduce default container disk size to 150GB 2025-10-28 13:38:16 -04:00
Tim PietruskyandGitHub 6337a6673a fix: allow also CUDA 12.8 & 12.9 (#228)
Release / release (push) Waiting to run
2025-10-24 18:48:26 +02:00
Tim PietruskyandGitHub 66e1b1605b Merge pull request #226 from runpod-workers/fix/cse-839-max-concurrency
Release / release (push) Waiting to run
fix: max concurrency = 30 instead of 300
2025-10-22 22:54:21 +02:00
Tim PietruskyandGitHub 60c8f257a8 Merge pull request #227 from runpod-workers/chore/vllm-0.11.0
chore: update vllm to 0.11.0
2025-10-22 22:53:51 +02:00
Tim Pietrusky fae16e7ee1 chore: update vllm to 0.11.0 2025-10-22 13:40:53 -07:00
max4c 2becd35345 Revert "fix: added back the HF_TOKEN (#219)"
Release / release (push) Waiting to run
This reverts commit 33d88df6c0.
2025-09-23 12:38:24 -07:00
33d88df6c0 fix: added back the HF_TOKEN (#219)
Release / release (push) Waiting to run
Co-authored-by: Tim Pietrusky <tim.pietrusky@runpod.io>
2025-09-23 19:25:12 +02:00
Tim Pietrusky ecd562e112 fix: remove "access token" as this is handled by the platform
Release / release (push) Waiting to run
2025-09-19 21:00:47 +02:00
5cffaab8e8 docs: how to use the reasoning parser (#218)
Co-authored-by: Tim Pietrusky <tim.pietrusky@runpod.io>
2025-09-17 07:49:37 +02:00
a0fe1dfdad feat: better hub support & concise README for the main repo (#215)
Release / release (push) Waiting to run
* feat: moved config into docs; added banner; auto detect "messages" in input

* docs: moved config into docs

* chore: added .DS_Store

* chore: get the original stuff working again

* chore: remove all changes

* docs: reduced toc and added small config table

---------

Co-authored-by: Tim Pietrusky <tim.pietrusky@runpod.io>
2025-09-01 16:47:48 +02:00
Tim Pietrusky 0e0d6df859 docs: updated example-tag for dev and release 2025-08-28 14:28:19 +02:00
Tim Pietrusky d1718aec00 ci: removed "github release" step as that is not needed 2025-08-28 14:27:50 +02:00
5f0fc69d75 feat: prepare worker-vllm for the hub (#214)
Release / release (push) Waiting to run
* docs: remove outdated video; remove old info; added missing config for tools

* ci: use proper release for dev (pr only) and production (release only)

* ci(hub): added openai example; use smollm2 as base model

* docs: added conventions to be able to work with ai ide's

* chore: remove outdated stuff

* chore: update copyright to 2025

* ci: added github permissions

* feat: added gpuIds, gputCount and allowedCudaVersions; removed default value for LOAD_FORMAT to check which influence this has on the ui

---------

Co-authored-by: Tim Pietrusky <tim.pietrusky@runpod.io>
2025-08-28 10:09:27 +02:00
Marut PandyaandGitHub aef1187a30 Merge pull request #211 from runpod-workers/fix/allow-none-as-string
fix: allow "None" as value & parse the value of RAW_OPENAI_OUTPUT correctly
2025-08-21 11:35:54 -07:00
Tim Pietrusky f7514dea4b refactor: moved MODEL_NAME & HF_TOKEN out of advanced into the top section 2025-08-18 16:05:43 +02:00
Tim Pietrusky 121a3dd44b fix: parse value for RAW_OPENAI_OUTPUT correctly 2025-08-13 12:20:44 +02:00
Tim Pietrusky e2e111b942 fix: allow "None" as string for setting env variables (like quantization) 2025-08-13 10:27:00 +02:00
Marut PandyaandGitHub 7aa17463d3 Merge pull request #200 from runpod-workers/release/0.10.0
chore(release): 0.10.0
2025-08-11 15:33:51 -07:00
Marut PandyaandGitHub 72a643dd0c Merge pull request #207 from JhennerTigreros/main
Update requirements and engine creation to support new 0.10.0 vLLM version
2025-08-09 09:08:19 -07:00
Marut PandyaandGitHub 15f569f970 Merge pull request #208 from runpod-workers/revert-202-feat/proper-deployment
[Revert]"feat: added dev & release workflows; added conventions to support AI IDE"
2025-08-09 09:06:53 -07:00
Marut PandyaandGitHub 2f2bd4c749 Revert "feat: added dev & release workflows; added conventions to support AI IDE" 2025-08-09 09:01:52 -07:00
Jhenner Tigreros fb0c030797 fix initialization on openaiservingmodels 2025-08-07 16:40:06 -05:00
Jhenner Tigreros 8b02a703b4 fix issues 2025-08-07 15:59:43 -05:00
Jhenner Tigreros d8863139d6 add model to test 2025-08-07 15:28:02 -05:00
Jhenner TigrerosandGitHub f5a063956e Fix requirements.txt to support gpt-oss models 2025-08-07 15:13:37 -05:00
Marut PandyaandGitHub 18748fd73e Merge pull request #202 from runpod-workers/feat/proper-deployment
feat: added dev & release workflows; added conventions to support AI IDE
2025-08-04 17:13:47 -07:00
Tim Pietrusky 0133c23be8 ci: added manual workflow trigger for releases 2025-08-04 09:58:23 +02:00
Tim Pietrusky a129cff47d docs: use "version" instead of actual version, so that people can check the releases 2025-07-31 12:03:17 +02:00
Tim Pietrusky 30f2c4630e refactor: use correct version 2025-07-31 12:02:46 +02:00
Tim Pietrusky b98636e432 feat: added "dev" and "release" workflows; removed "vllm-base-image" as it's not needed 2025-07-28 16:40:20 +02:00
pandyamarut 185205c750 chore(release): 0.10.0
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-07-25 10:18:06 -07:00
pandyamarut b948e530a1 chore(release): 0.10.0
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-07-25 10:17:50 -07:00
Marut PandyaandGitHub 4f22d6f107 Merge pull request #193 from runpod-workers/release/0.9.1
chore(release): v0.9.1
2025-06-26 13:23:33 -07:00
pandyamarut 8839689132 chore(release): v0.9.1
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-06-26 11:06:23 -07:00
Marut PandyaandGitHub 5ddc2326cd Merge pull request #191 from runpod-workers/feat/0.9.1
feat: update to 0.9.1 & added CONFIG_FORMAT to run magistral
2025-06-26 10:17:54 -07:00
Tim Pietrusky 46a3300cbb chore: reverted changeds to only focus on vllm update 2025-06-20 14:56:39 +02:00
Tim Pietrusky 1e9a731380 Fix Mistral tokenizer initialization: let vLLM handle tokenizer for mistral models 2025-06-14 15:31:56 +02:00
Tim Pietrusky c47e649a24 Add CONFIG_FORMAT environment variable support 2025-06-14 15:12:46 +02:00
Tim Pietrusky 7192bcaeef Trigger build automatically on feat/0.9.1 branch 2025-06-14 13:49:22 +02:00
Tim Pietrusky 8665ffb78d Revert workflow back to original configuration 2025-06-14 13:47:16 +02:00
Tim Pietrusky 57431b30ad Fix workflow: use standard GitHub runners and actions 2025-06-14 13:42:46 +02:00
Tim Pietrusky 437a84c77a ci: added workflow to build the image 2025-06-14 13:31:36 +02:00
Tim Pietrusky a4062fc488 feat: update to 0.9.1 2025-06-14 13:31:27 +02:00
Marut PandyaandGitHub 9631407c1d Merge pull request #189 from runpod-workers/hf-mm
add multi modal env var
2025-06-10 17:03:18 -07:00
pandyamarut 1a93932ab2 add multi modal env var
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-06-10 17:02:42 -07:00
Marut PandyaandGitHub 4c6c88c3b9 Merge pull request #188 from WorstDev01/add-mm-limit-parameter
Add multimodal limit parameter support
2025-06-10 14:59:21 -07:00
WorstDev01 a58a76783d Add multimodal limit parameter support
- Updated convert_limit_mm_per_prompt to handle multiple types
- Added limit_mm_per_prompt parameter for image and video limits

Note: Consider adjusting default values - perhaps image limit > 1 or video=1
2025-06-10 23:36:47 +02:00
Marut PandyaandGitHub 26919c8849 Merge pull request #185 from runpod-workers/up-0.9.0
Version upgrade
2025-06-05 12:00:05 -07:00
pandyamarut 70cd1c8113 update vllm version 0.9.0
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-06-05 11:59:15 -07:00
Marut PandyaandGitHub deeff579f8 Merge pull request #183 from SorenDreano/fix/model_name_in_local_args
remove requirements for MODEL_NAME in local_model_args.json
2025-06-04 12:45:00 -07:00
Soren Dreano 11f96a09d7 remove requirements for MODEL_NAME in local_model_args.json
We want to use the same local_model_args.json for multiple models
which have different names. It would be very convenient to only
have a single local_args file and not have to create it every time

A warning should be enough for users
2025-05-23 17:59:19 +02:00
Marut PandyaandGitHub 23e8ecf85b Merge pull request #169 from RedHitMark/main
fix lora and multi-lora
2025-05-14 16:25:26 -07:00
Marut PandyaandGitHub 6db2c44d3b Update Dockerfile 2025-05-09 09:27:54 -07:00
Marut PandyaandGitHub 9b7ca4d0b0 Update tests.json 2025-05-08 17:12:59 -07:00
Marut PandyaandGitHub 2a4eaf0356 Merge pull request #182 from runpod-workers/up-0.8.5
update vllm
2025-05-08 11:40:23 -07:00
pandyamarut ba19cc97bf update vllm
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-05-08 11:34:58 -07:00
Marut PandyaandGitHub 6075f2c590 Merge pull request #181 from runpod-workers/revert-177-main
Revert "fix: added back limit_mm_per_prompt to engine args"
2025-05-07 12:31:15 -07:00
Marut PandyaandGitHub a9786a2481 Revert "fix: added back limit_mm_per_prompt to engine args" 2025-05-07 12:29:33 -07:00
Marut PandyaandGitHub 0b6bc7a2be Update tests.json 2025-05-07 11:14:50 -07:00
Marut PandyaandGitHub d0ab58ee17 Merge pull request #180 from muhsinking/patch-1
Update README.md table to fix table of contents links
2025-05-03 21:02:37 -07:00
Marut PandyaandGitHub 4e474c41c8 Merge pull request #177 from aleksandar-babic/main
fix: added back limit_mm_per_prompt to engine args
2025-05-03 21:01:58 -07:00
Mo KingandGitHub e9d13c155e Update README.md to fix table of contents links to environment variable sections
Separates environment variables into multiple tables, so that the table of contents will correctly jump to the appropriate section when clicked.
2025-04-30 12:45:54 -04:00
Marut PandyaandGitHub e807342e90 Merge pull request #178 from runpod-workers/up-0.8.4
update vllm
2025-04-21 13:15:03 -07:00
pandyamarut f33e8d2bcd update vllm
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-04-21 13:14:32 -07:00
Marut PandyaandGitHub 6b64bb93bd Merge pull request #147 from mohamednaji7/BitsAndBytes
completing the "bitsandbytes" option - based on  https://docs.vllm.ai/en/stable/quantization/bnb.html
2025-04-21 11:39:53 -07:00
Aleksandar Babic a53cf777ff chore: added limit_mm_per_prompt to worker config 2025-04-21 10:14:05 -04:00
Aleksandar Babic cfc258674b chore: added trailing comma to the final arg 2025-04-21 10:06:08 -04:00
Aleksandar Babic 8beafed06b fix: added back limit_mm_per_prompt to engine args 2025-04-21 10:02:46 -04:00
Marut PandyaandGitHub d77c53c3b7 Merge pull request #175 from runpod-workers/up-0.8.3
update vllm
2025-04-07 11:58:03 -07:00
pandyamarut 3d067cd472 update vllm
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-04-07 11:54:57 -07:00
Marut PandyaandGitHub f1360ccae7 Merge pull request #173 from KAJdev/patch-1
Update hub.json
2025-04-03 14:52:06 -07:00
Marut PandyaandGitHub 96f1b86126 Merge pull request #174 from KAJdev/patch-2
Update tests.json
2025-04-03 10:14:49 -07:00
Ezekiel WotringandGitHub 3a095f3e10 Update tests.json 2025-04-03 09:10:01 -08:00
Ezekiel WotringandGitHub 7cf7f3e4e6 Update hub.json 2025-04-03 09:04:28 -08:00
Marut PandyaandGitHub 4395d0c67b Update hub.json 2025-04-03 08:10:28 -07:00
Marut PandyaandGitHub 5864fa6843 Update hub.json 2025-03-31 15:55:35 -07:00
Marut PandyaandGitHub 067f0bc173 Update tests.json 2025-03-31 15:49:31 -07:00
Marut PandyaandGitHub 0869068e7c Create tests.json 2025-03-31 15:32:06 -07:00
Marut PandyaandGitHub 19f25b17de Update hub.json 2025-03-31 15:14:40 -07:00
Marut PandyaandGitHub 70aa748c30 Update hub.json 2025-03-31 15:14:24 -07:00
Marut PandyaandGitHub da3e5f524b Merge pull request #171 from runpod-workers/update
update vllm 0.8.2
2025-03-26 15:56:04 -07:00
pandyamarut acbdf63de8 update vllm 0.8.2
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-03-26 15:55:30 -07:00
RedHitMark 084d000324 fix lora and multi-lora 2025-03-14 21:45:09 +01:00
Hailong YangandGitHub fa31d9663d Update README.md 2025-03-11 22:24:22 -04:00
Marut PandyaandGitHub b8fb313483 Merge pull request #168 from runpod-workers/wc-up
update worker config
2025-03-11 12:23:22 -07:00
pandyamarut 9635daf336 update worker config
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-03-11 12:22:53 -07:00
Marut PandyaandGitHub fb4e700090 Merge pull request #166 from KAJdev/patch-1
Create hub.json
2025-03-10 12:14:47 -07:00
Marut PandyaandGitHub d4872ed9c8 Merge pull request #167 from runpod-workers/rachfop-patch-1
Update requirements.txt
2025-03-10 12:13:47 -07:00
Patrick RachfordandGitHub b2eef50c3b Update requirements.txt
Use the latest runpod version from here:
https://github.com/runpod/runpod-python/releases/tag/1.7.7
2025-03-10 08:46:28 -07:00
Ezekiel WotringandGitHub 8005bcc1a8 fix description 2025-03-07 13:22:34 -09:00
Ezekiel WotringandGitHub aa7b00ddda Create hub.json 2025-03-07 13:20:52 -09:00
Marut PandyaandGitHub dc6f3239bd Update README.md 2025-02-24 18:39:14 -08:00
Marut PandyaandGitHub f9d0fcb78c Merge pull request #165 from runpod-workers/hfix
[HF]: set default max_token size
2025-02-24 17:24:50 -08:00
pandyamarut 99b952e55e set default max_token size
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-02-24 17:22:44 -08:00
Marut PandyaandGitHub 389fad7952 Merge pull request #164 from runpod-workers/up-0.7.3
update vllm
2025-02-24 15:08:02 -08:00
pandyamarut 56dc4ad075 update vllm
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-02-24 15:01:45 -08:00
Marut PandyaandGitHub 6dcf39e159 Merge pull request #161 from runpod-workers/revert-157-m-c
Revert "Enabling model caching."
2025-02-18 14:33:27 -08:00
Marut PandyaandGitHub 2b1d618287 Revert "Enabling model caching." 2025-02-18 10:45:47 -08:00
Marut PandyaandGitHub d7e9c49fe4 Merge pull request #160 from runpod-workers/up-0.7.2
update vllm
2025-02-11 13:59:18 -08:00
pandyamarut c9791f1163 update vllm
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-02-11 13:27:57 -08:00
Marut PandyaandGitHub 6fc770415d Merge pull request #157 from runpod-workers/m-c
Enabling model caching.
2025-02-06 11:52:19 -08:00
Mohamed NagyandGitHub 04288240f6 updating the . in ['awq', 'squeezellm', 'gptq'. 'bitsandbytes'] for the QUNATIZATION row 2025-02-02 14:58:48 +02:00
Marut PandyaandGitHub 9e8d9196b0 Merge pull request #154 from runpod-workers/fx-eng
update engine.py
2025-01-28 21:40:26 -08:00
pandyamarut 30dd7c1eb5 update engine.py
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-01-28 21:40:00 -08:00
Marut PandyaandGitHub aa7c37ffb0 Merge pull request #152 from runpod-workers/fix0.7.0-1
update oai serving classes
2025-01-28 20:58:40 -08:00
pandyamarut dc8c88027a update serving classes
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-01-28 20:58:07 -08:00
Marut PandyaandGitHub a948e90caa Merge pull request #151 from runpod-workers/fix0.7.0
dynamic lora loading
2025-01-28 19:02:59 -08:00
pandyamarut c703254f71 dynamic lora loading
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-01-28 19:00:57 -08:00
Marut PandyaandGitHub 2747106403 Merge pull request #150 from runpod-workers/up-0.7.0
update vllm 0.7.0
2025-01-28 14:27:37 -08:00
pandyamarut 91ed30e9a2 update readme
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-01-28 14:21:33 -08:00
pandyamarut fcbfe84f63 update vllm 0.7.0
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2025-01-28 14:18:10 -08:00
Marut PandyaandGitHub 610429df23 Merge pull request #143 from sihamouda/main
Add limit_mm_per_prompt engine argument for multimodels input
2025-01-27 16:41:47 -08:00
Hailong Yang a578c6df23 update docker file 2025-01-26 23:28:27 -05:00
Mohamed NagyandGitHub 9299f43b8b solving "typing_extensions" compatibility with "bitsandbytes"
```
2025-01-22 18:04:01 [INFO] > [stage-0 5/8] RUN --mount=type=cache,target=/root/.cache/pip python3 -m pip install --upgrade pip && python3 -m pip install --upgrade -r /requirements.txt:
2025-01-22 18:04:01 [INFO] #13 8.904
2025-01-22 18:04:01 [INFO] #13 8.904 The conflict is caused by:
2025-01-22 18:04:01 [INFO] #13 8.904 The user requested typing-extensions==4.7.1
2025-01-22 18:04:01 [INFO] #13 8.904 bitsandbytes 0.45.0 depends on typing_extensions>=4.8.0
```
2025-01-22 18:06:46 +02:00
mohamednaji7 131c17569f correct access to "args" dictionary 2025-01-21 22:33:28 +02:00
mohamednaji7 8882f6d50b adding 'bitsandbytes' to QUANTIZATION 2025-01-21 14:46:40 +02:00
mohamednaji7 331bc30101 adding 'bitsandbytes' option 2025-01-21 14:08:37 +02:00
mohamednaji7 a27f72a33a inforce args.quantization for bnb load_froamt 2025-01-21 14:01:32 +02:00
mohamednaji7 7167985f23 including bitsandbytes "src:https://docs.vllm.ai/en/stable/quantization/bnb.html" 2025-01-21 13:49:36 +02:00
sihamouda 0e3359a70e add engine argument for multimodels input 2025-01-19 02:44:39 +01:00
Marut PandyaandGitHub 3f0a20d28e Merge pull request #141 from runpod-workers/main
Rebase
2025-01-02 20:49:48 -08:00
pandyamarut 8e3c26be14 update worker-config
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-12-30 17:41:10 -08:00
pandyamarut 66ea8b1110 update engine
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-12-30 17:13:03 -08:00
Marut PandyaandGitHub a3d432afdf Merge pull request #140 from runpod-workers/nw-updte
upgrade vllm version
2024-12-30 15:23:44 -08:00
pandyamarut 06c2bb1715 upgrade vllm version
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-12-30 15:20:11 -08:00
Marut PandyaandGitHub d2e355eae9 Merge pull request #137 from kldzj/fix-tool-calling
fix: openai tool calling
2024-12-15 20:50:47 -08:00
kldzj b7787d8ca8 fix: remove unused import 2024-12-06 16:29:06 +01:00
kldzj b1fca5d257 fix: move tool flags away from engine args 2024-12-06 16:07:23 +01:00
kldzj 3e86d16892 fix: openai tool calling 2024-12-06 13:08:48 +01:00
Marut PandyaandGitHub d9f54ce76a Update README.md 2024-11-29 16:30:45 -08:00
Marut PandyaandGitHub 149da95cd0 Merge pull request #133 from kldzj/tool-calling
feat: add tool calling flags
2024-11-29 16:29:56 -08:00
Marut PandyaandGitHub 0a89394f1d Update worker-config.json 2024-11-29 16:29:33 -08:00
Nikolai Kolodziej 8df7f41f1d fix: set empty tool_call_parser to None 2024-11-24 06:55:43 +01:00
Nikolai Kolodziej 4d7b8c03c0 feat: tool calling flags 2024-11-24 06:51:41 +01:00
pandyamarut 6c6bf50379 update env
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-11-22 15:14:57 -08:00
pandyamarut 27a2ee5754 add model cache
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-11-22 13:11:12 -08:00
Marut PandyaandGitHub 2df915a145 Merge pull request #132 from runpod-workers/wc-uo
update worker-config
2024-11-20 14:54:45 -08:00
pandyamarut aadc025849 update worker-config
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-11-20 14:42:56 -08:00
Marut PandyaandGitHub 8b4a49073d Merge pull request #131 from runpod-workers/up-0.6.4
[Core]Update vllm-0.6.4
2024-11-20 10:37:46 -08:00
pandyamarut 4e10641d69 update vllm
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-11-19 12:14:04 -08:00
Marut PandyaandGitHub 6e8696c12a Merge pull request #121 from sven-knoblauch/lora-modules
add changes for lora adapter support and /v1/models endpoint
2024-10-31 15:07:02 -04:00
Marut PandyaandGitHub b49e81a75a Merge pull request #126 from runpod-workers/up-wc-1
update worker-config
2024-10-15 17:52:13 -07:00
pandyamarut 65932f85e1 update worker-config
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-10-15 17:47:58 -07:00
Marut PandyaandGitHub 94840cfbbb Update README.md 2024-10-15 17:38:31 -07:00
Marut PandyaandGitHub ce47c41f4a Merge pull request #125 from runpod-workers/up-0.6.3
update vllm
2024-10-15 17:04:20 -07:00
pandyamarut c03ecc42fe update vllm
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-10-15 16:49:41 -07:00
Dean QuiñanolaandGitHub ae56b9f43d Merge pull request #123 from runpod-workers/dependency-update-refactored 2024-10-13 20:23:33 -07:00
Dean QuiñanolaandGitHub 891699be1e Merge pull request #124 from runpod-workers/readme-correction 2024-10-13 20:23:05 -07:00
Dean QuiñanolaandGitHub c28aa02576 Update README.md
v1.5.0 not v15
2024-10-12 17:11:59 -07:00
Dean QuiñanolaandGitHub eba20c0704 Update CI-runpod_dep.yml
Dependency has changed to `runpod~=<version>` and not `runpod==<version>`
2024-10-12 16:47:31 -07:00
Sven Knoblauch 677a01e8f3 update code for case of no lora adapter 2024-10-09 14:51:33 +02:00
Sven Knoblauch 5cd12ba331 add changes for lora adapter support and /v1/models endpoint 2024-10-09 11:01:12 +02:00
Dean QuiñanolaandGitHub 850c686538 Merge pull request #120 from runpod-workers/runpod-v1.7-and-up
Update requirements.txt to support runpod-python 1.7.*
2024-10-08 10:52:20 -07:00
Dean QuiñanolaandGitHub de2876e659 Update requirements.txt 2024-10-08 10:48:10 -07:00
Marut PandyaandGitHub d3ee3236c0 Merge pull request #118 from runpod-workers/up-wc
update worker-config
2024-10-01 11:23:02 -07:00
pandyamarut 0781e93054 update worker-config
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-10-01 11:21:27 -07:00
Marut PandyaandGitHub 251e807012 Update README.md 2024-10-01 11:17:30 -07:00
Marut PandyaandGitHub 29346769ed Merge pull request #117 from runpod-workers/up-0.6.2
update vllm
2024-10-01 11:05:40 -07:00
pandyamarut 1420091588 update vll
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-09-27 19:23:50 -07:00
Marut PandyaandGitHub d46adeaee9 Merge pull request #110 from runpod-workers/up-0.6.1
update vllm v0.6.1
2024-09-16 15:12:50 -07:00
pandyamarut 5c0dca44bd update
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-09-16 15:01:21 -07:00
pandyamarut cc301ac123 update
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-09-16 15:00:01 -07:00
pandyamarut 2ac6a0108f update vllm v0.6.0
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-09-16 14:55:40 -07:00
Marut PandyaandGitHub b1554ea10f Merge pull request #109 from runpod-workers/0.5.5-update
[Update] Docs, bug fix.
2024-09-06 12:36:09 -07:00
pandyamarut 0d794a3914 fix
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-09-06 12:26:09 -07:00
pandyamarut 3dad3a754c update vllm
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-09-06 12:21:34 -07:00
Marut PandyaandGitHub 44cef385df Merge pull request #108 from runpod-workers/cmpl-htf
[Bug]fix oai completion api error
2024-09-06 11:06:33 -07:00
pandyamarut 814f50af38 fix oai completion api error
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-09-06 11:03:47 -07:00
Marut PandyaandGitHub f3a530b7fe Merge pull request #107 from runpod-workers/pandyamarut-patch-1
Update README.md
2024-08-28 23:32:48 -07:00
Marut PandyaandGitHub cdf78e7c89 Update README.md 2024-08-28 23:32:36 -07:00
Marut PandyaandGitHub ab40d9c9a8 Merge pull request #106 from runpod-workers/up-0.5.5
update vllm version 0.5.5
2024-08-28 23:31:15 -07:00
pandyamarut 3293245c81 update tags
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-08-28 23:28:39 -07:00
pandyamarut 5e1c8c8128 update vllm version 0.5.5
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-08-28 22:46:45 -07:00
Marut PandyaandGitHub 286d6ba702 Merge pull request #102 from carlson-svg/main
Add human readable worker-config.json
2024-08-26 20:22:47 -07:00
carlson-svg 8d734f8340 Merge branch 'add-worker-config' 2024-08-26 01:25:09 -07:00
carlson-svg 4fa4a8e0e6 added to worker config docs to table of contents + added side note 2024-08-26 01:20:18 -07:00
carlson-svg 39ce8a64c0 initial documentation for worker-config.json 2024-08-22 15:40:54 -07:00
carlson-svg 825ef25b60 changed to minimumCudaVersion to camel case 2024-08-21 12:47:48 -07:00
carlson-svg 1e9aeb6e8f adding "minimum_cuda_version" to each version 2024-08-21 12:44:45 -07:00
carlson-svg e6172dddd4 took out space in imageName from version 0.5.4 2024-08-19 15:17:20 -07:00
carlson-svg 21a1e138b4 updated version of human readable config 2024-08-18 23:57:19 -07:00
carlson-svg a40e7803ee converted to human readable format 2024-08-18 23:24:40 -07:00
CarlsonandGitHub 5e245793bc Merge pull request #1 from carlson-svg/add-worker-config
v0 worker-config
2024-08-13 20:43:47 -07:00
Marut PandyaandGitHub 2111c9e7a5 Update README.md 2024-08-12 21:02:43 -07:00
carlson-svg 0ae11ea6df v0 worker-config 2024-08-09 15:10:08 -07:00
Marut PandyaandGitHub 7f46582949 Merge pull request #96 from runpod-workers/rel-v0.5.4
update vllm version 0.5.4
2024-08-09 15:01:16 -07:00
Marut PandyaandGitHub 571ef2b805 Update README.md 2024-08-09 14:58:46 -07:00
pandyamarut 967eaba573 change to float
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-08-09 14:41:07 -07:00
Marut PandyaandGitHub eb75a3ac03 Merge pull request #95 from runpod-workers/runpod-package-update
Update runpod package version
2024-08-09 12:04:25 -07:00
pandyamarut 9cb9336cf5 update vllm version 0.5.4
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-08-09 12:01:42 -07:00
pandyamarutandGitHub 6a15a9e750 Update package version 2024-08-07 22:38:37 +00:00
Marut PandyaandGitHub f023f57217 Update README.md 2024-08-07 15:38:26 -07:00
Marut PandyaandGitHub 673597fd46 Update README.md 2024-08-07 15:32:23 -07:00
Marut PandyaandGitHub c50543ebd9 Update README.md 2024-08-07 15:30:33 -07:00
Marut PandyaandGitHub 17a2d844ec Merge pull request #93 from runpod-workers/up-rdme
Update README.md
2024-08-05 14:36:39 -07:00
pandyamarut 3498e99b2f update
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-08-05 14:33:56 -07:00
pandyamarut 5da96ce9a6 update
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-08-05 14:26:56 -07:00
Marut PandyaandGitHub e32626ca9d Update README.md 2024-08-05 14:19:38 -07:00
Marut PandyaandGitHub 37d140aba6 Update docker-bake.hcl 2024-08-02 16:53:59 -07:00
Marut PandyaandGitHub 66ed2a2a5f Merge pull request #90 from runpod-workers/pandyamarut-patch-1
Update README.md
2024-08-02 16:03:18 -07:00
pandyamarut e846ecae9d update readme
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-08-02 14:13:55 -07:00
Marut PandyaandGitHub 9f066be620 Update README.md 2024-08-02 13:29:18 -07:00
Marut PandyaandGitHub 8a010c3804 Merge pull request #82 from runpod-workers/any-arg-and-refactor
Allow any vLLM engine args as env vars, Update vLLM, refactor
2024-08-01 15:28:11 -07:00
pandyamarut 14cacd55fe update docker
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-07-31 18:44:46 -07:00
Marut PandyaandGitHub e1b41795f7 Update README.md 2024-07-31 12:46:34 -07:00
Marut PandyaandGitHub 0814d76654 Update README.md 2024-07-30 17:09:01 -07:00
pandyamarut f3534a4ea7 fix openai compat
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-07-27 15:49:45 -07:00
Marut PandyaandGitHub b61ea5ea46 Delete test.py 2024-07-26 17:32:16 -07:00
pandyamarut 0f8657e58d update env default args
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-07-26 16:52:51 -07:00
pandyamarut bd96b5e0de update v0.5.3.post1
Signed-off-by: pandyamarut <pandyamarut@gmail.com>
2024-07-25 21:29:45 -07:00
alpayariyak 5bd6f3a75e 0.5.3, any vllm arg as env var, refactor and fixes, moving away from building separate image from vLLM fork 2024-07-25 12:41:48 -07:00
alpayariyak a08d83f600 Allow any vLLM engine args as env vars, refactor 2024-07-02 19:44:01 +00:00
alpayariyak 0e1e38326a Fix deprecated max_context_len_to_capture engine argument 2024-06-13 17:48:05 +00:00
alpayariyak c8458fef2b preparation for 1.0.0 release 2024-06-12 12:28:03 -07:00
alpayariyak bad5ddd892 Fix vLLM 0.4.1 bug for OpenAI /models route 2024-06-10 20:38:49 +00:00
alpayariyak f19ce12ab0 Fix Building Docker with model built-in #71 2024-06-07 15:29:46 -07:00
alpayariyak 1bb6f84541 Deprecated kv cache dtype warning 2024-05-10 16:29:20 +00:00
30cb56a3df Fix MODEL_REVISION env var (Merge pull request #50 from joennlae/rename-revision and #67 from mikljohansson/main)
Fixed MODEL_REVISION environment variable

Co-Authored-By: Jannis Schönleber <1493766+joennlae@users.noreply.github.com>
Co-Authored-By: Mikael Johansson <mikl.johansson@gmail.com>
2024-05-09 20:45:07 -04:00
alpayariyak 00add8707a Temporarily disable build and push github actions 2024-05-09 20:33:52 -04:00
alpayariyak ec7ea0b760 Update default base image version to fix github actions build 2024-05-09 20:18:34 -04:00
alpayariyak 9f2cb7b1d0 Update documentation to include rename of fp8_e5m2 to fp8 2024-05-09 23:59:11 +00:00
alpayariyak 4abe494635 Fix hf-transfer error 2024-05-09 23:51:07 +00:00
Alpay AriyakandGitHub 4f61b04afe Update README.md 2024-05-09 01:05:04 -04:00
Alpay Ariyakandalpayariyak 874379a0c5 1.0.0preview update for Llama 3 support and more (vLLM 0.3.3 -> 0.4.2) (#62) 2024-05-09 00:42:08 -04:00
Mikael Johansson f06a64d5b9 Fixed MODEL_REVISION environment variable 2024-05-02 13:45:43 +02:00
alpayariyak 0a5b5bc095 Add badges 2024-03-15 21:23:52 -04:00
alpayariyak 2936e4d95d Update automatic builds, documentation 2024-03-15 11:57:38 -04:00
Alpay AriyakandGitHub cee4e484d5 Update README.md for 0.3.2 2024-03-12 19:07:37 -04:00
Alpay AriyakandGitHub 6160769996 Release 0.3.2 2024-03-12 17:44:47 -05:00
alpayariyak d25b6f9628 Fix sampling params 2024-03-12 22:15:57 +00:00
alpayariyak c8ee100d80 Small refactor 2024-03-06 17:08:57 +00:00
alpayariyak fee8d8eee4 Fix submodule 2024-03-05 19:17:53 +00:00
alpayariyak db7167d57f 0.3.3 2024-03-05 19:14:35 +00:00
Alpay Ariyakandalpayariyak d91ccb866f 0.3.1: bug fixes 2024-02-29 02:55:44 -05:00
Alpay AriyakandGitHub 36e9b670ee Add notice on what to do when HuggingFace is down 2024-02-28 17:10:39 -05:00
Alpay Ariyakandalpayariyak 91167b873a v0.3.0: OpenAI Compatibility, Dynamic Stream Batching, Refactor, Error Catching 2024-02-23 22:34:00 -05:00
alpayariyak 819102cfd6 Merge branch 'openai-sse-output' of https://github.com/runpod-workers/worker-vllm into openai-sse-output 2024-02-24 03:18:37 +00:00
alpayariyak 985bbf1cb5 Fix Multi-GPU, tokenizer trust remote code 2024-02-24 03:18:25 +00:00
Alpay AriyakandGitHub 6f5718f191 Update Docker image tag in README.md 2024-02-23 02:15:50 -05:00
Alpay AriyakandGitHub 235d0d31d0 Merge pull request #50 from runpod-workers/tagged-releases
feat: auto build cuda version
2024-02-22 23:14:57 -05:00
alpayariyak 708f68d7f8 Final Bug fixes, configurable oai response role, served model name override, documentation 2024-02-23 04:14:03 +00:00
alpayariyak b42d45ce0f Bug fixes, refactors 2024-02-23 03:46:47 +00:00
Justin Merrell 7221caceff feat: auto build cuda version 2024-02-22 20:48:54 -05:00
alpayariyak a2d9535652 Update documentation further 2024-02-23 01:34:38 +00:00
alpayariyak 9129d0a252 New ENV Vars 2024-02-22 23:58:20 +00:00
alpayariyak 6bcd9d7c67 Preparing for 0.3.0 2024-02-22 18:04:34 -05:00
Alpay AriyakandGitHub b4204c612c Merge pull request #48 from rachfop/patch-1
Fixes import statement in docs
2024-02-21 23:55:11 -05:00
Patrick RachfordandGitHub 7993818f5f Update README.md
Remove formatting of tables
2024-02-21 19:28:03 -08:00
Patrick RachfordandGitHub e97917cc14 Fixes import statement
Fixes import statements, formats tables, run black on code blocks
2024-02-21 19:17:23 -08:00
Alpay AriyakandGitHub 3549cf24d5 Merge branch 'main' into openai-sse-output 2024-02-21 19:56:55 -05:00
alpayariyak aed0408f19 Documentation for 0.3.0, small fixes and changes 2024-02-21 19:28:59 -05:00
alpayariyak e191149259 OpenAI Compatibility, Dynamic Batching, Refactor 2024-02-21 04:36:04 +00:00
Alpay AriyakandGitHub 2941db0fb8 Update worker-vllm version 2024-02-09 23:12:29 -05:00
Alpay AriyakandGitHub bfeb60c54e Merge pull request #45 from willsamu/fix-tokenizer-input
fix: build error if no `TOKENIZER_NAME` provided
2024-02-09 22:51:18 -05:00
alpayariyak 7b3fd05542 Small refactor to tokenizer fix 2024-02-09 22:50:00 -05:00
Samuel Will b0e7b575f3 fix: default value for tokenizer 2024-02-09 10:24:58 +00:00
alpayariyak 4f5e0d37c4 Fix tokenizer's trust_remote_code parameter 2024-02-08 23:53:13 +00:00
alpayariyak a94ef66f71 Dynamic Batch Size [needs refactor] 2024-02-06 03:47:27 +00:00
alpayariyak 45081e4037 Add __init__.py 2024-02-06 02:44:35 +00:00
alpayariyak fef8c81cb9 OpenAI Compatible worker, Refactor 2024-02-06 02:44:14 +00:00
alpayariyak 15b06bb687 Merge branch 'main' into openai-sse-output 2024-02-02 20:03:29 -05:00
Alpay AriyakandGitHub 2b5b8dfb61 Fix Model and Tokenizer download for bake-in option, add revision configuration for both. 2024-02-02 19:58:50 -05:00
alpayariyak 8de10468dd Working tokenizer and model download fix
Fix handler startup
2024-02-02 19:55:35 -05:00
alpayariyak b7051d37ca Move test_openai_stream.py 2024-02-02 22:12:26 +00:00
alpayariyak b1720a154d Added download of model extras into weights folder, separate download of tokenizer, making engine.py utilize downloaded tokenizer, model and tokenizer revision 2024-01-31 22:57:32 -05:00
alpayariyak afa33a2875 Handle errors 2024-02-01 03:01:51 +00:00
alpayariyak 068303ce8f OpenAI Proxy Server for EndPoints and more examples 2024-02-01 02:32:32 +00:00
alpayariyak 3bbcf0021b Fix: Yield if tokens left in batch
Temp: default model for testing image
2024-02-01 00:52:39 +00:00
alpayariyak dab8bad906 OpenAI Chat Completions Stream 2024-01-31 23:27:31 +00:00
Casper f4d7c75504 Snapshot download only tokenizer/config related things 2024-01-31 22:16:44 +01:00
Casper 3adc9e3336 Remove unused import 2024-01-31 18:27:49 +01:00
Casper fd00a1ece3 Update to use snapshot_download 2024-01-31 18:24:57 +01:00
Casper 664dd35782 Download tokenizer upon build 2024-01-31 17:59:52 +01:00
alpayariyak 370698442c Update RunPod SDK version and Docker Tag 2024-01-31 00:54:58 -05:00
alpayariyak 3e2cd080a2 Fix Tensor Parallel 2024-01-31 05:12:58 +00:00
alpayariyak e7b340d73b Update vLLM base image 2024-01-31 03:37:55 +00:00
alpayariyak 46eee12819 Simplify Tensor Parallel 2024-01-31 03:28:02 +00:00
alpayariyak 12d6f0778e Fixed Model bake-in, added Custom Chat Templates, Custom Tokenizer 2024-01-31 03:13:21 +00:00
Alpay AriyakandGitHub fa5556434c Bug fix 2024-01-29 11:26:22 -05:00
alpayariyak 97726372c0 Update release tag in README.md 2024-01-25 23:37:07 -05:00
alpayariyak 9fc8e1e54c Non-streaming OpenAI Chat Completions 2024-01-25 23:24:18 -05:00
alpayariyak 4cebe66b36 0.2.0 Release
- You no longer need a linux-based machine or NVIDIA GPUs to build the worker.
- Over 3x lighter Docker image size.
- OpenAI Chat Completion output format (optional to use).
- Extremely fast image build time.
- Docker Secrets-protected Hugging Face token support for building the image with a model baked in without exposing your token.
- Support for `n` and `best_of` sampling parameters, which allow you to generate multiple responses from a single prompt.
- New environment variables for various configuration.
- vLLM Version: 0.2.7
2024-01-25 20:49:15 -05:00
Alpay Ariyakandalpayariyak 368c5f87fb Temporary Dockerfile Fix
Temporary Dockerfile fix
2024-01-25 20:48:26 -05:00
alpayariyak 15cc7cd36f Updated Documentation 2024-01-19 10:48:12 -05:00
alpayariyak ef3c303743 Added support for n parameter 2024-01-19 15:34:25 +00:00
alpayariyak 584852f0f6 Docker-Protected HF Token, Refactor, Better Documentation 2024-01-18 18:20:51 -05:00
Alpay AriyakandGitHub 65454c024a Update README.md (temporary) 2024-01-17 00:16:56 -05:00
Justin Merrell f023e2e097 Update README.md 2024-01-16 19:55:20 -05:00
27 changed files with 3450 additions and 412 deletions
-3
View File
@@ -1,3 +0,0 @@
MODEL_NAME="mistralai/Mistral-7B-Instruct-v0.1"
MODEL_BASE_PATH="./models"
DISABLE_LOG_STATS=0
+79
View File
@@ -0,0 +1,79 @@
# Contributing to worker-vllm
## 🚀 Release Process
### Development Workflow
1. **Feature Development**
```bash
git checkout -b feature/your-feature-name
# Make your changes
git push origin feature/your-feature-name
```
- Creates pull request → triggers dev build: `runpod/worker-v1-vllm:dev-refs-pull-214-merge`
2. **Main Branch**
```bash
git checkout main
git merge feature/your-feature-name
git push origin main
```
- No automatic builds on main (staging area)
### Creating Releases
**Method 1: GitHub UI (Recommended)**
1. Go to [Releases](https://github.com/runpod-workers/worker-vllm/releases)
2. Click **"Create a new release"**
3. **Tag version**: `v2.8.0` (with "v" prefix, semantic versioning)
4. **Target**: `main` branch
5. **Title**: `Release 2.8.0`
6. **Description**: Brief changelog
7. Click **"Publish release"**
**Method 2: Git CLI**
```bash
git checkout main
git tag v2.8.0
git push origin v2.8.0
```
### What Happens Automatically
✅ **GitHub Release** created (if using Method 1)
✅ **Docker Image** built and pushed: `runpod/worker-v1-vllm:v2.8.0`
✅ **Documentation** updated with new version references
## 📋 Version Format
- **Format**: `vMAJOR.MINOR.PATCH` (e.g., `v2.8.0`)
- **With "v" prefix**: Use `v2.8.0` for git tags
- **Semantic Versioning**: Follow [SemVer](https://semver.org/)
## 🐛 Development
### Running Tests
```bash
# Update test configuration in .runpod/tests.json
# Tests run automatically via RunPod platform
```
### Model Updates
- Update `MODEL_NAME` in `.runpod/tests.json` and `worker-config.json`
- Ensure model has vLLM support and chat template (for OpenAI compatibility)
### Environment Variables
See [README.md](../README.md) for full list of supported environment variables.
## 🔧 CI/CD Workflows
- **Dev builds**: All pull requests → `dev-refs-pull-<PR#>-merge` images
- **Release builds**: Git tags → versioned images + GitHub releases
- **Manual triggers**: Available in GitHub Actions for emergency releases
+27 -10
View File
@@ -19,32 +19,49 @@ jobs:
- name: Check for new package version and update
run: |
# Get current version
current_version=$(grep -oP 'runpod==\K[^"]+' ./builder/requirements.txt)
echo "Fetching the current runpod version from requirements.txt..."
# Get current version, allowing both == and ~= in the search pattern
current_version=$(grep -oP 'runpod[~=]{1,2}\K[^"]+' ./builder/requirements.txt)
echo "Current version: $current_version"
# Get new version
# Extract major and minor from current version
current_major_minor=$(echo $current_version | cut -d. -f1,2)
echo "Current major.minor: $current_major_minor"
echo "Fetching the latest runpod version from PyPI..."
# Get new version from PyPI
new_version=$(curl -s https://pypi.org/pypi/runpod/json | jq -r .info.version)
echo "NEW_VERSION_ENV=$new_version" >> $GITHUB_ENV
echo "New version: $new_version"
# Extract major and minor from new version
new_major_minor=$(echo $new_version | cut -d. -f1,2)
echo "New major.minor: $new_major_minor"
if [ -z "$new_version" ]; then
echo "Failed to fetch the new version."
echo "ERROR: Failed to fetch the new version from PyPI."
exit 1
fi
# Check if the version is already up-to-date
if [ "$current_version" = "$new_version" ]; then
echo "The package version is already up-to-date."
# Check if the major or minor version is different
if [ "$current_major_minor" = "$new_major_minor" ]; then
echo "No update needed. The new version ($new_major_minor) is within the allowed range (~= $current_major_minor)."
exit 0
fi
# Update requirements.txt
sed -i "s/runpod==.*/runpod==$new_version/" ./builder/requirements.txt
echo "New major/minor detected ($new_major_minor). Updating requirements.txt..."
# Update requirements.txt, preserving the existing constraint type (~= or ==)
sed -i "s/runpod[~=][^ ]*/runpod~=$new_version/" ./builder/requirements.txt
echo "requirements.txt has been updated."
- name: Create Pull Request
uses: peter-evans/create-pull-request@v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
commit-message: Update package version
commit-message: Update runpod package version
title: Update runpod package version
body: The package version has been updated to ${{ env.NEW_VERSION_ENV }}
branch: runpod-package-update
+60
View File
@@ -0,0 +1,60 @@
name: Development
on:
pull_request:
branches:
- "**"
permissions:
contents: read
jobs:
dev:
runs-on: [blacksmith-8vcpu-ubuntu-2204, linux]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Clear space to remove unused folders
run: |
rm -rf /usr/share/dotnet
rm -rf /opt/ghc
rm -rf "/usr/local/share/boost"
rm -rf "$AGENT_TOOLSDIRECTORY"
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: blacksmith docker layer cache
uses: useblacksmith/build-push-action@v1
with:
setup-only: true
- name: Set environment variables
run: |
echo "DOCKERHUB_REPO=${{ vars.DOCKERHUB_REPO || 'runpod' }}" >> $GITHUB_ENV
echo "DOCKERHUB_IMG=${{ vars.DOCKERHUB_IMG || 'worker-v1-vllm' }}" >> $GITHUB_ENV
echo "HUGGINGFACE_ACCESS_TOKEN=${{ secrets.HUGGINGFACE_ACCESS_TOKEN }}" >> $GITHUB_ENV
# Convert branch name to safe docker tag (replace / with -)
BRANCH_NAME="${GITHUB_REF##refs/heads/}"
SAFE_BRANCH_NAME=$(echo "$BRANCH_NAME" | sed 's/[^a-zA-Z0-9._-]/-/g' | sed 's/--*/-/g')
echo "RELEASE_VERSION=dev-${SAFE_BRANCH_NAME}" >> $GITHUB_ENV
- name: Build and push the images to Docker Hub
uses: docker/bake-action@v2
with:
push: true
set: |
*.args.DOCKERHUB_REPO=${{ env.DOCKERHUB_REPO }}
*.args.DOCKERHUB_IMG=${{ env.DOCKERHUB_IMG }}
*.args.RELEASE_VERSION=${{ env.RELEASE_VERSION }}
*.args.HUGGINGFACE_ACCESS_TOKEN=${{ env.HUGGINGFACE_ACCESS_TOKEN }}
@@ -1,40 +0,0 @@
name: CD | Docker-Build-Release
on:
push:
branches:
- "main"
release:
types: [published]
workflow_dispatch:
inputs:
image_tag:
description: "Docker Image Tag"
required: false
default: "dev"
jobs:
docker-build:
runs-on: DO
# DO is a custom runner deployed on DigitalOcean, only available for workflows under the runpod-workers organization.
# If you would like to use this workflow, you can replace DO with ubuntu-latest or any other runner.
steps:
- name: Set up QEMU
uses: docker/setup-qemu-action@v2
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
# Build and push step
- name: Build and push
uses: docker/build-push-action@v4
with:
push: true
tags: ${{ vars.DOCKERHUB_REPO }}/${{ vars.DOCKERHUB_IMG }}:${{ (github.event_name == 'release' && github.event.release.tag_name) || (github.event_name == 'workflow_dispatch' && github.event.inputs.image_tag) || 'dev' }}
+86
View File
@@ -0,0 +1,86 @@
name: Release
on:
push:
tags:
- "v[0-9]+.[0-9]+.[0-9]+*" # Trigger on version tags like v1.0.0, v2.1.0, etc.
workflow_dispatch:
inputs:
version:
description: "Version to release (e.g., v2.8.0)"
required: true
type: string
permissions:
contents: write # Required for creating GitHub releases
jobs:
release:
runs-on: [blacksmith-8vcpu-ubuntu-2204, linux]
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Clear space to remove unused folders
run: |
rm -rf /usr/share/dotnet
rm -rf /opt/ghc
rm -rf "/usr/local/share/boost"
rm -rf "$AGENT_TOOLSDIRECTORY"
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: blacksmith docker layer cache
uses: useblacksmith/build-push-action@v1
with:
setup-only: true
- name: Set environment variables
run: |
echo "DOCKERHUB_REPO=${{ vars.DOCKERHUB_REPO || 'runpod' }}" >> $GITHUB_ENV
echo "DOCKERHUB_IMG=${{ vars.DOCKERHUB_IMG || 'worker-v1-vllm' }}" >> $GITHUB_ENV
echo "HUGGINGFACE_ACCESS_TOKEN=${{ secrets.HUGGINGFACE_ACCESS_TOKEN }}" >> $GITHUB_ENV
# Determine version based on trigger type
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
# Manual trigger: use input version
VERSION="${{ github.event.inputs.version }}"
echo "RELEASE_VERSION=${VERSION}" >> $GITHUB_ENV
echo "IS_MANUAL_RELEASE=true" >> $GITHUB_ENV
else
# Tag trigger: use tag name (remove refs/tags/ prefix)
VERSION=${GITHUB_REF#refs/tags/}
echo "RELEASE_VERSION=${VERSION}" >> $GITHUB_ENV
echo "IS_MANUAL_RELEASE=false" >> $GITHUB_ENV
fi
- name: Build and push the images to Docker Hub
uses: docker/bake-action@v2
with:
push: true
set: |
*.args.DOCKERHUB_REPO=${{ env.DOCKERHUB_REPO }}
*.args.DOCKERHUB_IMG=${{ env.DOCKERHUB_IMG }}
*.args.RELEASE_VERSION=${{ env.RELEASE_VERSION }}
*.args.HUGGINGFACE_ACCESS_TOKEN=${{ env.HUGGINGFACE_ACCESS_TOKEN }}
- name: Release Summary
run: |
echo "🚀 Release completed!"
echo "Version: ${{ env.RELEASE_VERSION }}"
echo "Docker Image: ${{ env.DOCKERHUB_REPO }}/${{ env.DOCKERHUB_IMG }}:${{ env.RELEASE_VERSION }}"
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
echo "Trigger: Manual workflow dispatch"
else
echo "Trigger: GitHub release (tag: ${{ github.ref_name }})"
fi
+3 -1
View File
@@ -2,4 +2,6 @@
runpod.toml
*.pyc
.env
test/*
test/*
vllm-base/vllm-*
.DS_Store
+263
View File
@@ -0,0 +1,263 @@
![vLLM worker banner](https://cpjrphpz3t5wbwfe.public.blob.vercel-storage.com/worker-vllm_banner.jpeg)
Run LLMs using [vLLM](https://docs.vllm.ai) with an OpenAI-compatible API
---
[![RunPod](https://api.runpod.io/badge/runpod-workers/worker-vllm)](https://www.runpod.io/console/hub/runpod-workers/worker-vllm)
---
## Endpoint Configuration
All behaviour is controlled through environment variables:
| Environment Variable | Description | Default | Options |
| ----------------------------------- | ------------------------------------------------- | ------------------- | ------------------------------------------------------------------ |
| `MODEL_NAME` | Path of the model weights | "facebook/opt-125m" | Local folder or Hugging Face repo ID |
| `HF_TOKEN` | HuggingFace access token for gated/private models | | Your HuggingFace access token |
| `MAX_MODEL_LEN` | Model's maximum context length | | Integer (e.g., 4096) |
| `QUANTIZATION` | Quantization method | | "awq", "gptq", "squeezellm", "bitsandbytes" |
| `TENSOR_PARALLEL_SIZE` | Number of GPUs | 1 | Integer |
| `GPU_MEMORY_UTILIZATION` | Fraction of GPU memory to use | 0.95 | Float between 0.0 and 1.0 |
| `MAX_NUM_SEQS` | Maximum number of sequences per iteration | 256 | Integer |
| `CUSTOM_CHAT_TEMPLATE` | Custom chat template override | | Jinja2 template string |
| `ENABLE_AUTO_TOOL_CHOICE` | Enable automatic tool selection | false | boolean (true or false) |
| `TOOL_CALL_PARSER` | Parser for tool calls | | "mistral", "hermes", "llama3_json", "granite", "deepseek_v3", etc. |
| `REASONING_PARSER` | Parser for reasoning-capable models | | "deepseek_r1", "qwen3", "granite", "hunyuan_a13b" |
| `OPENAI_SERVED_MODEL_NAME_OVERRIDE` | Override served model name in API | | String |
| `MAX_CONCURRENCY` | Maximum concurrent requests | 300 | Integer |
**Pass any vLLM engine arg** not listed above by setting an env var with the **UPPERCASED** field name (e.g. `MAX_MODEL_LEN=4096`, `ENABLE_CHUNKED_PREFILL=true`). The worker auto-discovers all `AsyncEngineArgs` fields from env. See the [vLLM engine args docs](https://docs.vllm.ai/en/latest/configuration/engine_args) for all available options.
For complete configuration options, see the [full configuration documentation](https://github.com/runpod-workers/worker-vllm/blob/main/docs/configuration.md).
## API Usage
This worker supports two API formats: **RunPod native** and **OpenAI-compatible**.
### RunPod Native API
For testing directly in the RunPod UI, use these examples in your endpoint's request tab.
#### Chat Completions
```json
{
"input": {
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "What is the capital of France?" }
],
"sampling_params": {
"max_tokens": 100,
"temperature": 0.7
}
}
}
```
#### Chat Completions (Streaming)
```json
{
"input": {
"messages": [
{ "role": "user", "content": "Write a short story about a robot." }
],
"sampling_params": {
"max_tokens": 500,
"temperature": 0.8
},
"stream": true
}
}
```
#### Text Generation
For direct text generation without chat format:
```json
{
"input": {
"prompt": "The capital of France is",
"sampling_params": {
"max_tokens": 64,
"temperature": 0.0
}
}
}
```
#### List Models
```json
{
"input": {
"openai_route": "/v1/models"
}
}
```
---
### OpenAI-Compatible API
For external clients and SDKs, use the `/openai/v1` path prefix with your RunPod API key.
#### Chat Completions
**Path:** `/openai/v1/chat/completions`
```json
{
"model": "meta-llama/Llama-2-7b-chat-hf",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "What is the capital of France?" }
],
"max_tokens": 100,
"temperature": 0.7
}
```
#### Chat Completions (Streaming)
```json
{
"model": "meta-llama/Llama-2-7b-chat-hf",
"messages": [
{ "role": "user", "content": "Write a short story about a robot." }
],
"max_tokens": 500,
"temperature": 0.8,
"stream": true
}
```
#### Text Completions
**Path:** `/openai/v1/completions`
```json
{
"model": "meta-llama/Llama-2-7b-chat-hf",
"prompt": "The capital of France is",
"max_tokens": 100,
"temperature": 0.7
}
```
#### List Models
**Path:** `/openai/v1/models`
```json
{}
```
#### Response Format
Both APIs return the same response format:
```json
{
"choices": [
{
"index": 0,
"message": { "role": "assistant", "content": "Paris." },
"finish_reason": "stop"
}
],
"usage": { "prompt_tokens": 9, "completion_tokens": 1, "total_tokens": 10 }
}
```
---
## Usage
Below are minimal `python` snippets so you can copy-paste to get started quickly.
> Replace `<ENDPOINT_ID>` with your endpoint ID and `<API_KEY>` with a [RunPod API key](https://docs.runpod.io/get-started/api-keys).
### OpenAI compatible API
Minimal Python example using the official `openai` SDK:
```python
from openai import OpenAI
import os
# Initialize the OpenAI Client with your RunPod API Key and Endpoint URL
client = OpenAI(
api_key=os.getenv("RUNPOD_API_KEY"),
base_url=f"https://api.runpod.ai/v2/<ENDPOINT_ID>/openai/v1",
)
```
`Chat Completions (Non-Streaming)`
```python
response = client.chat.completions.create(
model="meta-llama/Llama-2-7b-chat-hf",
messages=[{"role": "user", "content": "Explain quantum computing in simple terms"}],
temperature=0,
max_tokens=100,
)
print(f"Response: {response.choices[0].message.content}")
```
`Chat Completions (Streaming)`
```python
response_stream = client.chat.completions.create(
model="meta-llama/Llama-2-7b-chat-hf",
messages=[{"role": "user", "content": "Explain quantum computing in simple terms"}],
temperature=0,
max_tokens=100,
stream=True
)
for response in response_stream:
print(response.choices[0].delta.content or "", end="", flush=True)
```
### RunPod Native API
```python
import requests
response = requests.post(
"https://api.runpod.ai/v2/<ENDPOINT_ID>/run",
headers={"Authorization": "Bearer <API_KEY>"},
json={
"input": {
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain quantum computing in simple terms"}
],
"sampling_params": {
"temperature": 0.7,
"max_tokens": 150
}
}
}
)
result = response.json()
print(result["output"])
```
## Compatibility
For supported models, see the [vLLM supported models documentation](https://docs.vllm.ai/en/latest/models/supported_models.html).
Anything not recognized by worker-vllm is forwarded to vLLM's engine, so advanced options in the vLLM docs (guided generation, LoRA, speculative decoding, etc.) also work.
## Documentation
- **[🚀 Deployment Guide](https://docs.runpod.io/serverless/vllm/get-started)** - Step-by-step setup
- **[📖 Configuration Reference](https://github.com/runpod-workers/worker-vllm/blob/main/docs/configuration.md)** - All environment variables
- **[🏗️ Advanced Deployment](https://github.com/runpod-workers/worker-vllm/blob/main/docs/deployment.md)** - Custom builds and strategies
- **[🔧 Development Guide](https://github.com/runpod-workers/worker-vllm/blob/main/docs/conventions.md)** - Architecture and patterns
+801
View File
@@ -0,0 +1,801 @@
{
"title": "vLLM",
"description": "Deploy OpenAI-Compatible Blazing-Fast LLM Endpoints powered by vLLM",
"type": "serverless",
"category": "language",
"iconUrl": "https://registry.npmmirror.com/@lobehub/icons-static-png/latest/files/dark/vllm-color.png",
"config": {
"runsOn": "GPU",
"containerDiskInGb": 150,
"gpuIds": "ADA_80_PRO,AMPERE_80",
"gpuCount": 1,
"allowedCudaVersions": ["12.9", "12.8"],
"presets": [
{
"name": "deepseek-ai/deepseek-r1-distill-llama-8b",
"defaults": {
"MODEL_NAME": "deepseek-ai/deepseek-r1-distill-llama-8b"
}
}
],
"env": [
{
"key": "MODEL_NAME",
"input": {
"name": "Model",
"type": "huggingface",
"description": "Hugging Face model name",
"required": true
}
},
{
"key": "TOKENIZER",
"input": {
"name": "Tokenizer",
"type": "string",
"description": "Name or path of the Hugging Face tokenizer to use.",
"advanced": true
}
},
{
"key": "TOKENIZER_MODE",
"input": {
"name": "Tokenizer Mode",
"type": "string",
"description": "The tokenizer mode.",
"options": [
{
"label": "auto",
"value": "auto"
},
{
"label": "slow",
"value": "slow"
}
],
"default": "auto",
"advanced": true
}
},
{
"key": "SKIP_TOKENIZER_INIT",
"input": {
"name": "Skip Tokenizer Init",
"type": "boolean",
"description": "Skip initialization of tokenizer and detokenizer.",
"default": false,
"advanced": true
}
},
{
"key": "TRUST_REMOTE_CODE",
"input": {
"name": "Trust Remote Code",
"type": "boolean",
"description": "Trust remote code from Hugging Face.",
"default": false,
"advanced": true
}
},
{
"key": "DOWNLOAD_DIR",
"input": {
"name": "Download Directory",
"type": "string",
"description": "Directory to download and load the weights.",
"advanced": true
}
},
{
"key": "LOAD_FORMAT",
"input": {
"name": "Load Format",
"type": "string",
"description": "The format of the model weights to load.",
"options": [
{
"label": "auto",
"value": "auto"
},
{
"label": "pt",
"value": "pt"
},
{
"label": "safetensors",
"value": "safetensors"
},
{
"label": "npcache",
"value": "npcache"
},
{
"label": "dummy",
"value": "dummy"
},
{
"label": "tensorizer",
"value": "tensorizer"
},
{
"label": "bitsandbytes",
"value": "bitsandbytes"
}
],
"advanced": true
}
},
{
"key": "DTYPE",
"input": {
"name": "Data Type",
"type": "string",
"description": "Data type for model weights and activations.",
"options": [
{
"label": "auto",
"value": "auto"
},
{
"label": "half",
"value": "half"
},
{
"label": "float16",
"value": "float16"
},
{
"label": "bfloat16",
"value": "bfloat16"
},
{
"label": "float",
"value": "float"
},
{
"label": "float32",
"value": "float32"
}
],
"default": "auto",
"advanced": true
}
},
{
"key": "KV_CACHE_DTYPE",
"input": {
"name": "KV Cache Data Type",
"type": "string",
"description": "Data type for KV cache storage.",
"options": [
{
"label": "auto",
"value": "auto"
},
{
"label": "fp8",
"value": "fp8"
}
],
"default": "auto",
"advanced": true
}
},
{
"key": "MAX_MODEL_LEN",
"input": {
"name": "Max Model Length",
"type": "number",
"description": "Model context length.",
"default": null,
"advanced": true
}
},
{
"key": "DISTRIBUTED_EXECUTOR_BACKEND",
"input": {
"name": "Distributed Executor Backend",
"type": "string",
"description": "Backend to use for distributed serving.",
"options": [
{
"label": "ray",
"value": "ray"
},
{
"label": "mp",
"value": "mp"
}
],
"advanced": true,
"default": "mp"
}
},
{
"key": "RAY_WORKERS_USE_NSIGHT",
"input": {
"name": "Ray Workers Use Nsight",
"type": "boolean",
"description": "If specified, use nsight to profile Ray workers.",
"default": false,
"advanced": true
}
},
{
"key": "PIPELINE_PARALLEL_SIZE",
"input": {
"name": "Pipeline Parallel Size",
"type": "number",
"description": "Number of pipeline stages.",
"default": 1,
"advanced": true
}
},
{
"key": "TENSOR_PARALLEL_SIZE",
"input": {
"name": "Tensor Parallel Size",
"type": "number",
"description": "Number of tensor parallel replicas.",
"default": 1,
"advanced": true
}
},
{
"key": "MAX_PARALLEL_LOADING_WORKERS",
"input": {
"name": "Max Parallel Loading Workers",
"type": "number",
"description": "Load model sequentially in multiple batches.",
"advanced": true
}
},
{
"key": "ENABLE_PREFIX_CACHING",
"input": {
"name": "Enable Prefix Caching",
"type": "boolean",
"description": "Enables automatic prefix caching.",
"default": false,
"advanced": true
}
},
{
"key": "DISABLE_SLIDING_WINDOW",
"input": {
"name": "Disable Sliding Window",
"type": "boolean",
"description": "Disables sliding window, capping to sliding window size.",
"default": false,
"advanced": true
}
},
{
"key": "SEED",
"input": {
"name": "Seed",
"type": "number",
"description": "Random seed for operations.",
"default": 0,
"advanced": true
}
},
{
"key": "MAX_NUM_BATCHED_TOKENS",
"input": {
"name": "Max Num Batched Tokens",
"type": "number",
"description": "Maximum number of batched tokens per iteration.",
"default": null,
"advanced": true
}
},
{
"key": "MAX_NUM_SEQS",
"input": {
"name": "Max Num Seqs",
"type": "number",
"description": "Maximum number of sequences per iteration.",
"default": 256,
"advanced": true
}
},
{
"key": "MAX_LOGPROBS",
"input": {
"name": "Max Logprobs",
"type": "number",
"description": "Max number of log probs to return when logprobs is specified in SamplingParams.",
"default": 20,
"advanced": true
}
},
{
"key": "DISABLE_LOG_STATS",
"input": {
"name": "Disable Log Stats",
"type": "boolean",
"description": "Disable logging statistics.",
"default": false,
"advanced": true
}
},
{
"key": "QUANTIZATION",
"input": {
"name": "Quantization",
"type": "string",
"description": "Method used to quantize the weights.",
"options": [
{
"label": "None",
"value": "None"
},
{
"label": "AWQ",
"value": "awq"
},
{
"label": "SqueezeLLM",
"value": "squeezellm"
},
{
"label": "GPTQ",
"value": "gptq"
}
],
"advanced": true
}
},
{
"key": "ENABLE_LORA",
"input": {
"name": "Enable LoRA",
"type": "boolean",
"description": "If True, enable handling of LoRA adapters.",
"default": false,
"advanced": true
}
},
{
"key": "MAX_LORAS",
"input": {
"name": "Max LoRAs",
"type": "number",
"description": "Max number of LoRAs in a single batch.",
"default": 1,
"advanced": true
}
},
{
"key": "MAX_LORA_RANK",
"input": {
"name": "Max LoRA Rank",
"type": "number",
"description": "Max LoRA rank.",
"default": 16,
"advanced": true
}
},
{
"key": "LORA_DTYPE",
"input": {
"name": "LoRA Data Type",
"type": "string",
"description": "Data type for LoRA.",
"options": [
{
"label": "auto",
"value": "auto"
},
{
"label": "float16",
"value": "float16"
},
{
"label": "bfloat16",
"value": "bfloat16"
},
{
"label": "float32",
"value": "float32"
}
],
"default": "auto",
"advanced": true
}
},
{
"key": "MAX_CPU_LORAS",
"input": {
"name": "Max CPU LoRAs",
"type": "number",
"description": "Maximum number of LoRAs to store in CPU memory.",
"advanced": true
}
},
{
"key": "FULLY_SHARDED_LORAS",
"input": {
"name": "Fully Sharded LoRAs",
"type": "boolean",
"description": "Enable fully sharded LoRA layers.",
"default": false,
"advanced": true
}
},
{
"key": "DEVICE",
"input": {
"name": "Device",
"type": "string",
"description": "Device type for vLLM execution.",
"options": [
{
"label": "auto",
"value": "auto"
},
{
"label": "cuda",
"value": "cuda"
},
{
"label": "neuron",
"value": "neuron"
},
{
"label": "cpu",
"value": "cpu"
},
{
"label": "openvino",
"value": "openvino"
},
{
"label": "tpu",
"value": "tpu"
},
{
"label": "xpu",
"value": "xpu"
}
],
"default": "auto",
"advanced": true
}
},
{
"key": "SCHEDULER_DELAY_FACTOR",
"input": {
"name": "Scheduler Delay Factor",
"type": "number",
"description": "Apply a delay before scheduling next prompt.",
"default": 0,
"advanced": true
}
},
{
"key": "ENABLE_CHUNKED_PREFILL",
"input": {
"name": "Enable Chunked Prefill",
"type": "boolean",
"description": "Enable chunked prefill requests.",
"default": false,
"advanced": true
}
},
{
"key": "SPECULATIVE_CONFIG",
"input": {
"name": "Speculative Config (JSON)",
"type": "string",
"description": "Full speculative decoding configuration as a JSON string. Overrides individual speculative env vars.",
"advanced": true
}
},
{
"key": "SPECULATIVE_METHOD",
"input": {
"name": "Speculative Method",
"type": "string",
"description": "Speculative decoding method to use.",
"options": [
{ "label": "None", "value": "" },
{ "label": "Draft Model", "value": "draft_model" },
{ "label": "N-gram", "value": "ngram" },
{ "label": "EAGLE", "value": "eagle" },
{ "label": "EAGLE3", "value": "eagle3" },
{ "label": "Medusa", "value": "medusa" },
{ "label": "MLP Speculator", "value": "mlp_speculator" }
],
"default": "",
"advanced": true
}
},
{
"key": "SPECULATIVE_MODEL",
"input": {
"name": "Speculative Model",
"type": "string",
"description": "The name of the draft model to be used in speculative decoding.",
"advanced": true
}
},
{
"key": "NUM_SPECULATIVE_TOKENS",
"input": {
"name": "Num Speculative Tokens",
"type": "number",
"description": "The number of speculative tokens to sample from the draft model.",
"advanced": true
}
},
{
"key": "NGRAM_PROMPT_LOOKUP_MAX",
"input": {
"name": "Ngram Prompt Lookup Max",
"type": "number",
"description": "Max size of window for ngram prompt lookup in speculative decoding.",
"advanced": true
}
},
{
"key": "MODEL_LOADER_EXTRA_CONFIG",
"input": {
"name": "Model Loader Extra Config",
"type": "string",
"description": "Extra config for model loader.",
"advanced": true
}
},
{
"key": "ENABLE_LOG_REQUESTS",
"input": {
"name": "Enable Log Requests",
"type": "boolean",
"description": "Enable vLLM request logging.",
"default": false,
"advanced": true
}
},
{
"key": "TOKENIZER_NAME",
"input": {
"name": "Tokenizer Name",
"type": "string",
"description": "Tokenizer repo to use a different tokenizer than the model's default",
"advanced": true
}
},
{
"key": "TOKENIZER_REVISION",
"input": {
"name": "Tokenizer Revision",
"type": "string",
"description": "Tokenizer revision to load",
"advanced": true
}
},
{
"key": "CUSTOM_CHAT_TEMPLATE",
"input": {
"name": "Custom Chat Template",
"type": "string",
"description": "Custom chat jinja template",
"advanced": true
}
},
{
"key": "GPU_MEMORY_UTILIZATION",
"input": {
"name": "GPU Memory Utilization",
"type": "number",
"description": "Sets GPU VRAM utilization",
"default": 0.95,
"advanced": true
}
},
{
"key": "BLOCK_SIZE",
"input": {
"name": "Block Size",
"type": "number",
"description": "Token block size for contiguous chunks of tokens",
"default": 16,
"advanced": true
}
},
{
"key": "SWAP_SPACE",
"input": {
"name": "Swap Space",
"type": "number",
"description": "CPU swap space size (GiB) per GPU",
"default": 4,
"advanced": true
}
},
{
"key": "ENFORCE_EAGER",
"input": {
"name": "Enforce Eager",
"type": "boolean",
"description": "Always use eager-mode PyTorch. If False (0), will use eager mode and CUDA graph in hybrid for maximal performance and flexibility",
"default": false,
"advanced": true
}
},
{
"key": "DISABLE_CUSTOM_ALL_REDUCE",
"input": {
"name": "Disable Custom All Reduce",
"type": "boolean",
"description": "Enables or disables custom all reduce",
"default": false,
"advanced": true
}
},
{
"key": "DEFAULT_BATCH_SIZE",
"input": {
"name": "Default Final Batch Size",
"type": "number",
"description": "Default and Maximum batch size for token streaming to reduce HTTP calls",
"default": 50,
"advanced": true
}
},
{
"key": "DEFAULT_MIN_BATCH_SIZE",
"input": {
"name": "Default Starting Batch Size",
"type": "number",
"description": "Batch size for the first request, which will be multiplied by the growth factor every subsequent request",
"default": 1,
"advanced": true
}
},
{
"key": "DEFAULT_BATCH_SIZE_GROWTH_FACTOR",
"input": {
"name": "Default Batch Size Growth Factor",
"type": "number",
"description": "Growth factor for dynamic batch size",
"default": 3,
"advanced": true
}
},
{
"key": "RAW_OPENAI_OUTPUT",
"input": {
"name": "Raw OpenAI Output",
"type": "boolean",
"description": "Raw OpenAI output instead of just the text",
"default": true,
"advanced": true
}
},
{
"key": "OPENAI_RESPONSE_ROLE",
"input": {
"name": "OpenAI Response Role",
"type": "string",
"description": "Role of the LLM's Response in OpenAI Chat Completions",
"default": "assistant",
"advanced": true
}
},
{
"key": "OPENAI_SERVED_MODEL_NAME_OVERRIDE",
"input": {
"name": "OpenAI Served Model Name Override",
"type": "string",
"description": "Overrides the name of the served model from model repo/path to specified name, which you will then be able to use the value for the `model` parameter when making OpenAI requests",
"advanced": true
}
},
{
"key": "MAX_CONCURRENCY",
"input": {
"name": "Max Concurrency",
"type": "number",
"description": "Max concurrent requests per worker. vLLM has an internal queue, so you don't have to worry about limiting by VRAM, this is for improving scaling/load balancing efficiency",
"default": 30,
"advanced": true
}
},
{
"key": "ENABLE_EXPERT_PARALLEL",
"input": {
"name": "Enable Expert Parallel",
"type": "boolean",
"description": "Enable Expert Parallel for MoE models",
"default": false,
"advanced": true
}
},
{
"key": "MODEL_REVISION",
"input": {
"name": "Model Revision",
"type": "string",
"description": "Model revision (branch) to load",
"advanced": true
}
},
{
"key": "BASE_PATH",
"input": {
"name": "Base Path",
"type": "string",
"description": "Storage directory for Huggingface cache and model",
"default": "/runpod-volume",
"advanced": true
}
},
{
"key": "ENABLE_AUTO_TOOL_CHOICE",
"input": {
"name": "Enable Auto Tool Choice",
"type": "boolean",
"description": "Enables or disables auto tool choice",
"default": false,
"advanced": true
}
},
{
"key": "TOOL_CALL_PARSER",
"input": {
"name": "Tool Call Parser",
"type": "string",
"description": "Tool call parser",
"options": [
{
"label": "None",
"value": ""
},
{
"label": "Hermes",
"value": "hermes"
},
{
"label": "Mistral",
"value": "mistral"
},
{
"label": "Llama3 JSON",
"value": "llama3_json"
},
{
"label": "Pythonic",
"value": "pythonic"
},
{
"label": "InternLM",
"value": "internlm"
}
],
"default": "",
"advanced": true
}
},
{
"key": "REASONING_PARSER",
"input": {
"name": "Reasoning Parser",
"type": "string",
"description": "Parser for reasoning-capable models (enables reasoning mode)",
"options": [
{ "label": "None", "value": "" },
{ "label": "DeepSeek R1", "value": "deepseek_r1" },
{ "label": "Qwen3", "value": "qwen3" },
{ "label": "Granite", "value": "granite" },
{ "label": "Hunyuan A13B", "value": "hunyuan_a13b" }
],
"default": "",
"advanced": true
}
}
]
}
}
+43
View File
@@ -0,0 +1,43 @@
{
"tests": [
{
"name": "basic_inference_test",
"input": {
"prompt": "Write a short poem about artificial intelligence."
},
"timeout": 30000
},
{
"name": "openai_messages_test",
"input": {
"openai_route": "/v1/chat/completions",
"openai_input": {
"messages": [
{
"role": "system",
"content": "You are a helpful assistant that writes concise responses."
},
{
"role": "user",
"content": "Explain what a neural network is in one sentence."
}
],
"max_tokens": 200,
"temperature": 0.1
}
},
"timeout": 30000
}
],
"config": {
"gpuTypeId": "NVIDIA GeForce RTX 4090",
"gpuCount": 1,
"env": [
{
"key": "MODEL_NAME",
"value": "HuggingFaceTB/SmolLM2-135M-Instruct"
}
],
"allowedCudaVersions": ["12.9", "12.8", "12.7", "12.6", "12.5"]
}
}
+50 -35
View File
@@ -1,49 +1,64 @@
# Base image - Set default to CUDA 11.8
ARG WORKER_CUDA_VERSION=11.8
FROM runpod/base:0.4.2-cuda${WORKER_CUDA_VERSION}.0 as builder
FROM nvidia/cuda:12.9.1-base-ubuntu22.04
ARG WORKER_CUDA_VERSION=11.8 # Required duplicate to keep in scope
RUN apt-get update -y \
&& apt-get install -y python3-pip
# Set Environment Variables
ENV WORKER_CUDA_VERSION=${WORKER_CUDA_VERSION} \
HF_DATASETS_CACHE="/runpod-volume/huggingface-cache/datasets" \
HUGGINGFACE_HUB_CACHE="/runpod-volume/huggingface-cache/hub" \
TRANSFORMERS_CACHE="/runpod-volume/huggingface-cache/hub" \
HF_TRANSFER=1
RUN ldconfig /usr/local/cuda-12.9/compat/
# Install vLLM with FlashInfer from the CUDA 12.9 wheel index.
RUN python3 -m pip install --upgrade pip && \
python3 -m pip install "vllm[flashinfer]==0.17.0" --extra-index-url https://download.pytorch.org/whl/cu129
# Install Python dependencies
# Install additional Python dependencies (after vLLM to avoid PyTorch version conflicts)
COPY builder/requirements.txt /requirements.txt
RUN --mount=type=cache,target=/root/.cache/pip \
python3.11 -m pip install --upgrade pip && \
python3.11 -m pip install --upgrade -r /requirements.txt && \
rm /requirements.txt
# Install torch and vllm based on CUDA version
RUN if [[ "${WORKER_CUDA_VERSION}" == 11.8* ]]; then \
python3.11 -m pip install -U --force-reinstall torch==2.1.2 xformers==0.0.23.post1 --index-url https://download.pytorch.org/whl/cu118; \
python3.11 -m pip install -e git+https://github.com/runpod/vllm-fork-for-sls-worker.git@cuda-11.8#egg=vllm; \
else \
python3.11 -m pip install -e git+https://github.com/runpod/vllm-fork-for-sls-worker.git#egg=vllm; \
fi && \
rm -rf /root/.cache/pip
# Add source files
COPY src .
python3 -m pip install --upgrade -r /requirements.txt
# Setup for Option 2: Building the Image with the Model included
ARG MODEL_NAME=""
ARG MODEL_BASE_PATH="/runpod-volume/"
ARG HF_TOKEN=""
ARG TOKENIZER_NAME=""
ARG BASE_PATH="/runpod-volume"
ARG QUANTIZATION=""
RUN if [ -n "$MODEL_NAME" ]; then \
export MODEL_BASE_PATH=$MODEL_BASE_PATH && \
export MODEL_NAME=$MODEL_NAME && \
python3.11 /download_model.py --model $MODEL_NAME; \
ARG MODEL_REVISION=""
ARG TOKENIZER_REVISION=""
ARG VLLM_NIGHTLY="false"
ENV MODEL_NAME=$MODEL_NAME \
MODEL_REVISION=$MODEL_REVISION \
TOKENIZER_NAME=$TOKENIZER_NAME \
TOKENIZER_REVISION=$TOKENIZER_REVISION \
BASE_PATH=$BASE_PATH \
QUANTIZATION=$QUANTIZATION \
HF_DATASETS_CACHE="${BASE_PATH}/huggingface-cache/datasets" \
HUGGINGFACE_HUB_CACHE="${BASE_PATH}/huggingface-cache/hub" \
HF_HOME="${BASE_PATH}/huggingface-cache/hub" \
HF_HUB_ENABLE_HF_TRANSFER=0 \
# Suppress Ray metrics agent warnings (not needed in containerized environments)
RAY_METRICS_EXPORT_ENABLED=0 \
RAY_DISABLE_USAGE_STATS=1 \
# Prevent rayon thread pool panic in containers where ulimit -u < nproc
# (tokenizers uses Rust's rayon which tries to spawn threads = CPU cores)
TOKENIZERS_PARALLELISM=false \
RAYON_NUM_THREADS=4
ENV PYTHONPATH="/:/vllm-workspace"
RUN if [ "${VLLM_NIGHTLY}" = "true" ]; then \
pip install -U vllm --pre --index-url https://pypi.org/simple --extra-index-url https://wheels.vllm.ai/nightly && \
apt-get update && apt-get install -y git && rm -rf /var/lib/apt/lists/* && \
pip install git+https://github.com/huggingface/transformers.git; \
fi
COPY src /src
RUN --mount=type=secret,id=HF_TOKEN,required=false \
if [ -f /run/secrets/HF_TOKEN ]; then \
export HF_TOKEN=$(cat /run/secrets/HF_TOKEN); \
fi && \
if [ -n "$QUANTIZATION" ]; then \
export QUANTIZATION=$QUANTIZATION; \
if [ -n "$MODEL_NAME" ]; then \
python3 /src/download_model.py; \
fi
# Start the handler
CMD ["python3.11", "/handler.py"]
CMD ["python3", "/src/handler.py"]
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2023 runpod-workers
Copyright (c) 2025 Runpod
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
+394 -101
View File
@@ -1,123 +1,361 @@
<div align="center">
<h1>vLLM 0.2.6 Endpoint | Serverless Worker </h1>
# OpenAI-Compatible vLLM Serverless Endpoint Worker
[![CD | Docker-Build-Release](https://github.com/runpod-workers/worker-vllm/actions/workflows/docker-build-release.yml/badge.svg)](https://github.com/runpod-workers/worker-vllm/actions/workflows/docker-build-release.yml)
🚀 | This serverless worker utilizes vLLM behind the scenes and is integrated into RunPod's serverless environment. It supports dynamic auto-scaling using the built-in RunPod autoscaling feature.
</div>
## Setting up the Serverless Worker
### Option 1: Deploy Any Model Using Pre-Built Docker Image
We now offer a pre-built Docker Image for the vLLM Worker that you can configure entirely with Environment Variables when creating the RunPod Serverless Endpoint:
<div align="center">
```runpod/worker-vllm:dev```
Deploy OpenAI-Compatible Blazing-Fast LLM Endpoints powered by the [vLLM](https://github.com/vllm-project/vllm) Inference Engine on RunPod Serverless with just a few clicks.
</div>
#### Environment Variables
- **Required**:
- `MODEL_NAME`: Hugging Face Model Repository (e.g., `openchat/openchat-3.5-1210`).
## Table of Contents
- **Optional**:
- `MAX_MODEL_LENGTH`: Maximum number of tokens for the engine to be able to handle. (default: maximum supported by the model)
- `MODEL_BASE_PATH`: Model storage directory (default: `/runpod-volume`).
- `HF_TOKEN`: Hugging Face token for private and gated models (e.g., Llama, Falcon).
- `NUM_GPU_SHARD`: Number of GPUs to split the model across. (default: `1`)
- `QUANTIZATION`: AWQ (`awq`), SqueezeLLM (`squeezellm`) or GPTQ (`gptq`) Quantization. The specified Model Repo must be of a quantized model. (default: `None`)
- `TRUST_REMOTE_CODE`: Whether to trust remote code with Hugging Face. (default: `0`)
- `MAX_CONCURRENCY`: Max concurrent requests. (default: `100`)
- `DEFAULT_BATCH_SIZE`: Token streaming batch size (default: `30`). This reduces the number of HTTP calls, increasing speed 8-10x vs non-batching, matching non-streaming performance.
- `DISABLE_LOG_STATS`: Enable (`0`) or disable (`1`) vLLM stats logging.
- `DISABLE_LOG_REQUESTS`: Enable (`0`) or disable (`1`) request logging.
- [Setting up the Serverless Worker](#setting-up-the-serverless-worker)
- [Option 1: Deploy Any Model Using Pre-Built Docker Image [Recommended]](#option-1-deploy-any-model-using-pre-built-docker-image-recommended)
- [Configuration](#configuration)
- [Option 2: Build Docker Image with Model Inside](#option-2-build-docker-image-with-model-inside)
- [Prerequisites](#prerequisites)
- [Arguments](#arguments)
- [Example: Building an image with OpenChat-3.5](#example-building-an-image-with-openchat-35)
- [(Optional) Including Huggingface Token](#optional-including-huggingface-token)
- [Compatible Model Architectures](#compatible-model-architectures)
- [Usage: OpenAI Compatibility](#usage-openai-compatibility)
- [Modifying your OpenAI Codebase to use your deployed vLLM Worker](#modifying-your-openai-codebase-to-use-your-deployed-vllm-worker)
- [OpenAI Request Input Parameters](#openai-request-input-parameters)
- [Chat Completions [RECOMMENDED]](#chat-completions-recommended)
- [Examples: Using your RunPod endpoint with OpenAI](#examples-using-your-runpod-endpoint-with-openai)
- [Chat Completions](#chat-completions)
- [Getting a list of names for available models](#getting-a-list-of-names-for-available-models)
- [Usage: Standard (Non-OpenAI)](#usage-standard-non-openai)
- [Request Input Parameters](#request-input-parameters)
- [Sampling Parameters](#sampling-parameters)
- [Text Input Formats](#text-input-formats)
### Option 2: Build Docker Image with Model Inside
[!WARNING] If you are getting errors while building the image, try adding `ENV MAX_JOBS` to the Dockerfile and increase Docker memory limit to at least 25GB.
# Setting up the Serverless Worker
To build an image with the model baked in, you must specify the following docker arguments when building the image:
## Option 1: Deploy Any Model Using Pre-Built Docker Image [Recommended]
**🚀 Deploy Guide**: Follow our [step-by-step deployment guide](https://docs.runpod.io/serverless/vllm/get-started) to deploy using the RunPod Console.
**📦 Docker Image**: `runpod/worker-v1-vllm:<version>`
- **Available Versions**: See [GitHub Releases](https://github.com/runpod-workers/worker-vllm/releases)
- **CUDA Compatibility**: Requires CUDA >= 12.1
### Configuration
Configure worker-vllm using environment variables:
| Environment Variable | Description | Default | Options |
| ----------------------------------- | ------------------------------------------------- | ------------------- | ------------------------------------------------------------------ |
| `MODEL_NAME` | Path of the model weights | "facebook/opt-125m" | Local folder or Hugging Face repo ID |
| `HF_TOKEN` | HuggingFace access token for gated/private models | | Your HuggingFace access token |
| `MAX_MODEL_LEN` | Model's maximum context length | | Integer (e.g., 4096) |
| `QUANTIZATION` | Quantization method | | "awq", "gptq", "squeezellm", "bitsandbytes" |
| `TENSOR_PARALLEL_SIZE` | Number of GPUs | 1 | Integer |
| `GPU_MEMORY_UTILIZATION` | Fraction of GPU memory to use | 0.95 | Float between 0.0 and 1.0 |
| `MAX_NUM_SEQS` | Maximum number of sequences per iteration | 256 | Integer |
| `CUSTOM_CHAT_TEMPLATE` | Custom chat template override | | Jinja2 template string |
| `ENABLE_AUTO_TOOL_CHOICE` | Enable automatic tool selection | false | boolean (true or false) |
| `TOOL_CALL_PARSER` | Parser for tool calls | | "mistral", "hermes", "llama3_json", "granite", "deepseek_v3", etc. |
| `OPENAI_SERVED_MODEL_NAME_OVERRIDE` | Override served model name in API | | String |
| `MAX_CONCURRENCY` | Maximum concurrent requests | 30 | Integer |
**Pass any vLLM engine arg** not listed above by setting an environment variable with the **UPPERCASED** field name (same names vLLM uses). The worker auto-discovers all `AsyncEngineArgs` fields from env. For example:
| Environment Variable | vLLM Engine Arg | Example Value |
| ------------------------- | ------------------------ | ------------- |
| `MAX_MODEL_LEN` | `max_model_len` | `4096` |
| `ENFORCE_EAGER` | `enforce_eager` | `true` |
| `ENABLE_CHUNKED_PREFILL` | `enable_chunked_prefill` | `true` |
Any env var whose name matches a valid `AsyncEngineArgs` field (uppercased) is applied automatically. Backward-compat aliases: `MODEL_NAME`, `TOKENIZER_NAME`, `MAX_CONTEXT_LEN_TO_CAPTURE`. This lets you configure any vLLM option without waiting for explicit worker support.
For the complete list of all available environment variables, examples, and detailed descriptions: **[Configuration](docs/configuration.md)**
## Option 2: Build Docker Image with Model Inside
To build an image with the model baked in, you must specify the following docker arguments when building the image.
### Prerequisites
- Docker
### Arguments
#### Arguments:
- **Required**
- `MODEL_NAME`
- **Optional**
- `MODEL_BASE_PATH`: Defaults to `/runpod-volume` for network storage. Use `/models` or for local container storage.
- `MODEL_REVISION`: Model revision to load (default: `main`).
- `BASE_PATH`: Storage directory where huggingface cache and model will be located. (default: `/runpod-volume`, which will utilize network storage if you attach it or create a local directory within the image if you don't. If your intention is to bake the model into the image, you should set this to something like `/models` to make sure there are no issues if you were to accidentally attach network storage.)
- `QUANTIZATION`
- `HF_TOKEN`
- `WORKER_CUDA_VERSION`: `11.8` or `12.1` (default: `11.8` due to a small amount of workers not having CUDA 12.1 support yet. `12.1` is recommended for optimal performance).
- `WORKER_CUDA_VERSION`: `12.1.0` (`12.1.0` is recommended for optimal performance).
- `TOKENIZER_NAME`: Tokenizer repository if you would like to use a different tokenizer than the one that comes with the model. (default: `None`, which uses the model's tokenizer)
- `TOKENIZER_REVISION`: Tokenizer revision to load (default: `main`).
- `VLLM_NIGHTLY`: Set to `true` to replace the pinned vLLM release with the latest nightly build and the latest `transformers` from source. Useful for testing unreleased vLLM features. (default: `false`)
#### Example: Building an image with OpenChat-3.5
`sudo docker build -t username/image:tag --build-arg MODEL_NAME="openchat/openchat_3.5" --build-arg MODEL_BASE_PATH="/models" .`
For the remaining settings, you may apply them as environment variables when running the container. Supported environment variables are listed in the [Environment Variables](#environment-variables) section.
### Compatible Models
- LLaMA & LLaMA-2 (`meta-llama/Llama-2-70b-hf`, `lmsys/vicuna-13b-v1.3`, `young-geng/koala`, `openlm-research/open_llama_13b`, etc.)
- Mistral (`mistralai/Mistral-7B-v0.1`, `mistralai/Mistral-7B-Instruct-v0.1`, etc.)
- Mixtral (`mistralai/Mixtral-8x7B-v0.1`, `mistralai/Mixtral-8x7B-Instruct-v0.1`, etc.)
- Aquila & Aquila2 (`BAAI/AquilaChat2-7B`, `BAAI/AquilaChat2-34B`, `BAAI/Aquila-7B`, `BAAI/AquilaChat-7B`, etc.)
- Baichuan & Baichuan2 (`baichuan-inc/Baichuan2-13B-Chat`, `baichuan-inc/Baichuan-7B`, etc.)
- BLOOM (`bigscience/bloom`, `bigscience/bloomz`, etc.)
- ChatGLM (`THUDM/chatglm2-6b`, `THUDM/chatglm3-6b`, etc.)
- Falcon (`tiiuae/falcon-7b`, `tiiuae/falcon-40b`, `tiiuae/falcon-rw-7b`, etc.)
- GPT-2 (`gpt2`, `gpt2-xl`, etc.)
- GPT BigCode (`bigcode/starcoder`, `bigcode/gpt_bigcode-santacoder`, etc.)
- GPT-J (`EleutherAI/gpt-j-6b`, `nomic-ai/gpt4all-j`, etc.)
- GPT-NeoX (`EleutherAI/gpt-neox-20b`, `databricks/dolly-v2-12b`, `stabilityai/stablelm-tuned-alpha-7b`, etc.)
- InternLM (`internlm/internlm-7b`, `internlm/internlm-chat-7b`, etc.)
- MPT (`mosaicml/mpt-7b`, `mosaicml/mpt-30b`, etc.)
- OPT (`facebook/opt-66b`, `facebook/opt-iml-max-30b`, etc.)
- Phi (`microsoft/phi-1_5`, `microsoft/phi-2`, etc.)
- Qwen (`Qwen/Qwen-7B`, `Qwen/Qwen-7B-Chat`, etc.)
- Yi (`01-ai/Yi-6B`, `01-ai/Yi-34B`, etc.)
And any other models supported by vLLM 0.2.6.
### Example: Building an image with OpenChat-3.5
Ensure that you have Docker installed and properly set up before running the docker build commands. Once built, you can deploy this serverless worker in your desired environment with confidence that it will automatically scale based on demand. For further inquiries or assistance, feel free to contact our support team.
## Model Inputs
You may either use a `prompt` or a list of `messages` as input. If you use `messages`, the model's chat template will be applied to the messages automatically, so the model must have one. If you use `prompt`, you may optionally apply the model's chat template to the prompt by setting `apply_chat_template` to `true`.
| Argument | Type | Default | Description |
|-----------------|------|--------------------|-----------------------------------------------------------------------------------------------|
| `prompt` | str | | Prompt string to generate text based on. |
| `messages` | list[dict[str, str]] | | List of messages, which will automatically have the model's chat template applied. Overrides `prompt`. |
| `apply_chat_template` | bool | False | Whether to apply the model's chat template to the `prompt`. |
| `sampling_params` | dict | {} | Sampling parameters to control the generation, like temperature, top_p, etc. |
| `stream` | bool | False | Whether to enable streaming of output. If True, responses are streamed as they are generated. |
| `batch_size` | int | DEFAULT_BATCH_SIZE | The number of tokens to stream every HTTP POST call. |
### Messages Format
Your list can contain any number of messages, and each message can have any role from the following list:
- `user`
- `assistant`
- `system`
The model's chat template will be applied to the messages automatically.
Example:
```json
[
{
"role": "system",
"content": "..."
},
{
"role": "user",
"content": "..."
},
{
"role": "assistant",
"content": "..."
}
]
```bash
docker build -t username/image:tag --build-arg MODEL_NAME="openchat/openchat_3.5" --build-arg BASE_PATH="/models" .
```
### Example: Building with vLLM Nightly
To use the latest unreleased vLLM build (installs from the nightly wheel index and `transformers` from source):
```bash
docker build -t username/image:tag --build-arg VLLM_NIGHTLY=true .
```
You can combine it with other arguments:
```bash
docker build -t username/image:tag --build-arg VLLM_NIGHTLY=true --build-arg MODEL_NAME="meta-llama/Llama-3.1-8B-Instruct" --build-arg BASE_PATH="/models" .
```
### (Optional) Including Huggingface Token
If the model you would like to deploy is private or gated, you will need to include it during build time as a Docker secret, which will protect it from being exposed in the image and on DockerHub.
1. Enable Docker BuildKit (required for secrets).
```bash
export DOCKER_BUILDKIT=1
```
2. Export your Hugging Face token as an environment variable
```bash
export HF_TOKEN="your_token_here"
```
2. Add the token as a secret when building
```bash
docker build -t username/image:tag --secret id=HF_TOKEN --build-arg MODEL_NAME="openchat/openchat_3.5" .
```
# Compatible Model Architectures
You can deploy **any model on Hugging Face** that is supported by vLLM. For the complete and up-to-date list of supported model architectures, see the [vLLM Supported Models documentation](https://docs.vllm.ai/en/latest/models/supported_models.html#list-of-text-only-language-models).
# Usage: OpenAI Compatibility
The vLLM Worker is fully compatible with OpenAI's API, and you can use it with any OpenAI Codebase by changing only 3 lines in total. The supported routes are <ins>Chat Completions</ins> and <ins>Models</ins> - with both streaming and non-streaming.
## Modifying your OpenAI Codebase to use your deployed vLLM Worker
**Python** (similar to Node.js, etc.):
1. When initializing the OpenAI Client in your code, change the `api_key` to your RunPod API Key and the `base_url` to your RunPod Serverless Endpoint URL in the following format: `https://api.runpod.ai/v2/<YOUR ENDPOINT ID>/openai/v1`, filling in your deployed endpoint ID. For example, if your Endpoint ID is `abc1234`, the URL would be `https://api.runpod.ai/v2/abc1234/openai/v1`.
- Before:
```python
from openai import OpenAI
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
```
- After:
```python
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get("RUNPOD_API_KEY"),
base_url="https://api.runpod.ai/v2/<YOUR ENDPOINT ID>/openai/v1",
)
```
2. Change the `model` parameter to your deployed model's name whenever using Completions or Chat Completions.
- Before:
```python
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Why is RunPod the best platform?"}],
temperature=0,
max_tokens=100,
)
```
- After:
```python
response = client.chat.completions.create(
model="<YOUR DEPLOYED MODEL REPO/NAME>",
messages=[{"role": "user", "content": "Why is RunPod the best platform?"}],
temperature=0,
max_tokens=100,
)
```
**Using http requests**:
1. Change the `Authorization` header to your RunPod API Key and the `url` to your RunPod Serverless Endpoint URL in the following format: `https://api.runpod.ai/v2/<YOUR ENDPOINT ID>/openai/v1`
- Before:
```bash
curl https://api.openai.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-4",
"messages": [
{
"role": "user",
"content": "Why is RunPod the best platform?"
}
],
"temperature": 0,
"max_tokens": 100
}'
```
- After:
```bash
curl https://api.runpod.ai/v2/<YOUR ENDPOINT ID>/openai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <YOUR OPENAI API KEY>" \
-d '{
"model": "<YOUR DEPLOYED MODEL REPO/NAME>",
"messages": [
{
"role": "user",
"content": "Why is RunPod the best platform?"
}
],
"temperature": 0,
"max_tokens": 100
}'
```
## OpenAI Request Input Parameters:
When using the chat completion feature of the vLLM Serverless Endpoint Worker, you can customize your requests with the following parameters:
### Chat Completions [RECOMMENDED]
<details>
<summary>Supported Chat Completions Inputs and Descriptions</summary>
| Parameter | Type | Default Value | Description |
| ------------------- | -------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `messages` | Union[str, List[Dict[str, str]]] | | List of messages, where each message is a dictionary with a `role` and `content`. The model's chat template will be applied to the messages automatically, so the model must have one or it should be specified as `CUSTOM_CHAT_TEMPLATE` env var. |
| `model` | str | | The model repo that you've deployed on your RunPod Serverless Endpoint. If you are unsure what the name is or are baking the model in, use the guide to get the list of available models in the **Examples: Using your RunPod endpoint with OpenAI** section |
| `temperature` | Optional[float] | 0.7 | Float that controls the randomness of the sampling. Lower values make the model more deterministic, while higher values make the model more random. Zero means greedy sampling. |
| `top_p` | Optional[float] | 1.0 | Float that controls the cumulative probability of the top tokens to consider. Must be in (0, 1]. Set to 1 to consider all tokens. |
| `n` | Optional[int] | 1 | Number of output sequences to return for the given prompt. |
| `max_tokens` | Optional[int] | None | Maximum number of tokens to generate per output sequence. |
| `seed` | Optional[int] | None | Random seed to use for the generation. |
| `stop` | Optional[Union[str, List[str]]] | list | List of strings that stop the generation when they are generated. The returned output will not contain the stop strings. |
| `stream` | Optional[bool] | False | Whether to stream or not |
| `presence_penalty` | Optional[float] | 0.0 | Float that penalizes new tokens based on whether they appear in the generated text so far. Values > 0 encourage the model to use new tokens, while values < 0 encourage the model to repeat tokens. |
| `frequency_penalty` | Optional[float] | 0.0 | Float that penalizes new tokens based on their frequency in the generated text so far. Values > 0 encourage the model to use new tokens, while values < 0 encourage the model to repeat tokens. |
| `logit_bias` | Optional[Dict[str, float]] | None | Unsupported by vLLM |
| `user` | Optional[str] | None | Unsupported by vLLM |
Additional parameters supported by vLLM:
| `best_of` | Optional[int] | None | Number of output sequences that are generated from the prompt. From these `best_of` sequences, the top `n` sequences are returned. `best_of` must be greater than or equal to `n`. This is treated as the beam width when `use_beam_search` is True. By default, `best_of` is set to `n`. |
| `top_k` | Optional[int] | -1 | Integer that controls the number of top tokens to consider. Set to -1 to consider all tokens. |
| `ignore_eos` | Optional[bool] | False | Whether to ignore the EOS token and continue generating tokens after the EOS token is generated. |
| `use_beam_search` | Optional[bool] | False | Whether to use beam search instead of sampling. |
| `stop_token_ids` | Optional[List[int]] | list | List of tokens that stop the generation when they are generated. The returned output will contain the stop tokens unless the stop tokens are special tokens. |
| `skip_special_tokens` | Optional[bool] | True | Whether to skip special tokens in the output. |
| `spaces_between_special_tokens`| Optional[bool] | True | Whether to add spaces between special tokens in the output. Defaults to True. |
| `add_generation_prompt` | Optional[bool] | True | Read more [here](https://huggingface.co/docs/transformers/main/en/chat_templating#what-are-generation-prompts) |
| `echo` | Optional[bool] | False | Echo back the prompt in addition to the completion |
| `repetition_penalty` | Optional[float] | 1.0 | Float that penalizes new tokens based on whether they appear in the prompt and the generated text so far. Values > 1 encourage the model to use new tokens, while values < 1 encourage the model to repeat tokens. |
| `min_p` | Optional[float] | 0.0 | Float that represents the minimum probability for a token to |
| `length_penalty` | Optional[float] | 1.0 | Float that penalizes sequences based on their length. Used in beam search.. |
| `include_stop_str_in_output` | Optional[bool] | False | Whether to include the stop strings in output text. Defaults to False.|
</details>
### Examples: Using your RunPod endpoint with OpenAI
First, initialize the OpenAI Client with your RunPod API Key and Endpoint URL:
```python
from openai import OpenAI
import os
# Initialize the OpenAI Client with your RunPod API Key and Endpoint URL
client = OpenAI(
api_key=os.environ.get("RUNPOD_API_KEY"),
base_url="https://api.runpod.ai/v2/<YOUR ENDPOINT ID>/openai/v1",
)
```
### Chat Completions:
This is the format used for GPT-4 and focused on instruction-following and chat. Examples of Open Source chat/instruct models include `meta-llama/Llama-2-7b-chat-hf`, `mistralai/Mixtral-8x7B-Instruct-v0.1`, `openchat/openchat-3.5-0106`, `NousResearch/Nous-Hermes-2-Mistral-7B-DPO` and more. However, if your model is a completion-style model with no chat/instruct fine-tune and/or does not have a chat template, you can still use this if you provide a chat template with the environment variable `CUSTOM_CHAT_TEMPLATE`.
- **Streaming**:
```python
# Create a chat completion stream
response_stream = client.chat.completions.create(
model="<YOUR DEPLOYED MODEL REPO/NAME>",
messages=[{"role": "user", "content": "Why is RunPod the best platform?"}],
temperature=0,
max_tokens=100,
stream=True,
)
# Stream the response
for response in response_stream:
print(chunk.choices[0].delta.content or "", end="", flush=True)
```
- **Non-Streaming**:
```python
# Create a chat completion
response = client.chat.completions.create(
model="<YOUR DEPLOYED MODEL REPO/NAME>",
messages=[{"role": "user", "content": "Why is RunPod the best platform?"}],
temperature=0,
max_tokens=100,
)
# Print the response
print(response.choices[0].message.content)
```
### Getting a list of names for available models:
In the case of baking the model into the image, sometimes the repo may not be accepted as the `model` in the request. In this case, you can list the available models as shown below and use that name.
```python
models_response = client.models.list()
list_of_models = [model.id for model in models_response]
print(list_of_models)
```
# Usage: Standard (Non-OpenAI)
## Request Input Parameters
<details>
<summary>Click to expand table</summary>
You may either use a `prompt` or a list of `messages` as input. If you use `messages`, the model's chat template will be applied to the messages automatically, so the model must have one. If you use `prompt`, you may optionally apply the model's chat template to the prompt by setting `apply_chat_template` to `true`.
| Argument | Type | Default | Description |
|-----------------------|----------------------|--------------------|--------------------------------------------------------------------------------------------------------|
| `prompt` | str | | Prompt string to generate text based on. |
| `messages` | list[dict[str, str]] | | List of messages, which will automatically have the model's chat template applied. Overrides `prompt`. |
| `apply_chat_template` | bool | False | Whether to apply the model's chat template to the `prompt`. |
| `sampling_params` | dict | {} | Sampling parameters to control the generation, like temperature, top_p, etc. You can find all available parameters in the `Sampling Parameters` section below. |
| `stream` | bool | False | Whether to enable streaming of output. If True, responses are streamed as they are generated. |
| `max_batch_size` | int | env var `DEFAULT_BATCH_SIZE` | The maximum number of tokens to stream every HTTP POST call. |
| `min_batch_size` | int | env var `DEFAULT_MIN_BATCH_SIZE` | The minimum number of tokens to stream every HTTP POST call. |
| `batch_size_growth_factor` | int | env var `DEFAULT_BATCH_SIZE_GROWTH_FACTOR` | The growth factor by which `min_batch_size` will be multiplied for each call until `max_batch_size` is reached. |
</details>
### Sampling Parameters
| Argument | Type | Default | Description |
|-------------------------------|-----------------------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `best_of` | Optional[int] | None | Number of output sequences generated from the prompt. The top `n` sequences are returned from these `best_of` sequences. Must be ≥ `n`. Treated as beam width in beam search. Default is `n`. |
Below are all available sampling parameters that you can specify in the `sampling_params` dictionary. If you do not specify any of these parameters, the default values will be used.
<details>
<summary>Click to expand table</summary>
| Argument | Type | Default | Description |
| ------------------------------- | --------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `n` | int | 1 | Number of output sequences generated from the prompt. The top `n` sequences are returned. |
| `best_of` | Optional[int] | `n` | Number of output sequences generated from the prompt. The top `n` sequences are returned from these `best_of` sequences. Must be ≥ `n`. Treated as beam width in beam search. Default is `n`. |
| `presence_penalty` | float | 0.0 | Penalizes new tokens based on their presence in the generated text so far. Values > 0 encourage new tokens, values < 0 encourage repetition. |
| `frequency_penalty` | float | 0.0 | Penalizes new tokens based on their frequency in the generated text so far. Values > 0 encourage new tokens, values < 0 encourage repetition. |
| `repetition_penalty` | float | 1.0 | Penalizes new tokens based on their appearance in the prompt and generated text. Values > 1 encourage new tokens, values < 1 encourage repetition. |
@@ -128,10 +366,65 @@ Example:
| `use_beam_search` | bool | False | Whether to use beam search instead of sampling. |
| `length_penalty` | float | 1.0 | Penalizes sequences based on their length. Used in beam search. |
| `early_stopping` | Union[bool, str] | False | Controls stopping condition in beam search. Can be `True`, `False`, or `"never"`. |
| `stop` | Union[None, str, List[str]] | None | List of strings that stop generation when produced. Output will not contain these strings. |
| `stop` | Union[None, str, List[str]] | None | List of strings that stop generation when produced. The output will not contain these strings. |
| `stop_token_ids` | Optional[List[int]] | None | List of token IDs that stop generation when produced. Output contains these tokens unless they are special tokens. |
| `ignore_eos` | bool | False | Whether to ignore the End-Of-Sequence token and continue generating tokens after its generation. |
| `max_tokens` | int | 16 | Maximum number of tokens to generate per output sequence. |
| `skip_special_tokens` | bool | True | Whether to skip special tokens in the output. |
| `spaces_between_special_tokens` | bool | True | Whether to add spaces between special tokens in the output. |
### Text Input Formats
You may either use a `prompt` or a list of `messages` as input.
1. `prompt`
The prompt string can be any string, and the model's chat template will not be applied to it unless `apply_chat_template` is set to `true`, in which case it will be treated as a user message.
Example:
```json
{
"input": {
"prompt": "why sky is blue?",
"sampling_params": {
"temperature": 0.7,
"max_tokens": 100
}
}
}
```
2. `messages`
Your list can contain any number of messages, and each message usually can have any role from the following list: - `user` - `assistant` - `system`
However, some models may have different roles, so you should check the model's chat template to see which roles are required.
The model's chat template will be applied to the messages automatically, so the model must have one.
Example:
```json
{
"input": {
"messages": [
{
"role": "system",
"content": "You are a helpful AI assistant that provides clear and concise responses."
},
{
"role": "user",
"content": "Can you explain the difference between supervised and unsupervised learning?"
},
{
"role": "assistant",
"content": "Sure! Supervised learning uses labeled data, meaning each input has a corresponding correct output. The model learns by mapping inputs to known outputs. In contrast, unsupervised learning works with unlabeled data, where the model identifies patterns, structures, or clusters without predefined answers."
}
],
"sampling_params": {
"temperature": 0.7,
"max_tokens": 100
}
}
}
```
</details>
+11 -3
View File
@@ -1,6 +1,14 @@
hf_transfer
runpod==1.5.2
ray
pandas
pyarrow
runpod
huggingface-hub
packaging
typing-extensions==4.7.1
typing-extensions>=4.8.0
pydantic
pydantic-settings
hf-transfer
transformers>=4.57.0
bitsandbytes>=0.45.0
kernels
torch-c-dlpack-ext
+26
View File
@@ -0,0 +1,26 @@
variable "DOCKERHUB_REPO" {
default = "runpod"
}
variable "DOCKERHUB_IMG" {
default = "worker-v1-vllm"
}
variable "RELEASE_VERSION" {
default = "latest"
}
variable "HUGGINGFACE_ACCESS_TOKEN" {
default = ""
}
group "default" {
targets = ["worker-vllm"]
}
target "worker-vllm" {
tags = ["${DOCKERHUB_REPO}/${DOCKERHUB_IMG}:${RELEASE_VERSION}"]
context = "."
dockerfile = "Dockerfile"
platforms = ["linux/amd64"]
}
+202
View File
@@ -0,0 +1,202 @@
# Configuration Reference
Complete guide to all environment variables and configuration options for worker-vllm.
## LLM Settings
| Variable | Default | Type/Choices | Description |
| ------------------------------ | ------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `MODEL_NAME` | 'facebook/opt-125m' | `str` | Name or path of the Hugging Face model to use. |
| `MODEL_REVISION` | 'main' | `str` | Model revision to load (default: main). |
| `TOKENIZER` | None | `str` | Name or path of the Hugging Face tokenizer to use. |
| `SKIP_TOKENIZER_INIT` | False | `bool` | Skip initialization of tokenizer and detokenizer. |
| `TOKENIZER_MODE` | 'auto' | ['auto', 'slow'] | The tokenizer mode. |
| `TRUST_REMOTE_CODE` | `False` | `bool` | Trust remote code from Hugging Face. |
| `DOWNLOAD_DIR` | None | `str` | Directory to download and load the weights. |
| `LOAD_FORMAT` | 'auto' | `str` | The format of the model weights to load. |
| `HF_TOKEN` | - | `str` | Hugging Face token for private and gated models. |
| `DTYPE` | 'auto' | ['auto', 'half', 'float16', 'bfloat16', 'float', 'float32'] | Data type for model weights and activations. |
| `KV_CACHE_DTYPE` | 'auto' | ['auto', 'fp8'] | Data type for KV cache storage. |
| `QUANTIZATION_PARAM_PATH` | None | `str` | Path to the JSON file containing the KV cache scaling factors. |
| `MAX_MODEL_LEN` | None | `int` | Model context length. |
| `GUIDED_DECODING_BACKEND` | 'outlines' | ['outlines', 'lm-format-enforcer'] | Which engine will be used for guided decoding by default. |
| `DISTRIBUTED_EXECUTOR_BACKEND` | None | ['ray', 'mp'] | Backend to use for distributed serving. |
| `WORKER_USE_RAY` | False | `bool` | Deprecated, use --distributed-executor-backend=ray. |
| `PIPELINE_PARALLEL_SIZE` | 1 | `int` | Number of pipeline stages. |
| `TENSOR_PARALLEL_SIZE` | 1 | `int` | Number of tensor parallel replicas. |
| `MAX_PARALLEL_LOADING_WORKERS` | None | `int` | Load model sequentially in multiple batches. |
| `RAY_WORKERS_USE_NSIGHT` | False | `bool` | If specified, use nsight to profile Ray workers. |
| `ENABLE_PREFIX_CACHING` | False | `bool` | Enables automatic prefix caching. |
| `DISABLE_SLIDING_WINDOW` | False | `bool` | Disables sliding window, capping to sliding window size. |
| `NUM_LOOKAHEAD_SLOTS` | 0 | `int` | Experimental scheduling config necessary for speculative decoding. |
| `SEED` | 0 | `int` | Random seed for operations. |
| `NUM_GPU_BLOCKS_OVERRIDE` | None | `int` | If specified, ignore GPU profiling result and use this number of GPU blocks. |
| `MAX_NUM_BATCHED_TOKENS` | None | `int` | Maximum number of batched tokens per iteration. |
| `MAX_NUM_SEQS` | 256 | `int` | Maximum number of sequences per iteration. |
| `MAX_LOGPROBS` | 20 | `int` | Max number of log probs to return when logprobs is specified in SamplingParams. |
| `DISABLE_LOG_STATS` | False | `bool` | Disable logging statistics. |
| `QUANTIZATION` | None | ['awq', 'squeezellm', 'gptq', 'bitsandbytes'] | Method used to quantize the weights. |
| `ROPE_SCALING` | None | `dict` | RoPE scaling configuration in JSON format. |
| `ROPE_THETA` | None | `float` | RoPE theta. Use with rope_scaling. |
| `TOKENIZER_POOL_SIZE` | 0 | `int` | Size of tokenizer pool to use for asynchronous tokenization. |
| `TOKENIZER_POOL_TYPE` | 'ray' | `str` | Type of tokenizer pool to use for asynchronous tokenization. |
| `TOKENIZER_POOL_EXTRA_CONFIG` | None | `dict` | Extra config for tokenizer pool. |
## LoRA (Low-Rank Adaptation) Settings
| Variable | Default | Type | Description |
| --------------------------- | ------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------------- |
| `ENABLE_LORA` | False | `bool` | If True, enable handling of LoRA adapters. |
| `MAX_LORAS` | 1 | `int` | Max number of LoRAs in a single batch. |
| `MAX_LORA_RANK` | 16 | `int` | Max LoRA rank. |
| `LORA_EXTRA_VOCAB_SIZE` | 256 | `int` | Maximum size of extra vocabulary for LoRA adapters. |
| `LORA_DTYPE` | 'auto' | ['auto', 'float16', 'bfloat16', 'float32'] | Data type for LoRA. |
| `LONG_LORA_SCALING_FACTORS` | None | `tuple` | Specify multiple scaling factors for LoRA adapters. |
| `MAX_CPU_LORAS` | None | `int` | Maximum number of LoRAs to store in CPU memory. |
| `FULLY_SHARDED_LORAS` | False | `bool` | Enable fully sharded LoRA layers. |
| `LORA_MODULES` | `[]` | `list[dict]` | Add lora adapters from Hugging Face `[{"name": "xx", "path": "xxx/xxxx", "base_model_name": "xxx/xxxx"}]` |
> **Note (Serverless)**: When LoRA adapters are configured via `LORA_MODULES`, initialization is deferred to the first request to ensure compatibility with RunPod Serverless. This means the first request will include LoRA loading time. Subsequent requests are unaffected. Check logs for "LoRA mode: X adapter(s) will load on first request" at startup.
## Speculative Decoding Settings
Speculative decoding can be configured in two ways:
### Option 1: JSON Configuration
Set `SPECULATIVE_CONFIG` to a JSON string with your full speculative decoding configuration:
```bash
SPECULATIVE_CONFIG='{"method": "ngram", "num_speculative_tokens": 5, "prompt_lookup_max": 4}'
```
### Option 2: Individual Environment Variables
| Variable | Default | Type/Choices | Description |
| ---------------------------------------- | ------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- |
| `SPECULATIVE_METHOD` | None | ['draft_model', 'ngram', 'eagle', 'eagle3', 'medusa', 'mlp_speculator'] | Speculative decoding method to use. |
| `SPECULATIVE_MODEL` | None | `str` | The name of the draft model to be used in speculative decoding. |
| `NUM_SPECULATIVE_TOKENS` | None | `int` | The number of speculative tokens to sample from the draft model. |
| `SPECULATIVE_DRAFT_TENSOR_PARALLEL_SIZE` | None | `int` | Number of tensor parallel replicas for the draft model. |
| `SPECULATIVE_MAX_MODEL_LEN` | None | `int` | The maximum sequence length supported by the draft model. |
| `SPECULATIVE_DISABLE_BY_BATCH_SIZE` | None | `int` | Disable speculative decoding if the number of enqueue requests is larger than this value. |
| `NGRAM_PROMPT_LOOKUP_MAX` | None | `int` | Max size of window for ngram prompt lookup in speculative decoding. |
| `NGRAM_PROMPT_LOOKUP_MIN` | None | `int` | Min size of window for ngram prompt lookup in speculative decoding. |
If `SPECULATIVE_CONFIG` is set, it takes priority over individual env vars. When using individual env vars without `SPECULATIVE_METHOD`, the method is auto-detected from the model name or configuration.
## Scheduling & Performance Settings
| Variable | Default | Type/Choices | Description |
| ------------------------------ | ------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `GPU_MEMORY_UTILIZATION` | `0.95` | `float` | Sets GPU VRAM utilization. |
| `MAX_PARALLEL_LOADING_WORKERS` | `None` | `int` | Load model sequentially in multiple batches, to avoid RAM OOM when using tensor parallel and large models. |
| `BLOCK_SIZE` | `16` | `8`, `16`, `32` | Token block size for contiguous chunks of tokens. |
| `SWAP_SPACE` | `4` | `int` | CPU swap space size (GiB) per GPU. |
| `ENFORCE_EAGER` | False | `bool` | Always use eager-mode PyTorch. If False(`0`), will use eager mode and CUDA graph in hybrid for maximal performance and flexibility. |
| `MAX_SEQ_LEN_TO_CAPTURE` | `8192` | `int` | Maximum context length covered by CUDA graphs. When a sequence has context length larger than this, we fall back to eager mode. |
| `DISABLE_CUSTOM_ALL_REDUCE` | `0` | `int` | Enables or disables custom all reduce. |
| `ENABLE_EXPERT_PARALLEL` | `False` | `bool` | Enable Expert Parallel for MoE models. |
| `ATTENTION_BACKEND` | `None` | `str` | Attention backend to use (e.g., `FLASH_ATTN`, `FLASHINFER`, `TRITON_FLASH_ATTN`). Replaces deprecated `VLLM_ATTENTION_BACKEND`. |
| `ASYNC_SCHEDULING` | `None` | `bool` | Enable async scheduling (overlaps engine scheduling with GPU execution). Default: enabled in vLLM 0.14.0+. Set to `false` to disable. |
| `STREAM_INTERVAL` | `1` | `int` | Controls how often to yield streaming results. Lower = more frequent updates. |
## Tokenizer Settings
| Variable | Default | Type/Choices | Description |
| ---------------------- | ------- | ----------------------------------- | ------------------------------------------------------------------------------------------------- |
| `TOKENIZER_NAME` | `None` | `str` | Tokenizer repository to use a different tokenizer than the model's default. |
| `TOKENIZER_REVISION` | `None` | `str` | Tokenizer revision to load. |
| `CUSTOM_CHAT_TEMPLATE` | `None` | `str` of single-line jinja template | Custom chat jinja template. [More Info](https://huggingface.co/docs/transformers/chat_templating) |
## Streaming & Batch Settings
The way this works is that the first request will have a batch size of `DEFAULT_MIN_BATCH_SIZE`, and each subsequent request will have a batch size of `previous_batch_size * DEFAULT_BATCH_SIZE_GROWTH_FACTOR`. This will continue until the batch size reaches `DEFAULT_BATCH_SIZE`. E.g. for the default values, the batch sizes will be `1, 3, 9, 27, 50, 50, 50, ...`. You can also specify this per request, with inputs `max_batch_size`, `min_batch_size`, and `batch_size_growth_factor`. This has nothing to do with vLLM's internal batching, but rather the number of tokens sent in each HTTP request from the worker.
| Variable | Default | Type/Choices | Description |
| ---------------------------------- | ------- | ------------ | --------------------------------------------------------------------------------------------------------- |
| `DEFAULT_BATCH_SIZE` | `50` | `int` | Default and Maximum batch size for token streaming to reduce HTTP calls. |
| `DEFAULT_MIN_BATCH_SIZE` | `1` | `int` | Batch size for the first request, which will be multiplied by the growth factor every subsequent request. |
| `DEFAULT_BATCH_SIZE_GROWTH_FACTOR` | `3` | `float` | Growth factor for dynamic batch size. |
## OpenAI Compatibility Settings
| Variable | Default | Type/Choices | Description |
| ----------------------------------- | ----------- | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `RAW_OPENAI_OUTPUT` | `1` | boolean as `int` | Enables raw OpenAI SSE format string output when streaming. **Required** to be enabled (which it is by default) for OpenAI compatibility. |
| `OPENAI_SERVED_MODEL_NAME_OVERRIDE` | `None` | `str` | Overrides the name of the served model from model repo/path to specified name, which you will then be able to use the value for the `model` parameter when making OpenAI requests |
| `OPENAI_RESPONSE_ROLE` | `assistant` | `str` | Role of the LLM's Response in OpenAI Chat Completions. |
| `ENABLE_AUTO_TOOL_CHOICE` | `false` | `bool` | Enables automatic tool selection for supported models. Set to `true` to activate. |
| `TOOL_CALL_PARSER` | `None` | `str` | Specifies the parser for tool calls. Options: `mistral`, `hermes`, `llama3_json`, `llama4_json`, `llama4_pythonic`, `granite`, `granite-20b-fc`, `deepseek_v3`, `internlm`, `jamba`, `phi4_mini_json`, `pythonic` |
| `REASONING_PARSER` | `None` | `str` | Parser for reasoning-capable models (enables reasoning mode). Examples: `deepseek_r1`, `qwen3`, `granite`, `hunyuan_a13b`. Leave unset to disable. |
| `TRUST_REQUEST_CHAT_TEMPLATE` | `false` | `bool` | Allow clients to send custom chat templates in API requests. **Security consideration:** Only enable if you trust your API clients. |
| `RETURN_TOKENS_AS_TOKEN_IDS` | `false` | `bool` | Return token IDs instead of decoded text strings in responses. |
| `EXCLUDE_TOOLS_WHEN_TOOL_CHOICE_NONE` | `false` | `bool` | Exclude tool definitions from the prompt when `tool_choice` is set to `none`. |
| `ENABLE_PROMPT_TOKENS_DETAILS` | `false` | `bool` | Include detailed prompt token information in API responses. |
| `ENABLE_FORCE_INCLUDE_USAGE` | `false` | `bool` | Always include usage statistics in API responses, even when not requested. |
| `ENABLE_LOG_OUTPUTS` | `false` | `bool` | Log model outputs for debugging purposes. |
| `LOG_ERROR_STACK` | `false` | `bool` | Include full stack traces in error responses for debugging. |
## Serverless & Concurrency Settings
| Variable | Default | Type/Choices | Description |
| ---------------------- | ------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `MAX_CONCURRENCY` | `30` | `int` | Max concurrent requests per worker. vLLM has an internal queue, so you don't have to worry about limiting by VRAM, this is for improving scaling/load balancing efficiency |
| `DISABLE_LOG_STATS` | False | `bool` | Enables or disables vLLM stats logging. |
| `ENABLE_LOG_REQUESTS` | False | `bool` | Enables vLLM request logging. (Replaces deprecated `DISABLE_LOG_REQUESTS` in vLLM 0.15.0) |
## Advanced Settings
| Variable | Default | Type | Description |
| --------------------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `MODEL_LOADER_EXTRA_CONFIG` | None | `dict` | Extra config for model loader. |
| `PREEMPTION_MODE` | None | `str` | If 'recompute', the engine performs preemption-aware recomputation. If 'save', the engine saves activations into the CPU memory as preemption happens. |
| `PREEMPTION_CHECK_PERIOD` | 1.0 | `float` | How frequently the engine checks if a preemption happens. |
| `PREEMPTION_CPU_CAPACITY` | 2 | `float` | The percentage of CPU memory used for the saved activations. |
| `DISABLE_LOGGING_REQUEST` | False | `bool` | Disable logging requests. |
| `MAX_LOG_LEN` | None | `int` | Max number of prompt characters or prompt ID numbers being printed in log. |
## UPPERCASED env vars: Pass any engine arg
Any vLLM `AsyncEngineArgs` field can be set via an environment variable using the **UPPERCASED** field name (the same names vLLM uses). The worker auto-discovers all fields from env — no prefix.
**Format:** `<FIELD_NAME_UPPERCASED>=<value>` (e.g. `MAX_MODEL_LEN=4096`)
**Examples:**
| Environment Variable | vLLM Engine Arg | Value Example |
| ------------------------ | ------------------------ | ------------- |
| `MAX_MODEL_LEN` | `max_model_len` | `4096` |
| `ENFORCE_EAGER` | `enforce_eager` | `true` |
| `ENABLE_CHUNKED_PREFILL` | `enable_chunked_prefill` | `true` |
| `NUM_SCHEDULER_STEPS` | `num_scheduler_steps` | `8` |
| `TOKENIZER_POOL_SIZE` | `tokenizer_pool_size` | `4` |
**Backward-compat aliases:** `MODEL_NAME` → `model`, `TOKENIZER_NAME` → `tokenizer`, `MAX_CONTEXT_LEN_TO_CAPTURE` → `max_seq_len_to_capture`, `MODEL_REVISION` → `revision`.
**Notes:**
- Only valid `AsyncEngineArgs` fields are applied. Unknown keys are silently ignored.
- Values are automatically cast to the correct type (`int`, `float`, `bool`, `str`, or JSON for `dict`/`list`/`tuple`).
- For a full list of available engine args, see the [vLLM AsyncEngineArgs documentation](https://docs.vllm.ai/en/latest/configuration/engine_args/).
## Docker Build Arguments
These variables are used when building custom Docker images with models baked in:
| Variable | Default | Type | Description |
| --------------------- | ---------------- | ----- | ------------------------------------------------- |
| `BASE_PATH` | `/runpod-volume` | `str` | Storage directory for huggingface cache and model |
| `WORKER_CUDA_VERSION` | `12.1.0` | `str` | CUDA version for the worker image |
## Deprecated Variables
⚠️ **The following variables are deprecated and will be removed in future versions:**
| Old Variable | New Variable | Note |
| ---------------------------- | ------------------------ | -------------------------------------------------------------------- |
| `MAX_CONTEXT_LEN_TO_CAPTURE` | `MAX_SEQ_LEN_TO_CAPTURE` | Use new variable name |
| `kv_cache_dtype=fp8_e5m2` | `kv_cache_dtype=fp8` | Simplified fp8 format |
| `USE_V2_BLOCK_MANAGER` | *(removed)* | V2 block manager is now the default in vLLM 0.13.0, setting ignored |
| `VLLM_ATTENTION_BACKEND` | `ATTENTION_BACKEND` | Use new env var name (old still works with deprecation warning) |
| `DISABLE_LOG_REQUESTS` | `ENABLE_LOG_REQUESTS` | Inverted logic in vLLM 0.15.0 (old still works with deprecation warning) |
+343
View File
@@ -0,0 +1,343 @@
# Worker vLLM - Development Conventions & Architecture Guide
## Project Overview
**worker-vllm** is a RunPod serverless worker that provides OpenAI-compatible endpoints for Large Language Model (LLM) inference, powered by the vLLM engine. It enables blazing-fast LLM deployment on RunPod's serverless infrastructure with minimal configuration.
### Core Purpose
- **Primary Function**: Deploy any Hugging Face LLM as an OpenAI-compatible API endpoint
- **Platform**: RunPod Serverless infrastructure
- **Engine**: vLLM (high-performance LLM inference engine)
- **Compatibility**: Drop-in replacement for OpenAI API (Chat Completions, Models)
## High-Level Architecture
### 1. **Entry Point & Request Flow**
```
RunPod Request → handler.py → JobInput → Engine Selection → vLLM Generation → Streaming Response
```
**Key Components:**
- `src/handler.py`: Main entry point using RunPod serverless framework
- `src/utils.py`: Request parsing and utility classes (`JobInput`, `BatchSize`)
- Two engine modes: OpenAI-compatible vs. standard vLLM
### 2. **Engine Architecture**
#### Core Classes:
- **`vLLMEngine`**: Base engine handling vLLM initialization and generation
- **`OpenAIvLLMEngine`**: Wrapper providing OpenAI API compatibility
- **Engine Selection**: Automatic routing based on `job_input.openai_route`
#### Key Design Patterns:
- **Dual API Support**: Same codebase serves both OpenAI-compatible and native vLLM APIs
- **Streaming by Default**: Token-level streaming with configurable batching
- **Dynamic Batching**: Adaptive batch sizes that grow from min → max for efficiency
### 3. **Configuration System**
#### Environment-Based Configuration:
- **Single Source of Truth**: All configuration via environment variables
- **Hierarchical Loading**: `DEFAULT_ARGS` → `os.environ` → `local_model_args.json` (for baked models)
- **vLLM Argument Mapping**: Automatic translation of env vars to vLLM `AsyncEngineArgs`
#### Key Configuration Files:
- `src/engine_args.py`: Centralized configuration management
- `src/constants.py`: Default values for core settings
- `.runpod/hub.json`: Hub UI configuration (CRITICAL: always update when changing defaults)
- `worker-config.json`: UI form generation for RunPod console (if exists)
## Core Development Concepts
### 1. **Deployment Models**
#### Option 1: Pre-built Images (Recommended)
- **Image**: `runpod/worker-v1-vllm:<version>` (see [GitHub Releases](https://github.com/runpod-workers/worker-vllm/releases))
- **Configuration**: Entirely via environment variables
- **Model Loading**: Downloads model at runtime from Hugging Face
- **Use Case**: Quick deployment, model experimentation
#### Option 2: Baked Model Images
- **Build Process**: Model downloaded during Docker build
- **Storage**: Model embedded in container image
- **Configuration**: Stored in `/local_model_args.json`
- **Use Case**: Production deployments, faster cold starts
### 2. **Request Processing Patterns**
#### Input Handling:
```python
class JobInput:
- llm_input: str | List[Dict] (prompt or messages)
- sampling_params: SamplingParams (generation settings)
- stream: bool (streaming vs batch response)
- openai_route: bool (API compatibility mode)
- batch_size configs: Dynamic batching parameters
```
#### Response Streaming:
- **Batched Streaming**: Tokens grouped into configurable batch sizes
- **Dynamic Growth**: `min_batch_size * growth_factor^n` up to `max_batch_size`
- **Usage Tracking**: Input/output token counting for billing
### 3. **Model & Tokenizer Management**
#### Tokenizer Handling:
- **Wrapper Pattern**: `TokenizerWrapper` for consistent chat template application
- **Special Cases**: Mistral models use vLLM's native tokenizer
- **Chat Templates**: Automatic application for message-based inputs
#### Model Loading:
- **Multi-GPU Support**: Automatic tensor parallelism detection
- **Quantization**: Support for AWQ, GPTQ, BitsAndBytes
- **Caching**: Hugging Face cache management
## Development Patterns & Best Practices
### 1. **Code Organization**
#### File Structure:
```
src/
├── handler.py # RunPod entry point
├── engine.py # Core vLLM engines
├── engine_args.py # Configuration management
├── utils.py # Request parsing & utilities
├── tokenizer.py # Tokenizer wrapper
├── constants.py # Default constants
└── download_model.py # Model downloading logic
```
#### Separation of Concerns:
- **Engine Logic**: Isolated in `engine.py` classes
- **Configuration**: Centralized in `engine_args.py`
- **Request Handling**: Abstracted via `JobInput` class
- **Platform Integration**: Contained in `handler.py`
### 2. **Error Handling & Logging**
#### Logging Strategy:
- **Structured Logging**: Consistent format across components
- **Performance Tracking**: Timer decorators for critical operations
- **Error Context**: Detailed error messages with configuration context
#### Error Responses:
- **OpenAI Compatibility**: Standard OpenAI error format
- **Graceful Degradation**: Fallback behaviors for edge cases
### 3. **Environment Variable Conventions**
#### Naming Patterns:
- **vLLM Settings**: Match vLLM parameter names (uppercase)
- **RunPod Settings**: `MAX_CONCURRENCY`, `DEFAULT_BATCH_SIZE`
- **OpenAI Settings**: `OPENAI_` prefix for compatibility settings
- **Feature Flags**: `ENABLE_*`, `DISABLE_*` pattern
#### Type Conventions:
- **Booleans**: String 'true'/'false' or int 0/1
- **Lists**: Comma-separated strings
- **Objects**: JSON strings for complex configurations
### 4. **Docker & Deployment**
#### Multi-Stage Builds:
- **Base**: CUDA runtime environment
- **Dependencies**: Python packages and vLLM
- **Model Download**: Optional model baking stage
- **Runtime**: Final application layer
#### Build Arguments:
- **MODEL_NAME**: Primary model identifier
- **BASE_PATH**: Storage location strategy
- **QUANTIZATION**: Optimization settings
- **WORKER_CUDA_VERSION**: CUDA compatibility
#### CI/CD Strategy:
- **Development Builds**: All non-main branches → `runpod/worker-v1-vllm:dev-<branch-name>`
- **Release Builds**: Git tags (numeric) only → `runpod/worker-v1-vllm:<version>`
- **Dependency Updates**: Automated runpod package version monitoring
#### Docker Bake Configuration:
- **File**: `docker-bake.hcl` (flexible variable-based configuration)
- **Variables**: `DOCKERHUB_REPO`, `DOCKERHUB_IMG`, `RELEASE_VERSION`, `HUGGINGFACE_ACCESS_TOKEN`
- **Platform**: `linux/amd64` (GPU-optimized)
## Release & Versioning Strategy
### 1. **Version Tagging**
- **Development**: `dev-<branch-name>` (e.g., `dev-feature-new-api`)
- **Specific Versions**: `2.7.0`, `2.8.0` (semantic versioning without "v" prefix)
- **Version Discovery**: Check [GitHub Releases](https://github.com/runpod-workers/worker-vllm/releases) for available versions
### 2. **Release Workflow**
1. **Feature Development**: Work on feature branches → triggers dev builds
2. **Main Branch Staging**: Merge features to main → stable codebase (no builds)
3. **Version Release**: Create git tag from main branch (e.g., `2.8.0`) → triggers versioned release + GitHub release
4. **Docker Hub**: Versioned image pushed with tag
### 3. **Branch Strategy**
- **Feature Branches**: `feature/*`, `fix/*`, `feat/*` etc. → Dev builds
- **Main Branch**: Stable codebase ready for release (no automatic builds)
- **Git Tags**: Must be created from main branch for formal version releases
### 4. **Deployment Recommendations**
- **Production**: Use specific version tags (e.g., `2.7.0`) for stability
- **Development**: Use `dev-<branch>` for testing specific features
- **Version Selection**: Check [GitHub Releases](https://github.com/runpod-workers/worker-vllm/releases) for available versions
- **Release Process**: Always tag from main branch: `git checkout main && git tag 2.8.0 && git push origin 2.8.0`
## Performance & Scaling Considerations
### 1. **Memory Management**
- **GPU Utilization**: Default 95% GPU memory utilization
- **KV Cache**: Configurable cache types (auto, fp8)
- **Swap Space**: CPU offloading for large contexts
### 2. **Concurrency Patterns**
- **Max Concurrency**: 30 concurrent requests by default
- **vLLM Queuing**: Internal request batching and scheduling
- **RunPod Integration**: Concurrency modifier for auto-scaling
### 3. **Optimization Features**
- **Prefix Caching**: Automatic caching of common prefixes
- **Speculative Decoding**: Draft model acceleration
- **Chunked Prefill**: Memory-efficient long context handling
## Testing & Development
### 1. **Local Development**
- **Environment**: Virtual environment with GPU support
- **Configuration**: `.env` files for local testing
- **Model Testing**: Small models for development (facebook/opt-125m)
### 2. **Docker Development**
- **Build Strategy**: `docker-bake.hcl` for consistent builds
- **Testing Images**: Separate dev/stable image tags
- **Layer Caching**: Optimized for rapid iteration
### 3. **Configuration Validation**
- **Argument Matching**: Automatic validation against vLLM parameters
- **Environment Validation**: Type checking and default value handling
- **Runtime Validation**: Model compatibility checks
## API Conventions
### 1. **OpenAI Compatibility**
- **Endpoint Mapping**: `/openai/v1/chat/completions`, `/openai/v1/models`
- **Request Format**: Exact OpenAI request/response schemas
- **Authentication**: RunPod API key in Authorization header
- **Model Names**: Hugging Face repo names or custom overrides
### 2. **Native vLLM API**
- **Input Format**: `prompt` or `messages` with `sampling_params`
- **Streaming**: Token-level streaming with configurable batching
- **Extensibility**: Support for vLLM-specific features
## Common Patterns & Utilities
### 1. **Configuration Loading**
```python
# Standard pattern for new configuration options
def get_engine_args():
args = DEFAULT_ARGS
args.update(os.environ) # Environment override
args.update(get_local_args()) # Baked model override
return match_vllm_args(args) # Validate against vLLM
```
### 2. **Error Handling**
```python
# Standard error response pattern
def create_error_response(message: str, err_type: str = "BadRequestError"):
return ErrorResponse(message=message, type=err_type)
```
### 3. **Async Generation**
```python
# Standard streaming pattern
async def generate(self, job_input: JobInput):
async for batch in self._generate_vllm(...):
yield batch # Batch-level yielding for efficiency
```
## Extension Points
### 1. **New Model Architectures**
- **Engine Args**: Add new parameters in `engine_args.py`
- **Compatibility**: Update vLLM argument mapping
- **Validation**: Add architecture-specific validation
### 2. **New API Features**
- **Engine Extension**: Extend `vLLMEngine` or `OpenAIvLLMEngine`
- **Input Parsing**: Extend `JobInput` class
- **Response Format**: Add new response generators
### 3. **Performance Optimizations**
- **Batching Strategy**: Modify `BatchSize` class
- **Memory Management**: Add new caching strategies
- **Hardware Optimization**: GPU-specific optimizations
## Security & Best Practices
### 1. **Secret Management**
- **Build Secrets**: Docker secrets for HF tokens
- **Runtime Secrets**: Environment variable injection
- **Token Handling**: Secure authentication patterns
### 2. **Resource Limits**
- **Memory Bounds**: Configurable GPU memory limits
- **Request Limits**: Concurrency and timeout controls
- **Model Safety**: Trust remote code flags
### 3. **Logging Security**
- **Sanitization**: No secrets in logs
- **Request Logging**: Configurable request/response logging
- **Performance Monitoring**: Safe metrics collection
---
This guide should be consulted whenever working on the worker-vllm codebase to ensure consistency with established patterns and architectural decisions.
Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

View File
+4 -25
View File
@@ -1,25 +1,4 @@
DEFAULT_BATCH_SIZE = 30
DEFAULT_MAX_CONCURRENCY = 300
sampling_param_types = {
"n": int,
"best_of": int,
"presence_penalty": float,
"frequency_penalty": float,
"repetition_penalty": float,
"temperature": float,
"top_p": float,
"top_k": int,
"min_p": float,
"use_beam_search": bool,
"length_penalty": float,
"early_stopping": (bool, str),
"stop": (str, list),
"stop_token_ids": list,
"ignore_eos": bool,
"max_tokens": int,
"logprobs": int,
"prompt_logprobs": int,
"skip_special_tokens": bool,
"spaces_between_special_tokens": bool,
}
DEFAULT_BATCH_SIZE = 50
DEFAULT_MAX_CONCURRENCY = 30
DEFAULT_BATCH_SIZE_GROWTH_FACTOR = 3
DEFAULT_MIN_BATCH_SIZE = 1
+97 -19
View File
@@ -1,22 +1,100 @@
import argparse
import os
from vllm.model_executor.weight_utils import prepare_hf_model_weights
import json
import logging
import glob
from shutil import rmtree
from huggingface_hub import snapshot_download
from utils import timer_decorator
BASE_DIR = "/"
TOKENIZER_PATTERNS = [["*.json", "tokenizer*"]]
MODEL_PATTERNS = [["*.safetensors"], ["*.bin"], ["*.pt"]]
def setup_env():
if os.getenv("TESTING_DOWNLOAD") == "1":
BASE_DIR = "tmp"
os.makedirs(BASE_DIR, exist_ok=True)
os.environ.update({
"HF_HOME": f"{BASE_DIR}/hf_cache",
"MODEL_NAME": "openchat/openchat-3.5-0106",
"HF_HUB_ENABLE_HF_TRANSFER": "1",
"TENSORIZE": "1",
"TENSORIZER_NUM_GPUS": "1",
"DTYPE": "auto"
})
@timer_decorator
def download(name, revision, type, cache_dir):
if type == "model":
pattern_sets = [model_pattern + TOKENIZER_PATTERNS[0] for model_pattern in MODEL_PATTERNS]
elif type == "tokenizer":
pattern_sets = TOKENIZER_PATTERNS
else:
raise ValueError(f"Invalid type: {type}")
try:
for pattern_set in pattern_sets:
path = snapshot_download(name, revision=revision, cache_dir=cache_dir,
allow_patterns=pattern_set)
for pattern in pattern_set:
if glob.glob(os.path.join(path, pattern)):
logging.info(f"Successfully downloaded {pattern} model files.")
return path
except ValueError:
raise ValueError(f"No patterns matching {pattern_sets} found for download.")
# @timer_decorator
# def tensorize_model(model_path): TODO: Add back once tensorizer is ready
# from vllm.engine.arg_utils import EngineArgs
# from vllm.model_executor.model_loader.tensorizer import TensorizerConfig, tensorize_vllm_model
# from torch.cuda import device_count
# tensorizer_num_gpus = int(os.getenv("TENSORIZER_NUM_GPUS", "1"))
# if tensorizer_num_gpus > device_count():
# raise ValueError(f"TENSORIZER_NUM_GPUS ({tensorizer_num_gpus}) exceeds available GPUs ({device_count()})")
# dtype = os.getenv("DTYPE", "auto")
# serialized_dir = f"{BASE_DIR}/serialized_model"
# os.makedirs(serialized_dir, exist_ok=True)
# serialized_uri = f"{serialized_dir}/model{'-%03d' if tensorizer_num_gpus > 1 else ''}.tensors"
# tensorize_vllm_model(
# EngineArgs(model=model_path, tensor_parallel_size=tensorizer_num_gpus, dtype=dtype),
# TensorizerConfig(tensorizer_uri=serialized_uri)
# )
# logging.info("Successfully serialized model to %s", str(serialized_uri))
# logging.info("Removing HF Model files after serialization")
# rmtree("/".join(model_path.split("/")[:-2]))
# return serialized_uri, tensorizer_num_gpus, dtype
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str)
parser.add_argument(
"--download_dir", type=str, default=os.environ.get("MODEL_BASE_PATH")
)
args = parser.parse_args()
if not args.model or not args.download_dir:
raise ValueError("Must specify model and download_dir")
if not os.path.exists(args.download_dir):
os.makedirs(args.download_dir)
prepare_hf_model_weights(
model_name_or_path=args.model,
cache_dir=args.download_dir,
)
setup_env()
cache_dir = os.getenv("HF_HOME")
model_name, model_revision = os.getenv("MODEL_NAME"), os.getenv("MODEL_REVISION") or None
tokenizer_name, tokenizer_revision = os.getenv("TOKENIZER_NAME") or model_name, os.getenv("TOKENIZER_REVISION") or model_revision
model_path = download(model_name, model_revision, "model", cache_dir)
metadata = {
"MODEL_NAME": model_path,
"MODEL_REVISION": os.getenv("MODEL_REVISION"),
"QUANTIZATION": os.getenv("QUANTIZATION"),
}
# if os.getenv("TENSORIZE") == "1": TODO: Add back once tensorizer is ready
# serialized_uri, tensorizer_num_gpus, dtype = tensorize_model(model_path)
# metadata.update({
# "MODEL_NAME": serialized_uri,
# "TENSORIZER_URI": serialized_uri,
# "TENSOR_PARALLEL_SIZE": tensorizer_num_gpus,
# "DTYPE": dtype
# })
tokenizer_path = download(tokenizer_name, tokenizer_revision, "tokenizer", cache_dir)
metadata.update({
"TOKENIZER_NAME": tokenizer_path,
"TOKENIZER_REVISION": tokenizer_revision
})
with open(f"{BASE_DIR}/local_model_args.json", "w") as f:
json.dump({k: v for k, v in metadata.items() if v not in (None, "")}, f)
+328 -72
View File
@@ -1,89 +1,345 @@
import os
import asyncio
import json
import logging
from typing import Union
import torch
from vllm import AsyncLLMEngine, AsyncEngineArgs
from transformers import AutoTokenizer
from utils import ServerlessConfig
import os
import time
from typing import AsyncGenerator, Optional
from dotenv import load_dotenv
from vllm import AsyncLLMEngine
from vllm.entrypoints.logger import RequestLogger
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
from vllm.entrypoints.openai.completion.protocol import CompletionRequest
from vllm.entrypoints.openai.completion.serving import OpenAIServingCompletion
from vllm.entrypoints.openai.engine.protocol import ErrorResponse
from vllm.entrypoints.openai.models.protocol import BaseModelPath, LoRAModulePath
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
class Tokenizer:
def __init__(self, model_name: str):
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.has_chat_template = bool(self.tokenizer.chat_template)
def apply_chat_template(self, input: Union[str, list[dict[str, str]]]) -> str:
if isinstance(input, list):
if not self.has_chat_template:
raise ValueError(
"Chat template does not exist for this model, you must provide a single string input instead of a list of messages"
)
elif isinstance(input, str):
input = [{"role": "user", "content": input}]
else:
raise ValueError("Input must be a string or a list of messages")
return self.tokenizer.apply_chat_template(
input, tokenize=False, add_generation_prompt=True
)
from constants import DEFAULT_BATCH_SIZE, DEFAULT_BATCH_SIZE_GROWTH_FACTOR, DEFAULT_MAX_CONCURRENCY, DEFAULT_MIN_BATCH_SIZE
from engine_args import get_engine_args
from tokenizer import TokenizerWrapper
from utils import BatchSize, DummyRequest, JobInput, create_error_response
class vLLMEngine:
def __init__(self):
def __init__(self, engine = None):
load_dotenv() # For local development
self.config = self._initialize_config()
self.serverless_config = ServerlessConfig()
self.tokenizer = Tokenizer(self.config["model"])
self.llm = self._initialize_llm()
self.engine_args = get_engine_args()
logging.info(f"Engine args: {self.engine_args}")
# Initialize vLLM engine first
self.llm = self._initialize_llm() if engine is None else engine.llm
# Only create custom tokenizer wrapper if not using mistral tokenizer mode
# For mistral models, let vLLM handle tokenizer initialization
if self.engine_args.tokenizer_mode != 'mistral':
self.tokenizer = TokenizerWrapper(self.engine_args.tokenizer or self.engine_args.model,
self.engine_args.tokenizer_revision,
self.engine_args.trust_remote_code)
else:
# For mistral models, we'll get the tokenizer from vLLM later
self.tokenizer = None
self.max_concurrency = int(os.getenv("MAX_CONCURRENCY", DEFAULT_MAX_CONCURRENCY))
self.default_batch_size = int(os.getenv("DEFAULT_BATCH_SIZE", DEFAULT_BATCH_SIZE))
self.batch_size_growth_factor = int(os.getenv("BATCH_SIZE_GROWTH_FACTOR", DEFAULT_BATCH_SIZE_GROWTH_FACTOR))
self.min_batch_size = int(os.getenv("MIN_BATCH_SIZE", DEFAULT_MIN_BATCH_SIZE))
def _initialize_config(self):
return {
"model": os.getenv("MODEL_NAME"),
"download_dir": os.getenv("MODEL_BASE_PATH", "/runpod-volume/"),
"quantization": self._get_quantization(),
"dtype": "auto" if os.getenv("QUANTIZATION") is None else "half",
"disable_log_stats": bool(int(os.getenv("DISABLE_LOG_STATS", 1))),
"disable_log_requests": bool(int(os.getenv("DISABLE_LOG_REQUESTS", 1))),
"trust_remote_code": bool(int(os.getenv("TRUST_REMOTE_CODE", 0))),
"gpu_memory_utilization": float(os.getenv("GPU_MEMORY_UTILIZATION", 0.98)),
"max_model_len": self._get_max_model_len(),
"tensor_parallel_size": self._get_num_gpu_shard(),
def _get_tokenizer_for_chat_template(self):
"""Get tokenizer for chat template application"""
if self.tokenizer is not None:
return self.tokenizer
else:
# For mistral models, get tokenizer from vLLM engine
# This is a fallback - ideally chat templates should be handled by vLLM directly
try:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
self.engine_args.tokenizer or self.engine_args.model,
revision=self.engine_args.tokenizer_revision or "main",
trust_remote_code=self.engine_args.trust_remote_code
)
# Create a minimal wrapper
class MinimalTokenizerWrapper:
def __init__(self, tokenizer):
self.tokenizer = tokenizer
self.custom_chat_template = os.getenv("CUSTOM_CHAT_TEMPLATE")
self.has_chat_template = bool(self.tokenizer.chat_template) or bool(self.custom_chat_template)
if self.custom_chat_template and isinstance(self.custom_chat_template, str):
self.tokenizer.chat_template = self.custom_chat_template
def apply_chat_template(self, input):
if isinstance(input, list):
if not self.has_chat_template:
raise ValueError(
"Chat template does not exist for this model, you must provide a single string input instead of a list of messages"
)
elif isinstance(input, str):
input = [{"role": "user", "content": input}]
else:
raise ValueError("Input must be a string or a list of messages")
return self.tokenizer.apply_chat_template(
input, tokenize=False, add_generation_prompt=True
)
return MinimalTokenizerWrapper(tokenizer)
except Exception as e:
logging.error(f"Failed to create fallback tokenizer: {e}")
raise e
def dynamic_batch_size(self, current_batch_size, batch_size_growth_factor):
return min(current_batch_size*batch_size_growth_factor, self.default_batch_size)
async def generate(self, job_input: JobInput):
try:
async for batch in self._generate_vllm(
llm_input=job_input.llm_input,
validated_sampling_params=job_input.sampling_params,
batch_size=job_input.max_batch_size,
stream=job_input.stream,
apply_chat_template=job_input.apply_chat_template,
request_id=job_input.request_id,
batch_size_growth_factor=job_input.batch_size_growth_factor,
min_batch_size=job_input.min_batch_size
):
yield batch
except Exception as e:
yield {"error": create_error_response(str(e)).model_dump()}
async def _generate_vllm(self, llm_input, validated_sampling_params, batch_size, stream, apply_chat_template, request_id, batch_size_growth_factor, min_batch_size: str) -> AsyncGenerator[dict, None]:
if apply_chat_template or isinstance(llm_input, list):
tokenizer_wrapper = self._get_tokenizer_for_chat_template()
llm_input = tokenizer_wrapper.apply_chat_template(llm_input)
results_generator = self.llm.generate(llm_input, validated_sampling_params, request_id)
n_responses, n_input_tokens, is_first_output = validated_sampling_params.n, 0, True
last_output_texts, token_counters = ["" for _ in range(n_responses)], {"batch": 0, "total": 0}
batch = {
"choices": [{"tokens": []} for _ in range(n_responses)],
}
max_batch_size = batch_size or self.default_batch_size
batch_size_growth_factor, min_batch_size = batch_size_growth_factor or self.batch_size_growth_factor, min_batch_size or self.min_batch_size
batch_size = BatchSize(max_batch_size, min_batch_size, batch_size_growth_factor)
async for request_output in results_generator:
if is_first_output: # Count input tokens only once
n_input_tokens = len(request_output.prompt_token_ids)
is_first_output = False
for output in request_output.outputs:
output_index = output.index
token_counters["total"] += 1
if stream:
new_output = output.text[len(last_output_texts[output_index]):]
batch["choices"][output_index]["tokens"].append(new_output)
token_counters["batch"] += 1
if token_counters["batch"] >= batch_size.current_batch_size:
batch["usage"] = {
"input": n_input_tokens,
"output": token_counters["total"],
}
yield batch
batch = {
"choices": [{"tokens": []} for _ in range(n_responses)],
}
token_counters["batch"] = 0
batch_size.update()
last_output_texts[output_index] = output.text
if not stream:
for output_index, output in enumerate(last_output_texts):
batch["choices"][output_index]["tokens"] = [output]
token_counters["batch"] += 1
if token_counters["batch"] > 0:
batch["usage"] = {"input": n_input_tokens, "output": token_counters["total"]}
yield batch
def _initialize_llm(self):
try:
return AsyncLLMEngine.from_engine_args(AsyncEngineArgs(**self.config))
start = time.time()
engine = AsyncLLMEngine.from_engine_args(self.engine_args)
end = time.time()
logging.info(f"Initialized vLLM engine in {end - start:.2f}s")
return engine
except Exception as e:
logging.error("Error initializing vLLM engine: %s", e)
raise e
class OpenAIvLLMEngine(vLLMEngine):
def __init__(self, vllm_engine):
super().__init__(vllm_engine)
self.served_model_name = os.getenv("OPENAI_SERVED_MODEL_NAME_OVERRIDE") or self.engine_args.served_model_name or self.engine_args.model
self.response_role = os.getenv("OPENAI_RESPONSE_ROLE") or "assistant"
self.lora_adapters = self._load_lora_adapters()
# Always defer OpenAI engine initialization to the first request.
# asyncio.run() creates a temporary event loop that gets closed, but async
# components (tokenizer pool, serving engines) bind futures to that loop.
# When Runpod's serverless handler runs in its own event loop, those futures
# are "attached to a different loop" causing RuntimeError.
# This affects all configurations, not just LoRA.
self._engines_initialized = False
if self.lora_adapters:
logging.info(f"LoRA mode: {len(self.lora_adapters)} adapter(s) will load on first request")
for adapter in self.lora_adapters:
logging.info(f" - {adapter.name}: {adapter.path}")
else:
logging.info("OpenAI engines will initialize on first request")
# Handle both integer and boolean string values for RAW_OPENAI_OUTPUT
raw_output_env = os.getenv("RAW_OPENAI_OUTPUT", "1")
if raw_output_env.lower() in ('true', 'false'):
self.raw_openai_output = raw_output_env.lower() == 'true'
else:
self.raw_openai_output = bool(int(raw_output_env))
def _load_lora_adapters(self):
adapters = []
try:
adapters = json.loads(os.getenv("LORA_MODULES", '[]'))
except Exception as e:
logging.info(f"---Initialized adapter json load error: {e}")
for i, adapter in enumerate(adapters):
try:
adapters[i] = LoRAModulePath(**adapter)
logging.info(f"---Initialized adapter: {adapter}")
except Exception as e:
logging.info(f"---Initialized adapter not worked: {e}")
continue
return adapters
async def _ensure_engines_initialized(self):
"""Initialize engines on first request to avoid event loop mismatch.
In Runpod Serverless, the startup code runs outside the handler's event
loop. Deferring initialization to the first request ensures all async
components (tokenizer pool, serving engines, LoRA state) are created in
the correct event loop context.
"""
if not self._engines_initialized:
logging.info("Initializing OpenAI serving engines...")
await self._initialize_engines()
self._engines_initialized = True
logging.info("OpenAI serving engines initialized successfully")
async def _initialize_engines(self):
self.model_config = self.llm.model_config
self.base_model_paths = [
BaseModelPath(name=self.served_model_name, model_path=self.engine_args.model)
]
self.serving_models = OpenAIServingModels(
engine_client=self.llm,
base_model_paths=self.base_model_paths,
lora_modules=self.lora_adapters,
)
await self.serving_models.init_static_loras()
def _get_num_gpu_shard(self):
final_num_gpu_shard = 1
if bool(int(os.getenv("USE_TENSOR_PARALLEL", 0))):
env_num_gpu_shard = int(os.getenv("TENSOR_PARALLEL_SIZE", 1))
num_gpu_available = torch.cuda.device_count()
final_num_gpu_shard = min(env_num_gpu_shard, num_gpu_available)
logging.info("Using %s GPU shards", final_num_gpu_shard)
return final_num_gpu_shard
def _get_max_model_len(self):
max_model_len = os.getenv("MAX_MODEL_LEN")
return int(max_model_len) if max_model_len is not None else None
def _get_n_current_jobs(self):
total_sequences = len(self.llm.engine.scheduler.waiting) + len(self.llm.engine.scheduler.swapped) + len(self.llm.engine.scheduler.running)
return total_sequences
# Get chat template from vLLM tokenizer if available
chat_template = None
if self.tokenizer and hasattr(self.tokenizer, 'tokenizer'):
chat_template = self.tokenizer.tokenizer.chat_template
self.chat_engine = OpenAIServingChat(
engine_client=self.llm,
models=self.serving_models,
response_role=self.response_role,
request_logger=None,
chat_template=chat_template,
chat_template_content_format="auto",
trust_request_chat_template=os.getenv('TRUST_REQUEST_CHAT_TEMPLATE', 'false').lower() == 'true',
return_tokens_as_token_ids=os.getenv('RETURN_TOKENS_AS_TOKEN_IDS', 'false').lower() == 'true',
reasoning_parser=os.getenv('REASONING_PARSER', "") or "",
enable_auto_tools=os.getenv('ENABLE_AUTO_TOOL_CHOICE', 'false').lower() == 'true',
exclude_tools_when_tool_choice_none=os.getenv('EXCLUDE_TOOLS_WHEN_TOOL_CHOICE_NONE', 'false').lower() == 'true',
tool_parser=os.getenv('TOOL_CALL_PARSER', "") or None,
enable_prompt_tokens_details=os.getenv('ENABLE_PROMPT_TOKENS_DETAILS', 'false').lower() == 'true',
enable_force_include_usage=os.getenv('ENABLE_FORCE_INCLUDE_USAGE', 'false').lower() == 'true',
enable_log_outputs=os.getenv('ENABLE_LOG_OUTPUTS', 'false').lower() == 'true',
log_error_stack=os.getenv('LOG_ERROR_STACK', 'false').lower() == 'true',
)
self.completion_engine = OpenAIServingCompletion(
engine_client=self.llm,
models=self.serving_models,
request_logger=None,
return_tokens_as_token_ids=os.getenv('RETURN_TOKENS_AS_TOKEN_IDS', 'false').lower() == 'true',
enable_prompt_tokens_details=os.getenv('ENABLE_PROMPT_TOKENS_DETAILS', 'false').lower() == 'true',
enable_force_include_usage=os.getenv('ENABLE_FORCE_INCLUDE_USAGE', 'false').lower() == 'true',
log_error_stack=os.getenv('LOG_ERROR_STACK', 'false').lower() == 'true',
)
def _get_quantization(self):
quantization = os.getenv("QUANTIZATION", "").lower()
return quantization if quantization in ["awq", "squeezellm", "gptq"] else None
def concurrency_modifier(self, current_concurrency):
n_current_jobs = self._get_n_current_jobs()
requested_concurrency = max(0, self.serverless_config.max_concurrency - n_current_jobs)
if not self.config["disable_log_stats"]:
logging.info("Current Jobs: %s", n_current_jobs)
logging.info("Concurrency Modifier Requested Jobs: %s", requested_concurrency)
return requested_concurrency
if hasattr(self.chat_engine, 'warmup'):
await self.chat_engine.warmup()
async def generate(self, openai_request: JobInput):
# Ensure engines are ready (no-op if already initialized at startup)
await self._ensure_engines_initialized()
if openai_request.openai_route == "/v1/models":
yield await self._handle_model_request()
elif openai_request.openai_route in ["/v1/chat/completions", "/v1/completions"]:
async for response in self._handle_chat_or_completion_request(openai_request):
yield response
else:
yield create_error_response("Invalid route").model_dump()
async def _handle_model_request(self):
models = await self.serving_models.show_available_models()
return models.model_dump()
async def _handle_chat_or_completion_request(self, openai_request: JobInput):
if openai_request.openai_route == "/v1/chat/completions":
request_class = ChatCompletionRequest
generator_function = self.chat_engine.create_chat_completion
elif openai_request.openai_route == "/v1/completions":
request_class = CompletionRequest
generator_function = self.completion_engine.create_completion
try:
request = request_class(
**openai_request.openai_input
)
except Exception as e:
yield create_error_response(str(e)).model_dump()
return
dummy_request = DummyRequest()
response_generator = await generator_function(request, raw_request=dummy_request)
if not openai_request.openai_input.get("stream") or isinstance(response_generator, ErrorResponse):
yield response_generator.model_dump()
else:
batch = []
batch_token_counter = 0
batch_size = BatchSize(self.default_batch_size, self.min_batch_size, self.batch_size_growth_factor)
async for chunk_str in response_generator:
if "data" in chunk_str:
if self.raw_openai_output:
data = chunk_str
elif "[DONE]" in chunk_str:
continue
else:
data = json.loads(chunk_str.removeprefix("data: ").rstrip("\n\n")) if not self.raw_openai_output else chunk_str
batch.append(data)
batch_token_counter += 1
if batch_token_counter >= batch_size.current_batch_size:
if self.raw_openai_output:
batch = "".join(batch)
yield batch
batch = []
batch_token_counter = 0
batch_size.update()
if batch:
if self.raw_openai_output:
batch = "".join(batch)
yield batch
+461
View File
@@ -0,0 +1,461 @@
import os
import json
import logging
from typing import get_origin, get_args
from torch.cuda import device_count
from vllm import AsyncEngineArgs
from vllm.model_executor.model_loader.tensorizer import TensorizerConfig
from src.utils import convert_limit_mm_per_prompt
# Backward-compat: env var names users already know → engine arg name
ENV_ALIASES = {
"MODEL_NAME": "model",
"MODEL_REVISION": "revision",
"TOKENIZER_NAME": "tokenizer",
}
# Literal defaults from original worker (used when env/local do not set a value)
DEFAULT_ARGS = {
"disable_log_stats": False,
"enable_log_requests": False,
"gpu_memory_utilization": 0.95,
"pipeline_parallel_size": 1,
"tensor_parallel_size": 1,
"skip_tokenizer_init": False,
"tokenizer_mode": "auto",
"trust_remote_code": False,
"load_format": "auto",
"dtype": "auto",
"kv_cache_dtype": "auto",
"seed": 0,
"worker_use_ray": False,
"block_size": 16,
"enable_prefix_caching": False,
"disable_sliding_window": False,
"swap_space": 4,
"cpu_offload_gb": 0,
"max_num_seqs": 256,
"max_logprobs": 20,
"enforce_eager": False,
"max_seq_len_to_capture": 8192,
"disable_custom_all_reduce": False,
"tokenizer_pool_size": 0,
"tokenizer_pool_type": "ray",
"enable_lora": False,
"max_loras": 1,
"max_lora_rank": 16,
"enable_prompt_adapter": False,
"max_prompt_adapters": 1,
"max_prompt_adapter_token": 0,
"fully_sharded_loras": False,
"lora_extra_vocab_size": 256,
"lora_dtype": "auto",
"device": "auto",
"ray_workers_use_nsight": False,
"num_lookahead_slots": 0,
"scheduler_delay_factor": 0.0,
"guided_decoding_backend": "outlines",
"spec_decoding_acceptance_method": "rejection_sampler",
"stream_interval": 1,
}
def _resolve_field_type(field_type: type) -> type:
"""Resolve Optional/Union to the concrete type for conversion."""
origin = get_origin(field_type)
args = get_args(field_type) if hasattr(field_type, "__args__") else ()
if origin is not None:
# Optional[X] is Union[X, None]; X | None is UnionType
non_none = [a for a in args if a is not type(None)]
if non_none:
return non_none[0]
return field_type
def _convert_env_value_to_field_type(value: str, field_name: str, field_type: type):
"""Convert env var string to the type expected by AsyncEngineArgs for this field."""
val = value.strip() if isinstance(value, str) else value
if val in ("", "None", "none"):
args = get_args(field_type) if hasattr(field_type, "__args__") else ()
if type(None) in (args or ()):
return None
raise ValueError("empty value not allowed for non-optional field")
effective_type = _resolve_field_type(field_type)
# bool
if effective_type is bool:
return str(val).lower() in ("true", "1", "yes", "on")
# int
if effective_type is int:
return int(val)
# float
if effective_type is float:
return float(val)
# str
if effective_type is str:
return str(val)
# dict, list, or complex (try JSON)
origin = get_origin(effective_type)
if effective_type in (dict, list) or origin in (dict, list):
try:
return json.loads(val)
except json.JSONDecodeError:
return val
# tuple (e.g. long_lora_scaling_factors) — comma-separated or JSON array
if effective_type is tuple or origin is tuple:
args = get_args(field_type) if hasattr(field_type, "__args__") else ()
elem_types = [a for a in args if a is not Ellipsis]
elem_type = elem_types[0] if elem_types else str
try:
parsed = json.loads(val)
if isinstance(parsed, list):
return tuple(elem_type(x) for x in parsed)
except (json.JSONDecodeError, TypeError):
pass
return tuple(elem_type(x.strip()) for x in str(val).split(",") if x.strip())
# Fallback: try int, float, then str
try:
return int(val)
except ValueError:
pass
try:
return float(val)
except ValueError:
pass
return str(val)
def _get_args_from_env_auto_discover() -> dict:
"""Auto-discover engine args from env vars using UPPERCASED field names.
For every field in AsyncEngineArgs, check os.getenv(FIELD_NAME).
E.g. MAX_MODEL_LEN=4096 -> max_model_len=4096.
Uses same type conversion as before; supports all vLLM engine args without manual listing.
"""
args = {}
valid_fields = AsyncEngineArgs.__dataclass_fields__
for field_name, field in valid_fields.items():
env_key = field_name.upper()
value = os.environ.get(env_key)
if value is None:
continue
try:
args[field_name] = _convert_env_value_to_field_type(
value, field_name, field.type
)
except (ValueError, TypeError, json.JSONDecodeError) as e:
logging.warning(
"Skip env %s=%r: %s", env_key, value, e
)
return args
def _apply_env_aliases(args: dict) -> None:
"""Apply ENV_ALIASES: if MODEL_NAME etc. are set, set the target engine arg."""
valid_fields = AsyncEngineArgs.__dataclass_fields__
for alias, target in ENV_ALIASES.items():
value = os.environ.get(alias)
if value is None or target not in valid_fields:
continue
try:
args[target] = _convert_env_value_to_field_type(
value, target, valid_fields[target].type
)
except (ValueError, TypeError, json.JSONDecodeError) as e:
logging.warning("Skip env alias %s=%r: %s", alias, value, e)
def get_speculative_config():
"""Build speculative decoding configuration from environment variables.
Supports two modes:
1. Full JSON config via SPECULATIVE_CONFIG env var
2. Individual env vars for common settings
"""
# Option 1: Full JSON configuration
spec_config_json = os.getenv('SPECULATIVE_CONFIG')
if spec_config_json:
try:
config = json.loads(spec_config_json)
logging.info(f"Using speculative config from SPECULATIVE_CONFIG: {config}")
return config
except json.JSONDecodeError as e:
logging.error(f"Failed to parse SPECULATIVE_CONFIG JSON: {e}")
return None
# Option 2: Build config from individual environment variables
spec_method = os.getenv('SPECULATIVE_METHOD')
spec_model = os.getenv('SPECULATIVE_MODEL')
_num_spec_tokens = os.getenv('NUM_SPECULATIVE_TOKENS')
_ngram_max = os.getenv('NGRAM_PROMPT_LOOKUP_MAX')
_ngram_min = os.getenv('NGRAM_PROMPT_LOOKUP_MIN')
# Convert numeric vars to int so '0' (hub.json default) is treated as unset
num_spec_tokens = (int(_num_spec_tokens) or None) if _num_spec_tokens else None
ngram_max = (int(_ngram_max) or None) if _ngram_max else None
ngram_min = (int(_ngram_min) or None) if _ngram_min else None
if not any([spec_method, spec_model, ngram_max]):
return None
config = {}
# Determine method
if spec_method:
config['method'] = spec_method
elif ngram_max and not spec_model:
config['method'] = 'ngram'
elif spec_model:
model_lower = spec_model.lower()
if 'eagle3' in model_lower:
config['method'] = 'eagle3'
elif 'eagle' in model_lower:
config['method'] = 'eagle'
elif 'medusa' in model_lower:
config['method'] = 'medusa'
else:
config['method'] = 'draft_model'
if spec_model:
config['model'] = spec_model
if num_spec_tokens:
config['num_speculative_tokens'] = num_spec_tokens
if ngram_max:
config['prompt_lookup_max'] = ngram_max
if ngram_min:
config['prompt_lookup_min'] = ngram_min
draft_tp = os.getenv('SPECULATIVE_DRAFT_TENSOR_PARALLEL_SIZE')
if draft_tp:
config['draft_tensor_parallel_size'] = int(draft_tp)
spec_max_len = os.getenv('SPECULATIVE_MAX_MODEL_LEN')
if spec_max_len:
config['max_model_len'] = int(spec_max_len)
disable_batch = os.getenv('SPECULATIVE_DISABLE_BY_BATCH_SIZE')
if disable_batch:
config['disable_by_batch_size'] = int(disable_batch)
spec_quant = os.getenv('SPECULATIVE_QUANTIZATION')
if spec_quant:
config['quantization'] = spec_quant
spec_revision = os.getenv('SPECULATIVE_MODEL_REVISION')
if spec_revision:
config['revision'] = spec_revision
spec_eager = os.getenv('SPECULATIVE_ENFORCE_EAGER')
if spec_eager:
config['enforce_eager'] = spec_eager.lower() == 'true'
if config:
logging.info(f"Built speculative config from env vars: {config}")
return config
return None
def _resolve_max_model_len(model, trust_remote_code=False, revision=None):
"""Resolve max_model_len from the model's HuggingFace config."""
try:
from transformers import AutoConfig
config = AutoConfig.from_pretrained(
model,
trust_remote_code=trust_remote_code,
revision=revision,
)
for attr in ('max_position_embeddings', 'n_positions', 'max_seq_len', 'seq_length'):
val = getattr(config, attr, None)
if val is not None:
logging.info(f"Resolved max_model_len={val} from model config ({attr})")
return val
except Exception as e:
logging.warning(f"Could not resolve max_model_len from model config: {e}")
return None
def _local_args_to_engine_args(local: dict) -> dict:
"""Map local args (e.g. from /local_model_args.json) to engine arg names and filter."""
valid = AsyncEngineArgs.__dataclass_fields__
out = {}
for k, v in local.items():
target = ENV_ALIASES.get(k, k.lower().replace("-", "_"))
if target not in valid or v in (None, "", "None"):
continue
out[target] = v
return out
def _sanitize_hf_overrides(hf_overrides: dict) -> dict | None:
"""Strip rope_scaling from hf_overrides sub-configs if vLLM rejects them.
Older vLLM (<0.7) required explicit mrope rope_scaling in hf_overrides for
models like Qwen2-VL. Newer vLLM auto-detects mrope and raises a ValueError
in patch_rope_scaling_dict when it finds conflicting rope_type values. Strip
the offending rope_scaling so the model loads with its native config.
"""
if not isinstance(hf_overrides, dict):
return hf_overrides
try:
from vllm.transformers_utils.config import patch_rope_scaling_dict
except ImportError:
return hf_overrides
import copy
cleaned = {}
changed = False
for key, value in hf_overrides.items():
if isinstance(value, dict) and "rope_scaling" in value:
rope_scaling = value.get("rope_scaling")
if isinstance(rope_scaling, dict):
try:
patch_rope_scaling_dict(copy.deepcopy(rope_scaling))
except (ValueError, Exception) as e:
logging.warning(
"Stripping hf_overrides['%s']['rope_scaling'] because vLLM "
"rejected it (%s). Newer vLLM auto-detects rope scaling from "
"the model config.", key, e
)
stripped = {k: v for k, v in value.items() if k != "rope_scaling"}
cleaned[key] = stripped if stripped else None
changed = True
continue
cleaned[key] = value
if not changed:
return hf_overrides
result = {k: v for k, v in cleaned.items() if v is not None}
return result or None
def get_local_args():
"""
Retrieve local arguments from a JSON file.
Returns:
dict: Local arguments.
"""
if not os.path.exists("/local_model_args.json"):
return {}
with open("/local_model_args.json", "r") as f:
local_args = json.load(f)
if local_args.get("MODEL_NAME") is None:
logging.warning("Model name not found in /local_model_args.json. There maybe was a problem when baking the model in.")
logging.info(f"Using baked in model with args: {local_args}")
os.environ["TRANSFORMERS_OFFLINE"] = "1"
os.environ["HF_HUB_OFFLINE"] = "1"
return local_args
def get_engine_args():
# Start with worker custom defaults (only where we differ from vLLM)
args = dict(DEFAULT_ARGS)
# Auto-discover: every AsyncEngineArgs field from env UPPERCASED (e.g. MAX_MODEL_LEN)
args.update(_get_args_from_env_auto_discover())
# Backward-compat aliases (MODEL_NAME → model, etc.)
_apply_env_aliases(args)
# Local baked-in model overrides
local = get_local_args()
if local:
args.update(_local_args_to_engine_args(local))
# Filter to valid engine args and drop sentinel empty values
valid_fields = AsyncEngineArgs.__dataclass_fields__
args = {
k: v for k, v in args.items()
if k in valid_fields and v not in (None, "", "None")
}
# Special conversion for limit_mm_per_prompt (e.g. "image=1,video=0")
limit_mm_env = os.getenv("LIMIT_MM_PER_PROMPT")
if limit_mm_env is not None:
args["limit_mm_per_prompt"] = convert_limit_mm_per_prompt(limit_mm_env)
# if args.get("TENSORIZER_URI"): TODO: add back once tensorizer is ready
# args["load_format"] = "tensorizer"
# args["model_loader_extra_config"] = TensorizerConfig(tensorizer_uri=args["TENSORIZER_URI"], num_readers=None)
# logging.info(f"Using tensorized model from {args['TENSORIZER_URI']}")
if "hf_overrides" in args:
sanitized = _sanitize_hf_overrides(args["hf_overrides"])
if sanitized:
args["hf_overrides"] = sanitized
else:
del args["hf_overrides"]
if args.get("load_format") == "bitsandbytes":
args["quantization"] = args["load_format"]
# Set tensor parallel size and max parallel loading workers if more than 1 GPU is available
num_gpus = device_count()
if num_gpus > 1:
args["tensor_parallel_size"] = num_gpus
args["max_parallel_loading_workers"] = None
if os.getenv("MAX_PARALLEL_LOADING_WORKERS"):
logging.warning("Overriding MAX_PARALLEL_LOADING_WORKERS with None because more than 1 GPU is available.")
# Deprecated env args backwards compatibility
if args.get("kv_cache_dtype") == "fp8_e5m2":
args["kv_cache_dtype"] = "fp8"
logging.warning("Using fp8_e5m2 is deprecated. Please use fp8 instead.")
if os.getenv("MAX_CONTEXT_LEN_TO_CAPTURE"):
args["max_seq_len_to_capture"] = int(os.getenv("MAX_CONTEXT_LEN_TO_CAPTURE"))
logging.warning("Using MAX_CONTEXT_LEN_TO_CAPTURE is deprecated. Please use MAX_SEQ_LEN_TO_CAPTURE instead.")
# if "gemma-2" in args.get("model", "").lower():
# os.environ["VLLM_ATTENTION_BACKEND"] = "FLASHINFER"
# logging.info("Using FLASHINFER for gemma-2 model.")
# Set max_num_batched_tokens to max_model_len for unlimited batching.
# vLLM defaults max_num_batched_tokens to 2048 when None, which is too low.
if args.get("max_model_len") == 0:
args["max_model_len"] = None
if args.get("max_num_batched_tokens") == 0:
args["max_num_batched_tokens"] = None
if args.get("max_num_batched_tokens") is None:
max_model_len = args.get("max_model_len")
if max_model_len is None:
max_model_len = _resolve_max_model_len(
args.get("model"),
trust_remote_code=args.get("trust_remote_code", False),
revision=args.get("revision"),
)
if max_model_len is not None:
args["max_num_batched_tokens"] = max_model_len
logging.info(f"Setting max_num_batched_tokens to {max_model_len}")
# VLLM_ATTENTION_BACKEND is deprecated, migrate to attention_backend
if os.getenv('VLLM_ATTENTION_BACKEND'):
logging.warning(
"VLLM_ATTENTION_BACKEND env var is deprecated. "
"Use ATTENTION_BACKEND instead (maps to --attention-backend CLI arg)."
)
if not args.get('attention_backend'):
args['attention_backend'] = os.getenv('VLLM_ATTENTION_BACKEND')
# DISABLE_LOG_REQUESTS is deprecated, use ENABLE_LOG_REQUESTS instead
if os.getenv('DISABLE_LOG_REQUESTS'):
logging.warning(
"DISABLE_LOG_REQUESTS env var is deprecated. "
"Use ENABLE_LOG_REQUESTS instead (default: False)."
)
# Honor old behavior: if DISABLE_LOG_REQUESTS=true, don't enable logging
if os.getenv('DISABLE_LOG_REQUESTS', 'False').lower() == 'true':
args['enable_log_requests'] = False
# Add speculative decoding configuration if present
speculative_config = get_speculative_config()
if speculative_config:
args["speculative_config"] = speculative_config
return AsyncEngineArgs(**args)
+49 -61
View File
@@ -1,67 +1,55 @@
#!/usr/bin/env python
from typing import Generator
import sys
import multiprocessing
import traceback
import runpod
from utils import validate_sampling_params, random_uuid
from engine import vLLMEngine
from runpod import RunPodLogger
vllm_engine = vLLMEngine()
async def handler(job: dict) -> Generator[dict, None, None]:
job_input = job["input"]
llm_input = job_input.get("messages", job_input.get("prompt"))
apply_chat_template = job_input.get("apply_chat_template", False)
log = RunPodLogger()
if apply_chat_template or isinstance(llm_input, list):
llm_input = vllm_engine.tokenizer.apply_chat_template(llm_input)
vllm_engine = None
openai_engine = None
stream = job_input.get("stream", False)
batch_size = job_input.get("batch_size", vllm_engine.serverless_config.default_batch_size)
sampling_params = job_input.get("sampling_params", {})
validated_params = validate_sampling_params(sampling_params)
request_id = random_uuid()
results_generator = vllm_engine.llm.generate(
llm_input, validated_params, request_id
async def handler(job):
try:
from utils import JobInput
job_input = JobInput(job["input"])
engine = openai_engine if job_input.openai_route else vllm_engine
results_generator = engine.generate(job_input)
async for batch in results_generator:
yield batch
except Exception as e:
error_str = str(e)
full_traceback = traceback.format_exc()
log.error(f"Error during inference: {error_str}")
log.error(f"Full traceback:\n{full_traceback}")
# CUDA errors = worker is broken, exit to let RunPod spin up a healthy one
if "CUDA" in error_str or "cuda" in error_str:
log.error("Terminating worker due to CUDA/GPU error")
sys.exit(1)
yield {"error": error_str}
# Only run in main process to prevent re-initialization when vLLM spawns worker subprocesses
if __name__ == "__main__" or multiprocessing.current_process().name == "MainProcess":
try:
from engine import vLLMEngine, OpenAIvLLMEngine
vllm_engine = vLLMEngine()
openai_engine = OpenAIvLLMEngine(vllm_engine)
log.info("vLLM engines initialized successfully")
except Exception as e:
log.error(f"Worker startup failed: {e}\n{traceback.format_exc()}")
sys.exit(1)
runpod.serverless.start(
{
"handler": handler,
"concurrency_modifier": lambda x: vllm_engine.max_concurrency if vllm_engine else 1,
"return_aggregate_stream": True,
}
)
batch = {"tokens": []}
last_output_text = ""
n_input_tokens, is_first_output = 0, True
async for request_output in results_generator:
if is_first_output: # Count input tokens only once
n_input_tokens = len(request_output.prompt_token_ids)
is_first_output = False
for output in request_output.outputs:
if stream:
batch["tokens"].append(
output.text[len(last_output_text):]
)
finished = request_output.finished
if len(batch["tokens"]) >= batch_size or finished:
batch["usage"] = {
"input": n_input_tokens,
"output": len(output.token_ids),
}
batch["finished"] = finished
yield batch
batch = {"tokens": []}
last_output_text = output.text
if not stream:
yield {"tokens": [last_output_text],
"usage": {
"input": n_input_tokens,
"output": len(output.token_ids),
},
"finished": True}
runpod.serverless.start(
{
"handler": handler,
"concurrency_modifier": lambda x: vllm_engine.serverless_config.max_concurrency,
"return_aggregate_stream": True,
}
)
+27
View File
@@ -0,0 +1,27 @@
from transformers import AutoTokenizer
import os
from typing import Union
class TokenizerWrapper:
def __init__(self, tokenizer_name_or_path, tokenizer_revision, trust_remote_code):
print(f"tokenizer_name_or_path: {tokenizer_name_or_path}, tokenizer_revision: {tokenizer_revision}, trust_remote_code: {trust_remote_code}")
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, revision=tokenizer_revision or "main", trust_remote_code=trust_remote_code)
self.custom_chat_template = os.getenv("CUSTOM_CHAT_TEMPLATE")
self.has_chat_template = bool(self.tokenizer.chat_template) or bool(self.custom_chat_template)
if self.custom_chat_template and isinstance(self.custom_chat_template, str):
self.tokenizer.chat_template = self.custom_chat_template
def apply_chat_template(self, input: Union[str, list[dict[str, str]]]) -> str:
if isinstance(input, list):
if not self.has_chat_template:
raise ValueError(
"Chat template does not exist for this model, you must provide a single string input instead of a list of messages"
)
elif isinstance(input, str):
input = [{"role": "user", "content": input}]
else:
raise ValueError("Input must be a string or a list of messages")
return self.tokenizer.apply_chat_template(
input, tokenize=False, add_generation_prompt=True
)
+95 -41
View File
@@ -1,51 +1,105 @@
import os
import logging
from typing import Any, Dict
from vllm import SamplingParams
from vllm.utils import random_uuid
from constants import sampling_param_types, DEFAULT_BATCH_SIZE, DEFAULT_MAX_CONCURRENCY
from http import HTTPStatus
from functools import wraps
from time import time
try:
from vllm.utils import random_uuid
from vllm.entrypoints.openai.engine.protocol import ErrorResponse, ErrorInfo, RequestResponseMetadata
from vllm import SamplingParams
except ImportError:
logging.warning("Error importing vllm, skipping related imports. This is ONLY expected when baking model into docker image from a machine without GPUs")
pass
logging.basicConfig(level=logging.INFO)
# Updated to parse multiple comma-separated multimodal limits (e.g., 'image=1,video=0')
def convert_limit_mm_per_prompt(input_string: str):
result = {}
pairs = input_string.split(',')
for pair in pairs:
key, value = pair.split('=')
result[key] = int(value)
return result
class ServerlessConfig:
def count_physical_cores():
with open('/proc/cpuinfo') as f:
content = f.readlines()
cores = set()
current_physical_id = None
current_core_id = None
for line in content:
if 'physical id' in line:
current_physical_id = line.strip().split(': ')[1]
elif 'core id' in line:
current_core_id = line.strip().split(': ')[1]
cores.add((current_physical_id, current_core_id))
return len(cores)
class JobInput:
def __init__(self, job):
self.llm_input = job.get("messages", job.get("prompt"))
self.stream = job.get("stream", False)
self.max_batch_size = job.get("max_batch_size")
self.apply_chat_template = job.get("apply_chat_template", False)
self.use_openai_format = job.get("use_openai_format", False)
samp_param = job.get("sampling_params", {})
if "max_tokens" not in samp_param:
samp_param["max_tokens"] = 100
self.sampling_params = SamplingParams(**samp_param)
# self.sampling_params = SamplingParams(max_tokens=100, **job.get("sampling_params", {}))
self.request_id = random_uuid()
batch_size_growth_factor = job.get("batch_size_growth_factor")
self.batch_size_growth_factor = float(batch_size_growth_factor) if batch_size_growth_factor else None
min_batch_size = job.get("min_batch_size")
self.min_batch_size = int(min_batch_size) if min_batch_size else None
self.openai_route = job.get("openai_route")
self.openai_input = job.get("openai_input")
class DummyState:
def __init__(self):
self._max_concurrency = int(
os.environ.get("MAX_CONCURRENCY", DEFAULT_MAX_CONCURRENCY)
)
self._default_batch_size = int(
os.environ.get("DEFAULT_BATCH_SIZE", DEFAULT_BATCH_SIZE)
)
self.request_metadata = None
class DummyRequest:
def __init__(self):
self.headers = {}
self.state = DummyState()
async def is_disconnected(self):
return False
@property
def max_concurrency(self):
return self._max_concurrency
@property
def default_batch_size(self):
return self._default_batch_size
def validate_sampling_params(params: Dict[str, Any]) -> SamplingParams:
validated_params = {}
for key, value in params.items():
expected_type = sampling_param_types.get(key)
if value is None:
validated_params[key] = None
continue
if expected_type is None:
continue
if isinstance(expected_type, tuple):
casted_value = next(
(t(value) for t in expected_type if isinstance(value, t)), None
)
class BatchSize:
def __init__(self, max_batch_size, min_batch_size, batch_size_growth_factor):
self.max_batch_size = max_batch_size
self.batch_size_growth_factor = batch_size_growth_factor
self.min_batch_size = min_batch_size
self.is_dynamic = batch_size_growth_factor > 1 and min_batch_size >= 1 and max_batch_size > min_batch_size
if self.is_dynamic:
self.current_batch_size = min_batch_size
else:
casted_value = value if isinstance(value, expected_type) else None
self.current_batch_size = max_batch_size
def update(self):
if self.is_dynamic:
self.current_batch_size = min(self.current_batch_size*self.batch_size_growth_factor, self.max_batch_size)
def create_error_response(message: str, err_type: str = "BadRequestError", status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> ErrorResponse:
return ErrorResponse(error=ErrorInfo(message=message,
type=err_type,
code=status_code.value))
def get_int_bool_env(env_var: str, default: bool) -> bool:
return int(os.getenv(env_var, int(default))) == 1
if casted_value is not None:
validated_params[key] = casted_value
return SamplingParams(**validated_params)
def timer_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time()
result = func(*args, **kwargs)
end = time()
logging.info(f"{func.__name__} completed in {end - start:.2f} seconds")
return result
return wrapper