AIニュース最前線
最新ニュースAI日報Hacker日報週報動画AIツールトレンド企業

AIニュース最前線

世界中のAI最新情報を日本語で毎時更新

最新ニュース日報トレンド企業プレミアムRSS
© 2026 ainew.jp特定商取引法に基づく表記
ニュース一覧元記事を開く
KDnuggets·2026年5月28日 23:00·約19分で読める

Ollama を用いたローカル言語モデルの設定調整

#LLM#Ollama#ローカル推論#モデルチューニング#データプライバシー
TL;DR

本記事は、Ollama を用いたローカル大規模言語モデルの実運用において、デフォルト設定の限界を克服し、プライバシーやパフォーマンスを最大化するための具体的なチューニング手法を解説している。

AI深層分析2026年6月13日 01:15
3
注目/ 5段階
深度40%
4
関連度30%
4
実用性20%
5
革新性10%
2

キーポイント

1

Ollama Modelfile の重要性と構成

Dockerfile に似た宣言型ファイル「Modelfile」を用いて、システム指示やパラメータを定義し、再利用可能なモデルバリアントを作成する方法が解説されている。

2

デフォルト設定の限界とリスク

汎用的なデフォルト設定は安全志向が強すぎるため、コーディング支援や自動化パイプラインなどでは遅延や予測不能な出力を招く可能性があり、カスタマイズが不可欠である。

3

サーバー環境変数による最適化

ハードウェア性能を引き出すために、Ollama サーバーレベルの環境変数を調整することで、推論速度やリソース管理を最適化する手法が含まれている。

4

Go テンプレート構文によるプロンプト制御

柔軟なプロンプトフローを実現するために、Ollama が採用する Go テンプレート構文を活用した精密な入力フォーマット化の技術が紹介されている。

5

カスタムモデルファイルによるパラメータの統合

Modelfile に温度やコンテキストサイズなどの設定を定義することで、API リクエストごとにパラメータを指定する必要なく、一貫した最適化された挙動を実現できます。

6

Temperature パラメータの役割と使い分け

低い値(0.1-0.2)は論理的で確定的な出力を、高い値(0.8-1.2)は多様性や創造性を引き出すため、タスクの種類に応じて調整する必要があります。

7

Top-K, Top-P, Min-P の役割と違い

Top-K は確率の高い固定数のトークンを制限し、Top-P は累積確率で動的に範囲を調整するが、Min-P は先頭のトークンに対する相対的な閾値でより柔軟かつ強力なフィルタリングを行う。

影響分析・編集コメントを表示

影響分析

この記事は、企業や開発者がクラウド依存から脱却し、オンプレミスで安全かつ効率的に AI を運用するための具体的な実装指針を提供しています。特に、単なる導入ではなく「設定の微調整」に焦点を当てることで、現場におけるパフォーマンス課題の解決策として即戦力となる情報を提供しており、ローカル LLM 運用の標準化に貢献する内容です。

編集コメント

クラウド API に依存しない自律的な AI 運用を実現する上で、パラメータ設定の知識は必須です。本記事はそのための実践的なロードマップとして非常に価値があります。

imageimage**

# イントロダクション

言語モデルは、機械学習の実践者や開発者がアプリケーションを構築する方法を依然として形作っています。能力が高くコンパクトな小型言語モデルの登場は、この状況に新たな興味深い層を加えています。サードパーティの API を経由せず、ローカルでモデルを実行することで、完全なデータプライバシーが保証され、トークンごとの API 利用料が不要となり、オフラインでの動作も可能になります。この革命を推進するツールの一つとして、軽量な Go ベースのエンジン、シンプルな CLI(コマンドラインインターフェース)、そして堅牢な Docker に似たモデル管理システムを備えていることから、Ollama はローカル推論の実行における標準の一つとして台頭しています。

しかし、単にモデルをプルしてデフォルト設定で実行するだけでは、最適化された状態とはなり得ません。デフォルトの設定は広範な一般ユーザー向けに調整されており、パフォーマンスや決定論的な推論、あるいは専門的なシステム要件よりも、安全で対話型のチャットを優先することが多いためです。コーディングアシスタントの構築、自動化された ETL パイプラインの実装、マルチエージェントシステムの開発を行っている場合、デフォルトの設定ではレイテンシの高さ、コンテキストウィンドウの制限、あるいはランダムで予測不能な出力といった問題を引き起こす可能性が高いでしょう。

ローカル AI アプリケーションを向上させるには、モデルレベルのハイパーパラメータとサーバーレベルの実行環境の両方を調整する方法を理解する必要があります。この記事では、Ollama の設定エンジン内部に深く入り込み、Ollama Modelfile を使用してローカル言語モデルのパラメータを微調整し、サーバー環境変数でハードウェアパフォーマンスを最適化し、Go テンプレート構文を使用して正確なプロンプトフローを形成する方法を探ります。

# 1. Ollama Modelfile: ローカルモデルの設計図

