Skip to content

Commit 6bd1075

Browse files
committed
Merge branch 'Maximilian-Winter/main' into main
2 parents fab064d + ca01f98 commit 6bd1075

File tree

7 files changed

+288
-1
lines changed

7 files changed

+288
-1
lines changed

docker/Dockerfile

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Define the image argument and provide a default value
2+
ARG IMAGE=python:3-slim-bullseye
3+
4+
# Use the image as specified
5+
FROM ${IMAGE}
6+
7+
# Re-declare the ARG after FROM
8+
ARG IMAGE
9+
10+
# Update and upgrade the existing packages
11+
RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends \
12+
python3 \
13+
python3-pip \
14+
ninja-build \
15+
build-essential
16+
17+
RUN python3 -m pip install --upgrade pip pytest cmake scikit-build setuptools fastapi uvicorn sse-starlette
18+
19+
# Perform the conditional installations based on the image
20+
RUN echo "Image: ${IMAGE}" && \
21+
if [ "${IMAGE}" = "python:3-slim-bullseye" ] ; then \
22+
echo "OpenBLAS install:" && \
23+
apt-get install -y --no-install-recommends libopenblas-dev && \
24+
LLAMA_OPENBLAS=1 pip install llama-cpp-python --verbose; \
25+
else \
26+
echo "CuBLAS install:" && \
27+
LLAMA_CUBLAS=1 pip install llama-cpp-python --verbose; \
28+
fi
29+
30+
# Clean up apt cache
31+
RUN rm -rf /var/lib/apt/lists/*
32+
33+
# Set a working directory for better clarity
34+
WORKDIR /app
35+
36+
# Copy files to the app directory
37+
RUN echo "Installing model...this can take some time..."
38+
COPY ./model.bin /app/model.bin
39+
COPY ./start_server.sh /app/start_server.sh
40+
41+
# Make the server start script executable
42+
RUN chmod +x /app/start_server.sh
43+
44+
# Set environment variable for the host
45+
ENV HOST=0.0.0.0
46+
47+
# Expose a port for the server
48+
EXPOSE 8000
49+
50+
# Run the server start script
51+
CMD ["/bin/sh", "/app/start_server.sh"]
File renamed without changes.
File renamed without changes.

docker/README.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Dockerfiles for building the llama-cpp-python server
2+
- `Dockerfile.openblas_simple` - a simple Dockerfile for non-GPU OpenBLAS
3+
- `Dockerfile.cuda_simple` - a simple Dockerfile for CUDA accelerated CuBLAS
4+
- `hug_model.py` - a Python utility for interactively choosing and downloading the latest `5_1` quantized models from [huggingface.co/TheBloke]( https://huggingface.co/TheBloke)
5+
- `Dockerfile` - a single OpenBLAS and CuBLAS combined Dockerfile that automatically installs a previously downloaded model `model.bin`
6+
7+
# Get model from Hugging Face
8+
`python3 ./hug_model.py`
9+
10+
You should now have a model in the current directory and `model.bin` symlinked to it for the subsequent Docker build and copy step. e.g.
11+
```
12+
docker $ ls -lh *.bin
13+
-rw-rw-r-- 1 user user 4.8G May 23 18:30 <downloaded-model-file>.q5_1.bin
14+
lrwxrwxrwx 1 user user 24 May 23 18:30 model.bin -> <downloaded-model-file>.q5_1.bin
15+
```
16+
**Note #1:** Make sure you have enough disk space to download the model. As the model is then copied into the image you will need at least
17+
**TWICE** as much disk space as the size of the model:
18+
19+
| Model | Quantized size |
20+
|------:|----------------:|
21+
| 7B | 5 GB |
22+
| 13B | 10 GB |
23+
| 30B | 25 GB |
24+
| 65B | 50 GB |
25+
26+
**Note #2:** If you want to pass or tune additional parameters, customise `./start_server.sh` before running `docker build ...`
27+
28+
# Install Docker Server
29+
30+
**Note #3:** This was tested with Docker running on Linux. If you can get it working on Windows or MacOS, please update this `README.md` with a PR!
31+
32+
[Install Docker Engine](https://docs.docker.com/engine/install)
33+
34+
# Use OpenBLAS
35+
Use if you don't have a NVidia GPU. Defaults to `python:3-slim-bullseye` Docker base image and OpenBLAS:
36+
## Build:
37+
`docker build --build-arg -t openblas .`
38+
## Run:
39+
`docker run --cap-add SYS_RESOURCE -t openblas`
40+
41+
# Use CuBLAS
42+
Requires a NVidia GPU with sufficient VRAM (approximately as much as the size above) and Docker NVidia support (see [container-toolkit/install-guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html))
43+
## Build:
44+
`docker build --build-arg IMAGE=nvidia/cuda:12.1.1-devel-ubuntu22.04 -t cublas .`
45+
## Run:
46+
`docker run --cap-add SYS_RESOURCE -t cublas`

docker/hug_model.py

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
import requests
2+
import json
3+
import os
4+
import struct
5+
6+
def make_request(url, params=None):
7+
print(f"Making request to {url}...")
8+
response = requests.get(url, params=params)
9+
if response.status_code == 200:
10+
return json.loads(response.text)
11+
else:
12+
print(f"Request failed with status code {response.status_code}")
13+
return None
14+
15+
def check_magic_and_version(filename):
16+
with open(filename, 'rb') as f:
17+
# Read the first 6 bytes from the file
18+
data = f.read(6)
19+
20+
# Unpack the binary data, interpreting the first 4 bytes as a little-endian unsigned int
21+
# and the next 2 bytes as a little-endian unsigned short
22+
magic, version = struct.unpack('<I H', data)
23+
24+
print(f"magic: 0x{magic:08x}, version: 0x{version:04x}, file: {filename}")
25+
26+
return magic, version
27+
28+
def download_file(url, destination):
29+
print(f"Downloading {url} to {destination}...")
30+
response = requests.get(url, stream=True)
31+
if response.status_code == 200:
32+
with open(destination, 'wb') as f:
33+
total_downloaded = 0
34+
for chunk in response.iter_content(chunk_size=1024):
35+
if chunk: # filter out keep-alive new chunks
36+
f.write(chunk)
37+
total_downloaded += len(chunk)
38+
if total_downloaded >= 10485760: # 10 MB
39+
print('.', end='', flush=True)
40+
total_downloaded = 0
41+
print("\nDownload complete.")
42+
43+
# Creating a symbolic link from destination to "model.bin"
44+
if os.path.isfile("model.bin"):
45+
os.remove("model.bin") # remove the existing link if any
46+
os.symlink(destination, "model.bin")
47+
else:
48+
print(f"Download failed with status code {response.status_code}")
49+
50+
def get_user_choice(model_list):
51+
# Print the enumerated list
52+
print("\n")
53+
for i, (model_id, rfilename) in enumerate(model_list):
54+
print(f"{i+1}: Model ID: {model_id}, RFilename: {rfilename}")
55+
56+
# Get user's choice
57+
choice = input("Choose a model to download by entering the corresponding number: ")
58+
try:
59+
index = int(choice) - 1
60+
if 0 <= index < len(model_list):
61+
# Return the chosen model
62+
return model_list[index]
63+
else:
64+
print("Invalid choice.")
65+
except ValueError:
66+
print("Invalid input. Please enter a number corresponding to a model.")
67+
except IndexError:
68+
print("Invalid choice. Index out of range.")
69+
70+
return None
71+
72+
import argparse
73+
74+
def main():
75+
# Create an argument parser
76+
parser = argparse.ArgumentParser(description='Process the model version.')
77+
parser.add_argument('-v', '--version', type=int, default=0x0003,
78+
help='an integer for the version to be used')
79+
80+
# Parse the arguments
81+
args = parser.parse_args()
82+
83+
# Define the parameters
84+
params = {
85+
"author": "TheBloke", # Filter by author
86+
"tags": "llama"
87+
}
88+
89+
models = make_request('https://huggingface.co/api/models', params=params)
90+
if models is None:
91+
return
92+
93+
model_list = []
94+
# Iterate over the models
95+
for model in models:
96+
model_id = model['id']
97+
model_info = make_request(f'https://huggingface.co/api/models/{model_id}')
98+
if model_info is None:
99+
continue
100+
101+
for sibling in model_info.get('siblings', []):
102+
rfilename = sibling.get('rfilename')
103+
if rfilename and 'q5_1' in rfilename:
104+
model_list.append((model_id, rfilename))
105+
106+
model_choice = get_user_choice(model_list)
107+
if model_choice is not None:
108+
model_id, rfilename = model_choice
109+
url = f"https://huggingface.co/{model_id}/resolve/main/{rfilename}"
110+
download_file(url, rfilename)
111+
_, version = check_magic_and_version(rfilename)
112+
if version != args.version:
113+
print(f"Warning: Expected version {args.version}, but found different version in the file.")
114+
115+
if __name__ == '__main__':
116+
main()

docker/start_server.sh

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/bin/sh
2+
3+
# For mmap support
4+
ulimit -l unlimited
5+
6+
if [ "$IMAGE" = "python:3-slim-bullseye" ]; then
7+
python3 -B -m llama_cpp.server --model /app/model.bin
8+
else
9+
# You may have to reduce --n_gpu_layers=1000 to 20 or less if you don't have enough VRAM
10+
python3 -B -m llama_cpp.server --model /app/model.bin --n_gpu_layers=1000
11+
fi

llama_cpp/llama.py

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,17 @@
44
import time
55
import math
66
import multiprocessing
7-
from typing import List, Optional, Union, Generator, Sequence, Iterator, Deque, Tuple
7+
from typing import (
8+
List,
9+
Optional,
10+
Union,
11+
Generator,
12+
Sequence,
13+
Iterator,
14+
Deque,
15+
Tuple,
16+
Callable,
17+
)
818
from collections import deque, OrderedDict
919

1020
from . import llama_cpp
@@ -72,6 +82,24 @@ def __init__(
7282
self.llama_state_size = llama_state_size
7383

7484

85+
LogitsProcessor = Callable[[List[int], List[float]], List[float]]
86+
87+
88+
class LogitsProcessorList(List[LogitsProcessor]):
89+
def __call__(self, input_ids: List[int], scores: List[float]) -> List[float]:
90+
for processor in self:
91+
scores = processor(input_ids, scores)
92+
return scores
93+
94+
95+
StoppingCriteria = Callable[[List[int], List[float]], bool]
96+
97+
98+
class StoppingCriteriaList(List[StoppingCriteria]):
99+
def __call__(self, input_ids: List[int], logits: List[float]) -> bool:
100+
return any([stopping_criteria(input_ids, logits) for stopping_criteria in self])
101+
102+
75103
class Llama:
76104
"""High-level Python wrapper for a llama.cpp model."""
77105

@@ -314,6 +342,7 @@ def _sample(
314342
mirostat_tau: llama_cpp.c_float,
315343
mirostat_eta: llama_cpp.c_float,
316344
penalize_nl: bool = True,
345+
logits_processor: Optional[LogitsProcessorList] = None,
317346
):
318347
assert self.ctx is not None
319348
assert len(self.eval_logits) > 0
@@ -326,6 +355,10 @@ def _sample(
326355
else last_n_tokens_size
327356
)
328357
logits = self.eval_logits[-1]
358+
359+
if logits_processor is not None:
360+
logits = logits_processor(list(self.eval_tokens), logits)
361+
329362
nl_logit = logits[self._token_nl]
330363
candidates = self._candidates
331364
for i, logit in enumerate(logits):
@@ -434,6 +467,7 @@ def sample(
434467
mirostat_eta: float = 0.1,
435468
mirostat_tau: float = 5.0,
436469
penalize_nl: bool = True,
470+
logits_processor: Optional[LogitsProcessorList] = None,
437471
):
438472
"""Sample a token from the model.
439473
@@ -466,6 +500,7 @@ def sample(
466500
mirostat_tau=llama_cpp.c_float(mirostat_tau),
467501
mirostat_eta=llama_cpp.c_float(mirostat_eta),
468502
penalize_nl=penalize_nl,
503+
logits_processor=logits_processor,
469504
)
470505

471506
def generate(
@@ -482,6 +517,8 @@ def generate(
482517
mirostat_mode: int = 0,
483518
mirostat_tau: float = 5.0,
484519
mirostat_eta: float = 0.1,
520+
logits_processor: Optional[LogitsProcessorList] = None,
521+
stopping_criteria: Optional[StoppingCriteriaList] = None,
485522
) -> Generator[int, Optional[Sequence[int]], None]:
486523
"""Create a generator of tokens from a prompt.
487524
@@ -539,7 +576,12 @@ def generate(
539576
mirostat_mode=mirostat_mode,
540577
mirostat_tau=mirostat_tau,
541578
mirostat_eta=mirostat_eta,
579+
logits_processor=logits_processor,
542580
)
581+
if stopping_criteria is not None and stopping_criteria(
582+
list(self.eval_tokens), self.eval_logits[-1]
583+
):
584+
return
543585
tokens_or_none = yield token
544586
tokens = [token]
545587
if tokens_or_none is not None:
@@ -637,6 +679,7 @@ def _create_completion(
637679
model: Optional[str] = None,
638680
) -> Union[Iterator[Completion], Iterator[CompletionChunk]]:
639681
assert self.ctx is not None
682+
640683
completion_id: str = f"cmpl-{str(uuid.uuid4())}"
641684
created: int = int(time.time())
642685
completion_tokens: List[int] = []
@@ -1334,6 +1377,11 @@ def n_vocab(self) -> int:
13341377
assert self.ctx is not None
13351378
return llama_cpp.llama_n_vocab(self.ctx)
13361379

1380+
def tokenizer(self) -> "LlamaTokenizer":
1381+
"""Return the tokenizer for this model."""
1382+
assert self.ctx is not None
1383+
return LlamaTokenizer(self)
1384+
13371385
@staticmethod
13381386
def token_eos() -> int:
13391387
"""Return the end-of-sequence token."""
@@ -1364,3 +1412,18 @@ def longest_token_prefix(a: Sequence[int], b: Sequence[int]):
13641412
else:
13651413
break
13661414
return longest_prefix
1415+
1416+
1417+
class LlamaTokenizer:
1418+
def __init__(self, llama: Llama):
1419+
self.llama = llama
1420+
1421+
def encode(self, text: str) -> List[int]:
1422+
return self.llama.tokenize(text.encode("utf-8", errors="ignore"))
1423+
1424+
def decode(self, tokens: List[int]) -> str:
1425+
return self.llama.detokenize(tokens).decode("utf-8", errors="ignore")
1426+
1427+
@classmethod
1428+
def from_ggml_file(cls, path: str) -> "LlamaTokenizer":
1429+
return cls(Llama(model_path=path, vocab_only=True))

0 commit comments

Comments
 (0)