diff --git a/DashAI/back/dependencies/job_queues/huey_job_queue.py b/DashAI/back/dependencies/job_queues/huey_job_queue.py index 2d45fb347..76e57d84d 100644 --- a/DashAI/back/dependencies/job_queues/huey_job_queue.py +++ b/DashAI/back/dependencies/job_queues/huey_job_queue.py @@ -462,17 +462,12 @@ def _ensure_worker(self) -> None: if self._worker_proc is not None and self._worker_proc.is_alive(): return - # A worker killed by a cancel or a crash leaves its rows behind - try: - from kink import di - - from DashAI.back.dependencies.model_cache_status import ( - clear_loaded_models, - ) - - clear_loaded_models(di["session_factory"]) - except Exception: - log.exception("Could not clear stale loaded model rows") + # A worker killed by a cancel or a crash leaves its rows behind. The + # first worker has nothing to clear: the app clears the table right + # after running migrations, and since this consumer starts alongside + # the app, on a fresh database the table may not exist yet. + if self._worker_proc is not None: + self._clear_model_rows() ctx = multiprocessing.get_context("spawn") self._worker_in_q = ctx.Queue() diff --git a/DashAI/back/models/hugging_face/llama_utils.py b/DashAI/back/models/hugging_face/llama_utils.py index fe7e73a35..98aa0b638 100644 --- a/DashAI/back/models/hugging_face/llama_utils.py +++ b/DashAI/back/models/hugging_face/llama_utils.py @@ -12,10 +12,20 @@ logger = logging.getLogger(__name__) -try: - import llama_cpp -except ImportError: - llama_cpp = None + +def _get_llama_cpp(): + """Import ``llama_cpp`` on first use, or return ``None`` if not installed. + + The import is deliberately lazy: in a CUDA build, importing ``llama_cpp`` + before ``torch`` makes torch skip its NCCL preload and ``import torch`` + then fails with "undefined symbol: ncclCommShrink". Importing this module + must therefore never import ``llama_cpp`` (see issue #1043). + """ + try: + import llama_cpp + except ImportError: + return None + return llama_cpp # llama_log_callback signature: void (*)(ggml_log_level level, @@ -445,13 +455,14 @@ def _capturing_log_cb(level, msg, user_data): def _lib_dir() -> Path: - return Path(os.path.dirname(llama_cpp.__file__)) / "lib" + return Path(os.path.dirname(_get_llama_cpp().__file__)) / "lib" @lru_cache(maxsize=1) def _load_llama_lib(): """Load llama.dll and install our own log callback so CUDA init output can be captured in _log_capture instead of printed to the real stderr.""" + llama_cpp = _get_llama_cpp() if llama_cpp is None: return None lib = llama_cpp.llama_cpp.load_shared_library("llama", _lib_dir()) @@ -468,7 +479,7 @@ def _load_llama_lib(): @lru_cache(maxsize=1) def _all_ggml_libs() -> tuple: """Load every shared lib in llama_cpp/lib/ so backend symbols are reachable.""" - if llama_cpp is None: + if _get_llama_cpp() is None: return () if sys.platform.startswith("win"): patterns = ("*.dll",) @@ -582,7 +593,7 @@ def get_llama_gpu_devices_formatted() -> list[str]: """GPU device strings visible to llama_cpp (not torch). Example: ["GPU 0: NVIDIA GeForce RTX 5080 - Compute Capability 12.0"] """ - if llama_cpp is None: + if _get_llama_cpp() is None: return [] try: @@ -620,6 +631,7 @@ def is_gpu_available_for_llama_cpp() -> bool: ``True`` if GPU offloading is available; ``False`` if ``llama-cpp-python`` is not installed or if the check raises an unexpected exception. """ + llama_cpp = _get_llama_cpp() if llama_cpp is None: return False try: @@ -665,5 +677,5 @@ def __is_gpu_available_for_llama_cpp_v02() -> bool: ``True`` if the ``ggml_init_cublas`` attribute is found in the loaded library, ``False`` otherwise. """ - lib = llama_cpp.llama_cpp._load_shared_library("llama") + lib = _get_llama_cpp().llama_cpp._load_shared_library("llama") return hasattr(lib, "ggml_init_cublas") diff --git a/Dockerfile.cuda b/Dockerfile.cuda index 067728548..138323499 100644 --- a/Dockerfile.cuda +++ b/Dockerfile.cuda @@ -29,22 +29,45 @@ COPY --from=ghcr.io/astral-sh/uv:0.11 /uv /bin/uv # cuda extra = cu128 torch wheels + llama-cpp-python compiled with CUDA offload COPY pyproject.toml uv.lock ./ -ENV UV_PROJECT_ENVIRONMENT=/opt/venv -ENV CMAKE_ARGS="-DGGML_CUDA=on" +# Pin a uv-managed interpreter and install it under /opt/python so the +# runtime stage can copy it next to the venv (the venv symlinks point at it). +ENV UV_PROJECT_ENVIRONMENT=/opt/venv \ + UV_PYTHON=3.12 \ + UV_PYTHON_PREFERENCE=only-managed \ + UV_PYTHON_INSTALL_DIR=/opt/python +# Build llama.cpp kernels for several GPU generations instead of only the +# build host's GPU: T4 (75), A100 (80), A10/RTX 30xx (86), L4/RTX 40xx (89), +# plus PTX for 89 so newer cards can JIT compile. +# GGML_NATIVE is the same trap on the CPU side: it is ON by default and compiles +# the CPU kernels with -march=native, so an image built on a host with AVX-512 +# dies with SIGILL on one without it. CUDA initialises first, so the crash looks +# like a GPU problem. Turn it off and name the baseline explicitly: AVX2/FMA/F16C +# are present on every Haswell-or-later host, AVX-512 is not. +ENV CMAKE_ARGS="-DGGML_CUDA=on -DCMAKE_CUDA_ARCHITECTURES=75-real;80-real;86-real;89-real;89-virtual \ +-DGGML_NATIVE=OFF -DGGML_AVX=ON -DGGML_AVX2=ON -DGGML_FMA=ON -DGGML_F16C=ON -DGGML_AVX512=OFF" RUN uv sync --locked --extra cuda --no-dev --no-install-project --no-cache # -------- Stage 3: runtime (CUDA runtime, no build tools) -------- FROM nvidia/cuda:12.8.0-runtime-ubuntu22.04 WORKDIR /app +# libgomp1: OpenMP runtime required by every llama-cpp-python shared library RUN apt-get update && apt-get install -y \ - python3 \ + libgomp1 \ && rm -rf /var/lib/apt/lists/* -# copy the resolved virtualenv only (not build tools) +# copy the managed interpreter and the resolved virtualenv (not build tools) +COPY --from=builder /opt/python /opt/python COPY --from=builder /opt/venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" +# libtorch_cuda.so has no DT_NEEDED entry for libnccl and relies on torch +# preloading it, which is skipped when llama_cpp is imported first +# ("undefined symbol: ncclCommShrink"). Preload it explicitly. +RUN ln -s "$(ls /opt/venv/lib/python3.*/site-packages/nvidia/nccl/lib/libnccl.so.2)" \ + /usr/local/lib/libnccl.so.2 +ENV LD_PRELOAD=/usr/local/lib/libnccl.so.2 + # application code COPY . . # built frontend from stage 1 diff --git a/tests/back/models/test_llama_import_order.py b/tests/back/models/test_llama_import_order.py new file mode 100644 index 000000000..9ead2261e --- /dev/null +++ b/tests/back/models/test_llama_import_order.py @@ -0,0 +1,35 @@ +"""Import-order guard for llama_cpp vs torch (issue #1043). + +In CUDA builds, importing ``llama_cpp`` before ``torch`` makes torch skip its +NCCL preload, and ``import torch`` then fails with +"undefined symbol: ncclCommShrink". These checks run in a fresh interpreter +because the current test process has already imported both libraries. +""" + +import subprocess +import sys +import textwrap + + +def _run(code: str) -> None: + result = subprocess.run( + [sys.executable, "-c", textwrap.dedent(code)], + capture_output=True, + text=True, + timeout=300, + ) + assert result.returncode == 0, result.stderr + + +def test_gguf_base_imports_torch_before_llama_cpp(): + _run( + """ + import sys + import DashAI.back.models.hugging_face.gguf_text_generation_base # noqa: F401 + modules = list(sys.modules) + if "llama_cpp" in modules: + assert modules.index("torch") < modules.index("llama_cpp"), ( + "llama_cpp was imported before torch" + ) + """ + )