Dockerfile がコンテナの構築方法を定義するのと同様に、Ollama Modelfile は、ローカル言語モデルがどのように動作すべきかを定義する宣言型設定ファイルです。これにより、システム指示のカスタマイズ、モデルパラメータの調整が可能になり、これらの設定をパッケージ化して、単一のコマンドで実行できる新しい再利用可能なモデルバリアントを作成できます。

基本的な Modelfile は、ベースモデル参照(FROM ディレクティブを使用)、システムレベルのガイドライン(SYSTEM を使用)、およびパラメータ変更(PARAMETER ディレクティブを使用)で構成されます:

// 例:カスタム開発者用 Modelfile

ベースモデルとして Llama 3.1 8B を使用

FROM llama3.1:8b

モデルレベルのパラメータを設定

PARAMETER temperature 0.2

PARAMETER num_ctx 8192

PARAMETER min_p 0.05

システムのペルソナと行動指針を定義する

SYSTEM """あなたはエリートで極めて正確なソフトウェアエンジニアです。

簡潔でモジュール化され、最適化されたコードソリューションを提供してください。

明示的に求められない限り、会話的な余計な言葉は含めないこと。"""

カスタムモデルをコンパイルして実行するには、ターミナルで ollama create コマンドを使用します:

'dev-llama' という名前のモデルを Modelfile から作成する

ollama create dev-llama -f ./Modelfile

新しく作成したモデルを実行する

ollama run dev-llama

これらのパラメータをモデル定義に直接カプセル化することで、dev-llama を照会するすべてのアプリケーションや API 呼び出しが、各 API リクエストで生の JSON パラメータペイロードを渡す必要なく、標準でこれらの最適化を引き継ぐことを保証できます。

# 2. サンプリングパラメータの微調整

モデルがテキストを生成する際、単語を「知っている」のではなく、語彙全体に対する次の最も確からしいトークンの確率分布を計算します。サンプリングパラメータは、この分布からエンジンが次のトークンを選択する方法を決定します。これらの設定を微調整することは、モデルの創造性と精度を特定のユースケースに合わせるための最も効果的な手段です。

// 温度:ランダム性のダイヤル

温度パラメータは、トークンの確率分布のスケーリングを制御します。数学的には、モデルによって生成された生のロジット(ソフトマックス前のスコア)が確率に変換される前に除算されます:

⟦CODE_0⟧

  • 低温(例:0.1 から 0.2): 低確率の選択肢を平坦化し、高確率の選択肢を増幅します。これにより、非常に決定論的かつ一貫性があり、論理的な補完結果が得られます。コード生成、数学的推論、構造化データ抽出(JSON/YAML)、事実に基づく要約に最適です。
  • 高温(例:0.8 から 1.2): トークン確率間の差を平坦化し、起こりにくいトークンをより競争力のあるものにします。これにより、回答に多様性、ランダム性、「創造性」が導入されます。創作活動やブレインストーミングに最適です。

高度に決定論的かつ構造化されたタスク向け設定

PARAMETER temperature 0.1

// Top-K, Top-P, Min-P: トークンプールを絞り込む

制御されていない場合、低温であってもモデルは確率分布の末尾から不適切なトークンを稀に選択することがあります。これを防ぐため、モデルエンジンでは最終的なトークンを選択する前にアクティブなトークンプールをフィルタリングします。

  • Top-K(例:40): ポールを最も確率の高い K 個の次候補トークンに制限します。ランクが 40 より低いトークンは、実際の確率がどうであれ即座に破棄されます。これは非常に不規則なトークンを剪定するための粗末だが効果的な方法です。
  • Top-P / Nucleus Sampling (例:0.90): 累積確率が閾値 P を超える動的なトークンのプールに制限を設けます。例えば 0.90 の場合、Ollama はすべてのトークンを確率の高い順に並べ替え、分布の最初の 90% を占めるトップグループのみを保持します。モデルが非常に自信を持っている場合、プールはわずか 2〜3 トークンに圧縮されることもありますが、混乱している場合はプールが拡大します。
  • Min-P (例:0.05 から 0.10): Top-P に代わる現代的で圧倒的に優れた代替手段です。静的な累積スライスを取るのではなく、min_p は先頭トークンの確率に対する動的閾値よりも低い確率を持つトークンをフィルタリングします。例えば、トップトークンの確率が 0.80 で min_p が 0.05 に設定されている場合、他のトークンが考慮されるための最小閾値は 0.80 * 0.05 = 0.04 となります。トップトークンが非常に確信を持っている場合(例:0.99)、他のすべてのトークンは積極的に剪定されます。一方、トップトークンの確信度が低い場合(例:0.15)、閾値は 0.0075 に低下し、創造的な選択肢を広範囲に保つことになります。

Modelfile で堅牢なサンプリング制限を設定する

PARAMETER top_k 40

PARAMETER top_p 0.90

PARAMETER min_p 0.05

**

⚠️ min_p を使用する際は、通常は top_p をデフォルト(1.0)のままにするか、0.95+ の高い値に設定して、min_p の優れた動的スケーリング挙動を妨げないようにしてください。

# 3. ストップループと反復出力

