黑苹果让llm跑在AMD GPU上的方法

(本来要发到远景的,但是快写完的时候才想起没有验证手机号它不让发帖,干脆发到小众,反正这也是软件相关的话题。)

最近 llama.cpp 的服务器命令行加入了对图像的支持(目前仅能图生文),借这个机会讲一下怎么让 llm 跑在 AMD GPU 上(仅限黑苹果)。下面的方法需要你会使用终端执行命令行。

安装步骤

  1. brew install libomp vulkan-headers glslang molten-vk shaderc vulkan-loader. 解释:使用 homebrew 安装如命令行所示的几个包,后面编译需要。如果你之前安装过这几个包,仍然还是需要执行这条命令,将它们更新到最新版本。
  2. git clone https://github.com/KhronosGroup/MoltenVK.git. 请自行克隆到想要的目录。
  3. cd MoltenVK && ./fetchDependencies --macos && make macos
  4. cp Package/Release/MoltenVK/dynamic/dylib/macOS/libMoltenVK.dylib /usr/local/Cellar/molten-vk/1.3.0/lib/libMoltenVK.dylib
  5. 说明:步骤 2-4 是编译安装MoltenVK.
  6. git clone https://github.com/ggml-org/llama.cpp.git 请自行克隆到想要的目录。
  7. cd llama.cpp.git
  8. git reset --hard 33eff402408. 说明:最新的llama.cpp编译出来会跑不起来(写本文时最新的commit是 62d4250e52),用 33eff402408 则没有问题。
  9. cmake -B build -DGGML_METAL=OFF -DGGML_VULKAN=ON -DBUILD_SHARED_LIBS=OFF
  10. cmake --build build --config Release --target install -j8
  11. 说明:步骤 6-10 是安装 llama.cpp.

如果以上步骤没有出错的话,会在系统上安装以 llama- 开头的一众命令,如下:

$ ls /usr/local/bin/llama-*
/usr/local/bin/llama-batched
/usr/local/bin/llama-batched-bench
/usr/local/bin/llama-bench
/usr/local/bin/llama-cli
/usr/local/bin/llama-convert-llama2c-to-ggml
/usr/local/bin/llama-cvector-generator
/usr/local/bin/llama-embedding
/usr/local/bin/llama-eval-callback
/usr/local/bin/llama-export-lora
/usr/local/bin/llama-gen-docs
/usr/local/bin/llama-gguf
/usr/local/bin/llama-gguf-hash
/usr/local/bin/llama-gguf-split
/usr/local/bin/llama-gritlm
/usr/local/bin/llama-imatrix
/usr/local/bin/llama-infill
/usr/local/bin/llama-llava-clip-quantize-cli
/usr/local/bin/llama-lookahead
/usr/local/bin/llama-lookup
/usr/local/bin/llama-lookup-create
/usr/local/bin/llama-lookup-merge
/usr/local/bin/llama-lookup-stats
/usr/local/bin/llama-mtmd-cli
/usr/local/bin/llama-parallel
/usr/local/bin/llama-passkey
/usr/local/bin/llama-perplexity
/usr/local/bin/llama-quantize
/usr/local/bin/llama-retrieval
/usr/local/bin/llama-run
/usr/local/bin/llama-save-load-state
/usr/local/bin/llama-server
/usr/local/bin/llama-simple
/usr/local/bin/llama-simple-chat
/usr/local/bin/llama-speculative
/usr/local/bin/llama-speculative-simple
/usr/local/bin/llama-tokenize
/usr/local/bin/llama-tts

演示

下面是以 gemma3 演示。执行如下命令:

llama-server -m gemma-3-12b-it-Q8_0.gguf --mmproj mmproj-model-f16.gguf --n-gpu-layers 100 -fa -n 1024

这两个文件 gemma-3-12b-it-Q8_0.gguf, mmproj-model-f16.gguf 可在 hugging-face 下载,也可在 hf-mirror.com 下载,关键字 ggml-org/gemma3.

成功之后,会显示以下信息:

ggml_vulkan: Found 1 Vulkan devices:
ggml_vulkan: 0 = AMD Radeon RX 6800 XT (MoltenVK) | uma: 0 | fp16: 1 | warp size: 64 | shared memory: 65536 | int dot: 0 | matrix cores: none
build: 5331 (33eff402) with Apple clang version 16.0.0 (clang-1600.0.26.6) for x86_64-apple-darwin24.4.0
system info: n_threads = 8, n_threads_batch = 8, total_threads = 16

