abetlen / llama-cpp-python

Python bindings for llama.cpp
https://llama-cpp-python.readthedocs.io
MIT License
7.69k stars 923 forks source link

CUDA unsupported, installation bypasses CUDA at all #1693

Open itinance opened 3 weeks ago

itinance commented 3 weeks ago

Prerequisites

Please answer the following questions for yourself before submitting an issue.

Expected Behavior

Although llama.cpp is installed perfectly and uses my GPU (RTX 4000), the Python bindings don't use the GPU. They stick with the CPU. I also had no impression that any CUDA-related libraries were used during the installation of this package.

1. GPU not used at all

llm = Llama(n_gpu_layers=33, model=...)

should utilize GPU. It doesn't.

2. Installation seems to not install any CUDA related libraries

Please provide a detailed written description of what you were trying to do, and what you expected llama-cpp-python to do.

Installation: CMAKE_ARGS="-DGGML_CUDA=on" pip install llama-cpp-python

Code:

from llama_cpp import Llama

llm = Llama(
      model_path="../models/LongWriter-llama3.1-8b-GGUF/LongWriter-llama3.1-8b-Q4_K_M.gguf",
      n_gpu_layers=33, # Uncomment to use GPU acceleration
      # seed=1337, # Uncomment to set a specific seed
      n_ctx=2048, # Uncomment to increase the context window
)
output = llm(
      "Q: Name the planets in the solar system? A: ", # Prompt
      max_tokens=32, # Generate up to 32 tokens, set to None to generate up to the end of the context window
      stop=["Q:", "\n"], # Stop generating just before the model would generate a new question
      echo=True # Echo the prompt back in the output
) # Generate a completion, can also call create_completion
print(output)

According to logfiles, only CPU is being used. According to gpustat, GPU is not used at all, stays at 0%.

Running llama.cpp on the same machine uses CUDA/GPU a lot with the appropriate setting, both directly executed on the host and also via docker-container.

Running ollama uses also my GPU without any issues. My GPU is RTX 4000.

Current Behavior

Please provide a detailed written description of what llama-cpp-python did, instead.

It uses only CPU.