ローカルモデルのデプロイメントにおける最もフラストレーションを伴う失敗の一つに、*反復ループ*があります。これは、モデルが同じ文、フレーズ、またはコードブロックを無限に生成し続ける状態です。通常、これは小規模なモデルサイズ(例えば 15 億パラメータや 30 億パラメータなど)と、ペナルティ境界の欠如という組み合わせによって引き起こされます。

Ollama は、これらのループ状態を防止および中断するために、3 つの主要なパラメータを提供しています。

// 反復と存在ペナルティ

  • 反復ペナルティ (repeat_penalty): 既に生成されたトークンの生ロジットに乗算し、再度出現する可能性を低減します。1.1 から 1.2 の値は、モデルが必要な文法用語("the" や "and" など)を避けてしまうことなく、ループを抑制するのに通常十分です。
  • 存在ペナルティ (presence_penalty): 生成されたテキストに少なくとも一度出現したトークンに対して、一律の一回限りのペナルティを適用し、モデルが全く新しいトピックや語彙を導入することを促します。
  • 頻度ペナルティ (frequency_penalty): トークンの出現回数に比例したペナルティを適用し、特定の用語の過剰使用を段階的に抑制します。

ループを抑制し、語彙の多様性を促進する

PARAMETER repeat_penalty 1.15

PARAMETER presence_penalty 0.05

PARAMETER frequency_penalty 0.05

// ストップシーケンスによる生成の停止

時折、モデルは内部でループを起こさないものの、自分のターンが終わったことに気づかず、ユーザーからの架空の応答を生成し続けることがあります。これを防ぐには、明示的なストップシーケンス(stop tokens)を定義してください。モデルがストップシーケンスを生成すると、エンジン即座に推論を停止し、応答を返します。

一般的なストップトークンとしては、チャットマーカーの</s>や、マークダウンセクションの見出し、あるいはカスタム区切り文字などが挙げられます:

ChatML タグまたは User 行が生成されたら生成を停止する

PARAMETER stop "</s>"

PARAMETER stop "<|im_start|>"

PARAMETER stop "User:"

# 4. コンテキストウィンドウとメモリの管理

**

ローカルハードウェアのリソース、特に GPU のビデオ RAM (VRAM) は非常に制約されています。モデルのメモリ構造をどのようにサイズ設定するかを理解することは、堅牢なローカルアプリケーションを構築する上で極めて重要です。

// コンテキスト長 (num_ctx)

コンテキスト長 (num_ctx) は、モデルが一度に処理できるアテンションウィンドウ(トークン単位)の大きさを定義します。これには、入力プロンプト(およびシステム履歴)と新たに生成された出力トークンの両方が含まれます。

デフォルトでは、Ollama は多くのモデルを保守的なコンテキストウィンドウ(2048 または 4096 トークン)で初期化します。これは低スペックなハードウェアでのメモリオーバーフローを防ぐためです。しかし、Llama 3.1 や Mistral などの最新のモデルは、ネイティブで最大 128,000 トークンのコンテキストウィンドウをサポートしています。検索拡張生成(RAG)システムを構築している場合や、大規模なコードファイルをインポートする場合は、2048 トークンではプロンプトが静かに切り捨てられ、文脈の喪失と極めて不正確な補完結果につながります。

このパラメータは Modelfile で明示的に増やすことができます:

Expand context window to 16,384 tokens

PARAMETER num_ctx 16384

**

⚠️ 注意計算(attention computation)の計算量は、コンテキスト長に対して二次関数的にスケールします($O(N^2)$)。num_ctx を 2 倍にすると、生成時にモデルのアクティブな状態を保存するために必要な VRAM が劇的に増加します。必ずハードウェアが増大した割り当てに対応できることを確認してください。

// KV Cache Quantization (OLLAMA_KV_CACHE_TYPE)

長い会話におけるトークン間の関係を追跡するため、モデルは VRAM 内にアクティブなキーバリュー(KV)キャッシュを保持します。コンテキスト長が大きい場合(32k や 128k など)、KV キャッシュのサイズはモデル自体の重みサイズを超え、メモリ不足によるクラッシュを引き起こす可能性があります。

これを防ぐため、Ollama は KV キャッシュ量子化をサポートしています。モデルの重みを 16 ビット浮動小数点数から 4 ビット整数に圧縮するのと同様に、KV キャッシュもテキスト品質への影響を最小限に抑えながら、より低い精度に量子化できます:

  • f16: 標準的な非圧縮 16 ビット浮動小数点キャッシュ(デフォルト)
  • q8_0: KV キャッシュを 8 ビット整数に圧縮し、出力品質への影響はほぼゼロのまま KV VRAM を約 50%節約します
  • q4_0: KV キャッシュを 4 ビット整数に圧縮し、モデルのパープレキシティがわずかに増加する代わりに、KV VRAM の 75%を節約して、コンシューマー向けハードウェアでも巨大なコンテキストサイズを実現可能にします

このパラメータは、OLLAMA_KV_CACHE_TYPE サーバー環境変数(次節で詳細解説)を通じて設定されます。

# 5. サーバーレベルの調整:環境変数

**

