Local LLMを始めてみよう in Macbook M4 MAX(64GB)

OpenAI APIはそれなりに使ったから、Local LLMでcoding agentを作りたいなあ〜
でもLocal LLMという単語しか知らないので調べていこ

良しなな文書はここに吊るす
これは悪くなさそう

llama.cppって何?の公式以外の良さそうなもの

What is local llm?
クラウド上のGPUではなく、手元のPCで動作させるLLMのこと

Why use local LLM?
- 編集できる
- 重みやモデルの実装をいじりたい
- セキュリティ
- 無制限に使用できる
- オープンソースなモデルを推進したい共同体根性
- オープンパラメーター(モデルの重みのみ)なだけな場合も

どこで見たか、手元のCPU/GPUが本来こなすべき事(HTTPリクエストを処理する以外の知能的な処理)をさせる、みたいなロマンもある、らしい

どうやってローカルのGPUでモデルを動かす?

llama.cppが重要そう

llama.cppはC++でllm推論を行うためのオープンソースプロジェクト。
元々はmetaのllamaをC++で推論するためのプロジェクトだった

なるほど確かに学習ではなく、推論ならCPUでもいいし、高速にしつつ、OSやCPUアーキテクチャの違いを吸収するクロスプラットフォームな開発をする発想があってもおかしくない??
今までみたいにAPIでchatbot開発するよりは低レイヤそうだな

前評判だとMLXというappleが開発しているappleシリコン向けの機械学習フレームワークを使うと良い、みたいな話だったが、llama.cppでもappleシリコンは問題なく使えるっぽい(llama.cppのgithubより)
Apple silicon is a first-class citizen - optimized via ARM NEON, Accelerate and Metal frameworks

MLXは機械学習フレームワーク(numpyライクな行列計算ライブラリ)なのに対してllama.cppはLLM推論に偏っているように見える。
llama.cppと関連が深く、行列計算ライブラリ開発ぽいことをしているプロジェクトはggml。

vLLMもアツいらしい

transfomerライブラリで使うHF形式もあるらしいけど、これは早いとか特に言及ないなあ
デファクトってだけなのかな?

どんなツールを使うとよさそう?

LM studioとollamaがなんか良さそう

どっちがええんや?

これだ

知名度的にollama使ってそのままollamaな人が多いけど、UIがGUIで十分ならLM studioみたいな感じかな?

どのモデルが良さそう?

codeナントカがいくつかあるからそれかも

codeagentのためにMCPやエージェントフレームワークで追加で必要なものは?

vscodeの拡張機能のroo clineで以下の設定画面があるので、ollamaで立てたLLMサーバーにAPI叩ける

roo clineにMCP clientの機能もあるのでそれ使えば良さそ〜
便利〜

ollamaがMLXサポートしてないので、推論速くしたい場合はLM studioとか使うと思うけど
一応その場合も機能ある

一旦深く考えすぎず、ollamaでllmを動かす体験をしてみよう
使えるモデル次第でまた考えよ

なんかollamaのdocumentおざなり、習うより慣れよ感
素直にダウンロード

zipファイルを解凍すると勝手にCLIインストールされる
ollama run でモデルを勝手にpullしてくれる(モデル初回利用時のみ)
ネットワークがたまたま貧弱で、llama3.3 70Bのダウンロード開始して寝て起きて完了だった。

local LLM反応きた、感動!
MLX対応してる?らしいので試してみたい

思いつきでqwen3:30bを試す
llama3.3より賢そう、日本語自体の自然さはllama3.3の方が良さそう

なんかollamaでmlxサポートはまだみたい
めっちゃ無視されてるwLM studioとかMLX-LM(こちらはapple公式)では動くみたい

以下で動いた。ollamaと比較するために4bitにした。(ollamaは4bit量子化がデフォルトらしい)
mamba create mlx-env python=3.12
mamba activate mlx-env
mamba install mlx-lm
mlx_lm.generate --model mlx-community/Qwen3-30B-A3B-4bit --prompt="核融合について解説して"
local llmってそもそも量子化とかで工夫してモデルサイズを小さくしているということがよく分かってなかった。恥ずべき。
mlx-communityには4bit-DWQとかmixed3-4bitとか4bit量子化にも色々あるみたい。多分ollama(というかGGUF形式)でも同じ。