llama_model_loader: loaded meta data with 33 key-value pairs and 292 tensors from ../models/LongWriter-llama3.1-8b-GGUF/LongWriter-llama3.1-8b-Q4_K_M.gguf (version GGUF V3 (latest))
llama_model_loader: Dumping metadata keys/values. Note: KV overrides do not apply in this output.
llama_model_loader: - kv   0:                       general.architecture str              = llama
llama_model_loader: - kv   1:                               general.type str              = model
llama_model_loader: - kv   2:                               general.name str              = LongWriter Llama3.1 8b
llama_model_loader: - kv   3:                       general.organization str              = THUDM
llama_model_loader: - kv   4:                           general.basename str              = LongWriter-llama3.1
llama_model_loader: - kv   5:                         general.size_label str              = 8B
llama_model_loader: - kv   6:                            general.license str              = llama3.1
llama_model_loader: - kv   7:                               general.tags arr[str,3]       = ["Long Context", "chatglm", "llama"]
llama_model_loader: - kv   8:                          general.languages arr[str,2]       = ["en", "zh"]
llama_model_loader: - kv   9:                           general.datasets arr[str,1]       = ["THUDM/LongWriter-6k"]
llama_model_loader: - kv  10:                          llama.block_count u32              = 32
llama_model_loader: - kv  11:                       llama.context_length u32              = 131072
llama_model_loader: - kv  12:                     llama.embedding_length u32              = 4096
llama_model_loader: - kv  13:                  llama.feed_forward_length u32              = 14336
llama_model_loader: - kv  14:                 llama.attention.head_count u32              = 32
llama_model_loader: - kv  15:              llama.attention.head_count_kv u32              = 8
llama_model_loader: - kv  16:                       llama.rope.freq_base f32              = 500000.000000
llama_model_loader: - kv  17:     llama.attention.layer_norm_rms_epsilon f32              = 0.000010
llama_model_loader: - kv  18:                          general.file_type u32              = 15
llama_model_loader: - kv  19:                           llama.vocab_size u32              = 128256
llama_model_loader: - kv  20:                 llama.rope.dimension_count u32              = 128
llama_model_loader: - kv  21:                       tokenizer.ggml.model str              = gpt2
llama_model_loader: - kv  22:                         tokenizer.ggml.pre str              = smaug-bpe
llama_model_loader: - kv  23:                      tokenizer.ggml.tokens arr[str,128256]  = ["!", "\"", "#", "$", "%", "&", "'", ...
llama_model_loader: - kv  24:                  tokenizer.ggml.token_type arr[i32,128256]  = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...
llama_model_loader: - kv  25:                      tokenizer.ggml.merges arr[str,280147]  = ["Ġ Ġ", "Ġ ĠĠĠ", "ĠĠ ĠĠ", "...
llama_model_loader: - kv  26:                tokenizer.ggml.bos_token_id u32              = 128000
llama_model_loader: - kv  27:                tokenizer.ggml.eos_token_id u32              = 128001
llama_model_loader: - kv  28:               general.quantization_version u32              = 2
llama_model_loader: - kv  29:                      quantize.imatrix.file str              = /models_out/LongWriter-llama3.1-8b-GG...
llama_model_loader: - kv  30:                   quantize.imatrix.dataset str              = /training_dir/calibration_datav3.txt
llama_model_loader: - kv  31:             quantize.imatrix.entries_count i32              = 224
llama_model_loader: - kv  32:              quantize.imatrix.chunks_count i32              = 125
llama_model_loader: - type  f32:   66 tensors
llama_model_loader: - type q4_K:  193 tensors
llama_model_loader: - type q6_K:   33 tensors
llm_load_vocab: special tokens cache size = 256
llm_load_vocab: token to piece cache size = 0.7999 MB
llm_load_print_meta: format           = GGUF V3 (latest)
llm_load_print_meta: arch             = llama
llm_load_print_meta: vocab type       = BPE
llm_load_print_meta: n_vocab          = 128256
llm_load_print_meta: n_merges         = 280147
llm_load_print_meta: vocab_only       = 0
llm_load_print_meta: n_ctx_train      = 131072
llm_load_print_meta: n_embd           = 4096
llm_load_print_meta: n_layer          = 32
llm_load_print_meta: n_head           = 32
llm_load_print_meta: n_head_kv        = 8
llm_load_print_meta: n_rot            = 128
llm_load_print_meta: n_swa            = 0
llm_load_print_meta: n_embd_head_k    = 128
llm_load_print_meta: n_embd_head_v    = 128
llm_load_print_meta: n_gqa            = 4
llm_load_print_meta: n_embd_k_gqa     = 1024
llm_load_print_meta: n_embd_v_gqa     = 1024
llm_load_print_meta: f_norm_eps       = 0.0e+00
llm_load_print_meta: f_norm_rms_eps   = 1.0e-05
llm_load_print_meta: f_clamp_kqv      = 0.0e+00
llm_load_print_meta: f_max_alibi_bias = 0.0e+00
llm_load_print_meta: f_logit_scale    = 0.0e+00
llm_load_print_meta: n_ff             = 14336
llm_load_print_meta: n_expert         = 0
llm_load_print_meta: n_expert_used    = 0
llm_load_print_meta: causal attn      = 1
llm_load_print_meta: pooling type     = 0
llm_load_print_meta: rope type        = 0
llm_load_print_meta: rope scaling     = linear
llm_load_print_meta: freq_base_train  = 500000.0
llm_load_print_meta: freq_scale_train = 1
llm_load_print_meta: n_ctx_orig_yarn  = 131072
llm_load_print_meta: rope_finetuned   = unknown
llm_load_print_meta: ssm_d_conv       = 0
llm_load_print_meta: ssm_d_inner      = 0
llm_load_print_meta: ssm_d_state      = 0
llm_load_print_meta: ssm_dt_rank      = 0
llm_load_print_meta: model type       = 8B
llm_load_print_meta: model ftype      = Q4_K - Medium
llm_load_print_meta: model params     = 8.03 B
llm_load_print_meta: model size       = 4.58 GiB (4.89 BPW)
llm_load_print_meta: general.name     = LongWriter Llama3.1 8b
llm_load_print_meta: BOS token        = 128000 '<|begin_of_text|>'
llm_load_print_meta: EOS token        = 128001 '<|end_of_text|>'
llm_load_print_meta: LF token         = 128 'Ä'
llm_load_print_meta: EOT token        = 128009 '<|eot_id|>'
llm_load_print_meta: max token length = 256
llm_load_tensors: ggml ctx size =    0.14 MiB
llm_load_tensors:        CPU buffer size =  4685.30 MiB
........................................................................................
llama_new_context_with_model: n_ctx      = 2048
llama_new_context_with_model: n_batch    = 512
llama_new_context_with_model: n_ubatch   = 512
llama_new_context_with_model: flash_attn = 0
llama_new_context_with_model: freq_base  = 500000.0
llama_new_context_with_model: freq_scale = 1
llama_kv_cache_init:        CPU KV buffer size =   256.00 MiB
llama_new_context_with_model: KV self size  =  256.00 MiB, K (f16):  128.00 MiB, V (f16):  128.00 MiB
llama_new_context_with_model:        CPU  output buffer size =     0.49 MiB
llama_new_context_with_model:        CPU compute buffer size =   258.50 MiB
llama_new_context_with_model: graph nodes  = 1030
llama_new_context_with_model: graph splits = 1
AVX = 1 | AVX_VNNI = 1 | AVX2 = 1 | AVX512 = 0 | AVX512_VBMI = 0 | AVX512_VNNI = 0 | AVX512_BF16 = 0 | FMA = 1 | NEON = 0 | SVE = 0 | ARM_FMA = 0 | F16C = 1 | FP16_VA = 0 | WASM_SIMD = 0 | BLAS = 0 | SSE3 = 1 | SSSE3 = 1 | VSX = 0 | MATMUL_INT8 = 0 | LLAMAFILE = 1 |
Model metadata: {'quantize.imatrix.entries_count': '224', 'quantize.imatrix.dataset': '/training_dir/calibration_datav3.txt', 'quantize.imatrix.chunks_count': '125', 'quantize.imatrix.file': '/models_out/LongWriter-llama3.1-8b-GGUF/LongWriter-llama3.1-8b.imatrix', 'tokenizer.ggml.eos_token_id': '128001', 'general.quantization_version': '2', 'tokenizer.ggml.model': 'gpt2', 'llama.rope.dimension_count': '128', 'llama.vocab_size': '128256', 'general.file_type': '15', 'llama.attention.layer_norm_rms_epsilon': '0.000010', 'llama.rope.freq_base': '500000.000000', 'general.architecture': 'llama', 'general.basename': 'LongWriter-llama3.1', 'tokenizer.ggml.bos_token_id': '128000', 'llama.attention.head_count': '32', 'tokenizer.ggml.pre': 'smaug-bpe', 'llama.context_length': '131072', 'general.name': 'LongWriter Llama3.1 8b', 'general.organization': 'THUDM', 'general.type': 'model', 'general.size_label': '8B', 'general.license': 'llama3.1', 'llama.feed_forward_length': '14336', 'llama.embedding_length': '4096', 'llama.block_count': '32', 'llama.attention.head_count_kv': '8'}
Using fallback chat format: llama-2

llama_print_timings:        load time =     315.34 ms
llama_print_timings:      sample time =       1.09 ms /    19 runs   (    0.06 ms per token, 17351.60 tokens per second)
llama_print_timings: prompt eval time =     315.31 ms /    13 tokens (   24.25 ms per token,    41.23 tokens per second)
llama_print_timings:        eval time =    1896.05 ms /    18 runs   (  105.34 ms per token,     9.49 tokens per second)
llama_print_timings:       total time =    2221.90 ms /    31 tokens
{'id': 'cmpl-b3e0c5d3-9736-4a26-a875-853dd8344900', 'object': 'text_completion', 'created': 1724059145, 'model': '../models/LongWriter-llama3.1-8b-GGUF/LongWriter-llama3.1-8b-Q4_K_M.gguf', 'choices': [{'text': 'Q: Name the planets in the solar system? A: 8: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune.', 'index': 0, 'logprobs': None, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 13, 'completion_tokens': 19, 'total_tokens': 32}}

Environment and Context

Please provide detailed information about your computer setup. This is important in case the issue is not reproducible except for under certain specific conditions.

$ lscpu

Architecture:             x86_64
  CPU op-mode(s):         32-bit, 64-bit
  Address sizes:          46 bits physical, 48 bits virtual
  Byte Order:             Little Endian
CPU(s):                   20
  On-line CPU(s) list:    0-19
Vendor ID:                GenuineIntel
  Model name:             13th Gen Intel(R) Core(TM) i5-13500
    CPU family:           6
    Model:                191
    Thread(s) per core:   2
    Core(s) per socket:   14
    Socket(s):            1
    Stepping:             2
    CPU max MHz:          4800.0000
    CPU min MHz:          800.0000
    BogoMIPS:             4992.00
    Flags:                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscal
                          l nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_f
                          req pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_de
                          adline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow
                           vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_
                          pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_
                          epp hwp_pkg_req umip pku ospke waitpkg gfni vaes vpclmulqdq tme rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_l
                          br flush_l1d arch_capabilities
Virtualization features:
  Virtualization:         VT-x
Caches (sum of all):
  L1d:                    544 KiB (14 instances)
  L1i:                    704 KiB (14 instances)
  L2:                     11.5 MiB (8 instances)
  L3:                     24 MiB (1 instance)
NUMA:
  NUMA node(s):           1
  NUMA node0 CPU(s):      0-19
Vulnerabilities:
  Gather data sampling:   Not affected
  Itlb multihit:          Not affected
  L1tf:                   Not affected
  Mds:                    Not affected
  Meltdown:               Not affected
  Mmio stale data:        Not affected
  Reg file data sampling: Mitigation; Clear Register File
  Retbleed:               Not affected
  Spec rstack overflow:   Not affected
  Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl and seccomp
  Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
  Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
  Srbds:                  Not affected
  Tsx async abort:        Not affected
hag

$ uname -a

Linux Ubuntu-2204-jammy-amd64-base 5.15.0-118-generic #128-Ubuntu SMP Fri Jul 5 09:28:59 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux

$ python3 --version
$ make --version
$ g++ --version

Python 3.10.12 GNU Make 4.3 g++ (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0

Failure Information (for bugs)

Please help provide information about the failure if this is a bug. If it is not a bug, please remove the rest of this template.

Steps to Reproduce

already written above

Please provide detailed steps for reproducing the issue. We are not sitting in front of your screen, so the more detail the better.

already written above

Note: Many issues seem to be regarding functional or performance issues / differences with llama.cpp. In these cases we need to confirm that you're comparing against the version of llama.cpp that was built with your python package, and which parameters you're passing to the context.

Try the following:

  1. git clone https://github.com/abetlen/llama-cpp-python
  2. cd llama-cpp-python
  3. rm -rf _skbuild/ # delete any old builds
  4. python -m pip install .
  5. cd ./vendor/llama.cpp
  6. Follow llama.cpp's instructions to cmake llama.cpp
  7. Run llama.cpp's ./main with the same arguments you previously passed to llama-cpp-python and see if you can reproduce the issue. If you can, log an issue with llama.cpp

Failure Logs

The test installation from the point above ("try the following") gives this:

Defaulting to user installation because normal site-packages is not writeable
Processing /home/xxx/test/x/llama-cpp-python
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: numpy>=1.20.0 in /home/xxx/.local/lib/python3.10/site-packages (from llama_cpp_python==0.2.88) (2.1.0)
Requirement already satisfied: jinja2>=2.11.3 in /home/xxx/.local/lib/python3.10/site-packages (from llama_cpp_python==0.2.88) (3.1.4)
Requirement already satisfied: typing-extensions>=4.5.0 in /home/xxx/.local/lib/python3.10/site-packages (from llama_cpp_python==0.2.88) (4.12.2)
Requirement already satisfied: diskcache>=5.6.1 in /home/xxx/.local/lib/python3.10/site-packages (from llama_cpp_python==0.2.88) (5.6.3)
Requirement already satisfied: MarkupSafe>=2.0 in /home/xxx/.local/lib/python3.10/site-packages (from jinja2>=2.11.3->llama_cpp_python==0.2.88) (2.1.5)
Building wheels for collected packages: llama_cpp_python
  Building wheel for llama_cpp_python (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for llama_cpp_python (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [54 lines of output]
      *** scikit-build-core 0.10.3 using CMake 3.30.2 (wheel)
      *** Configuring CMake...
      loading initial cache file /tmp/tmpphr2omul/build/CMakeInit.txt
      -- The C compiler identification is GNU 11.4.0
      -- The CXX compiler identification is GNU 11.4.0
      -- Detecting C compiler ABI info
      -- Detecting C compiler ABI info - done
      -- Check for working C compiler: /usr/lib/ccache/x86_64-linux-gnu-gcc - skipped
      -- Detecting C compile features
      -- Detecting C compile features - done
      -- Detecting CXX compiler ABI info
      -- Detecting CXX compiler ABI info - done
      -- Check for working CXX compiler: /usr/lib/ccache/x86_64-linux-gnu-g++ - skipped
      -- Detecting CXX compile features
      -- Detecting CXX compile features - done
      CMake Error at CMakeLists.txt:72 (add_subdirectory):
        The source directory

          /home/xxx/test/x/llama-cpp-python/vendor/llama.cpp

        does not contain a CMakeLists.txt file.

      CMake Error at CMakeLists.txt:9 (install):
        install TARGETS given target "llama" which does not exist.
      Call Stack (most recent call first):
        CMakeLists.txt:73 (llama_cpp_python_install_target)

      CMake Error at CMakeLists.txt:9 (install):
        install TARGETS given target "ggml" which does not exist.
      Call Stack (most recent call first):
        CMakeLists.txt:74 (llama_cpp_python_install_target)

      CMake Error at CMakeLists.txt:107 (add_subdirectory):
        add_subdirectory given source "vendor/llama.cpp/examples/llava" which is
        not an existing directory.

      CMake Error at CMakeLists.txt:108 (set_target_properties):
        set_target_properties Can not find target to add properties to:
        llava_shared

      CMake Error at CMakeLists.txt:9 (install):
        install TARGETS given target "llava_shared" which does not exist.
      Call Stack (most recent call first):
        CMakeLists.txt:113 (llama_cpp_python_install_target)

      -- Configuring incomplete, errors occurred!

      *** CMake configuration failed
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for llama_cpp_python
Failed to build llama_cpp_python
ERROR: Could not build wheels for llama_cpp_python, which is required to install pyproject.toml-based projects

Example environment info:

llama-cpp-python$ git log | head -1
commit 658b244c5aa924fc6f4d04f92445dd8f724b6017

llama-cpp-python$ python3 --version
Python 3.10.12

llama-cpp-python$ pip list | egrep "uvicorn|fastapi|sse-starlette|numpy"
fastapi                           0.112.0
fastapi-cli                       0.0.5
numpy                             2.1.0
prometheus-fastapi-instrumentator 7.0.0
uvicorn                           0.30.5

llama-cpp-python/vendor/llama.cpp$ git log | head -3
commit 658b244c5aa924fc6f4d04f92445dd8f724b6017
Merge: 7bf07ec 3c7501b
Author: Andrei Betlen <abetlen@gmail.com>
itinance commented 3 weeks ago

For the sake of completeness: if someone is looking for a llama.cpp binding that works with CUDA support, no matter which underlying programming language, I can recommend the NodeJS bindings: https://github.com/withcatai/node-llama-cpp

Installation was blazing fast and easy. It just works.