Modelfile パラメータが特定のモデルの動作方法を調整する一方で、サーバー環境変数は Ollama のバックグラウンドデーモン自体をカスタマイズします。これらの設定は、Ollama がオペレーティングシステムとどのように相互作用し、システムメモリを処理し、並列処理を管理し、ハードウェアアクセラレーション層を利用するかを決定します。

これらの変数の設定方法はホスト OS に依存します:

  • macOS: ターミナルでの exports 設定か、アプリケーション環境ファイル内の修正(またはバックグラウンドサービスの場合は launchctl を経由して起動)
  • Linux (Systemd): systemctl edit ollama.service を使用して環境構成を注入
  • Windows (WSL2 / System): 標準の Windows システム環境変数、または WSL ターミナルプロファイルで設定

// 必須のサーバー変数

変数名

デフォルト値

目的とベストプラクティス

OLLAMA_HOST

127.0.0.1:11434

サーバーネットワークインターフェースをバインドします。API をローカルネットワーク上の他のコンピュータに公開するには、0.0.0.0:11434 に設定してください。

OLLAMA_MODELS

プラットフォーム固有のデフォルト設定

モデルの保存場所を変更します。ブートドライブの容量が不足している場合、この設定を高速な外部 NVMe SSD に指すことを強く推奨します。

OLLAMA_KEEP_ALIVE

5 分 (5m)

最後のリクエスト実行後、モデルが GPU メモリ上に保持される時間を制御します。アクティブなパイプラインでの再読み込み遅延を防ぐには 1 時間 (1h) に設定するか、無限に保持させるには -1 を設定してください。

OLLAMA_NUM_PARALLEL

1

並列リクエスト処理を有効化します。この値を 2 または 4 に設定すると、モデルインスタンスが分割され、同時 API リクエストを処理できるようになりますが、VRAM の消費量は増大します。

OLLAMA_KV_CACHE_TYPE

f16

長いコンテキスト長において VRAM を節約します。一般的な使用には q8_0 に、消費者向け GPU で巨大なコンテキストサイズを扱う場合は q4_0 に設定してください。

OLLAMA_FLASH_ATTENTION

0 (無効)

1 に設定すると Flash Attention が有効化されます。これは対応するハードウェア(最新の NVIDIA または Apple GPU)において、プロンプトの事前充填実行速度を劇的に向上させ、メモリ使用量を削減します。

// 例:Linux (Systemd) での設定注入

Ubuntu/Debian で本番環境サービスを実行している実践者は、これらの環境変数を注入するためにサービスファイルを編集してください:

Ollama の systemd 設定エディタを開く

sudo systemctl edit ollama.service

エディタブロック内で、以下の設定を追加します:

[Service]

Environment="OLLAMA_NUM_PARALLEL=4"

Environment="OLLAMA_KEEP_ALIVE=24h"

Environment="OLLAMA_KV_CACHE_TYPE=q8_0"

Environment="OLLAMA_FLASH_ATTENTION=1"

ファイルを保存し、ハードウェア最適化を適用するためにデーモンを再起動してください:

systemd 定義の再読み込みとサービスの再起動

sudo systemctl daemon-reload

sudo systemctl restart ollama

# 6. プロンプトテンプレート: Go テンプレート構文

**

言語モデルは、チャット履歴やユーザークエリ、システムロールをネイティブには理解しません。代わりに、システムペルソナ、ユーザーメッセージ、アシスタント応答を区別する特殊なトークンでフォーマットされた、単一の連続した生テキストストリームを期待します。

Ollama は Go テキストテンプレートエンジン** を使用して、高レベルのチャット履歴(例:標準的な OpenAI 互換のロール JSON アレイ)を、モデルが期待する正確なテキスト形式に変換します。

もしテンプレートが正しく設定されていない場合、システムプロンプトは完全に無視され、モデルがあなたの指示を識別できず、推論パフォーマンスが著しく低下します。

// Go テンプレートの構造の理解

Ollama の Modelfile における TEMPLATE ディレクティブは、構造化タグを使用して指示を解析します。以下に、Qwen や Mistral-instruct、Hermes などのモデルでよく使用される人気のある ChatML フォーマットへのマッピング例を示します:

メッセージストリームのフォーマットを定義する

TEMPLATE """{{ if .System }}

システム

{{ .System }}

{{ end }}{{ if .Prompt }}

ユーザー

{{ .Prompt }}

{{ end }}

アシスタント

{{ .Response }}

"""

このブロック内の Go テンプレートロジックを分解してみましょう:

翻訳全文

決定論的かつ高度に制限されたパラメータ

PARAMETER temperature 0.0

PARAMETER min_p 0.05

PARAMETER top_p 0.95

PARAMETER top_k 10

ループを抑制する

PARAMETER repeat_penalty 1.1

明示的な停止マーカー

PARAMETER stop ""

PARAMETER stop "User:"

// 2. クリエイティブライティング(ブレインストーミング/インタラクティブエージェント)

対話型インターフェース、動的なエージェントワークフロー、ストーリー生成のために設計されています。温度を上げつつも語彙の停滞を防ぎます。

FROM llama3.1:8b

表現力豊かで多様なパラメータ

PARAMETER temperature 0.9

PARAMETER min_p 0.08

PARAMETER top_p 0.98

