Spaces:
Paused
Paused
Roll back to f79b9e8cd3c2
Browse filesFiles changed (2)
- Dockerfile+1-21
- app.py+7-51
1234567891011121314151617181920212223242526# Stage 1: llama.cpp built with CUDA, for GPU hardware. No prebuilt CUDA wheel exists# for the pinned llama-cpp-python version, so it is compiled here. It is installed# apart from the CPU wheel (/opt/llama-cuda) and used only when a GPU is present;# on CPU hardware the image behaves exactly as before. GGML_NATIVE=off keeps the# build free of instructions specific to the build machine's CPU.FROM nvidia/cuda:12.4.1-devel-ubuntu22.04 AS llama-cudaRUN apt-get update && apt-get install -y --no-install-recommends python3 python3-pip cmake git build-essential \&& rm -rf /var/lib/apt/lists/*RUN CMAKE_ARGS="-DGGML_CUDA=on -DGGML_NATIVE=off" FORCE_CMAKE=1 \pip install --no-cache-dir --no-deps --no-binary llama-cpp-python --target /opt/llama-cuda llama-cpp-python==0.3.36# the CUDA libraries that build links against (the driver itself comes from the GPU host)RUN mkdir -p /opt/cuda-libs && cp -a /usr/local/cuda/lib64/libcudart.so.12* /usr/local/cuda/lib64/libcublas.so.12* \/usr/local/cuda/lib64/libcublasLt.so.12* /opt/cuda-libs/# Stage 2: the service. Python 3.11: the version this image has been built and run withFROM python:3.11-slim# On GPU hardware the host's NVIDIA runtime mounts the driver when these are set.ENV NVIDIA_VISIBLE_DEVICES=all \NVIDIA_DRIVER_CAPABILITIES=compute,utilityCOPY --from=llama-cuda /opt/llama-cuda /opt/llama-cudaCOPY --from=llama-cuda /opt/cuda-libs /opt/cuda-libsWORKDIR /app# Install system dependencies123456# Python 3.11: the version this image has been built and run withFROM python:3.11-slimWORKDIR /app# Install system dependencies
72 unmodified lines7374757677787980818283848586878889909192939495705 unmodified lines80180280380480580680780813 unmodified lines8228238248258268278288298302 unmodified lines8338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668 unmodified lines87587687787887988088188288388488588688788888989089189289389489572 unmodified linesLOCAL_LLM_FILE = os.environ.get("LOCAL_LLM_FILE", "Qwen3.5-2B-Q4_K_M.gguf")LOCAL_LLM_CTX = int(os.environ.get("LOCAL_LLM_CTX", "4096"))LOCAL_LLM_THREADS = int(os.environ.get("LOCAL_LLM_THREADS", "2"))# The CUDA build of llama.cpp and the CUDA libraries it links (see the Dockerfile).# Used only when the host provides an NVIDIA driver; otherwise the CPU wheel is.LLAMA_CUDA_DIR = os.environ.get("LLAMA_CUDA_DIR", "/opt/llama-cuda")CUDA_LIBS_DIR = os.environ.get("CUDA_LIBS_DIR", "/opt/cuda-libs")LOCAL_LLM_GPU = os.environ.get("LOCAL_LLM_GPU", "auto").lower() # auto | offdef gpu_runtime_present() -> bool:"""Whether this machine has an NVIDIA driver and the image has the CUDA build."""if LOCAL_LLM_GPU == "off" or not os.path.isdir(os.path.join(LLAMA_CUDA_DIR, "llama_cpp")):return Falsetry:import ctypesctypes.CDLL("libcuda.so.1")return Trueexcept OSError:return FalseLOCAL_LLM_MAX_TOKENS = int(os.environ.get("LOCAL_LLM_MAX_TOKENS", "320"))LOCAL_LLM_TEMPERATURE = float(os.environ.get("LOCAL_LLM_TEMPERATURE", "0.3"))LOCAL_LLM_MAX_INPUT_CHARS = int(os.environ.get("LOCAL_LLM_MAX_INPUT_CHARS", "2400"))705 unmodified linesdef __init__(self):self.llm = Noneself.error: Optional[str] = Noneself.accelerator = "cpu"self.gpu_error: Optional[str] = Noneself._chatml = Falseself._prefill = ""self._load_lock = threading.Lock()13 unmodified lines"loaded": self.ready,"loading": self._load_lock.locked(),"error": self.error,# "cuda" only when the model was actually loaded onto a GPU"accelerator": self.accelerator if self.ready else None,"gpu_error": self.gpu_error,}def load(self):2 unmodified linesif self.llm is not None or self.error:return self.llmtry:try:path = hf_hub_download(repo_id=LOCAL_LLM_REPO, filename=LOCAL_LLM_FILE, revision=LOCAL_LLM_REVISION, token=HF_TOKEN or None)except Exception:# A stale HF_TOKEN must not block the download of a public modelpath = hf_hub_download(repo_id=LOCAL_LLM_REPO, filename=LOCAL_LLM_FILE, revision=LOCAL_LLM_REVISION, token=False)gpu = Falseif gpu_runtime_present():# Try the CUDA build in a child process first; if it cannot load the# model on the GPU, say why and carry on with the CPU wheel.try:self._probe(path, gpu=True)gpu = Trueexcept Exception as e:self.gpu_error = f"{type(e).__name__}: {str(e)[:300]}"logger.error(f"GPU build unusable, using CPU: {self.gpu_error}")if gpu:import ctypesfor lib in ("libcudart.so.12", "libcublasLt.so.12", "libcublas.so.12"):ctypes.CDLL(os.path.join(CUDA_LIBS_DIR, lib), mode=ctypes.RTLD_GLOBAL)sys.path.insert(0, LLAMA_CUDA_DIR)else:self._probe(path)from llama_cpp import Llama# n_threads_batch (prompt processing) defaults to the host's core# count, which a Space container reports far above its 2 vCPUs.llm = Llama(model_path=path, n_ctx=LOCAL_LLM_CTX, n_threads=LOCAL_LLM_THREADS,n_threads_batch=LOCAL_LLM_THREADS, n_gpu_layers=-1 if gpu else 0, verbose=False)self.accelerator = "cuda" if gpu else "cpu"template = str((llm.metadata or {}).get("tokenizer.chat_template", ""))self._chatml = "<|im_start|>" in template# Qwen3.5 answers directly when the assistant turn opens with an8 unmodified linesreturn self.llm@staticmethoddef _probe(path: str, gpu: bool = False) -> None:"""Load the model once in a child process. A native crash there (forexample a CPU instruction the prebuilt wheel needs but this machinelacks, or a CUDA build that cannot reach the GPU) raises here insteadof killing the API process."""code = ("import sys; from llama_cpp import Llama; "f"m = Llama(model_path=sys.argv[1], n_ctx=256, n_threads=1, n_threads_batch=1, n_gpu_layers={-1 if gpu else 0}, verbose=False); ""m.create_completion('Hi', max_tokens=1)")env = dict(os.environ)if gpu:env["PYTHONPATH"] = LLAMA_CUDA_DIR + os.pathsep + env.get("PYTHONPATH", "")env["LD_LIBRARY_PATH"] = CUDA_LIBS_DIR + os.pathsep + env.get("LD_LIBRARY_PATH", "")r = subprocess.run([sys.executable, "-c", code, path], capture_output=True, text=True, timeout=300, env=env)if r.returncode != 0:raise RuntimeError(f"llama.cpp probe exited with {r.returncode}: {(r.stderr or '')[-200:]}")72 unmodified lines737475767778705 unmodified lines78478578678778878913 unmodified lines8038048058068078082 unmodified lines8118128138148158168178188198208218228238248258268278 unmodified lines83683783883984084184284384484584684784884985085172 unmodified linesLOCAL_LLM_FILE = os.environ.get("LOCAL_LLM_FILE", "Qwen3.5-2B-Q4_K_M.gguf")LOCAL_LLM_CTX = int(os.environ.get("LOCAL_LLM_CTX", "4096"))LOCAL_LLM_THREADS = int(os.environ.get("LOCAL_LLM_THREADS", "2"))LOCAL_LLM_MAX_TOKENS = int(os.environ.get("LOCAL_LLM_MAX_TOKENS", "320"))LOCAL_LLM_TEMPERATURE = float(os.environ.get("LOCAL_LLM_TEMPERATURE", "0.3"))LOCAL_LLM_MAX_INPUT_CHARS = int(os.environ.get("LOCAL_LLM_MAX_INPUT_CHARS", "2400"))705 unmodified linesdef __init__(self):self.llm = Noneself.error: Optional[str] = Noneself._chatml = Falseself._prefill = ""self._load_lock = threading.Lock()13 unmodified lines"loaded": self.ready,"loading": self._load_lock.locked(),"error": self.error,}def load(self):2 unmodified linesif self.llm is not None or self.error:return self.llmtry:from llama_cpp import Llamatry:path = hf_hub_download(repo_id=LOCAL_LLM_REPO, filename=LOCAL_LLM_FILE, revision=LOCAL_LLM_REVISION, token=HF_TOKEN or None)except Exception:# A stale HF_TOKEN must not block the download of a public modelpath = hf_hub_download(repo_id=LOCAL_LLM_REPO, filename=LOCAL_LLM_FILE, revision=LOCAL_LLM_REVISION, token=False)self._probe(path)# n_threads_batch (prompt processing) defaults to the host's core# count, which a Space container reports far above its 2 vCPUs.llm = Llama(model_path=path, n_ctx=LOCAL_LLM_CTX, n_threads=LOCAL_LLM_THREADS,n_threads_batch=LOCAL_LLM_THREADS, verbose=False)template = str((llm.metadata or {}).get("tokenizer.chat_template", ""))self._chatml = "<|im_start|>" in template# Qwen3.5 answers directly when the assistant turn opens with an8 unmodified linesreturn self.llm@staticmethoddef _probe(path: str) -> None:"""Load the model once in a child process. A native crash there (forexample a CPU instruction the prebuilt wheel needs but this machinelacks) raises here instead of killing the API process."""code = ("import sys; from llama_cpp import Llama; ""m = Llama(model_path=sys.argv[1], n_ctx=256, n_threads=1, n_threads_batch=1, verbose=False); ""m.create_completion('Hi', max_tokens=1)")r = subprocess.run([sys.executable, "-c", code, path], capture_output=True, text=True, timeout=300)if r.returncode != 0:raise RuntimeError(f"llama.cpp probe exited with {r.returncode}: {(r.stderr or '')[-200:]}")
Dockerfile+1-21
app.py+7-51