diksha commited on
Commit
ce587a5
·
1 Parent(s): 19c7557

Runpod model testing

Browse files
.gitattributes CHANGED
@@ -56,3 +56,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
56
  # Video files - compressed
57
  *.mp4 filter=lfs diff=lfs merge=lfs -text
58
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
56
  # Video files - compressed
57
  *.mp4 filter=lfs diff=lfs merge=lfs -text
58
  *.webm filter=lfs diff=lfs merge=lfs -text
59
+ *.json filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:12.1.0-base-ubuntu22.04
2
+
3
+ RUN apt-get update -y \
4
+ && apt-get install -y python3-pip
5
+
6
+ RUN ldconfig /usr/local/cuda-12.1/compat/
7
+
8
+ # Install Python dependencies
9
+ COPY builder/requirements.txt /requirements.txt
10
+ RUN --mount=type=cache,target=/root/.cache/pip \
11
+ python3 -m pip install --upgrade pip && \
12
+ python3 -m pip install --upgrade -r /requirements.txt
13
+
14
+ # Install vLLM (switching back to pip installs since issues that required building fork are fixed and space optimization is not as important since caching) and FlashInfer
15
+ RUN python3 -m pip install vllm==0.6.3 && \
16
+ python3 -m pip install flashinfer -i https://flashinfer.ai/whl/cu121/torch2.3
17
+
18
+ # Setup for Option 2: Building the Image with the Model included
19
+ ARG MODEL_NAME=""
20
+ ARG TOKENIZER_NAME=""
21
+ ARG BASE_PATH="/runpod-volume"
22
+ ARG QUANTIZATION=""
23
+ ARG MODEL_REVISION=""
24
+ ARG TOKENIZER_REVISION=""
25
+
26
+ ENV MODEL_NAME=$MODEL_NAME \
27
+ MODEL_REVISION=$MODEL_REVISION \
28
+ TOKENIZER_NAME=$TOKENIZER_NAME \
29
+ TOKENIZER_REVISION=$TOKENIZER_REVISION \
30
+ BASE_PATH=$BASE_PATH \
31
+ QUANTIZATION=$QUANTIZATION \
32
+ HF_DATASETS_CACHE="${BASE_PATH}/huggingface-cache/datasets" \
33
+ HUGGINGFACE_HUB_CACHE="${BASE_PATH}/huggingface-cache/hub" \
34
+ HF_HOME="${BASE_PATH}/huggingface-cache/hub" \
35
+ HF_HUB_ENABLE_HF_TRANSFER=1
36
+
37
+ ENV PYTHONPATH="/:/vllm-workspace"
38
+
39
+
40
+ COPY src /src
41
+ RUN --mount=type=secret,id=HF_TOKEN,required=false \
42
+ if [ -f /run/secrets/HF_TOKEN ]; then \
43
+ export HF_TOKEN=$(cat /run/secrets/HF_TOKEN); \
44
+ fi && \
45
+ if [ -n "$MODEL_NAME" ]; then \
46
+ python3 /src/download_model.py; \
47
+ fi
48
+
49
+ # Start the handler
50
+ CMD ["python3", "/src/handler.py"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 runpod-workers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md ADDED
@@ -0,0 +1,603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ # OpenAI-Compatible vLLM Serverless Endpoint Worker
4
+ 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.
5
+ <!--
6
+ ![vLLM Version](https://img.shields.io/badge/dynamic/yaml?url=https%3A%2F%2Fraw.githubusercontent.com%2Frunpod-workers%2Fworker-vllm%2Fmain%2Fvllm-base-image%2Fvllm-metadata.yml&query=%24.version&style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjU1cHgiIGhlaWdodD0iNTZweCIgc3R5bGU9InNoYXBlLXJlbmRlcmluZzpnZW9tZXRyaWNQcmVjaXNpb247IHRleHQtcmVuZGVyaW5nOmdlb21ldHJpY1ByZWNpc2lvbjsgaW1hZ2UtcmVuZGVyaW5nOm9wdGltaXplUXVhbGl0eTsgZmlsbC1ydWxlOmV2ZW5vZGQ7IGNsaXAtcnVsZTpldmVub2RkIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI%2BCjxnPjxwYXRoIHN0eWxlPSJvcGFjaXR5OjEiIGZpbGw9IiMzN2E0ZmUiIGQ9Ik0gNTEuNSwwLjUgQyA0Ni41ODIyLDE4LjA4MzggNDEuOTE1NiwzNS43NTA1IDM3LjUsNTMuNUMgMzIuMTY2Nyw1My41IDI2LjgzMzMsNTMuNSAyMS41LDUzLjVDIDIwLjgzMzMsNTMuNSAyMC41LDUzLjE2NjcgMjAuNSw1Mi41QyAyMS4zMzgyLDUyLjE1ODMgMjEuNjcxNiw1MS40OTE2IDIxLjUsNTAuNUMgMjIuMjIyOSw0Ni44NTU1IDIzLjIyMjksNDMuMTg4OSAyNC41LDM5LjVDIDI0LjY5MTcsMzYuMzk5MiAyNS4zNTg0LDMzLjM5OTIgMjYuNSwzMC41QyAyNi4yOTA3LDI5LjkxNCAyNS45NTc0LDI5LjQxNCAyNS41LDI5QyAyNy40NDE0LDI3LjE4NDEgMjguMTA4MSwyNS4xODQxIDI3LjUsMjNDIDI5LjI0MTUsMTguNTM4NyAzMC45MDgyLDE0LjAzODcgMzIuNSw5LjVDIDM4Ljc3NTcsNi4xOTM1OCA0NS4xMDkxLDMuMTkzNTggNTEuNSwwLjUgWiIvPjwvZz4KPGc%2BPHBhdGggc3R5bGU9Im9wYWNpdHk6MC45ODQiIGZpbGw9IiNmY2I3MWQiIGQ9Ik0gMjIuNSwxMi41IEMgMjEuNTA0NiwyNC45ODkgMjEuMTcxMywzNy42NTU3IDIxLjUsNTAuNUMgMjEuNjcxNiw1MS40OTE2IDIxLjMzODIsNTIuMTU4MyAyMC41LDUyLjVDIDEzLjAzMTEsMzkuMjI4NyA2LjM2NDQxLDI1LjU2MjEgMC41LDExLjVDIDguMDE5MDUsMTEuMTc1IDE1LjM1MjQsMTEuNTA4NCAyMi41LDEyLjUgWiIvPjwvZz4KPGc%2BPHBhdGggc3R5bGU9Im9wYWNpdHk6MC4wMiIgZmlsbD0iI2Q3ZGZlOCIgZD0iTSAyMi41LDEyLjUgQyAyMy4xNjY3LDIxLjUgMjMuODMzMywzMC41IDI0LjUsMzkuNUMgMjMuMjIyOSw0My4xODg5IDIyLjIyMjksNDYuODU1NSAyMS41LDUwLjVDIDIxLjE3MTMsMzcuNjU1NyAyMS41MDQ2LDI0Ljk4OSAyMi41LDEyLjUgWiIvPjwvZz4KPGc%2BPHBhdGggc3R5bGU9Im9wYWNpdHk6MC43NTMiIGZpbGw9IiNjZmQ2ZGQiIGQ9Ik0gNTEuNSwwLjUgQyA1Mi42MTI5LDEuOTQ2MzkgNTIuNzc5NiwzLjYxMzA1IDUyLDUuNUMgNDcuODAzNiwyMi4yODg3IDQzLjMwMzYsMzguOTU1MyAzOC41LDU1LjVDIDMyLjUsNTUuNSAyNi41LDU1LjUgMjAuNSw1NS41QyAyMC44MzMzLDU0LjgzMzMgMjEuMTY2Nyw1NC4xNjY3IDIxLjUsNTMuNUMgMjYuODMzMyw1My41IDMyLjE2NjcsNTMuNSAzNy41LDUzLjVDIDQxLjkxNTYsMzUuNzUwNSA0Ni41ODIyLDE4LjA4MzggNTEuNSwwLjUgWiIvPjwvZz4KPC9zdmc%2BCg%3D%3D&label=STABLE%20vLLM%20Version&link=https%3A%2F%2Fgithub.com%2Fvllm-project%2Fvllm)
7
+ ![Worker Version](https://img.shields.io/github/v/tag/runpod-workers/worker-vllm?style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDI2LjUuMywgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IgoJIHZpZXdCb3g9IjAgMCAyMDAwIDIwMDAiIHN0eWxlPSJlbmFibGUtYmFja2dyb3VuZDpuZXcgMCAwIDIwMDAgMjAwMDsiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPgoJLnN0MHtmaWxsOiM2NzNBQjc7fQo8L3N0eWxlPgo8Zz4KCTxnPgoJCTxwYXRoIGNsYXNzPSJzdDAiIGQ9Ik0xMDE3Ljk1LDcxMS4wNGMtNC4yMiwyLjM2LTkuMTgsMy4wMS0xMy44NiwxLjgyTDM4Ni4xNyw1NTUuM2MtNDEuNzItMTAuNzYtODYuMDItMC42My0xMTYuNiwyOS43MwoJCQlsLTEuNCwxLjM5Yy0zNS45MiwzNS42NS0yNy41NSw5NS44LDE2Ljc0LDEyMC4zbDU4NC4zMiwzMjQuMjNjMzEuMzYsMTcuNCw1MC44Miw1MC40NSw1MC44Miw4Ni4zMnY4MDYuNzYKCQkJYzAsMzUuNDktMzguNDEsNTcuNjctNjkuMTUsMzkuOTRsLTcwMy4xNS00MDUuNjRjLTIzLjYtMTMuNjEtMzguMTMtMzguNzgtMzguMTMtNjYuMDJWNjY2LjYzYzAtODcuMjQsNDYuNDUtMTY3Ljg5LDEyMS45Mi0yMTEuNjYKCQkJTDkzMy44NSw0Mi4xNWMyMy40OC0xMy44LDUxLjQ3LTE3LjcsNzcuODMtMTAuODRsNzQ1LjcxLDE5NC4xYzMxLjUzLDguMjEsMzYuOTksNTAuNjUsOC41Niw2Ni41N0wxMDE3Ljk1LDcxMS4wNHoiLz4KCQk8cGF0aCBjbGFzcz0ic3QwIiBkPSJNMTUyNy43NSw1MzYuMzhsMTI4Ljg5LTc5LjYzbDE4OS45MiwxMDkuMTdjMjcuMjQsMTUuNjYsNDMuOTcsNDQuNzMsNDMuODIsNzYuMTVsLTQsODU3LjYKCQkJYy0wLjExLDI0LjM5LTEzLjE1LDQ2Ljg5LTM0LjI1LDU5LjExbC03MDEuNzUsNDA2LjYxYy0zMi4zLDE4LjcxLTcyLjc0LTQuNTktNzIuNzQtNDEuOTJ2LTc5Ny40MwoJCQljMC0zOC45OCwyMS4wNi03NC45MSw1NS4wNy05My45Nmw1OTAuMTctMzMwLjUzYzE4LjIzLTEwLjIxLDE4LjY1LTM2LjMsMC43NS00Ny4wOUwxNTI3Ljc1LDUzNi4zOHoiLz4KCQk8cGF0aCBjbGFzcz0ic3QwIiBkPSJNMTUyNC4wMSw2NjUuOTEiLz4KCTwvZz4KPC9nPgo8L3N2Zz4K&logoColor=%23ffffff&label=STABLE%20Worker%20Version&color=%23673ab7)
8
+ ![vLLM Version](https://img.shields.io/badge/dynamic/yaml?url=https%3A%2F%2Fraw.githubusercontent.com%2Frunpod-workers%2Fworker-vllm%2Fmain%2Fvllm-base-image%2Fvllm-metadata.yml&query=%24.dev_version&style=for-the-badge&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjU1cHgiIGhlaWdodD0iNTZweCIgc3R5bGU9InNoYXBlLXJlbmRlcmluZzpnZW9tZXRyaWNQcmVjaXNpb247IHRleHQtcmVuZGVyaW5nOmdlb21ldHJpY1ByZWNpc2lvbjsgaW1hZ2UtcmVuZGVyaW5nOm9wdGltaXplUXVhbGl0eTsgZmlsbC1ydWxlOmV2ZW5vZGQ7IGNsaXAtcnVsZTpldmVub2RkIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI%2BCjxnPjxwYXRoIHN0eWxlPSJvcGFjaXR5OjEiIGZpbGw9IiMzN2E0ZmUiIGQ9Ik0gNTEuNSwwLjUgQyA0Ni41ODIyLDE4LjA4MzggNDEuOTE1NiwzNS43NTA1IDM3LjUsNTMuNUMgMzIuMTY2Nyw1My41IDI2LjgzMzMsNTMuNSAyMS41LDUzLjVDIDIwLjgzMzMsNTMuNSAyMC41LDUzLjE2NjcgMjAuNSw1Mi41QyAyMS4zMzgyLDUyLjE1ODMgMjEuNjcxNiw1MS40OTE2IDIxLjUsNTAuNUMgMjIuMjIyOSw0Ni44NTU1IDIzLjIyMjksNDMuMTg4OSAyNC41LDM5LjVDIDI0LjY5MTcsMzYuMzk5MiAyNS4zNTg0LDMzLjM5OTIgMjYuNSwzMC41QyAyNi4yOTA3LDI5LjkxNCAyNS45NTc0LDI5LjQxNCAyNS41LDI5QyAyNy40NDE0LDI3LjE4NDEgMjguMTA4MSwyNS4xODQxIDI3LjUsMjNDIDI5LjI0MTUsMTguNTM4NyAzMC45MDgyLDE0LjAzODcgMzIuNSw5LjVDIDM4Ljc3NTcsNi4xOTM1OCA0NS4xMDkxLDMuMTkzNTggNTEuNSwwLjUgWiIvPjwvZz4KPGc%2BPHBhdGggc3R5bGU9Im9wYWNpdHk6MC45ODQiIGZpbGw9IiNmY2I3MWQiIGQ9Ik0gMjIuNSwxMi41IEMgMjEuNTA0NiwyNC45ODkgMjEuMTcxMywzNy42NTU3IDIxLjUsNTAuNUMgMjEuNjcxNiw1MS40OTE2IDIxLjMzODIsNTIuMTU4MyAyMC41LDUyLjVDIDEzLjAzMTEsMzkuMjI4NyA2LjM2NDQxLDI1LjU2MjEgMC41LDExLjVDIDguMDE5MDUsMTEuMTc1IDE1LjM1MjQsMTEuNTA4NCAyMi41LDEyLjUgWiIvPjwvZz4KPGc%2BPHBhdGggc3R5bGU9Im9wYWNpdHk6MC4wMiIgZmlsbD0iI2Q3ZGZlOCIgZD0iTSAyMi41LDEyLjUgQyAyMy4xNjY3LDIxLjUgMjMuODMzMywzMC41IDI0LjUsMzkuNUMgMjMuMjIyOSw0My4xODg5IDIyLjIyMjksNDYuODU1NSAyMS41LDUwLjVDIDIxLjE3MTMsMzcuNjU1NyAyMS41MDQ2LDI0Ljk4OSAyMi41LDEyLjUgWiIvPjwvZz4KPGc%2BPHBhdGggc3R5bGU9Im9wYWNpdHk6MC43NTMiIGZpbGw9IiNjZmQ2ZGQiIGQ9Ik0gNTEuNSwwLjUgQyA1Mi42MTI5LDEuOTQ2MzkgNTIuNzc5NiwzLjYxMzA1IDUyLDUuNUMgNDcuODAzNiwyMi4yODg3IDQzLjMwMzYsMzguOTU1MyAzOC41LDU1LjVDIDMyLjUsNTUuNSAyNi41LDU1LjUgMjAuNSw1NS41QyAyMC44MzMzLDU0LjgzMzMgMjEuMTY2Nyw1NC4xNjY3IDIxLjUsNTMuNUMgMjYuODMzMyw1My41IDMyLjE2NjcsNTMuNSAzNy41LDUzLjVDIDQxLjkxNTYsMzUuNzUwNSA0Ni41ODIyLDE4LjA4MzggNTEuNSwwLjUgWiIvPjwvZz4KPC9zdmc%2BCg%3D%3D&label=DEV%20vLLM%20Version%20&link=https%3A%2F%2Fgithub.com%2Fvllm-project%2Fvllm)\
9
+ ![Docker Pulls](https://img.shields.io/docker/pulls/runpod/worker-vllm?style=for-the-badge&logo=docker&label=Docker%20Pulls&link=https%3A%2F%2Fhub.docker.com%2Frepository%2Fdocker%2Frunpod%2Fworker-vllm%2Fgeneral) -->
10
+ <!--
11
+ ![Docker Automatic Build](https://img.shields.io/github/actions/workflow/status/runpod-workers/worker-vllm/docker-build-release.yml?style=flat&label=BUILD) -->
12
+
13
+
14
+ </div>
15
+
16
+ # News:
17
+
18
+ ### 1. UI for Deploying vLLM Worker on RunPod console:
19
+ ![Demo of Deploying vLLM Worker on RunPod console with new UI](media/ui_demo.gif)
20
+
21
+ ### 2. Worker vLLM `v1.6.0` with vLLM `0.6.3` now available under `stable` tags
22
+
23
+ Update v1.6.0 is now available, use the image tag `runpod/worker-v1-vllm:v1.6.0stable-cuda12.1.0`.
24
+
25
+ ### 3. OpenAI-Compatible [Embedding Worker](https://github.com/runpod-workers/worker-infinity-embedding) Released
26
+ Deploy your own OpenAI-compatible Serverless Endpoint on RunPod with multiple embedding models and fast inference for RAG and more!
27
+
28
+
29
+
30
+ ### 4. Caching Accross RunPod Machines
31
+ Worker vLLM is now cached on all RunPod machines, resulting in near-instant deployment! Previously, downloading and extracting the image took 3-5 minutes on average.
32
+
33
+
34
+ ## Table of Contents
35
+ - [Setting up the Serverless Worker](#setting-up-the-serverless-worker)
36
+ - [Option 1: Deploy Any Model Using Pre-Built Docker Image **[RECOMMENDED]**](#option-1-deploy-any-model-using-pre-built-docker-image-recommended)
37
+ - [Prerequisites](#prerequisites)
38
+ - [Environment Variables](#environment-variables)
39
+ - [LLM Settings](#llm-settings)
40
+ - [Tokenizer Settings](#tokenizer-settings)
41
+ - [Tensor Parallelism (Multi-GPU) Settings](#tensor-parallelism-multi-gpu-settings)
42
+ - [System Settings](#system-settings)
43
+ - [Streaming Batch Size](#streaming-batch-size)
44
+ - [OpenAI Settings](#openai-settings)
45
+ - [Serverless Settings](#serverless-settings)
46
+ - [Option 2: Build Docker Image with Model Inside](#option-2-build-docker-image-with-model-inside)
47
+ - [Prerequisites](#prerequisites-1)
48
+ - [Arguments](#arguments)
49
+ - [Example: Building an image with OpenChat-3.5](#example-building-an-image-with-openchat-35)
50
+ - [(Optional) Including Huggingface Token](#optional-including-huggingface-token)
51
+ - [Compatible Model Architectures](#compatible-model-architectures)
52
+ - [Usage: OpenAI Compatibility](#usage-openai-compatibility)
53
+ - [Modifying your OpenAI Codebase to use your deployed vLLM Worker](#modifying-your-openai-codebase-to-use-your-deployed-vllm-worker)
54
+ - [OpenAI Request Input Parameters](#openai-request-input-parameters)
55
+ - [Chat Completions](#chat-completions)
56
+ - [Examples: Using your RunPod endpoint with OpenAI](#examples-using-your-runpod-endpoint-with-openai)
57
+ - [Usage: standard](#non-openai-usage)
58
+ - [Input Request Parameters](#input-request-parameters)
59
+ - [Text Input Formats](#text-input-formats)
60
+ - [Sampling Parameters](#sampling-parameters)
61
+ - [Worker Config](#worker-config)
62
+ - [Writing your worker-config.json](#writing-your-worker-configjson)
63
+ - [Example of schema](#example-of-schema)
64
+ - [Example of versions](#example-of-versions)
65
+
66
+ # Setting up the Serverless Worker
67
+
68
+ ### Option 1: Deploy Any Model Using Pre-Built Docker Image [Recommended]
69
+
70
+ > [!NOTE]
71
+ > You can now deploy from the dedicated UI on the RunPod console with all of the settings and choices listed.
72
+ > Try now by accessing in Explore or Serverless pages on the RunPod console!
73
+
74
+
75
+ 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:
76
+
77
+ ---
78
+
79
+ ## RunPod Worker Images
80
+
81
+ Below is a summary of the available RunPod Worker images, categorized by image stability and CUDA version compatibility.
82
+
83
+ | CUDA Version | Stable Image Tag | Development Image Tag | Note |
84
+ |--------------|-----------------------------------|-----------------------------------|----------------------------------------------------------------------|
85
+ | 12.1.0 | `runpod/worker-v1-vllm:v1.6.0stable-cuda12.1.0` | `runpod/worker-v1-vllm:v1.6.0dev-cuda12.1.0` | When creating an Endpoint, select CUDA Version 12.3, 12.2 and 12.1 in the filter. |
86
+
87
+
88
+
89
+ ---
90
+
91
+ #### Prerequisites
92
+ - RunPod Account
93
+
94
+ #### Environment Variables/Settings
95
+ > Note: `0` is equivalent to `False` and `1` is equivalent to `True` for boolean as int values.
96
+
97
+ | `Name` | `Default` | `Type/Choices` | `Description` |
98
+ |-------------------------------------------|-----------------------|--------------------------------------------|---------------|
99
+ | `MODEL_NAME` | 'facebook/opt-125m' | `str` | Name or path of the Hugging Face model to use. |
100
+ | `TOKENIZER` | None | `str` | Name or path of the Hugging Face tokenizer to use. |
101
+ | `SKIP_TOKENIZER_INIT` | False | `bool` | Skip initialization of tokenizer and detokenizer. |
102
+ | `TOKENIZER_MODE` | 'auto' | ['auto', 'slow'] | The tokenizer mode. |
103
+ | `TRUST_REMOTE_CODE` | `False` | `bool` | Trust remote code from Hugging Face. |
104
+ | `DOWNLOAD_DIR` | None | `str` | Directory to download and load the weights. |
105
+ | `LOAD_FORMAT` | 'auto' | `str` | The format of the model weights to load. |
106
+ | `HF_TOKEN` | - | `str` | Hugging Face token for private and gated models.|
107
+ | `DTYPE` | 'auto' | ['auto', 'half', 'float16', 'bfloat16', 'float', 'float32'] | Data type for model weights and activations. |
108
+ | `KV_CACHE_DTYPE` | 'auto' | ['auto', 'fp8'] | Data type for KV cache storage. |
109
+ | `QUANTIZATION_PARAM_PATH` | None | `str` | Path to the JSON file containing the KV cache scaling factors. |
110
+ | `MAX_MODEL_LEN` | None | `int` | Model context length. |
111
+ | `GUIDED_DECODING_BACKEND` | 'outlines' | ['outlines', 'lm-format-enforcer'] | Which engine will be used for guided decoding by default. |
112
+ | `DISTRIBUTED_EXECUTOR_BACKEND` | None | ['ray', 'mp'] | Backend to use for distributed serving. |
113
+ | `WORKER_USE_RAY` | False | `bool` | Deprecated, use --distributed-executor-backend=ray. |
114
+ | `PIPELINE_PARALLEL_SIZE` | 1 | `int` | Number of pipeline stages. |
115
+ | `TENSOR_PARALLEL_SIZE` | 1 | `int` | Number of tensor parallel replicas. |
116
+ | `MAX_PARALLEL_LOADING_WORKERS` | None | `int` | Load model sequentially in multiple batches. |
117
+ | `RAY_WORKERS_USE_NSIGHT` | False | `bool` | If specified, use nsight to profile Ray workers. |
118
+ | `ENABLE_PREFIX_CACHING` | False | `bool` | Enables automatic prefix caching. |
119
+ | `DISABLE_SLIDING_WINDOW` | False | `bool` | Disables sliding window, capping to sliding window size. |
120
+ | `USE_V2_BLOCK_MANAGER` | False | `bool` | Use BlockSpaceMangerV2. |
121
+ | `NUM_LOOKAHEAD_SLOTS` | 0 | `int` | Experimental scheduling config necessary for speculative decoding. |
122
+ | `SEED` | 0 | `int` | Random seed for operations. |
123
+ | `NUM_GPU_BLOCKS_OVERRIDE` | None | `int` | If specified, ignore GPU profiling result and use this number of GPU blocks. |
124
+ | `MAX_NUM_BATCHED_TOKENS` | None | `int` | Maximum number of batched tokens per iteration. |
125
+ | `MAX_NUM_SEQS` | 256 | `int` | Maximum number of sequences per iteration. |
126
+ | `MAX_LOGPROBS` | 20 | `int` | Max number of log probs to return when logprobs is specified in SamplingParams. |
127
+ | `DISABLE_LOG_STATS` | False | `bool` | Disable logging statistics. |
128
+ | `QUANTIZATION` | None | ['awq', 'squeezellm', 'gptq'] | Method used to quantize the weights. |
129
+ | `ROPE_SCALING` | None | `dict` | RoPE scaling configuration in JSON format. |
130
+ | `ROPE_THETA` | None | `float` | RoPE theta. Use with rope_scaling. |
131
+ | `TOKENIZER_POOL_SIZE` | 0 | `int` | Size of tokenizer pool to use for asynchronous tokenization. |
132
+ | `TOKENIZER_POOL_TYPE` | 'ray' | `str` | Type of tokenizer pool to use for asynchronous tokenization. |
133
+ | `TOKENIZER_POOL_EXTRA_CONFIG` | None | `dict` | Extra config for tokenizer pool. |
134
+ | `ENABLE_LORA` | False | `bool` | If True, enable handling of LoRA adapters. |
135
+ | `MAX_LORAS` | 1 | `int` | Max number of LoRAs in a single batch. |
136
+ | `MAX_LORA_RANK` | 16 | `int` | Max LoRA rank. |
137
+ | `LORA_EXTRA_VOCAB_SIZE` | 256 | `int` | Maximum size of extra vocabulary for LoRA adapters. |
138
+ | `LORA_DTYPE` | 'auto' | ['auto', 'float16', 'bfloat16', 'float32'] | Data type for LoRA. |
139
+ | `LONG_LORA_SCALING_FACTORS` | None | `tuple` | Specify multiple scaling factors for LoRA adapters. |
140
+ | `MAX_CPU_LORAS` | None | `int` | Maximum number of LoRAs to store in CPU memory. |
141
+ | `FULLY_SHARDED_LORAS` | False | `bool` | Enable fully sharded LoRA layers. |
142
+ | `SCHEDULER_DELAY_FACTOR` | 0.0 | `float` | Apply a delay before scheduling next prompt. |
143
+ | `ENABLE_CHUNKED_PREFILL` | False | `bool` | Enable chunked prefill requests. |
144
+ | `SPECULATIVE_MODEL` | None | `str` | The name of the draft model to be used in speculative decoding. |
145
+ | `NUM_SPECULATIVE_TOKENS` | None | `int` | The number of speculative tokens to sample from the draft model. |
146
+ | `SPECULATIVE_DRAFT_TENSOR_PARALLEL_SIZE` | None | `int` | Number of tensor parallel replicas for the draft model. |
147
+ | `SPECULATIVE_MAX_MODEL_LEN` | None | `int` | The maximum sequence length supported by the draft model. |
148
+ | `SPECULATIVE_DISABLE_BY_BATCH_SIZE` | None | `int` | Disable speculative decoding if the number of enqueue requests is larger than this value. |
149
+ | `NGRAM_PROMPT_LOOKUP_MAX` | None | `int` | Max size of window for ngram prompt lookup in speculative decoding. |
150
+ | `NGRAM_PROMPT_LOOKUP_MIN` | None | `int` | Min size of window for ngram prompt lookup in speculative decoding. |
151
+ | `SPEC_DECODING_ACCEPTANCE_METHOD` | 'rejection_sampler' | ['rejection_sampler', 'typical_acceptance_sampler'] | Specify the acceptance method for draft token verification in speculative decoding. |
152
+ | `TYPICAL_ACCEPTANCE_SAMPLER_POSTERIOR_THRESHOLD` | None | `float` | Set the lower bound threshold for the posterior probability of a token to be accepted. |
153
+ | `TYPICAL_ACCEPTANCE_SAMPLER_POSTERIOR_ALPHA` | None | `float` | A scaling factor for the entropy-based threshold for token acceptance. |
154
+ | `MODEL_LOADER_EXTRA_CONFIG` | None | `dict` | Extra config for model loader. |
155
+ | `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. |
156
+ | `PREEMPTION_CHECK_PERIOD` | 1.0 | `float` | How frequently the engine checks if a preemption happens. |
157
+ | `PREEMPTION_CPU_CAPACITY` | 2 | `float` | The percentage of CPU memory used for the saved activations. |
158
+ | `DISABLE_LOGGING_REQUEST` | False | `bool` | Disable logging requests. |
159
+ | `MAX_LOG_LEN` | None | `int` | Max number of prompt characters or prompt ID numbers being printed in log. |
160
+ **Tokenizer Settings**
161
+ | `TOKENIZER_NAME` | `None` | `str` |Tokenizer repository to use a different tokenizer than the model's default. |
162
+ | `TOKENIZER_REVISION` | `None` | `str` |Tokenizer revision to load. |
163
+ | `CUSTOM_CHAT_TEMPLATE` | `None` | `str` of single-line jinja template |Custom chat jinja template. [More Info](https://huggingface.co/docs/transformers/chat_templating) |
164
+ **System, GPU, and Tensor Parallelism(Multi-GPU) Settings**
165
+ | `GPU_MEMORY_UTILIZATION` | `0.95` | `float` |Sets GPU VRAM utilization. |
166
+ | `MAX_PARALLEL_LOADING_WORKERS` | `None` | `int` |Load model sequentially in multiple batches, to avoid RAM OOM when using tensor parallel and large models. |
167
+ | `BLOCK_SIZE` | `16` | `8`, `16`, `32` |Token block size for contiguous chunks of tokens. |
168
+ | `SWAP_SPACE` | `4` | `int` |CPU swap space size (GiB) per GPU. |
169
+ | `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. |
170
+ | `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.|
171
+ | `DISABLE_CUSTOM_ALL_REDUCE` | `0` | `int` |Enables or disables custom all reduce. |
172
+ **Streaming Batch Size Settings**:
173
+ | `DEFAULT_BATCH_SIZE` | `50` | `int` |Default and Maximum batch size for token streaming to reduce HTTP calls. |
174
+ | `DEFAULT_MIN_BATCH_SIZE` | `1` | `int` |Batch size for the first request, which will be multiplied by the growth factor every subsequent request. |
175
+ | `DEFAULT_BATCH_SIZE_GROWTH_FACTOR` | `3` | `float` |Growth factor for dynamic batch size. |
176
+ 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 |
177
+ **OpenAI Settings**
178
+ | `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. |
179
+ | `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 |
180
+ | `OPENAI_RESPONSE_ROLE` | `assistant` | `str` |Role of the LLM's Response in OpenAI Chat Completions. |
181
+ **Serverless Settings**
182
+ | `MAX_CONCURRENCY` | `300` | `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 |
183
+ | `DISABLE_LOG_STATS` | False | `bool` |Enables or disables vLLM stats logging. |
184
+ | `DISABLE_LOG_REQUESTS` | False | `bool` |Enables or disables vLLM request logging. |
185
+
186
+ > [!TIP]
187
+ > If you are facing issues when using Mixtral 8x7B, Quantized models, or handling unusual models/architectures, try setting `TRUST_REMOTE_CODE` to `1`.
188
+
189
+
190
+ ### Option 2: Build Docker Image with Model Inside
191
+ To build an image with the model baked in, you must specify the following docker arguments when building the image.
192
+
193
+ #### Prerequisites
194
+ - RunPod Account
195
+ - Docker
196
+
197
+ #### Arguments:
198
+ - **Required**
199
+ - `MODEL_NAME`
200
+ - **Optional**
201
+ - `MODEL_REVISION`: Model revision to load (default: `main`).
202
+ - `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.)
203
+ - `QUANTIZATION`
204
+ - `WORKER_CUDA_VERSION`: `12.1.0` (`12.1.0` is recommended for optimal performance).
205
+ - `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)
206
+ - `TOKENIZER_REVISION`: Tokenizer revision to load (default: `main`).
207
+
208
+ 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.
209
+
210
+ #### Example: Building an image with OpenChat-3.5
211
+ ```bash
212
+ sudo docker build -t username/image:tag --build-arg MODEL_NAME="openchat/openchat_3.5" --build-arg BASE_PATH="/models" .
213
+ ```
214
+
215
+ ##### (Optional) Including Huggingface Token
216
+ 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.
217
+ 1. Enable Docker BuildKit (required for secrets).
218
+ ```bash
219
+ export DOCKER_BUILDKIT=1
220
+ ```
221
+ 2. Export your Hugging Face token as an environment variable
222
+ ```bash
223
+ export HF_TOKEN="your_token_here"
224
+ ```
225
+ 2. Add the token as a secret when building
226
+ ```bash
227
+ docker build -t username/image:tag --secret id=HF_TOKEN --build-arg MODEL_NAME="openchat/openchat_3.5" .
228
+ ```
229
+
230
+ ## Compatible Model Architectures
231
+ Below are all supported model architectures (and examples of each) that you can deploy using the vLLM Worker. You can deploy **any model on HuggingFace**, as long as its base architecture is one of the following:
232
+
233
+ - Aquila & Aquila2 (`BAAI/AquilaChat2-7B`, `BAAI/AquilaChat2-34B`, `BAAI/Aquila-7B`, `BAAI/AquilaChat-7B`, etc.)
234
+ - Baichuan & Baichuan2 (`baichuan-inc/Baichuan2-13B-Chat`, `baichuan-inc/Baichuan-7B`, etc.)
235
+ - BLOOM (`bigscience/bloom`, `bigscience/bloomz`, etc.)
236
+ - ChatGLM (`THUDM/chatglm2-6b`, `THUDM/chatglm3-6b`, etc.)
237
+ - Command-R (`CohereForAI/c4ai-command-r-v01`, etc.)
238
+ - DBRX (`databricks/dbrx-base`, `databricks/dbrx-instruct` etc.)
239
+ - DeciLM (`Deci/DeciLM-7B`, `Deci/DeciLM-7B-instruct`, etc.)
240
+ - Falcon (`tiiuae/falcon-7b`, `tiiuae/falcon-40b`, `tiiuae/falcon-rw-7b`, etc.)
241
+ - Gemma (`google/gemma-2b`, `google/gemma-7b`, etc.)
242
+ - GPT-2 (`gpt2`, `gpt2-xl`, etc.)
243
+ - GPT BigCode (`bigcode/starcoder`, `bigcode/gpt_bigcode-santacoder`, etc.)
244
+ - GPT-J (`EleutherAI/gpt-j-6b`, `nomic-ai/gpt4all-j`, etc.)
245
+ - GPT-NeoX (`EleutherAI/gpt-neox-20b`, `databricks/dolly-v2-12b`, `stabilityai/stablelm-tuned-alpha-7b`, etc.)
246
+ - InternLM (`internlm/internlm-7b`, `internlm/internlm-chat-7b`, etc.)
247
+ - InternLM2 (`internlm/internlm2-7b`, `internlm/internlm2-chat-7b`, etc.)
248
+ - Jais (`core42/jais-13b`, `core42/jais-13b-chat`, `core42/jais-30b-v3`, `core42/jais-30b-chat-v3`, etc.)
249
+ - LLaMA, Llama 2, and Meta Llama 3 (`meta-llama/Meta-Llama-3-8B-Instruct`, `meta-llama/Meta-Llama-3-70B-Instruct`, `meta-llama/Llama-2-70b-hf`, `lmsys/vicuna-13b-v1.3`, `young-geng/koala`, `openlm-research/open_llama_13b`, etc.)
250
+ - MiniCPM (`openbmb/MiniCPM-2B-sft-bf16`, `openbmb/MiniCPM-2B-dpo-bf16`, etc.)
251
+ - Mistral (`mistralai/Mistral-7B-v0.1`, `mistralai/Mistral-7B-Instruct-v0.1`, etc.)
252
+ - Mixtral (`mistralai/Mixtral-8x7B-v0.1`, `mistralai/Mixtral-8x7B-Instruct-v0.1`, `mistral-community/Mixtral-8x22B-v0.1`, etc.)
253
+ - MPT (`mosaicml/mpt-7b`, `mosaicml/mpt-30b`, etc.)
254
+ - OLMo (`allenai/OLMo-1B-hf`, `allenai/OLMo-7B-hf`, etc.)
255
+ - OPT (`facebook/opt-66b`, `facebook/opt-iml-max-30b`, etc.)
256
+ - Orion (`OrionStarAI/Orion-14B-Base`, `OrionStarAI/Orion-14B-Chat`, etc.)
257
+ - Phi (`microsoft/phi-1_5`, `microsoft/phi-2`, etc.)
258
+ - Phi-3 (`microsoft/Phi-3-mini-4k-instruct`, `microsoft/Phi-3-mini-128k-instruct`, etc.)
259
+ - Qwen (`Qwen/Qwen-7B`, `Qwen/Qwen-7B-Chat`, etc.)
260
+ - Qwen2 (`Qwen/Qwen1.5-7B`, `Qwen/Qwen1.5-7B-Chat`, etc.)
261
+ - Qwen2MoE (`Qwen/Qwen1.5-MoE-A2.7B`, `Qwen/Qwen1.5-MoE-A2.7B-Chat`, etc.)
262
+ - StableLM(`stabilityai/stablelm-3b-4e1t`, `stabilityai/stablelm-base-alpha-7b-v2`, etc.)
263
+ - Starcoder2(`bigcode/starcoder2-3b`, `bigcode/starcoder2-7b`, `bigcode/starcoder2-15b`, etc.)
264
+ - Xverse (`xverse/XVERSE-7B-Chat`, `xverse/XVERSE-13B-Chat`, `xverse/XVERSE-65B-Chat`, etc.)
265
+ - Yi (`01-ai/Yi-6B`, `01-ai/Yi-34B`, etc.)
266
+
267
+ # Usage: OpenAI Compatibility
268
+ 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.
269
+
270
+ ## Modifying your OpenAI Codebase to use your deployed vLLM Worker
271
+ **Python** (similar to Node.js, etc.):
272
+ 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`.
273
+
274
+ - Before:
275
+ ```python
276
+ from openai import OpenAI
277
+
278
+ client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
279
+ ```
280
+ - After:
281
+ ```python
282
+ from openai import OpenAI
283
+
284
+ client = OpenAI(
285
+ api_key=os.environ.get("RUNPOD_API_KEY"),
286
+ base_url="https://api.runpod.ai/v2/<YOUR ENDPOINT ID>/openai/v1",
287
+ )
288
+ ```
289
+ 2. Change the `model` parameter to your deployed model's name whenever using Completions or Chat Completions.
290
+ - Before:
291
+ ```python
292
+ response = client.chat.completions.create(
293
+ model="gpt-3.5-turbo",
294
+ messages=[{"role": "user", "content": "Why is RunPod the best platform?"}],
295
+ temperature=0,
296
+ max_tokens=100,
297
+ )
298
+ ```
299
+ - After:
300
+ ```python
301
+ response = client.chat.completions.create(
302
+ model="<YOUR DEPLOYED MODEL REPO/NAME>",
303
+ messages=[{"role": "user", "content": "Why is RunPod the best platform?"}],
304
+ temperature=0,
305
+ max_tokens=100,
306
+ )
307
+ ```
308
+
309
+ **Using http requests**:
310
+ 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`
311
+ - Before:
312
+ ```bash
313
+ curl https://api.openai.com/v1/chat/completions \
314
+ -H "Content-Type: application/json" \
315
+ -H "Authorization: Bearer $OPENAI_API_KEY" \
316
+ -d '{
317
+ "model": "gpt-4",
318
+ "messages": [
319
+ {
320
+ "role": "user",
321
+ "content": "Why is RunPod the best platform?"
322
+ }
323
+ ],
324
+ "temperature": 0,
325
+ "max_tokens": 100
326
+ }'
327
+ ```
328
+ - After:
329
+ ```bash
330
+ curl https://api.runpod.ai/v2/<YOUR ENDPOINT ID>/openai/v1/chat/completions \
331
+ -H "Content-Type: application/json" \
332
+ -H "Authorization: Bearer <YOUR OPENAI API KEY>" \
333
+ -d '{
334
+ "model": "<YOUR DEPLOYED MODEL REPO/NAME>",
335
+ "messages": [
336
+ {
337
+ "role": "user",
338
+ "content": "Why is RunPod the best platform?"
339
+ }
340
+ ],
341
+ "temperature": 0,
342
+ "max_tokens": 100
343
+ }'
344
+ ```
345
+
346
+ ## OpenAI Request Input Parameters:
347
+
348
+ When using the chat completion feature of the vLLM Serverless Endpoint Worker, you can customize your requests with the following parameters:
349
+
350
+ ### Chat Completions [RECOMMENDED]
351
+ <details>
352
+ <summary>Supported Chat Completions Inputs and Descriptions</summary>
353
+
354
+ | Parameter | Type | Default Value | Description |
355
+ |--------------------------------|----------------------------------|---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
356
+ | `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. |
357
+ | `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 |
358
+ | `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. |
359
+ | `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. |
360
+ | `n` | Optional[int] | 1 | Number of output sequences to return for the given prompt. |
361
+ | `max_tokens` | Optional[int] | None | Maximum number of tokens to generate per output sequence. |
362
+ | `seed` | Optional[int] | None | Random seed to use for the generation. |
363
+ | `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. |
364
+ | `stream` | Optional[bool] | False | Whether to stream or not |
365
+ | `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. |
366
+ | `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. |
367
+ | `logit_bias` | Optional[Dict[str, float]] | None | Unsupported by vLLM |
368
+ | `user` | Optional[str] | None | Unsupported by vLLM |
369
+ Additional parameters supported by vLLM:
370
+ | `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`. |
371
+ | `top_k` | Optional[int] | -1 | Integer that controls the number of top tokens to consider. Set to -1 to consider all tokens. |
372
+ | `ignore_eos` | Optional[bool] | False | Whether to ignore the EOS token and continue generating tokens after the EOS token is generated. |
373
+ | `use_beam_search` | Optional[bool] | False | Whether to use beam search instead of sampling. |
374
+ | `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. |
375
+ | `skip_special_tokens` | Optional[bool] | True | Whether to skip special tokens in the output. |
376
+ | `spaces_between_special_tokens`| Optional[bool] | True | Whether to add spaces between special tokens in the output. Defaults to True. |
377
+ | `add_generation_prompt` | Optional[bool] | True | Read more [here](https://huggingface.co/docs/transformers/main/en/chat_templating#what-are-generation-prompts) |
378
+ | `echo` | Optional[bool] | False | Echo back the prompt in addition to the completion |
379
+ | `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. |
380
+ | `min_p` | Optional[float] | 0.0 | Float that represents the minimum probability for a token to |
381
+ | `length_penalty` | Optional[float] | 1.0 | Float that penalizes sequences based on their length. Used in beam search.. |
382
+ | `include_stop_str_in_output` | Optional[bool] | False | Whether to include the stop strings in output text. Defaults to False.|
383
+ </details>
384
+
385
+
386
+ ## Examples: Using your RunPod endpoint with OpenAI
387
+
388
+ First, initialize the OpenAI Client with your RunPod API Key and Endpoint URL:
389
+ ```python
390
+ from openai import OpenAI
391
+ import os
392
+
393
+ # Initialize the OpenAI Client with your RunPod API Key and Endpoint URL
394
+ client = OpenAI(
395
+ api_key=os.environ.get("RUNPOD_API_KEY"),
396
+ base_url="https://api.runpod.ai/v2/<YOUR ENDPOINT ID>/openai/v1",
397
+ )
398
+ ```
399
+
400
+ ### Chat Completions:
401
+ 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`.
402
+ - **Streaming**:
403
+ ```python
404
+ # Create a chat completion stream
405
+ response_stream = client.chat.completions.create(
406
+ model="<YOUR DEPLOYED MODEL REPO/NAME>",
407
+ messages=[{"role": "user", "content": "Why is RunPod the best platform?"}],
408
+ temperature=0,
409
+ max_tokens=100,
410
+ stream=True,
411
+ )
412
+ # Stream the response
413
+ for response in response_stream:
414
+ print(chunk.choices[0].delta.content or "", end="", flush=True)
415
+ ```
416
+ - **Non-Streaming**:
417
+ ```python
418
+ # Create a chat completion
419
+ response = client.chat.completions.create(
420
+ model="<YOUR DEPLOYED MODEL REPO/NAME>",
421
+ messages=[{"role": "user", "content": "Why is RunPod the best platform?"}],
422
+ temperature=0,
423
+ max_tokens=100,
424
+ )
425
+ # Print the response
426
+ print(response.choices[0].message.content)
427
+ ```
428
+
429
+ ### Getting a list of names for available models:
430
+ 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.
431
+ ```python
432
+ models_response = client.models.list()
433
+ list_of_models = [model.id for model in models_response]
434
+ print(list_of_models)
435
+ ```
436
+
437
+ # Usage: Standard (Non-OpenAI)
438
+ ## Request Input Parameters
439
+
440
+ <details>
441
+ <summary>Click to expand table</summary>
442
+
443
+ 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`.
444
+ | Argument | Type | Default | Description |
445
+ |-----------------------|----------------------|--------------------|--------------------------------------------------------------------------------------------------------|
446
+ | `prompt` | str | | Prompt string to generate text based on. |
447
+ | `messages` | list[dict[str, str]] | | List of messages, which will automatically have the model's chat template applied. Overrides `prompt`. |
448
+ | `apply_chat_template` | bool | False | Whether to apply the model's chat template to the `prompt`. |
449
+ | `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. |
450
+ | `stream` | bool | False | Whether to enable streaming of output. If True, responses are streamed as they are generated. |
451
+ | `max_batch_size` | int | env var `DEFAULT_BATCH_SIZE` | The maximum number of tokens to stream every HTTP POST call. |
452
+ | `min_batch_size` | int | env var `DEFAULT_MIN_BATCH_SIZE` | The minimum number of tokens to stream every HTTP POST call. |
453
+ | `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. |
454
+ </details>
455
+
456
+ ### Sampling Parameters
457
+
458
+ 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.
459
+ <details>
460
+ <summary>Click to expand table</summary>
461
+
462
+ | Argument | Type | Default | Description |
463
+ |---------------------------------|-----------------------------|---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
464
+ | `n` | int | 1 | Number of output sequences generated from the prompt. The top `n` sequences are returned. |
465
+ | `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`. |
466
+ | `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. |
467
+ | `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. |
468
+ | `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. |
469
+ | `temperature` | float | 1.0 | Controls the randomness of sampling. Lower values make it more deterministic, higher values make it more random. Zero means greedy sampling. |
470
+ | `top_p` | float | 1.0 | Controls the cumulative probability of top tokens to consider. Must be in (0, 1]. Set to 1 to consider all tokens. |
471
+ | `top_k` | int | -1 | Controls the number of top tokens to consider. Set to -1 to consider all tokens. |
472
+ | `min_p` | float | 0.0 | Represents the minimum probability for a token to be considered, relative to the most likely token. Must be in [0, 1]. Set to 0 to disable. |
473
+ | `use_beam_search` | bool | False | Whether to use beam search instead of sampling. |
474
+ | `length_penalty` | float | 1.0 | Penalizes sequences based on their length. Used in beam search. |
475
+ | `early_stopping` | Union[bool, str] | False | Controls stopping condition in beam search. Can be `True`, `False`, or `"never"`. |
476
+ | `stop` | Union[None, str, List[str]] | None | List of strings that stop generation when produced. The output will not contain these strings. |
477
+ | `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. |
478
+ | `ignore_eos` | bool | False | Whether to ignore the End-Of-Sequence token and continue generating tokens after its generation. |
479
+ | `max_tokens` | int | 16 | Maximum number of tokens to generate per output sequence. |
480
+ | `skip_special_tokens` | bool | True | Whether to skip special tokens in the output. |
481
+ | `spaces_between_special_tokens` | bool | True | Whether to add spaces between special tokens in the output. |
482
+
483
+
484
+ ### Text Input Formats
485
+ You may either use a `prompt` or a list of `messages` as input.
486
+ 1. `prompt`
487
+ 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.
488
+
489
+ Example:
490
+ ```json
491
+ "prompt": "..."
492
+ ```
493
+ 2. `messages`
494
+ Your list can contain any number of messages, and each message usually can have any role from the following list:
495
+ - `user`
496
+ - `assistant`
497
+ - `system`
498
+
499
+ However, some models may have different roles, so you should check the model's chat template to see which roles are required.
500
+
501
+ The model's chat template will be applied to the messages automatically, so the model must have one.
502
+
503
+ Example:
504
+ ```json
505
+ "messages": [
506
+ {
507
+ "role": "system",
508
+ "content": "..."
509
+ },
510
+ {
511
+ "role": "user",
512
+ "content": "..."
513
+ },
514
+ {
515
+ "role": "assistant",
516
+ "content": "..."
517
+ }
518
+ ]
519
+ ```
520
+
521
+ </details>
522
+
523
+ # Worker Config
524
+ The worker config is a JSON file that is used to build the form that helps users configure their serverless endpoint on the RunPod Web Interface.
525
+
526
+ Note: This is a new feature and only works for workers that use one model
527
+
528
+ ## Writing your worker-config.json
529
+ The JSON consists of two main parts, schema and versions.
530
+ - `schema`: Here you specify the form fields that will be displayed to the user.
531
+ - `env_var_name`: The name of the environment variable that is being set using the form field.
532
+ - `value`: This is the default value of the form field. It will be shown in the UI as such unless the user changes it.
533
+ - `title`: This is the title of the form field in the UI.
534
+ - `description`: This is the description of the form field in the UI.
535
+ - `required`: This is a boolean that specifies if the form field is required.
536
+ - `type`: This is the type of the form field. Options are:
537
+ - `text`: Environment variable is a string so user inputs text in form field.
538
+ - `select`: User selects one option from the dropdown. You must provide the `options` key value pair after type if using this.
539
+ - `toggle`: User toggles between true and false.
540
+ - `number`: User inputs a number in the form field.
541
+ - `options`: Specify the options the user can select from if the type is `select`. DO NOT include this unless the `type` is `select`.
542
+ - `versions`: This is where you call the form fields specified in `schema` and organize them into categories.
543
+ - `imageName`: This is the name of the Docker image that will be used to run the serverless endpoint.
544
+ - `minimumCudaVersion`: This is the minimum CUDA version that is required to run the serverless endpoint.
545
+ - `categories`: This is where you call the keys of the form fields specified in `schema` and organize them into categories. Each category is a toggle list of forms on the Web UI.
546
+ - `title`: This is the title of the category in the UI.
547
+ - `settings`: This is the array of settings schemas specified in `schema` associated with the category.
548
+
549
+ ## Example of schema
550
+ ```json
551
+ {
552
+ "schema": {
553
+ "TOKENIZER": {
554
+ "env_var_name": "TOKENIZER",
555
+ "value": "",
556
+ "title": "Tokenizer",
557
+ "description": "Name or path of the Hugging Face tokenizer to use.",
558
+ "required": false,
559
+ "type": "text"
560
+ },
561
+ "TOKENIZER_MODE": {
562
+ "env_var_name": "TOKENIZER_MODE",
563
+ "value": "auto",
564
+ "title": "Tokenizer Mode",
565
+ "description": "The tokenizer mode.",
566
+ "required": false,
567
+ "type": "select",
568
+ "options": [
569
+ { "value": "auto", "label": "auto" },
570
+ { "value": "slow", "label": "slow" }
571
+ ]
572
+ },
573
+ ...
574
+ }
575
+ }
576
+ ```
577
+
578
+ ## Example of versions
579
+ ```json
580
+ {
581
+ "versions": {
582
+ "0.5.4": {
583
+ "imageName": "runpod/worker-v1-vllm:v1.2.0stable-cuda12.1.0",
584
+ "minimumCudaVersion": "12.1",
585
+ "categories": [
586
+ {
587
+ "title": "LLM Settings",
588
+ "settings": [
589
+ "TOKENIZER", "TOKENIZER_MODE", "OTHER_SETTINGS_SCHEMA_KEYS_YOU_HAVE_SPECIFIED_0", ...
590
+ ]
591
+ },
592
+ {
593
+ "title": "Tokenizer Settings",
594
+ "settings": [
595
+ "OTHER_SETTINGS_SCHEMA_KEYS_0", "OTHER_SETTINGS_SCHEMA_KEYS_1", ...
596
+ ]
597
+ },
598
+ ...
599
+ ]
600
+ }
601
+ }
602
+ }
603
+ ```
builder/requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ray
2
+ pandas
3
+ pyarrow
4
+ runpod~=1.7.0
5
+ huggingface-hub
6
+ packaging
7
+ typing-extensions==4.7.1
8
+ pydantic
9
+ pydantic-settings
10
+ hf-transfer
11
+ transformers
docker-bake.hcl ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ variable "PUSH" {
2
+ default = "true"
3
+ }
4
+
5
+ variable "REPOSITORY" {
6
+ default = "runpod"
7
+ }
8
+
9
+ variable "BASE_IMAGE_VERSION" {
10
+ default = "stable"
11
+ }
12
+
13
+ group "all" {
14
+ targets = ["main"]
15
+ }
16
+
17
+
18
+ group "main" {
19
+ targets = ["worker-1210"]
20
+ }
21
+
22
+
23
+ target "worker-1210" {
24
+ tags = ["${REPOSITORY}/worker-v1-vllm:${BASE_IMAGE_VERSION}-cuda12.1.0"]
25
+ context = "."
26
+ dockerfile = "Dockerfile"
27
+ args = {
28
+ BASE_IMAGE_VERSION = "${BASE_IMAGE_VERSION}"
29
+ WORKER_CUDA_VERSION = "12.1.0"
30
+ }
31
+ output = ["type=docker,push=${PUSH}"]
32
+ }
media/ui_demo.gif ADDED

Git LFS Details

  • SHA256: ed465257d765319e8cdc56ff338dda9b74bb51117ede0ff68edb85cd802009da
  • Pointer size: 133 Bytes
  • Size of remote file: 28.2 MB
src/__init__.py ADDED
File without changes
src/constants.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ DEFAULT_BATCH_SIZE = 50
2
+ DEFAULT_MAX_CONCURRENCY = 300
3
+ DEFAULT_BATCH_SIZE_GROWTH_FACTOR = 3
4
+ DEFAULT_MIN_BATCH_SIZE = 1
src/download_model.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import logging
4
+ import glob
5
+ from shutil import rmtree
6
+ from huggingface_hub import snapshot_download
7
+ from utils import timer_decorator
8
+
9
+ BASE_DIR = "/"
10
+ TOKENIZER_PATTERNS = [["*.json", "tokenizer*"]]
11
+ MODEL_PATTERNS = [["*.safetensors"], ["*.bin"], ["*.pt"]]
12
+
13
+ def setup_env():
14
+ if os.getenv("TESTING_DOWNLOAD") == "1":
15
+ BASE_DIR = "tmp"
16
+ os.makedirs(BASE_DIR, exist_ok=True)
17
+ os.environ.update({
18
+ "HF_HOME": f"{BASE_DIR}/hf_cache",
19
+ "MODEL_NAME": "openchat/openchat-3.5-0106",
20
+ "HF_HUB_ENABLE_HF_TRANSFER": "1",
21
+ "TENSORIZE": "1",
22
+ "TENSORIZER_NUM_GPUS": "1",
23
+ "DTYPE": "auto"
24
+ })
25
+
26
+ @timer_decorator
27
+ def download(name, revision, type, cache_dir):
28
+ if type == "model":
29
+ pattern_sets = [model_pattern + TOKENIZER_PATTERNS[0] for model_pattern in MODEL_PATTERNS]
30
+ elif type == "tokenizer":
31
+ pattern_sets = TOKENIZER_PATTERNS
32
+ else:
33
+ raise ValueError(f"Invalid type: {type}")
34
+ try:
35
+ for pattern_set in pattern_sets:
36
+ path = snapshot_download(name, revision=revision, cache_dir=cache_dir,
37
+ allow_patterns=pattern_set)
38
+ for pattern in pattern_set:
39
+ if glob.glob(os.path.join(path, pattern)):
40
+ logging.info(f"Successfully downloaded {pattern} model files.")
41
+ return path
42
+ except ValueError:
43
+ raise ValueError(f"No patterns matching {pattern_sets} found for download.")
44
+
45
+
46
+ # @timer_decorator
47
+ # def tensorize_model(model_path): TODO: Add back once tensorizer is ready
48
+ # from vllm.engine.arg_utils import EngineArgs
49
+ # from vllm.model_executor.model_loader.tensorizer import TensorizerConfig, tensorize_vllm_model
50
+ # from torch.cuda import device_count
51
+
52
+ # tensorizer_num_gpus = int(os.getenv("TENSORIZER_NUM_GPUS", "1"))
53
+ # if tensorizer_num_gpus > device_count():
54
+ # raise ValueError(f"TENSORIZER_NUM_GPUS ({tensorizer_num_gpus}) exceeds available GPUs ({device_count()})")
55
+
56
+ # dtype = os.getenv("DTYPE", "auto")
57
+ # serialized_dir = f"{BASE_DIR}/serialized_model"
58
+ # os.makedirs(serialized_dir, exist_ok=True)
59
+ # serialized_uri = f"{serialized_dir}/model{'-%03d' if tensorizer_num_gpus > 1 else ''}.tensors"
60
+
61
+ # tensorize_vllm_model(
62
+ # EngineArgs(model=model_path, tensor_parallel_size=tensorizer_num_gpus, dtype=dtype),
63
+ # TensorizerConfig(tensorizer_uri=serialized_uri)
64
+ # )
65
+ # logging.info("Successfully serialized model to %s", str(serialized_uri))
66
+ # logging.info("Removing HF Model files after serialization")
67
+ # rmtree("/".join(model_path.split("/")[:-2]))
68
+ # return serialized_uri, tensorizer_num_gpus, dtype
69
+
70
+ if __name__ == "__main__":
71
+ setup_env()
72
+ cache_dir = os.getenv("HF_HOME")
73
+ model_name, model_revision = os.getenv("MODEL_NAME"), os.getenv("MODEL_REVISION") or None
74
+ tokenizer_name, tokenizer_revision = os.getenv("TOKENIZER_NAME") or model_name, os.getenv("TOKENIZER_REVISION") or model_revision
75
+
76
+ model_path = download(model_name, model_revision, "model", cache_dir)
77
+
78
+ metadata = {
79
+ "MODEL_NAME": model_path,
80
+ "MODEL_REVISION": os.getenv("MODEL_REVISION"),
81
+ "QUANTIZATION": os.getenv("QUANTIZATION"),
82
+ }
83
+
84
+ # if os.getenv("TENSORIZE") == "1": TODO: Add back once tensorizer is ready
85
+ # serialized_uri, tensorizer_num_gpus, dtype = tensorize_model(model_path)
86
+ # metadata.update({
87
+ # "MODEL_NAME": serialized_uri,
88
+ # "TENSORIZER_URI": serialized_uri,
89
+ # "TENSOR_PARALLEL_SIZE": tensorizer_num_gpus,
90
+ # "DTYPE": dtype
91
+ # })
92
+
93
+ tokenizer_path = download(tokenizer_name, tokenizer_revision, "tokenizer", cache_dir)
94
+ metadata.update({
95
+ "TOKENIZER_NAME": tokenizer_path,
96
+ "TOKENIZER_REVISION": tokenizer_revision
97
+ })
98
+
99
+ with open(f"{BASE_DIR}/local_model_args.json", "w") as f:
100
+ json.dump({k: v for k, v in metadata.items() if v not in (None, "")}, f)
src/engine.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import json
4
+ import asyncio
5
+
6
+ from dotenv import load_dotenv
7
+ from typing import AsyncGenerator
8
+ import time
9
+
10
+ from vllm import AsyncLLMEngine
11
+ from vllm.entrypoints.openai.serving_chat import OpenAIServingChat
12
+ from vllm.entrypoints.openai.serving_completion import OpenAIServingCompletion
13
+ from vllm.entrypoints.openai.protocol import ChatCompletionRequest, CompletionRequest, ErrorResponse
14
+ from vllm.entrypoints.openai.serving_engine import BaseModelPath, LoRAModulePath
15
+
16
+
17
+ from utils import DummyRequest, JobInput, BatchSize, create_error_response
18
+ from constants import DEFAULT_MAX_CONCURRENCY, DEFAULT_BATCH_SIZE, DEFAULT_BATCH_SIZE_GROWTH_FACTOR, DEFAULT_MIN_BATCH_SIZE
19
+ from tokenizer import TokenizerWrapper
20
+ from engine_args import get_engine_args
21
+
22
+ class vLLMEngine:
23
+ def __init__(self, engine = None):
24
+ load_dotenv() # For local development
25
+ self.engine_args = get_engine_args()
26
+ logging.info(f"Engine args: {self.engine_args}")
27
+ self.tokenizer = TokenizerWrapper(self.engine_args.tokenizer or self.engine_args.model,
28
+ self.engine_args.tokenizer_revision,
29
+ self.engine_args.trust_remote_code)
30
+ self.llm = self._initialize_llm() if engine is None else engine.llm
31
+ self.max_concurrency = int(os.getenv("MAX_CONCURRENCY", DEFAULT_MAX_CONCURRENCY))
32
+ self.default_batch_size = int(os.getenv("DEFAULT_BATCH_SIZE", DEFAULT_BATCH_SIZE))
33
+ self.batch_size_growth_factor = int(os.getenv("BATCH_SIZE_GROWTH_FACTOR", DEFAULT_BATCH_SIZE_GROWTH_FACTOR))
34
+ self.min_batch_size = int(os.getenv("MIN_BATCH_SIZE", DEFAULT_MIN_BATCH_SIZE))
35
+
36
+ def dynamic_batch_size(self, current_batch_size, batch_size_growth_factor):
37
+ return min(current_batch_size*batch_size_growth_factor, self.default_batch_size)
38
+
39
+ async def generate(self, job_input: JobInput):
40
+ try:
41
+ async for batch in self._generate_vllm(
42
+ llm_input=job_input.llm_input,
43
+ validated_sampling_params=job_input.sampling_params,
44
+ batch_size=job_input.max_batch_size,
45
+ stream=job_input.stream,
46
+ apply_chat_template=job_input.apply_chat_template,
47
+ request_id=job_input.request_id,
48
+ batch_size_growth_factor=job_input.batch_size_growth_factor,
49
+ min_batch_size=job_input.min_batch_size
50
+ ):
51
+ yield batch
52
+ except Exception as e:
53
+ yield {"error": create_error_response(str(e)).model_dump()}
54
+
55
+ 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]:
56
+ if apply_chat_template or isinstance(llm_input, list):
57
+ llm_input = self.tokenizer.apply_chat_template(llm_input)
58
+ results_generator = self.llm.generate(llm_input, validated_sampling_params, request_id)
59
+ n_responses, n_input_tokens, is_first_output = validated_sampling_params.n, 0, True
60
+ last_output_texts, token_counters = ["" for _ in range(n_responses)], {"batch": 0, "total": 0}
61
+
62
+ batch = {
63
+ "choices": [{"tokens": []} for _ in range(n_responses)],
64
+ }
65
+
66
+ max_batch_size = batch_size or self.default_batch_size
67
+ 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
68
+ batch_size = BatchSize(max_batch_size, min_batch_size, batch_size_growth_factor)
69
+
70
+
71
+ async for request_output in results_generator:
72
+ if is_first_output: # Count input tokens only once
73
+ n_input_tokens = len(request_output.prompt_token_ids)
74
+ is_first_output = False
75
+
76
+ for output in request_output.outputs:
77
+ output_index = output.index
78
+ token_counters["total"] += 1
79
+ if stream:
80
+ new_output = output.text[len(last_output_texts[output_index]):]
81
+ batch["choices"][output_index]["tokens"].append(new_output)
82
+ token_counters["batch"] += 1
83
+
84
+ if token_counters["batch"] >= batch_size.current_batch_size:
85
+ batch["usage"] = {
86
+ "input": n_input_tokens,
87
+ "output": token_counters["total"],
88
+ }
89
+ yield batch
90
+ batch = {
91
+ "choices": [{"tokens": []} for _ in range(n_responses)],
92
+ }
93
+ token_counters["batch"] = 0
94
+ batch_size.update()
95
+
96
+ last_output_texts[output_index] = output.text
97
+
98
+ if not stream:
99
+ for output_index, output in enumerate(last_output_texts):
100
+ batch["choices"][output_index]["tokens"] = [output]
101
+ token_counters["batch"] += 1
102
+
103
+ if token_counters["batch"] > 0:
104
+ batch["usage"] = {"input": n_input_tokens, "output": token_counters["total"]}
105
+ yield batch
106
+
107
+ def _initialize_llm(self):
108
+ try:
109
+ start = time.time()
110
+ engine = AsyncLLMEngine.from_engine_args(self.engine_args)
111
+ end = time.time()
112
+ logging.info(f"Initialized vLLM engine in {end - start:.2f}s")
113
+ return engine
114
+ except Exception as e:
115
+ logging.error("Error initializing vLLM engine: %s", e)
116
+ raise e
117
+
118
+
119
+ class OpenAIvLLMEngine(vLLMEngine):
120
+ def __init__(self, vllm_engine):
121
+ super().__init__(vllm_engine)
122
+ self.served_model_name = os.getenv("OPENAI_SERVED_MODEL_NAME_OVERRIDE") or self.engine_args.model
123
+ self.response_role = os.getenv("OPENAI_RESPONSE_ROLE") or "assistant"
124
+ asyncio.run(self._initialize_engines())
125
+ self.raw_openai_output = bool(int(os.getenv("RAW_OPENAI_OUTPUT", 1)))
126
+
127
+ async def _initialize_engines(self):
128
+ self.model_config = await self.llm.get_model_config()
129
+ self.base_model_paths = [
130
+ BaseModelPath(name=self.engine_args.model, model_path=self.engine_args.model)
131
+ ]
132
+
133
+ lora_modules = os.getenv('LORA_MODULES', None)
134
+ if lora_modules is not None:
135
+ try:
136
+ lora_modules = json.loads(lora_modules)
137
+ lora_modules = [LoRAModulePath(**lora_modules)]
138
+ except:
139
+ lora_modules = None
140
+
141
+
142
+
143
+ self.chat_engine = OpenAIServingChat(
144
+ engine_client=self.llm,
145
+ model_config=self.model_config,
146
+ base_model_paths=self.base_model_paths,
147
+ response_role=self.response_role,
148
+ chat_template=self.tokenizer.tokenizer.chat_template,
149
+ lora_modules=lora_modules,
150
+ prompt_adapters=None,
151
+ request_logger=None
152
+ )
153
+ self.completion_engine = OpenAIServingCompletion(
154
+ engine_client=self.llm,
155
+ model_config=self.model_config,
156
+ base_model_paths=self.base_model_paths,
157
+ lora_modules=lora_modules,
158
+ prompt_adapters=None,
159
+ request_logger=None
160
+ )
161
+
162
+ async def generate(self, openai_request: JobInput):
163
+ if openai_request.openai_route == "/v1/models":
164
+ yield await self._handle_model_request()
165
+ elif openai_request.openai_route in ["/v1/chat/completions", "/v1/completions"]:
166
+ async for response in self._handle_chat_or_completion_request(openai_request):
167
+ yield response
168
+ else:
169
+ yield create_error_response("Invalid route").model_dump()
170
+
171
+ async def _handle_model_request(self):
172
+ models = await self.chat_engine.show_available_models()
173
+ return models.model_dump()
174
+
175
+ async def _handle_chat_or_completion_request(self, openai_request: JobInput):
176
+ if openai_request.openai_route == "/v1/chat/completions":
177
+ request_class = ChatCompletionRequest
178
+ generator_function = self.chat_engine.create_chat_completion
179
+ elif openai_request.openai_route == "/v1/completions":
180
+ request_class = CompletionRequest
181
+ generator_function = self.completion_engine.create_completion
182
+
183
+ try:
184
+ request = request_class(
185
+ **openai_request.openai_input
186
+ )
187
+ except Exception as e:
188
+ yield create_error_response(str(e)).model_dump()
189
+ return
190
+
191
+ dummy_request = DummyRequest()
192
+ response_generator = await generator_function(request, raw_request=dummy_request)
193
+
194
+ if not openai_request.openai_input.get("stream") or isinstance(response_generator, ErrorResponse):
195
+ yield response_generator.model_dump()
196
+ else:
197
+ batch = []
198
+ batch_token_counter = 0
199
+ batch_size = BatchSize(self.default_batch_size, self.min_batch_size, self.batch_size_growth_factor)
200
+
201
+ async for chunk_str in response_generator:
202
+ if "data" in chunk_str:
203
+ if self.raw_openai_output:
204
+ data = chunk_str
205
+ elif "[DONE]" in chunk_str:
206
+ continue
207
+ else:
208
+ data = json.loads(chunk_str.removeprefix("data: ").rstrip("\n\n")) if not self.raw_openai_output else chunk_str
209
+ batch.append(data)
210
+ batch_token_counter += 1
211
+ if batch_token_counter >= batch_size.current_batch_size:
212
+ if self.raw_openai_output:
213
+ batch = "".join(batch)
214
+ yield batch
215
+ batch = []
216
+ batch_token_counter = 0
217
+ batch_size.update()
218
+ if batch:
219
+ if self.raw_openai_output:
220
+ batch = "".join(batch)
221
+ yield batch
222
+
src/engine_args.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import logging
4
+ from torch.cuda import device_count
5
+ from vllm import AsyncEngineArgs
6
+ from vllm.model_executor.model_loader.tensorizer import TensorizerConfig
7
+
8
+ RENAME_ARGS_MAP = {
9
+ "MODEL_NAME": "model",
10
+ "MODEL_REVISION": "revision",
11
+ "TOKENIZER_NAME": "tokenizer",
12
+ "MAX_CONTEXT_LEN_TO_CAPTURE": "max_seq_len_to_capture"
13
+ }
14
+
15
+ DEFAULT_ARGS = {
16
+ "disable_log_stats": os.getenv('DISABLE_LOG_STATS', 'False').lower() == 'true',
17
+ "disable_log_requests": os.getenv('DISABLE_LOG_REQUESTS', 'False').lower() == 'true',
18
+ "gpu_memory_utilization": float(os.getenv('GPU_MEMORY_UTILIZATION', 0.95)),
19
+ "pipeline_parallel_size": int(os.getenv('PIPELINE_PARALLEL_SIZE', 1)),
20
+ "tensor_parallel_size": int(os.getenv('TENSOR_PARALLEL_SIZE', 1)),
21
+ "served_model_name": os.getenv('SERVED_MODEL_NAME', None),
22
+ "tokenizer": os.getenv('TOKENIZER', None),
23
+ "skip_tokenizer_init": os.getenv('SKIP_TOKENIZER_INIT', 'False').lower() == 'true',
24
+ "tokenizer_mode": os.getenv('TOKENIZER_MODE', 'auto'),
25
+ "trust_remote_code": os.getenv('TRUST_REMOTE_CODE', 'False').lower() == 'true',
26
+ "download_dir": os.getenv('DOWNLOAD_DIR', None),
27
+ "load_format": os.getenv('LOAD_FORMAT', 'auto'),
28
+ "dtype": os.getenv('DTYPE', 'auto'),
29
+ "kv_cache_dtype": os.getenv('KV_CACHE_DTYPE', 'auto'),
30
+ "quantization_param_path": os.getenv('QUANTIZATION_PARAM_PATH', None),
31
+ "seed": int(os.getenv('SEED', 0)),
32
+ "max_model_len": int(os.getenv('MAX_MODEL_LEN', 0)) or None,
33
+ "worker_use_ray": os.getenv('WORKER_USE_RAY', 'False').lower() == 'true',
34
+ "distributed_executor_backend": os.getenv('DISTRIBUTED_EXECUTOR_BACKEND', None),
35
+ "max_parallel_loading_workers": int(os.getenv('MAX_PARALLEL_LOADING_WORKERS', 0)) or None,
36
+ "block_size": int(os.getenv('BLOCK_SIZE', 16)),
37
+ "enable_prefix_caching": os.getenv('ENABLE_PREFIX_CACHING', 'False').lower() == 'true',
38
+ "disable_sliding_window": os.getenv('DISABLE_SLIDING_WINDOW', 'False').lower() == 'true',
39
+ "use_v2_block_manager": os.getenv('USE_V2_BLOCK_MANAGER', 'False').lower() == 'true',
40
+ "swap_space": int(os.getenv('SWAP_SPACE', 4)), # GiB
41
+ "cpu_offload_gb": int(os.getenv('CPU_OFFLOAD_GB', 0)), # GiB
42
+ "max_num_batched_tokens": int(os.getenv('MAX_NUM_BATCHED_TOKENS', 0)) or None,
43
+ "max_num_seqs": int(os.getenv('MAX_NUM_SEQS', 256)),
44
+ "max_logprobs": int(os.getenv('MAX_LOGPROBS', 20)), # Default value for OpenAI Chat Completions API
45
+ "revision": os.getenv('REVISION', None),
46
+ "code_revision": os.getenv('CODE_REVISION', None),
47
+ "rope_scaling": os.getenv('ROPE_SCALING', None),
48
+ "rope_theta": float(os.getenv('ROPE_THETA', 0)) or None,
49
+ "tokenizer_revision": os.getenv('TOKENIZER_REVISION', None),
50
+ "quantization": os.getenv('QUANTIZATION', None),
51
+ "enforce_eager": os.getenv('ENFORCE_EAGER', 'False').lower() == 'true',
52
+ "max_context_len_to_capture": int(os.getenv('MAX_CONTEXT_LEN_TO_CAPTURE', 0)) or None,
53
+ "max_seq_len_to_capture": int(os.getenv('MAX_SEQ_LEN_TO_CAPTURE', 8192)),
54
+ "disable_custom_all_reduce": os.getenv('DISABLE_CUSTOM_ALL_REDUCE', 'False').lower() == 'true',
55
+ "tokenizer_pool_size": int(os.getenv('TOKENIZER_POOL_SIZE', 0)),
56
+ "tokenizer_pool_type": os.getenv('TOKENIZER_POOL_TYPE', 'ray'),
57
+ "tokenizer_pool_extra_config": os.getenv('TOKENIZER_POOL_EXTRA_CONFIG', None),
58
+ "enable_lora": os.getenv('ENABLE_LORA', 'False').lower() == 'true',
59
+ "max_loras": int(os.getenv('MAX_LORAS', 1)),
60
+ "max_lora_rank": int(os.getenv('MAX_LORA_RANK', 16)),
61
+ "enable_prompt_adapter": os.getenv('ENABLE_PROMPT_ADAPTER', 'False').lower() == 'true',
62
+ "max_prompt_adapters": int(os.getenv('MAX_PROMPT_ADAPTERS', 1)),
63
+ "max_prompt_adapter_token": int(os.getenv('MAX_PROMPT_ADAPTER_TOKEN', 0)),
64
+ "fully_sharded_loras": os.getenv('FULLY_SHARDED_LORAS', 'False').lower() == 'true',
65
+ "lora_extra_vocab_size": int(os.getenv('LORA_EXTRA_VOCAB_SIZE', 256)),
66
+ "long_lora_scaling_factors": tuple(map(float, os.getenv('LONG_LORA_SCALING_FACTORS', '').split(','))) if os.getenv('LONG_LORA_SCALING_FACTORS') else None,
67
+ "lora_dtype": os.getenv('LORA_DTYPE', 'auto'),
68
+ "max_cpu_loras": int(os.getenv('MAX_CPU_LORAS', 0)) or None,
69
+ "device": os.getenv('DEVICE', 'auto'),
70
+ "ray_workers_use_nsight": os.getenv('RAY_WORKERS_USE_NSIGHT', 'False').lower() == 'true',
71
+ "num_gpu_blocks_override": int(os.getenv('NUM_GPU_BLOCKS_OVERRIDE', 0)) or None,
72
+ "num_lookahead_slots": int(os.getenv('NUM_LOOKAHEAD_SLOTS', 0)),
73
+ "model_loader_extra_config": os.getenv('MODEL_LOADER_EXTRA_CONFIG', None),
74
+ "ignore_patterns": os.getenv('IGNORE_PATTERNS', None),
75
+ "preemption_mode": os.getenv('PREEMPTION_MODE', None),
76
+ "scheduler_delay_factor": float(os.getenv('SCHEDULER_DELAY_FACTOR', 0.0)),
77
+ "enable_chunked_prefill": os.getenv('ENABLE_CHUNKED_PREFILL', None),
78
+ "guided_decoding_backend": os.getenv('GUIDED_DECODING_BACKEND', 'outlines'),
79
+ "speculative_model": os.getenv('SPECULATIVE_MODEL', None),
80
+ "speculative_draft_tensor_parallel_size": int(os.getenv('SPECULATIVE_DRAFT_TENSOR_PARALLEL_SIZE', 0)) or None,
81
+ "num_speculative_tokens": int(os.getenv('NUM_SPECULATIVE_TOKENS', 0)) or None,
82
+ "speculative_max_model_len": int(os.getenv('SPECULATIVE_MAX_MODEL_LEN', 0)) or None,
83
+ "speculative_disable_by_batch_size": int(os.getenv('SPECULATIVE_DISABLE_BY_BATCH_SIZE', 0)) or None,
84
+ "ngram_prompt_lookup_max": int(os.getenv('NGRAM_PROMPT_LOOKUP_MAX', 0)) or None,
85
+ "ngram_prompt_lookup_min": int(os.getenv('NGRAM_PROMPT_LOOKUP_MIN', 0)) or None,
86
+ "spec_decoding_acceptance_method": os.getenv('SPEC_DECODING_ACCEPTANCE_METHOD', 'rejection_sampler'),
87
+ "typical_acceptance_sampler_posterior_threshold": float(os.getenv('TYPICAL_ACCEPTANCE_SAMPLER_POSTERIOR_THRESHOLD', 0)) or None,
88
+ "typical_acceptance_sampler_posterior_alpha": float(os.getenv('TYPICAL_ACCEPTANCE_SAMPLER_POSTERIOR_ALPHA', 0)) or None,
89
+ "qlora_adapter_name_or_path": os.getenv('QLORA_ADAPTER_NAME_OR_PATH', None),
90
+ "disable_logprobs_during_spec_decoding": os.getenv('DISABLE_LOGPROBS_DURING_SPEC_DECODING', None),
91
+ "otlp_traces_endpoint": os.getenv('OTLP_TRACES_ENDPOINT', None),
92
+ "use_v2_block_manager": os.getenv('USE_V2_BLOCK_MANAGER', 'true')
93
+ }
94
+
95
+ def match_vllm_args(args):
96
+ """Rename args to match vllm by:
97
+ 1. Renaming keys to lower case
98
+ 2. Renaming keys to match vllm
99
+ 3. Filtering args to match vllm's AsyncEngineArgs
100
+
101
+ Args:
102
+ args (dict): Dictionary of args
103
+
104
+ Returns:
105
+ dict: Dictionary of args with renamed keys
106
+ """
107
+ renamed_args = {RENAME_ARGS_MAP.get(k, k): v for k, v in args.items()}
108
+ matched_args = {k: v for k, v in renamed_args.items() if k in AsyncEngineArgs.__dataclass_fields__}
109
+ return {k: v for k, v in matched_args.items() if v not in [None, ""]}
110
+ def get_local_args():
111
+ """
112
+ Retrieve local arguments from a JSON file.
113
+
114
+ Returns:
115
+ dict: Local arguments.
116
+ """
117
+ if not os.path.exists("/local_model_args.json"):
118
+ return {}
119
+
120
+ with open("/local_model_args.json", "r") as f:
121
+ local_args = json.load(f)
122
+
123
+ if local_args.get("MODEL_NAME") is None:
124
+ raise ValueError("Model name not found in /local_model_args.json. There was a problem when baking the model in.")
125
+
126
+ logging.info(f"Using baked in model with args: {local_args}")
127
+ os.environ["TRANSFORMERS_OFFLINE"] = "1"
128
+ os.environ["HF_HUB_OFFLINE"] = "1"
129
+
130
+ return local_args
131
+ def get_engine_args():
132
+ # Start with default args
133
+ args = DEFAULT_ARGS
134
+
135
+ # Get env args that match keys in AsyncEngineArgs
136
+ args.update(os.environ)
137
+
138
+ # Get local args if model is baked in and overwrite env args
139
+ args.update(get_local_args())
140
+
141
+ # if args.get("TENSORIZER_URI"): TODO: add back once tensorizer is ready
142
+ # args["load_format"] = "tensorizer"
143
+ # args["model_loader_extra_config"] = TensorizerConfig(tensorizer_uri=args["TENSORIZER_URI"], num_readers=None)
144
+ # logging.info(f"Using tensorized model from {args['TENSORIZER_URI']}")
145
+
146
+
147
+ # Rename and match to vllm args
148
+ args = match_vllm_args(args)
149
+
150
+ # Set tensor parallel size and max parallel loading workers if more than 1 GPU is available
151
+ num_gpus = device_count()
152
+ if num_gpus > 1:
153
+ args["tensor_parallel_size"] = num_gpus
154
+ args["max_parallel_loading_workers"] = None
155
+ if os.getenv("MAX_PARALLEL_LOADING_WORKERS"):
156
+ logging.warning("Overriding MAX_PARALLEL_LOADING_WORKERS with None because more than 1 GPU is available.")
157
+
158
+ # Deprecated env args backwards compatibility
159
+ if args.get("kv_cache_dtype") == "fp8_e5m2":
160
+ args["kv_cache_dtype"] = "fp8"
161
+ logging.warning("Using fp8_e5m2 is deprecated. Please use fp8 instead.")
162
+ if os.getenv("MAX_CONTEXT_LEN_TO_CAPTURE"):
163
+ args["max_seq_len_to_capture"] = int(os.getenv("MAX_CONTEXT_LEN_TO_CAPTURE"))
164
+ logging.warning("Using MAX_CONTEXT_LEN_TO_CAPTURE is deprecated. Please use MAX_SEQ_LEN_TO_CAPTURE instead.")
165
+
166
+ # if "gemma-2" in args.get("model", "").lower():
167
+ # os.environ["VLLM_ATTENTION_BACKEND"] = "FLASHINFER"
168
+ # logging.info("Using FLASHINFER for gemma-2 model.")
169
+
170
+ return AsyncEngineArgs(**args)
src/handler.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import runpod
3
+ from utils import JobInput
4
+ from engine import vLLMEngine, OpenAIvLLMEngine
5
+ import logging
6
+ import asyncio
7
+ import nest_asyncio
8
+
9
+ # Configure logging
10
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
11
+
12
+ # Apply nest_asyncio to allow nested event loops
13
+ nest_asyncio.apply()
14
+
15
+ async def handler(job):
16
+ try:
17
+ logging.info("Received job: %s", job) # Log the received job
18
+ job_input = JobInput(job["input"])
19
+
20
+ # Log the input details
21
+ logging.info("Parsed job input: %s", job_input)
22
+
23
+ model_name = job_input.openai_input['model']
24
+ os.environ["MODEL_NAME"] = model_name
25
+ logging.info(f"MODEL_NAME set to: {model_name}")
26
+
27
+ # Initialize engines and log their creation
28
+ logging.info("Initializing vLLMEngine.")
29
+ vllm_engine = vLLMEngine()
30
+ logging.info("vLLMEngine initialized successfully.")
31
+
32
+ logging.info("Initializing OpenAIvLLMEngine.")
33
+ OpenAIvLLM = OpenAIvLLMEngine(vllm_engine)
34
+ logging.info("OpenAIvLLMEngine initialized successfully.")
35
+
36
+ # Determine which engine to use and log the decision
37
+ engine = OpenAIvLLM if job_input.openai_route else vllm_engine
38
+ engine_type = "OpenAIvLLM" if job_input.openai_route else "vLLM"
39
+ logging.info(f"Using engine: {engine_type}")
40
+
41
+ # Generate results and log the start of the generation process
42
+ logging.info("Starting to generate results.")
43
+ results_generator = engine.generate(job_input)
44
+
45
+ async for batch in results_generator:
46
+ logging.info("Yielding batch: %s", batch) # Log each yielded batch
47
+ yield batch
48
+
49
+ logging.info("Finished processing job: %s", job) # Log completion of job processing
50
+
51
+ except Exception as e:
52
+ logging.error(f"Error in handler: {str(e)}")
53
+ raise
54
+
55
+ def start_handler():
56
+ # Wrapper function to handle event loop creation
57
+ try:
58
+ loop = asyncio.get_event_loop()
59
+ except RuntimeError:
60
+ loop = asyncio.new_event_loop()
61
+ asyncio.set_event_loop(loop)
62
+
63
+ runpod.serverless.start(
64
+ {
65
+ "handler": handler,
66
+ "concurrency_modifier": lambda x: 300,
67
+ "return_aggregate_stream": True,
68
+ }
69
+ )
70
+
71
+ if __name__ == "__main__":
72
+ start_handler()
src/tokenizer.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer
2
+ import os
3
+ from typing import Union
4
+
5
+ class TokenizerWrapper:
6
+ def __init__(self, tokenizer_name_or_path, tokenizer_revision, trust_remote_code):
7
+ print(f"tokenizer_name_or_path: {tokenizer_name_or_path}, tokenizer_revision: {tokenizer_revision}, trust_remote_code: {trust_remote_code}")
8
+ self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path, revision=tokenizer_revision or "main", trust_remote_code=trust_remote_code)
9
+ self.custom_chat_template = os.getenv("CUSTOM_CHAT_TEMPLATE")
10
+ self.has_chat_template = bool(self.tokenizer.chat_template) or bool(self.custom_chat_template)
11
+ if self.custom_chat_template and isinstance(self.custom_chat_template, str):
12
+ self.tokenizer.chat_template = self.custom_chat_template
13
+
14
+ def apply_chat_template(self, input: Union[str, list[dict[str, str]]]) -> str:
15
+ if isinstance(input, list):
16
+ if not self.has_chat_template:
17
+ raise ValueError(
18
+ "Chat template does not exist for this model, you must provide a single string input instead of a list of messages"
19
+ )
20
+ elif isinstance(input, str):
21
+ input = [{"role": "user", "content": input}]
22
+ else:
23
+ raise ValueError("Input must be a string or a list of messages")
24
+
25
+ return self.tokenizer.apply_chat_template(
26
+ input, tokenize=False, add_generation_prompt=True
27
+ )
src/utils.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from http import HTTPStatus
4
+ from functools import wraps
5
+ from time import time
6
+ from vllm.entrypoints.openai.protocol import RequestResponseMetadata
7
+
8
+ try:
9
+ from vllm.utils import random_uuid
10
+ from vllm.entrypoints.openai.protocol import ErrorResponse
11
+ from vllm import SamplingParams
12
+ except ImportError:
13
+ logging.warning("Error importing vllm, skipping related imports. This is ONLY expected when baking model into docker image from a machine without GPUs")
14
+ pass
15
+
16
+ logging.basicConfig(level=logging.INFO)
17
+
18
+ def count_physical_cores():
19
+ with open('/proc/cpuinfo') as f:
20
+ content = f.readlines()
21
+
22
+ cores = set()
23
+ current_physical_id = None
24
+ current_core_id = None
25
+
26
+ for line in content:
27
+ if 'physical id' in line:
28
+ current_physical_id = line.strip().split(': ')[1]
29
+ elif 'core id' in line:
30
+ current_core_id = line.strip().split(': ')[1]
31
+ cores.add((current_physical_id, current_core_id))
32
+
33
+ return len(cores)
34
+
35
+
36
+ class JobInput:
37
+ def __init__(self, job):
38
+ self.llm_input = job.get("messages", job.get("prompt"))
39
+ self.stream = job.get("stream", False)
40
+ self.max_batch_size = job.get("max_batch_size")
41
+ self.apply_chat_template = job.get("apply_chat_template", False)
42
+ self.use_openai_format = job.get("use_openai_format", False)
43
+ self.sampling_params = SamplingParams(**job.get("sampling_params", {}))
44
+ self.request_id = random_uuid()
45
+ batch_size_growth_factor = job.get("batch_size_growth_factor")
46
+ self.batch_size_growth_factor = float(batch_size_growth_factor) if batch_size_growth_factor else None
47
+ min_batch_size = job.get("min_batch_size")
48
+ self.min_batch_size = int(min_batch_size) if min_batch_size else None
49
+ self.openai_route = job.get("openai_route")
50
+ self.openai_input = job.get("openai_input")
51
+ class DummyState:
52
+ def __init__(self):
53
+ self.request_metadata = None
54
+
55
+ class DummyRequest:
56
+ def __init__(self):
57
+ self.headers = {}
58
+ self.state = DummyState()
59
+ async def is_disconnected(self):
60
+ return False
61
+
62
+ class BatchSize:
63
+ def __init__(self, max_batch_size, min_batch_size, batch_size_growth_factor):
64
+ self.max_batch_size = max_batch_size
65
+ self.batch_size_growth_factor = batch_size_growth_factor
66
+ self.min_batch_size = min_batch_size
67
+ self.is_dynamic = batch_size_growth_factor > 1 and min_batch_size >= 1 and max_batch_size > min_batch_size
68
+ if self.is_dynamic:
69
+ self.current_batch_size = min_batch_size
70
+ else:
71
+ self.current_batch_size = max_batch_size
72
+
73
+ def update(self):
74
+ if self.is_dynamic:
75
+ self.current_batch_size = min(self.current_batch_size*self.batch_size_growth_factor, self.max_batch_size)
76
+
77
+ def create_error_response(message: str, err_type: str = "BadRequestError", status_code: HTTPStatus = HTTPStatus.BAD_REQUEST) -> ErrorResponse:
78
+ return ErrorResponse(message=message,
79
+ type=err_type,
80
+ code=status_code.value)
81
+
82
+ def get_int_bool_env(env_var: str, default: bool) -> bool:
83
+ return int(os.getenv(env_var, int(default))) == 1
84
+
85
+ def timer_decorator(func):
86
+ @wraps(func)
87
+ def wrapper(*args, **kwargs):
88
+ start = time()
89
+ result = func(*args, **kwargs)
90
+ end = time()
91
+ logging.info(f"{func.__name__} completed in {end - start:.2f} seconds")
92
+ return result
93
+ return wrapper
worker-config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8d7f06292a8283339c11659fd78b0365eaf1649d9b722ba7dcc23c744130f21
3
+ size 38447