PARAMETER top_k 60

ループや反復を防止するためのより強力なペナルティ

PARAMETER repeat_penalty 1.20

PARAMETER presence_penalty 0.15

PARAMETER frequency_penalty 0.10

// 3. RAG パワーハウス(大規模コンテキスト/高メモリ)

長い PDF マニュアルの読解、ローカルデータベースへの照会、またはマルチファイルワークスペースの処理のために設計されています。コンテキスト長を最大化し、メモリーフットプリントを最適化します。

FROM llama3.1:8b

大規模なコンテキスト割り当て

PARAMETER num_ctx 32768 (コンテキスト数)

PARAMETER temperature 0.3

PARAMETER min_p 0.05

大規模なプロンプトでのループ防止

PARAMETER repeat_penalty 1.15

# まとめ

ローカル言語モデルのエンジニアリングは、出力の品質と物理的なハードウェア制約という現実との間の繊細なバランスです。デフォルト設定でモデルをデプロイすると、パフォーマンス、スループット、精度の面で大きな損失が生じます。

温度や min_p といったサンプリングパラメータを制御することで、モデルに高い精度を持たせたり、創造的な魅力を引き出したりすることが可能です。反復ペナルティとストップシーケンスを実装すれば、ローカルモデルが無限ループに陥るのを防ぐことができます。同時に、KV キャッシュ量子化やフラッシュアテンションを通じて VRAM を最適化しながらコンテキスト長を拡張することで、消費者向け GPU でも複雑な検索タスクに取り組むことが可能になります。

Ollama の Modelfile をマスターし、サーバー環境変数を設定することで、AI ツールの受動的な利用者から、高性能でプライベートかつ美しく最適化されたローカルインテリジェンスパイプラインを設計するシステムエンジニアへと移行し始めることになります。パラメータは常に調整し続け、メモリ使用量は最小限に保ち、ローカルエージェントが構築されるのを待ちましょう。

Matthew Mayo (@mattmayo13) は、コンピュータサイエンスの修士号およびデータマイニングの大学院ディプロマを取得しています。KDnuggets と Statology の編集長、そして Machine Learning Mastery の寄稿編集者として、Matthew は複雑なデータサイエンスの概念を誰もが理解できるようにすることを目的としています。彼の専門的な関心には、自然言語処理(Natural Language Processing)、言語モデル、機械学習アルゴリズム、および新興の AI への探求が含まれます。彼はデータサイエンスコミュニティにおける知識の民主化という使命に駆り立てられています。Matthew は 6 歳の頃からコーディングを続けています。

原文を表示
Tweaking Local Language Model Settings with Ollama
Tweaking Local Language Model Settings with Ollama

**

# Introduction

Language models continue to shape how machine learning practitioners and developers build applications. The advent of capable, compact small language models add an intriguing layer to the mix. By bypassing third-party APIs, running models locally guarantees complete data privacy, eliminates per-token API costs, and enables offline operation. Among the tools powering this revolution, Ollama has emerged as one of the standards for running local inference due to its lightweight Go-based engine, simple CLI, and robust Docker-like model management system.

However, simply pulling a model and running it with the default settings is rarely optimal. Default configurations are tuned for a broad, general-purpose audience, often prioritizing safe, conversational chat over performance, deterministic reasoning, or specialized system needs. If you are building a coding assistant, an automated ETL pipeline, or a multi-agent system, the default configurations will likely lead to high latency, context-window limitations, or random and unpredictable outputs.

To elevate your local AI applications, you need to understand how to tune both the model-level hyperparameters and the server-level runtime environments. In this article, we will go deep under the hood of Ollama's configuration engine, exploring how to fine-tune local language model parameters using the Ollama Modelfile, optimize hardware performance with server environment variables, and format precise prompt flows using Go template syntax**.

# 1. The Ollama Modelfile: Your Local Model Blueprint

**

Much like a Dockerfile defines how a container is built, an Ollama Modelfile is a declarative configuration file that defines how a local language model should behave. It lets you customize system instructions, adjust model parameters, and package these configurations into a new, reusable model variant that you can run with a single command.

A basic Modelfile consists of a base model reference (using the FROM directive), system-level guidelines (using SYSTEM), and parameter modifications (using the PARAMETER directive):

// Example: A Custom Developer Modelfile

code
# Use Llama 3.1 8B as the base model
FROM llama3.1:8b

# Set model-level parameters
PARAMETER temperature 0.2
PARAMETER num_ctx 8192
PARAMETER min_p 0.05

# Define system persona and behavioral guidelines
SYSTEM """You are an elite, highly precise software engineer. 
Provide concise, modular, and optimized code solutions. 
Do not include conversational filler unless explicitly asked."""

To compile and run your custom model, you use the ollama create command in your terminal:

code
# Create the model named 'dev-llama' from the Modelfile
ollama create dev-llama -f ./Modelfile

# Run the newly created model
ollama run dev-llama

By encapsulating these parameters directly into the model definition, you ensure that every application or API call querying dev-llama inherits these optimizations out-of-the-box, without needing to pass raw JSON parameter payloads in each API request.

# 2. Fine-Tuning the Sampling Parameters

