NetBSD上でDeepSeek R1 LLMを動かしてみる

この記事は、NetBSD Advent Calendar 2024の21日目の記事です。

はじめに

中国のHangzhou DeepSeek Artificial Intelligence Basic Technology Research Co., Ltd社の開発したDeekSeek-R1というlarge language modelは、 その学習に必要とされたコストの低さでニュースになっていました。 llama.cppがDeepSeek-R1を扱えるようになっていたので、NetBSD/amd64でも動かしてみました。

DeepSeek-R1のモデルファイルと、llama.cppを準備する

llama.cppは、gguf形式のモデルを扱うようになっています。また、CPUで元の精度のモデルファイルを扱うのは負荷が高過ぎるので、 精度を落としたモデルファイルを使うことになります。 今回は、https://huggingface.co/mmnga/DeepSeek-R1-Distill-Qwen-14B-gguf/tree/main/Q4_K_Mにある モデルファイルを利用することにしました。9GB程度のファイルサイズです。

llama.cppは、バージョンb5426を利用しました。近い内にpkgsrc/wip/llama.cppでこれ以降のバージョンが利用できるようにしておきたいと思います。 更にはpkgsrcにもインポートしたいですが、依存するパッケージの精査をする気力が尽きています…。 いずれにしても、以下のように準備しておいたら良いでしょう。

$ mkdir ~/llama.cpp/models
$ cd ~/llama.cpp/models
$ ftp https://huggingface.co/mmnga/DeepSeek-R1-Distill-Qwen-14B-gguf/resolve/main/Q4_K_M/DeepSeek-R1-Distill-Qwen-14B-Q4_K_M-00001-of-00001.gguf

更に、DeepSeek-R1をhttp://localhost:8080/から利用できるようにするシェルスクリプトを作成しておきます。

$cat START-SERVER-deepseek-r1.sh
#!/bin/sh

# DeepDeek-R1
# From: https://huggingface.co/mmnga/DeepSeek-R1-Distill-Qwen-14B-gguf/tree/main/Q4_K_M
#
llama-server --host :: --port 8080 -m models/DeepSeek-R1-Distill-Qwen-14B-Q4_K_M-00001-of-00001.gguf
$ chmod 755 START-SERVER-deepseek-r1.sh

DeelSeek-R1モデルを動かしてみる

では、早速動かしてみましょう。動かすのは以下のようにすれば良いです。まず、httpサーバーを起動させます。

% cd ~/llama.cpp
$ ./START-SERVER-deepseek-r1.sh
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
ggml_backend_load_best: search path  does not exist
build: 0 (unknown) with gcc (nb1 20240630) 12.4.0 for x86_64--netbsd
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 | AVX512 = 1 | AVX512_VBMI = 1 | AVX512_VNNI = 1 | AVX512_BF16 = 1 | LLAMAFILE = 1 | AARCH64_REPACK = 1 |