system_info: n_threads = 8 (n_threads_batch = 8) / 16 | CPU : SSE3 = 1 | SSSE3 = 1 | AVX = 1 | AVX2 = 1 | F16C = 1 | FMA = 1 | BMI2 = 1 | LLAMAFILE = 1 | ACCELERATE = 1 | AARCH64_REPACK = 1 |

main: binding port with default address family
main: HTTP server is listening, hostname: 127.0.0.1, port: 8080, http threads: 15
main: loading model
srv    load_model: loading model '/Volumes/D/ai/models/gemma-3/gemma-3-12b-it-Q8_0.gguf'
llama_model_load_from_file_impl: using device Vulkan0 (AMD Radeon RX 6800 XT) - 16368 MiB free
llama_model_loader: loaded meta data with 40 key-value pairs and 626 tensors from /Volumes/D/ai/models/gemma-3/gemma-3-12b-it-Q8_0.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              = gemma3
llama_model_loader: - kv   1:                               general.type str              = model
llama_model_loader: - kv   2:                               general.name str              = Gemma 3 12b It
llama_model_loader: - kv   3:                           general.finetune str              = it
llama_model_loader: - kv   4:                           general.basename str              = gemma-3
llama_model_loader: - kv   5:                         general.size_label str              = 12B
llama_model_loader: - kv   6:                            general.license str              = gemma
llama_model_loader: - kv   7:                   general.base_model.count u32              = 1
llama_model_loader: - kv   8:                  general.base_model.0.name str              = Gemma 3 12b Pt
llama_model_loader: - kv   9:          general.base_model.0.organization str              = Google
llama_model_loader: - kv  10:              general.base_model.0.repo_url str              = https://huggingface.co/google/gemma-3...
llama_model_loader: - kv  11:                               general.tags arr[str,1]       = ["image-text-to-text"]
llama_model_loader: - kv  12:                      gemma3.context_length u32              = 131072
llama_model_loader: - kv  13:                    gemma3.embedding_length u32              = 3840
llama_model_loader: - kv  14:                         gemma3.block_count u32              = 48
llama_model_loader: - kv  15:                 gemma3.feed_forward_length u32              = 15360
llama_model_loader: - kv  16:                gemma3.attention.head_count u32              = 16
llama_model_loader: - kv  17:    gemma3.attention.layer_norm_rms_epsilon f32              = 0.000001
llama_model_loader: - kv  18:                gemma3.attention.key_length u32              = 256
llama_model_loader: - kv  19:              gemma3.attention.value_length u32              = 256
llama_model_loader: - kv  20:                          general.file_type u32              = 7
llama_model_loader: - kv  21:                      gemma3.rope.freq_base f32              = 1000000.000000
llama_model_loader: - kv  22:            gemma3.attention.sliding_window u32              = 1024
llama_model_loader: - kv  23:             gemma3.attention.head_count_kv u32              = 8
llama_model_loader: - kv  24:                   gemma3.rope.scaling.type str              = linear
llama_model_loader: - kv  25:                 gemma3.rope.scaling.factor f32              = 8.000000
llama_model_loader: - kv  26:                       tokenizer.ggml.model str              = llama
llama_model_loader: - kv  27:                         tokenizer.ggml.pre str              = default
llama_model_loader: - kv  28:                      tokenizer.ggml.tokens arr[str,262144]  = ["<pad>", "<eos>", "<bos>", "<unk>", ...
llama_model_loader: - kv  29:                      tokenizer.ggml.scores arr[f32,262144]  = [-1000.000000, -1000.000000, -1000.00...
llama_model_loader: - kv  30:                  tokenizer.ggml.token_type arr[i32,262144]  = [3, 3, 3, 3, 3, 4, 3, 3, 3, 3, 3, 3, ...
llama_model_loader: - kv  31:                tokenizer.ggml.bos_token_id u32              = 2
llama_model_loader: - kv  32:                tokenizer.ggml.eos_token_id u32              = 1
llama_model_loader: - kv  33:            tokenizer.ggml.unknown_token_id u32              = 3
llama_model_loader: - kv  34:            tokenizer.ggml.padding_token_id u32              = 0
llama_model_loader: - kv  35:               tokenizer.ggml.add_bos_token bool             = true
llama_model_loader: - kv  36:               tokenizer.ggml.add_eos_token bool             = false
llama_model_loader: - kv  37:                    tokenizer.chat_template str              = {{ bos_token }}\n{%- if messages[0]['r...
llama_model_loader: - kv  38:            tokenizer.ggml.add_space_prefix bool             = false
llama_model_loader: - kv  39:               general.quantization_version u32              = 2
llama_model_loader: - type  f32:  289 tensors
llama_model_loader: - type q8_0:  337 tensors
print_info: file format = GGUF V3 (latest)
print_info: file type   = Q8_0
print_info: file size   = 11.64 GiB (8.50 BPW)
load: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect
load: special tokens cache size = 6414
load: token to piece cache size = 1.9446 MB
print_info: arch             = gemma3
print_info: vocab_only       = 0
print_info: n_ctx_train      = 131072
print_info: n_embd           = 3840
print_info: n_layer          = 48
print_info: n_head           = 16
print_info: n_head_kv        = 8
print_info: n_rot            = 256
print_info: n_swa            = 1024
print_info: n_swa_pattern    = 6
print_info: n_embd_head_k    = 256
print_info: n_embd_head_v    = 256
print_info: n_gqa            = 2
print_info: n_embd_k_gqa     = 2048
print_info: n_embd_v_gqa     = 2048
print_info: f_norm_eps       = 0.0e+00
print_info: f_norm_rms_eps   = 1.0e-06
print_info: f_clamp_kqv      = 0.0e+00
print_info: f_max_alibi_bias = 0.0e+00
print_info: f_logit_scale    = 0.0e+00
print_info: f_attn_scale     = 6.2e-02
print_info: n_ff             = 15360
print_info: n_expert         = 0
print_info: n_expert_used    = 0
print_info: causal attn      = 1
print_info: pooling type     = 0
print_info: rope type        = 2
print_info: rope scaling     = linear
print_info: freq_base_train  = 1000000.0
print_info: freq_scale_train = 0.125
print_info: n_ctx_orig_yarn  = 131072
print_info: rope_finetuned   = unknown
print_info: ssm_d_conv       = 0
print_info: ssm_d_inner      = 0
print_info: ssm_d_state      = 0
print_info: ssm_dt_rank      = 0
print_info: ssm_dt_b_c_rms   = 0
print_info: model type       = 12B
print_info: model params     = 11.77 B
print_info: general.name     = Gemma 3 12b It
print_info: vocab type       = SPM
print_info: n_vocab          = 262144
print_info: n_merges         = 0
print_info: BOS token        = 2 '<bos>'
print_info: EOS token        = 1 '<eos>'
print_info: EOT token        = 106 '<end_of_turn>'
print_info: UNK token        = 3 '<unk>'
print_info: PAD token        = 0 '<pad>'
print_info: LF token         = 248 '<0x0A>'
print_info: EOG token        = 1 '<eos>'
print_info: EOG token        = 106 '<end_of_turn>'
print_info: max token length = 48
load_tensors: loading model tensors, this can take a while... (mmap = true)
load_tensors: offloading 48 repeating layers to GPU
load_tensors: offloading output layer to GPU
load_tensors: offloaded 49/49 layers to GPU
load_tensors:   CPU_Mapped model buffer size =  1020.00 MiB
load_tensors:      Vulkan0 model buffer size = 11924.17 MiB
.......................................................................................
llama_context: constructing llama_context
llama_context: n_seq_max     = 1
llama_context: n_ctx         = 4096
llama_context: n_ctx_per_seq = 4096
llama_context: n_batch       = 2048
llama_context: n_ubatch      = 512
llama_context: causal_attn   = 1
llama_context: flash_attn    = 1
llama_context: freq_base     = 1000000.0
llama_context: freq_scale    = 0.125
llama_context: n_ctx_per_seq (4096) < n_ctx_train (131072) -- the full capacity of the model will not be utilized
llama_context: Vulkan_Host  output buffer size =     1.00 MiB
llama_kv_cache_unified: kv_size = 4096, type_k = 'f16', type_v = 'f16', n_layer = 48, can_shift = 1, padding = 256
llama_kv_cache_unified:    Vulkan0 KV buffer size =  1536.00 MiB
llama_kv_cache_unified: KV self size  = 1536.00 MiB, K (f16):  768.00 MiB, V (f16):  768.00 MiB
llama_context:    Vulkan0 compute buffer size =   519.50 MiB
llama_context: Vulkan_Host compute buffer size =    60.01 MiB
llama_context: graph nodes  = 1833
llama_context: graph splits = 98
common_init_from_params: setting dry_penalty_last_n to ctx_size = 4096
common_init_from_params: warming up the model with an empty run - please wait ... (--no-warmup to disable)
clip_ctx: CLIP using Vulkan0 backend
clip_model_loader: model name:
clip_model_loader: description:
clip_model_loader: GGUF version: 3
clip_model_loader: alignment:    32
clip_model_loader: n_tensors:    439
clip_model_loader: n_kv:         16

load_hparams: projector:          gemma3
load_hparams: n_embd:             1152
load_hparams: n_head:             16
load_hparams: n_ff:               4304
load_hparams: n_layer:            27
load_hparams: projection_dim:     3840
load_hparams: image_size:         896
load_hparams: patch_size:         14

load_hparams: has_llava_proj:     0
load_hparams: minicpmv_version:   0
load_hparams: proj_scale_factor:  4
load_hparams: n_wa_pattern:       0
load_hparams: ffn_op:             gelu
load_hparams: model size:         814.60 MiB
load_hparams: metadata size:      0.15 MiB
alloc_compute_meta:    Vulkan0 compute buffer size =  1132.00 MiB
alloc_compute_meta:        CPU compute buffer size =     9.19 MiB
srv    load_model: loaded multimodal model, '/Volumes/D/ai/models/gemma-3/mmproj-model-f16.gguf'
srv    load_model: ctx_shift is not supported by multimodal, it will be disabled
srv          init: initializing slots, n_slots = 1
slot         init: id  0 | task -1 | new slot n_ctx_slot = 4096
main: model loaded
main: chat template, chat_template: {{ bos_token }}
{%- if messages[0]['role'] == 'system' -%}
    {%- if messages[0]['content'] is string -%}
        {%- set first_user_prefix = messages[0]['content'] + '

' -%}
    {%- else -%}
        {%- set first_user_prefix = messages[0]['content'][0]['text'] + '

' -%}
    {%- endif -%}
    {%- set loop_messages = messages[1:] -%}
{%- else -%}
    {%- set first_user_prefix = "" -%}
    {%- set loop_messages = messages -%}
{%- endif -%}
{%- for message in loop_messages -%}
    {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}
        {{ raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") }}
    {%- endif -%}
    {%- if (message['role'] == 'assistant') -%}
        {%- set role = "model" -%}
    {%- else -%}
        {%- set role = message['role'] -%}
    {%- endif -%}
    {{ '<start_of_turn>' + role + '
' + (first_user_prefix if loop.first else "") }}
    {%- if message['content'] is string -%}
        {{ message['content'] | trim }}
    {%- elif message['content'] is iterable -%}
        {%- for item in message['content'] -%}
            {%- if item['type'] == 'image' -%}
                {{ '<start_of_image>' }}
            {%- elif item['type'] == 'text' -%}
                {{ item['text'] | trim }}
            {%- endif -%}
        {%- endfor -%}
    {%- else -%}
        {{ raise_exception("Invalid content type") }}
    {%- endif -%}
    {{ '<end_of_turn>
' }}
{%- endfor -%}
{%- if add_generation_prompt -%}
    {{'<start_of_turn>model
'}}
{%- endif -%}
, example_format: '<start_of_turn>user
You are a helpful assistant

Hello<end_of_turn>
<start_of_turn>model
Hi there<end_of_turn>
<start_of_turn>user
How are you?<end_of_turn>
<start_of_turn>model
'
main: server is listening on http://127.0.0.1:8080 - starting the main loop
srv  update_slots: all slots are idle

最后倒数第二行可以看到,服务器监听在 http://127.0.0.1:8080. 在浏览器中打开这个地址,可以看到在文本输入框的右边有个按钮可以上传图片。

演示图片就不上传了,太麻烦。

可以试试 LM studio,Mac平台后端可选CPU/ Metal显卡加速,白苹果的M系CPU还有Apple MLX engine加速