When a model generates text, it doesn't "know" words; it calculates a probability distribution over its vocabulary for the next most likely token. Sampling parameters dictate how** the engine chooses the next token from this distribution. Tweaking these settings is the single most effective way to align the model’s creativity and precision with your specific use case.

// Temperature: The Randomness Dial

The temperature parameter controls the scaling of the token probability distribution. Mathematically, it divides the raw logits (pre-softmax scores) generated by the model before they are converted into probabilities:

  • Low temperature (e.g., 0.1 to 0.2): Flattens low-probability options and amplifies high-probability ones. This results in highly deterministic, consistent, and logical completions. Ideal for code generation, mathematical reasoning, structured data extraction (JSON/YAML), and factual summarization.
  • High temperature (e.g., 0.8 to 1.2): Flattens the differences between token probabilities, making less likely tokens more competitive. This introduces diversity, randomness, and "creativity" into the responses. Ideal for creative writing and brainstorming.
code
# Configure for highly deterministic, structured tasks
PARAMETER temperature 0.1

// Top-K, Top-P, and Min-P: Narrowing the Token Pool

Left unchecked, even at low temperatures, models can occasionally select highly inappropriate tokens from the tail end of the probability distribution. To prevent this, model engines filter the active token pool before selecting the final token.

  • Top-K (e.g. 40): Restricts the pool to the K most probable next tokens. Any token ranked lower than 40 is immediately discarded, regardless of its actual probability. This is a crude but effective way to prune highly erratic tokens.
  • Top-P / Nucleus Sampling (e.g. 0.90): Restricts the pool to a dynamic set of tokens whose cumulative probability exceeds the threshold P. For example, at 0.90, Ollama sorts all tokens from highest to lowest probability and keeps only the top group that makes up the first 90% of the distribution. If the model is highly confident, the pool might compress to just 2 or 3 tokens; if it is confused, the pool expands.
  • Min-P (e.g. 0.05 to 0.10): A modern, vastly superior alternative to Top-P. Instead of taking a static cumulative slice, min_p filters out tokens whose probability is lower than a dynamic threshold relative to the leading token's probability. For example, if the top token has a probability of 0.80 and min_p is set to 0.05, the minimum threshold for any other token to be considered is 0.80 * 0.05 = 0.04. If the top token is highly certain (e.g. 0.99), all other tokens are aggressively pruned. If the top token is uncertain (e.g. 0.15), the threshold drops to 0.0075, keeping a wide pool of creative choices open.
code
# Establish robust sampling limits in the Modelfile
PARAMETER top_k 40
PARAMETER top_p 0.90
PARAMETER min_p 0.05

⚠️ When using min_p, you should generally leave top_p at its default (1.0) or set it highly (0.95+) so it doesn't interfere with the superior, dynamic scaling behavior of min_p.

# 3. Stopping Loops and Repetitive Outputs

**

One of the most frustrating failures in local model deployment is the *repetition loop*, where a model begins generating the exact same sentence, phrase, or code block indefinitely. This is usually triggered by a combination of a small model size (e.g. 1.5B or 3B parameters) and a lack of penalty boundaries.

Ollama provides three key parameters to prevent and interrupt these looping states.

// Repetition and Presence Penalties

  • Repetition penalty (repeat_penalty): Multiplies the raw logits of tokens that have already been generated, making them less likely to appear again. A value of 1.1 to 1.2 is usually sufficient to discourage looping without making the model avoid necessary grammar words (like "the" or "and").
  • Presence penalty (presence_penalty): Applies a flat, one-time penalty to any token that has appeared at least once in the generated text, encouraging the model to introduce completely new topics or vocabulary.
  • Frequency penalty (frequency_penalty): Applies a penalty proportional to the number of times a token has appeared, steadily discouraging the overuse of specific terms.
code
# Discourage loops and encourage vocabulary variety
PARAMETER repeat_penalty 1.15
PARAMETER presence_penalty 0.05
PARAMETER frequency_penalty 0.05

// Halting Generation with Stop Sequences

Sometimes, the model doesn't loop internally, but it fails to realize when it has finished its turn, continuing to hallucinate fake responses from the user. You can prevent this by defining explicit stop sequences** (stop tokens). When the model generates a stop sequence, the engine immediately halts inference and returns the response.

Common stop tokens include chat markers like <|im_end|>, markdown section headers, or custom delimiters:

code
# Stop generating when ChatML tags or User lines are generated
PARAMETER stop "<|im_end|>"
PARAMETER stop "<|im_start|>"
PARAMETER stop "User:"

# 4. Managing Context Windows and Memory

**

Local hardware resources — specifically video RAM (VRAM) on your GPU — are highly constrained. Understanding how to size your model’s memory structures is vital for building robust local applications.

// Context Length (num_ctx)

The context length (num_ctx) defines the size of the attention window (in tokens) that the model can process at once. This includes both the input prompt (and system history) and the newly generated output tokens.