LM studioも動かしてみたけどなんかプロセスをkillallしてもメモリ使用量が50GBに張り付いていて、よくわかんないし怪しいからuninstall
キャッシュなども消した
ダウンロードしたLLMのメモリをheadlessで確保し続けるとかなのかなあ、、

qwen3-30B-A3B-4bitを比較
MLX
核融合の読みを「かくえいごう」としてしまっている以外は問題なさそう。
マルチモーダルじゃないとこんな所(音)を間違えるとかもあるんだね。
https://huggingface.co/mlx-community から選択。
❯ mlx_lm.generate --model mlx-community/Qwen3-30B-A3B-4bit --prompt "核融合について解説して" --max-tokens 2048
Fetching 12 files: 100%|███████████████████████████████████████████████████████| 12/12 [00:00<00:00, 214177.23it/s]
==========
<think>
Okay, the user asked me to explain nuclear fusion. Let me start by recalling what I know about it. Nuclear fusion is the process where two light atomic nuclei combine to form a heavier nucleus, releasing energy. This is different from fission, which is splitting heavy nuclei. I should mention that it's the process that powers the sun and stars.
First, I need to define nuclear fusion clearly. Maybe start with the basic concept: combining light elements. Then explain the energy release. I should mention that it's the opposite of fission. Also, the conditions required for fusion, like high temperature and pressure, since the nuclei need to overcome the electrostatic repulsion.
Next, the main example is the sun. The proton-proton chain reaction and the CNO cycle. I should explain those briefly. Also, mention that in stars, hydrogen fuses into helium. But maybe the user is more interested in practical applications, like in energy production. So I should talk about fusion as a potential energy source, like in experimental reactors such as tokamaks or stellarators.
I need to explain the challenges. The main issue is achieving the necessary conditions for fusion. The energy required to initiate fusion is high, and maintaining the plasma is difficult. Also, the materials used need to withstand high temperatures and radiation. Maybe mention the difference between magnetic confinement and inertial confinement.
Then, current projects like the International Thermonuclear Experimental Reactor (ITER) in France. Also, mention that fusion is still in the experimental phase but has the potential for nearly limitless energy with minimal waste. But I should note the challenges: achieving break-even (where the energy output exceeds the input), and the technical hurdles.
I should also compare it to fission. Fusion produces less radioactive waste, but there are still challenges with neutron activation. Also, the fuel sources: deuterium and tritium, which are isotopes of hydrogen. Deuterium is abundant in seawater, but tritium is rare and needs to be bred from lithium.
Wait, the user might not know the difference between deuterium and tritium. I should explain that. Also, the reaction equation: for example, deuterium + tritium → helium + neutron + energy. The energy released is due to the mass defect, as per E=mc².
I should check if I'm missing any key points. Maybe mention that fusion is the primary energy source in stars, and that on Earth, it's being researched for clean energy. Also, the environmental benefits compared to fossil fuels and fission.
But I need to make sure the explanation is clear and not too technical. Avoid jargon where possible, but some terms are necessary. Maybe define terms like plasma, magnetic confinement, etc.
Also, the user might be interested in the current state of fusion research. So mention that while it's not yet commercially viable, there's significant progress. Companies like Helion Energy or Tokamak Energy are working on it.
I should structure the answer with an introduction, the process, examples (sun, stars), the conditions needed, challenges, current research, and potential benefits. Keep it organized but conversational.
Wait, the user wrote "核融合について解説して" which is Japanese for "Explain about nuclear fusion." So the user might be Japanese, but the answer is in English. But the user might be okay with that. Alternatively, maybe they want the answer in Japanese. But the initial instruction was to write the thinking in English, then the answer in Japanese. Wait, the user's message is in Japanese, but the assistant's response is in English. Wait, no, the user's query is in Japanese, but the assistant's response is in English. But the user might expect the answer in Japanese. However, the initial instruction says to write the thinking in English, then the answer in Japanese. Wait, the user's message is in Japanese, but the assistant's response is in English. But maybe the user wants the answer in Japanese. However, the initial instruction says to write the thinking in English, then the answer in Japanese. So I need to make sure the final answer is in Japanese. But the user's query is in Japanese, so maybe they want the answer in Japanese. But the assistant's previous response was in English. Wait, the user's message is "核融合について解説して" which is Japanese. So the user is asking for an explanation in Japanese. But the assistant's thinking process is in English, and the answer is in Japanese. So I need to make sure the final answer is in Japanese. But the user's instruction here is to write the thinking in English, then the answer in Japanese. So I need to proceed accordingly.
But the user's message is in Japanese, so the answer should be in Japanese. However, the assistant's previous response was in English. But according to the instructions, the thinking is in English, and the answer is in Japanese. So I need to write the thinking in English, then the answer in Japanese. So the final answer should be in Japanese. Therefore, after the thinking process in English, the answer is in Japanese.
So, to recap: the thinking process is in English, and the answer is in Japanese. Therefore, I need to structure the response with the thinking in English, then the answer in Japanese.
But the user's query is in Japanese, so the answer should be in Japanese. Therefore, the assistant's response should be in Japanese. But the thinking process is in English. So the final answer is in Japanese.
Therefore, after the thinking process, the answer is written in Japanese. So I need to make sure that the final answer is in Japanese, while the thinking is in English.
So, the answer should be in Japanese. Let me proceed to write the answer in Japanese, based on the thinking process I had in English.
</think>
核融合(かくえいごう)は、軽い原子核が結合してより重い原子核を形成し、エネルギーを放出する反応です。このプロセスは、太陽や他の星のエネルギー源であり、地球でもクリーンなエネルギーとして研究されています。
### 1. **核融合の基本**
核融合は、**軽い元素(例:水素の同位体)が高エネルギーで衝突し、結合する**現象です。この際、**質量の減少**(質量欠損)によってエネルギーが放出され、アインシュタインの式 $ E = mc^2 $ に従って巨大なエネルギーが得られます。
### 2. **太陽での核融合**
太陽では、**水素(プロトン)がヘリウムに変換される**プロセスが起こります。主な反応は「**プロトン-プロトン連鎖反応**」で、以下のようになります:
- $ ^1H + ^1H \rightarrow ^2H + e^+ + \nu $(陽子が重水素に変わる)
- $ ^2H + ^1H \rightarrow ^3He + \gamma $(重水素と水素がヘリウム-3に変わる)
- $ ^3He + ^3He \rightarrow ^4He + 2e^+ $(ヘリウム-3がヘリウム-4に変わる)
この反応で、太陽は約1,500万℃の高温と圧力を維持し、エネルギーを放出しています。
### 3. **地球での応用**
核融合は、**無限に近いエネルギー源**とされ、以下のような利点があります:
- **燃料の豊富さ**:重水素($ ^2H $)は海水に豊富に存在し、トリチウム($ ^3H $)はリチウムから生成されます。
- **環境への影響**:放射性廃棄物が少なく、CO₂排出がほぼゼロです。
- **安全性**:核分裂(原子力)に比べて事故のリスクが低いです。
### 4. **技術的課題**
核融合を実用化するには、以下の課題があります:
- **高温・高圧の維持**:約1億℃のプラズマを安定して閉じ込めなければなりません。
- **エネルギー収支**:出力エネルギーが入力エネルギーを上回る「**ブレイク・イーブン**」を達成する必要があります。
- **材料の耐久性**:中性子放射線にさらされるため、材料の劣化が懸念されます。
### 5. **現在の研究**
- **トカマク装置**:磁場でプラズマを閉じ込める方法(例:欧州のITER)。
- **インパルス型**:レーザーで高圧をかけ、短時間で核融合を起こす(例:米国のNIF)。
- **民間企業**:Helion EnergyやTokamak Energyなど、実用化に向けた研究が進んでいます。
### 6. **将来の展望**
核融合は、**クリーンで持続可能なエネルギー**として期待されています。ただし、技術的・経済的な課題を乗り越える必要があります。もし実現すれば、化石燃料依存の削減や気候変動対策に大きく貢献するでしょう。
核融合は、人類のエネルギー問題解決の鍵となる技術です。今後の進展に注目が集まっています。
==========
Prompt: 15 tokens, 199.687 tokens-per-sec
Generation: 2011 tokens, 112.001 tokens-per-sec
Peak memory: 17.388 GB
ollama
❯ ollama run qwen3:30b-a3b --verbose
>>> 核融合について解説して
<think>
Okay, the user asked me to explain nuclear fusion. Let me start by recalling what I know about it. Nuclear
fusion is the process where two light atomic nuclei combine to form a heavier nucleus, releasing energy. I
remember that this is what powers the sun and other stars. But I need to make sure I get the details right.
First, I should explain the basic concept. Fusion occurs when the nuclei of atoms are brought close enough
together that the strong nuclear force can overcome the electrostatic repulsion between them. This requires
extremely high temperatures and pressures, which is why it's difficult to achieve on Earth. The most common
example is the fusion of hydrogen isotopes, like deuterium and tritium, to form helium.
I should mention the conditions needed for fusion. The sun's core has temperatures around 15 million degrees
Celsius and immense pressure. On Earth, we try to replicate this with methods like magnetic confinement (like
tokamaks) or inertial confinement (using lasers). But these are still in experimental stages.
Next, the energy released. When nuclei fuse, a small amount of mass is converted into energy according to
Einstein's equation E=mc². The mass difference between the initial and final nuclei is what's converted into
energy. For example, fusing hydrogen into helium releases a significant amount of energy.
I should also talk about the applications. The sun's energy comes from fusion, and there's a lot of research
into using fusion as a clean energy source. Unlike fission, fusion doesn't produce long-lived radioactive
waste, but there are challenges like achieving a net energy gain and containing the plasma.
Wait, I need to check if I'm mixing up any terms. Fusion vs. fission. Fission is splitting heavy nuclei,
while fusion is combining light ones. Also, the isotopes involved: deuterium (hydrogen-2) and tritium
(hydrogen-3) are common in experiments because they have a lower Coulomb barrier. The reaction produces
helium and a neutron, which is why there's some radioactive byproduct.
Another point: the potential for fusion as a future energy source. Projects like the International
Thermonuclear Experimental Reactor (ITER) are aiming to demonstrate that fusion can be a viable energy
source. But it's still not commercially viable yet.
I should also mention the challenges. The main ones are achieving and maintaining the necessary conditions
for fusion, dealing with plasma instability, and the high cost of the technology. Additionally, the materials
used in the reactor must withstand extreme conditions, which is a big engineering challenge.
Are there other fusion reactions besides hydrogen? Yes, like using deuterium and deuterium, which can produce
helium and a neutron, or tritium and deuterium. Each has different energy outputs and challenges.
I need to make sure the explanation is clear and not too technical. Avoid jargon where possible, but some
terms are necessary. Also, clarify that while fusion is a promising energy source, it's not yet widely used,
and there are ongoing research efforts.
Wait, the user might be a student or someone with a basic science background. So I should explain concepts
like nuclear forces, the Coulomb barrier, and the mass-energy conversion in simple terms. Maybe use an
example like the sun's energy production to illustrate the process.
Also, mention the difference between fusion and fission in terms of energy output and waste. Fusion produces
more energy per unit mass and less radioactive waste, which is a big advantage.
I should structure the answer with an introduction, the basic process, conditions required, examples, energy
release, applications, challenges, and future prospects. Keep it organized so it's easy to follow.
</think>
核融合(かくゆうごう)は、**軽い原子核が結合してより重い原子核を形成し、エネルギーを放出するプロセス**です。こ
の現象は、太陽や他の星のエネルギー源であり、地球上でもクリーンエネルギーの実現を目指して研究が進められています
。以下に、核融合の基本的な仕組みや特徴、応用、課題を解説します。
---
### **1. 核融合の基本概念**
- **定義**:軽い原子核(例:水素の同位体)が高温・高圧の下で結合し、より重い原子核(例:ヘリウム)を生成する過
程。
- **エネルギーの放出**:結合時にわずかな質量がエネルギーに変換される(**アインシュタインの式:$ E = mc^2 $**)
。この質量欠損がエネルギーとして解放される。
---
### **2. 核融合の条件**
核融合が起こるためには、**原子核同士のクーロン反発力を克服する**必要があります。これには以下の条件が必要です:
- **高温・高圧**:約1億度(太陽の中心は約1,500万度)の高温で、原子核が十分な運動エネルギーを持ち、衝突しやすく
なります。
- **核の種類**:軽い元素(水素、ヘリウムなど)が適しています。例えば、**水素の同位体(重水素・三重水素)**の結
合がよく研究されています。
---
### **3. 代表的な核融合反応**
- **水素→ヘリウムの反応**(太陽の主なプロセス):
- **プロトン-プロトン連鎖**:水素(プロトン)が結合してヘリウムを生成。
- **炭素-酸素サイクル**:より重い星で起こる反応。
- **実験的な反応**:
- **重水素(D)+三重水素(T)→ ヘリウム+中性子**:
$$
D + T \rightarrow \text{He} + n + 17.6 \, \text{MeV}
$$
(中性子が放射性物質を生成するため、研究中)
---
### **4. 核融合のエネルギー発生メカニズム**
- **質量欠損の例**:4つの水素原子が1つのヘリウム原子に結合する際、約0.7%の質量がエネルギーに変換されます。
- **エネルギー効率**:1kgの水素をヘリウムに変えると、約6.3×10^14ジュールのエネルギーが得られます(これは化石燃
料の何倍ものエネルギー密度)。
---
### **5. 応用と意義**
- **太陽のエネルギー源**:核融合が太陽光を生み出しています。
- **クリーンエネルギーの可能性**:
- **燃料の豊富さ**:水素は地球上に無尽蔵に存在(海水から抽出可能)。
- **放射性廃棄物の少なさ**:核融合の副産物は中性子やヘリウムで、半減期が短い(例:Tの半減期は12.3年)。
---
### **6. 課題と技術的挑戦**
- **高温・高圧の維持**:地球では実現が難しい。
- **磁場閉じ込め**(例:トカマク):プラズマを磁場で閉じ込める。
- **慣性閉じ込め**(例:レーザー):高エネルギーで物質を圧縮。
- **エネルギー収支の逆転**:現状では「入力エネルギー>出力エネルギー」の段階(実験的な成功はあり)。
- **材料の耐久性**:中性子の衝撃で構造物が劣化する問題。
---
### **7. 今後の展望**
- **ITER(国際熱核融合実験堆積)**:フランスで建設中の実験炉で、10億ドル規模のプロジェクト。
- **商業化の目標**:2050年頃を目標に、実用化に向けた研究が進む。
- **代替エネルギー**:再生可能エネルギーと併用し、炭素排出ゼロの社会を実現する可能性。
---
### **まとめ**
核融合は、**宇宙のエネルギー源であり、未来のクリーンエネルギーの鍵**です。しかし、技術的・経済的な課題が多く、
実用化にはさらなる研究と革新が必要です。太陽の力を使いこなすことで、持続可能な社会の実現が期待されています。
total duration: 30.027518291s
load duration: 29.218333ms
prompt eval count: 15 token(s)
prompt eval duration: 2.171540209s
prompt eval rate: 6.91 tokens/s
eval count: 1857 token(s)
eval duration: 27.82576075s
eval rate: 66.74 tokens/s

mlx: 112.001 tokens-per-sec
ollama: 66.74 tokens/s
だそうな、、だいぶ違うぞほんまか???
ちなみにmlxのmax-tokenのデフォルトパラメータが少なすぎたのでコマンド引数で変更しているよ

M4チップがチリチリ言ってて人工知能が情報エントロピーを下げている音がする

エージェントをローカルLLMで作る必要is何?
最新のlocal llmすごいすごい!で満足してしまった。。。