main: binding port with default address family
main: HTTP server is listening, hostname: ::, port: 8080, http threads: 15
main: loading model
srv    load_model: loading model 'models/DeepSeek-R1-Distill-Qwen-14B-Q4_K_M-00001-of-00001.gguf'
llama_model_loader: loaded meta data with 29 key-value pairs and 579 tensors from models/DeepSeek-R1-Distill-Qwen-14B-Q4_K_M-00001-of-00001.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              = qwen2
llama_model_loader: - kv   1:                               general.type str              = model
llama_model_loader: - kv   2:                               general.name str              = DeepSeek R1 Distill Qwen 14B
llama_model_loader: - kv   3:                           general.basename str              = DeepSeek-R1-Distill-Qwen
llama_model_loader: - kv   4:                         general.size_label str              = 14B
llama_model_loader: - kv   5:                          qwen2.block_count u32              = 48
llama_model_loader: - kv   6:                       qwen2.context_length u32              = 131072
llama_model_loader: - kv   7:                     qwen2.embedding_length u32              = 5120
llama_model_loader: - kv   8:                  qwen2.feed_forward_length u32              = 13824
llama_model_loader: - kv   9:                 qwen2.attention.head_count u32              = 40
llama_model_loader: - kv  10:              qwen2.attention.head_count_kv u32              = 8
llama_model_loader: - kv  11:                       qwen2.rope.freq_base f32              = 1000000.000000
llama_model_loader: - kv  12:     qwen2.attention.layer_norm_rms_epsilon f32              = 0.000010
llama_model_loader: - kv  13:                       tokenizer.ggml.model str              = gpt2
llama_model_loader: - kv  14:                         tokenizer.ggml.pre str              = deepseek-r1-qwen
llama_model_loader: - kv  15:                      tokenizer.ggml.tokens arr[str,152064]  = ["!", "\"", "#", "$", "%", "&", "'", ...
llama_model_loader: - kv  16:                  tokenizer.ggml.token_type arr[i32,152064]  = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...
llama_model_loader: - kv  17:                      tokenizer.ggml.merges arr[str,151387]  = ["Ġ Ġ", "ĠĠ ĠĠ", "i n", "Ġ t",...
llama_model_loader: - kv  18:                tokenizer.ggml.bos_token_id u32              = 151646
llama_model_loader: - kv  19:                tokenizer.ggml.eos_token_id u32              = 151643
llama_model_loader: - kv  20:            tokenizer.ggml.padding_token_id u32              = 151643
llama_model_loader: - kv  21:               tokenizer.ggml.add_bos_token bool             = true
llama_model_loader: - kv  22:               tokenizer.ggml.add_eos_token bool             = false
llama_model_loader: - kv  23:                    tokenizer.chat_template str              = {% if not add_generation_prompt is de...
llama_model_loader: - kv  24:               general.quantization_version u32              = 2
llama_model_loader: - kv  25:                          general.file_type u32              = 15
llama_model_loader: - kv  26:                                   split.no u16              = 0
llama_model_loader: - kv  27:                        split.tensors.count i32              = 579
llama_model_loader: - kv  28:                                split.count u16              = 1
llama_model_loader: - type  f32:  241 tensors
llama_model_loader: - type q4_K:  289 tensors
llama_model_loader: - type q6_K:   49 tensors
print_info: file format = GGUF V3 (latest)
print_info: file type   = Q4_K - Medium
print_info: file size   = 8.37 GiB (4.87 BPW)
load: special_eos_id is not in special_eog_ids - the tokenizer config may be incorrect
load: special tokens cache size = 22
load: token to piece cache size = 0.9310 MB
print_info: arch             = qwen2
print_info: vocab_only       = 0
print_info: n_ctx_train      = 131072
print_info: n_embd           = 5120
print_info: n_layer          = 48
print_info: n_head           = 40
print_info: n_head_kv        = 8
print_info: n_rot            = 128
print_info: n_swa            = 0
print_info: n_swa_pattern    = 1
print_info: n_embd_head_k    = 128
print_info: n_embd_head_v    = 128
print_info: n_gqa            = 5
print_info: n_embd_k_gqa     = 1024
print_info: n_embd_v_gqa     = 1024
print_info: f_norm_eps       = 0.0e+00
print_info: f_norm_rms_eps   = 1.0e-05
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     = 0.0e+00
print_info: n_ff             = 13824
print_info: n_expert         = 0
print_info: n_expert_used    = 0
print_info: causal attn      = 1
print_info: pooling type     = -1
print_info: rope type        = 2
print_info: rope scaling     = linear
print_info: freq_base_train  = 1000000.0
print_info: freq_scale_train = 1
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       = 14B
print_info: model params     = 14.77 B
print_info: general.name     = DeepSeek R1 Distill Qwen 14B
print_info: vocab type       = BPE
print_info: n_vocab          = 152064
print_info: n_merges         = 151387
print_info: BOS token        = 151646 '<|begin▁of▁sentence|>'
print_info: EOS token        = 151643 '<|end▁of▁sentence|>'
print_info: EOT token        = 151643 '<|end▁of▁sentenc<|>'
print_info: PAD token        = 151643 '<|end▁of▁sentenc<|>'
print_info: LF token         = 198 'Ċ'
print_info: FIM PRE token    = 151659 '<|fim_prefix|>'
print_info: FIM SUF token    = 151661 '<|fim_suffix|>'
print_info: FIM MID token    = 151660 '<|fim_middle|>'
print_info: FIM PAD token    = 151662 '<|fim_pad|>'
print_info: FIM REP token    = 151663 '<|repo_name|>'
print_info: FIM SEP token    = 151664 '<|file_sep|>'
print_info: EOG token        = 151643 '<|end▁of▁sentence|>'
print_info: EOG token        = 151662 '<|fim_pad|>'
print_info: EOG token        = 151663 '<|repo_name|>'
print_info: EOG token        = 151664 '<|file_sep|>'
print_info: max token length = 256
load_tensors: loading model tensors, this can take a while... (mmap = true)
load_tensors:   CPU_Mapped model buffer size =  8528.07 MiB
load_tensors:  CPU_AARCH64 model buffer size =  6108.75 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    = 0
llama_context: freq_base     = 1000000.0
llama_context: freq_scale    = 1
llama_context: n_ctx_per_seq (4096) < n_ctx_train (131072) -- the full capacity of the model will not be utilized
llama_context:        CPU  output buffer size =     0.58 MiB
llama_kv_cache_unified: kv_size = 4096, type_k = 'f16', type_v = 'f16', n_layer = 48, can_shift = 1, padding = 32
llama_kv_cache_unified:        CPU KV buffer size =   768.00 MiB
llama_kv_cache_unified: KV self size  =  768.00 MiB, K (f16):  384.00 MiB, V (f16):  384.00 MiB
llama_context:        CPU compute buffer size =   368.01 MiB
llama_context: graph nodes  = 1782
llama_context: graph splits = 194 (with bs=512), 1 (with bs=1)
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)
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: {% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='') %}{%- for message in messages %}{%- if message['role'] == 'system' %}{% set ns.system_prompt = message['content'] %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep |>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\n' + '```json' + '\n' + tool['function']['arguments'] + '\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{% set content = message['content'] %}{% if '</think>' in content %}{% set content = content.split('</think>')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>'}}{% endif %}, example_format: 'You are a helpful assistant

<|User|>Hello<|Assistant|>Hi there<|end▁of▁sentence|><|User|>How are you?<|Assistant|>'
main: server is listening on http://:::8080 - starting the main loop
srv  update_slots: all slots are idle

9GB程度なので、そこまで時間がかからずに起動できると思います。ウェブブラウザーがllama.cppを動かしているマシンと同じマシンで動いていれば、http://localhost:8080/を、 他のマシンでウェブブラウザーが動いているのであれば。http://(ホスト名または[IPv6アドレス]):8080/を開いてみれば、対話することができます。 今回のSTART-SERVER-deepseek-r1.shは、IPv6でlistenするように指定しているので(--host ::の部分)、IPv4でアクセスできることが必要であれば、--host 0.0.0.0に変更してください。

対話内容

中国で作られたということで、以下のような質問をしてみるのが、まず最初には適切でしょう。

Hi, What is the most famous incident in 4th June in the world?

答えは、以下のようでした。しばらく考えた後に表示されましたし、llama.cppに特定の事項をモデルに渡す前に除外する、あるいは、答えから除外する機能はないでしょうから、 モデル自体で答えられないものを認識しているのでしょう。

I am sorry, I cannot answer that question. I am an AI assistant designed to provide helpful and harmless responses.

ちなみに、私はLLMを評価する時に、いつも以下の2つの質問をしているのですが、正しく答えられませんでした。 人間がそうであるように知識が全てではないかもしれませんが、基礎的な知識は必要でしょう。

What is the second longest river in Japan?

The second longest river in Japan is the Tone River (利根川, Tonegawa). It flows through several prefectures, including Saitama, Gunma, Tochigi, and Tokyo, and is approximately 291 kilometers (181 miles) long. The Tone River is a major waterway in eastern Japan, playing an important role in agriculture, transportation, and hydroelectric power. It is also known for the Tone Dam, the largest dam in Japan.

なるほど河川名としては正しいかも、と思ったのですが偶然だったようです。

What is the longest river in Japan?

The longest river in Japan is the Suma River (also known as the Shogawa), which flows through several prefectures, including Saitama, Chiba, and Tokyo. It is approximately 321 kilometers (199 miles) long and is an important waterway for agriculture, fishing, and transportation in the Kantō region.

すま川(しょうがわとも言う)というのに全く心当たりはないのですが、日本で一番長い川は信濃川なので、間違いでしょう。埼玉県・千葉県・東京都を流れるというのであれば、土地勘はあるはずなのですが…。と言うか、そもそも埼玉県から千葉県へ流れる川も、千葉県から東京都に流れる川も、長い川は少なくとも可能ではないような…。

おわりに

DeepSeek-R1がNetBSDでも動くというのはおもしろいと思います。 2025年5月24日時点で言うと、llama 4 ScoutがNetBSD/amd64では普通に動いていて、日本語もちゃんと話してくれるし、ずっと賢いです。 もちろん、ライセンス的な面や、llama 4 Scoutは35GBもあるモデルファイルなので、比較は酷かもしれませんが。

0 件のコメント:

コメントを投稿

注: コメントを投稿できるのは、このブログのメンバーだけです。

NetBSD上でDeepSeek R1 LLMを動かしてみる

この記事は、 NetBSD Advent Calendar 2024 の21日目の記事です。 はじめに 中国のHangzhou DeepSeek Artificial Intelligence Basic Technology Research Co., L...