By default, Ollama initializes many models with a conservative context window of 2048 or 4096 tokens to prevent memory overflow on lower-end hardware. However, modern models like Llama 3.1 or Mistral support native context windows up to 128,000 tokens**. If you are building a retrieval-augmented generation (RAG) system or importing large code files, 2048 tokens will result in silent prompt truncation, leading to loss of context and highly inaccurate completions.

You can explicitly increase this parameter in your Modelfile:

code
# Expand context window to 16,384 tokens
PARAMETER num_ctx 16384

⚠️ Attention computation scales quadratically ($O(N^2)$) with context length. Doubling your num_ctx will dramatically increase the VRAM required to store the model's active state during generation. Be sure your hardware can handle the increased allocation.

// KV Cache Quantization (OLLAMA_KV_CACHE_TYPE)

To track relationships between tokens over a long conversation, the model stores an active key-value (KV) cache in VRAM. At large context lengths (like 32k or 128k), the size of the KV cache could exceed the weight size of the model itself, causing out-of-memory crashes.

To combat this, Ollama supports KV cache quantization. Much like model weights can be compressed from 16-bit floats to 4-bit integers, the KV cache can be quantized to lower precisions with minimal degradation in text quality:

  • f16: Standard, uncompressed 16-bit floating-point cache (default)
  • q8_0: Compresses the KV cache to 8-bit integers, saving roughly 50% of KV VRAM with virtually zero impact on output quality
  • q4_0: Compresses the KV cache to 4-bit integers, saving 75% of KV VRAM, allowing massive context sizes on consumer hardware at the expense of a slight increase in model perplexity

This parameter is set via the OLLAMA_KV_CACHE_TYPE server environment variable (detailed in the next section).

# 5. Server-Level Tuning: Environment Variables

**

While Modelfile parameters adjust how a specific model operates, server environment variables** customize the Ollama background daemon itself. These configurations dictate how Ollama interacts with your operating system, handles system memory, manages parallel processing, and utilizes your hardware acceleration layers.

How you set these variables depends on your host operating system:

  • macOS: Set via terminal exports or modified inside your application environment files (or launched via launchctl for background services)
  • Linux (Systemd): Configured via systemctl edit ollama.service to inject environment configurations
  • Windows (WSL2 / System): Set in standard Windows System Environment Variables or in your WSL terminal profile

// The Essential Server Variables

Variable Name

Default Value

Purpose & Best Practices

OLLAMA_HOST

127.0.0.1:11434

Binds the server network interface. Set to 0.0.0.0:11434 to expose the API to other computers on your local network.

OLLAMA_MODELS

Platform-specific default

Changes model storage location. Highly recommended to point this to a high-speed external NVMe SSD if your boot drive is low on space.

OLLAMA_KEEP_ALIVE

5m (5 minutes)

Controls how long models stay loaded in GPU memory after your last request. Set to 1h to prevent reload latency in active pipelines, or -1 to keep it loaded indefinitely.

OLLAMA_NUM_PARALLEL

1

Enables parallel request handling. Setting this to 2 or 4 splits model instances to handle concurrent API requests, though it multiplies VRAM consumption.

OLLAMA_KV_CACHE_TYPE

f16

Saves VRAM on large context lengths. Set to q8_0 for general usage, or q4_0 for massive context sizes on consumer GPUs.

OLLAMA_FLASH_ATTENTION

0 (disabled)

Set to 1 to enable Flash Attention. This dramatically increases prompt pre-fill execution speed and reduces memory usage on supported hardware (modern NVIDIA/Apple GPUs).

// Example: Injecting Configurations on Linux (Systemd)

For practitioners running production services on Ubuntu/Debian, edit the service file to inject these environment variables:

code
# Open the systemd configuration editor for Ollama
sudo systemctl edit ollama.service

Inside the editor block, add the following configuration:

code
[Service]
Environment="OLLAMA_NUM_PARALLEL=4"
Environment="OLLAMA_KEEP_ALIVE=24h"
Environment="OLLAMA_KV_CACHE_TYPE=q8_0"
Environment="OLLAMA_FLASH_ATTENTION=1"

Save the file and restart the daemon to apply your hardware optimizations:

code
# Reload systemd definitions and restart the service
sudo systemctl daemon-reload
sudo systemctl restart ollama

# 6. Prompt Templating: Go Template Syntax

**

A language model does not natively understand chat histories, user queries, or system roles. Instead, they expect a single, continuous stream of raw text formatted with special tokens that separate the system persona, the user message, and the assistant response.

Ollama uses the Go text template engine** to convert high-level chat histories (e.g. standard OpenAI-compatible role JSON arrays) into the exact text format expected by the model.

If your template is configured incorrectly, your system prompt will be completely ignored, the model might fail to identify your instructions, and inference performance will severely degrade.

// Understanding the Go Template Structure

The TEMPLATE directive in an Ollama Modelfile uses structured tags to parse instructions. Here is an example mapping to the popular ChatML format (often used by models like Qwen, Mistral-instruct, and Hermes):

code
# Define the message stream formatting
TEMPLATE """{{ if .System }}<|im_start|>system
{{ .System }}<|im_end|>
{{ end }}{{ if .Prompt }}<|im_start|>user
{{ .Prompt }}<|im_end|>
{{ end }}<|im_start|>assistant
{{ .Response }}<|im_end|>"""

Let’s break down the Go template logic in this block:

  • {{ if .System }} ... {{ end }}: Checks if a system prompt has been defined. If it has, it prints the start block <|im_start|>system, injects the system prompt variable {{ .System }}, and closes it with <|im_end|>.
  • {{ if .Prompt }} ... {{ end }}: Takes the incoming user query ({{ .Prompt }}) and wraps it inside the user tokens <|im_start|>user and <|im_end|>.
  • <|im_start|>assistant \n {{ .Response }}<|im_end|>: Directs the model that it is now the assistant's turn to generate text. The engine streams the incoming output into {{ .Response }} and appends the final end-of-text marker.

When creating a new model, it is important to inspect the source model's documentation to identify its precise template structure (e.g. Llama uses special headers like <|start_header_id|>system<|end_header_id|>, whereas Mistral uses bracket-based sequences like [INST] and [/INST]). Matching the expected template guarantees the highest possible instruction-following fidelity.

# 7. Practitioner Reference Architectures

**

To help you immediately apply these parameters, here are three pre-configured Modelfiles tailored to specific common runtime scenarios:

// 1. The Precise JSON Parser (Structured Extraction / Coding)

Designed for ETL pipelines, JSON extraction, and high-accuracy software development. Minimizes temperature and leverages dynamic pruning to strip out erratic tokens.

code
FROM llama3.1:8b

# Deterministic and highly restricted parameters
PARAMETER temperature 0.0
PARAMETER min_p 0.05
PARAMETER top_p 0.95
PARAMETER top_k 10

# Discourage loops
PARAMETER repeat_penalty 1.1

# Explicit stop markers
PARAMETER stop "<|im_end|>"
PARAMETER stop "User:"

// 2. The Creative Writer (Brainstorming / Interactive Agent)

Designed for conversational interfaces, dynamic agent workflows, and story generation. Elevates temperature while preventing vocabulary stagnation.

code
FROM llama3.1:8b

# Highly expressive and diverse parameters
PARAMETER temperature 0.9
PARAMETER min_p 0.08
PARAMETER top_p 0.98
PARAMETER top_k 60

# Stronger penalties to prevent loops and repetitiveness
PARAMETER repeat_penalty 1.20
PARAMETER presence_penalty 0.15
PARAMETER frequency_penalty 0.10

// 3. The RAG Powerhouse (Large Context / High Memory)

Designed for reading long PDF manuals, querying local databases, or processing multi-file workspaces. Maximizes context length and optimizes memory footprints.

code
FROM llama3.1:8b

# Large context allocation
PARAMETER num_ctx 32768
PARAMETER temperature 0.3
PARAMETER min_p 0.05

# Prevent looping on large prompts
PARAMETER repeat_penalty 1.15

# Wrapping Up

Local language model engineering is a delicate balance between quality of output and the realities of physical hardware constraints. Deploying a model using defaults leaves substantial performance, throughput, and accuracy on the table.

By taking control of sampling parameters like temperature and min_p, you can force models to be highly precise or creatively engaging. Implementing repetition penalties and stop sequences keeps your local models from falling into endless loops. At the same time, scaling up the context length while optimizing VRAM through KV cache quantization and flash attention** allows you to tackle complex retrieval tasks on consumer GPUs.

By mastering the Ollama Modelfile and configuring server environment variables, you begin your transition from a passive consumer of AI tools to a systems engineer who designs high-performance, private, and beautifully optimized local intelligent pipelines. Keep your parameters tuned, keep your memory footprint lean, and let your local agents build.

Matthew Mayo (@mattmayo13) holds a master's degree in computer science and a graduate diploma in data mining. As managing editor of KDnuggets & Statology, and contributing editor at Machine Learning Mastery, Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, language models, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.

この記事をシェア

関連記事

Latent Space2026年6月20日 17:06

[AINews] 今日特に大きな出来事はありませんでした

Latent Space は、GLM 5.2 が依然として注目されていると指摘しつつ、AIE WF 2026 の通常チケットが月曜日に完売すると発表しました。同サイト購読者向けに限定割引を提供し、参加者には Warp や Datadog などからのスポンサークレジットも付与されます。

TechCrunch AI★42026年6月20日 01:01

米国がアンソロピックの「Fable 5」発売を禁止、しかし市場は動じず

米国政府は国家安全保障上の懸念から、アマゾンの研究者らがガードレール回避手法を発見したとして、アンソロピックに対し最新モデル「Fable 5」と「Mythos 5」の販売差し止めを命じた。サイバーセキュリティ研究者らはこの措置が危険だとする公開書簡に署名し、同社も他モデルでも同様の抜け道が存在すると指摘している。

GitHub Blog★42026年6月20日 01:00

社内データ分析エージェントの構築方法について

GitHub は、大規模なデータ組織が直面する自己完結型のデータアクセスと洞察提供の課題に対し、AI を活用した信頼性の高い解決策として、社内でデータ分析エージェントを構築したことを発表した。

今日のまとめ

AI日報で今日の重要ニュースをまとめ読み

ニュース一覧に戻る元記事を読む