Ollama 모델별 최적화된 설정 으로 실행 가능하도록 Custom 설정을 추가하는 방법에 대해서 살펴보겠습니다.

Ollama 모델별 최적화 가이드 (qwen3.5:9b 예시)

대상 독자: Ollama로 로컬 LLM을 운영하면서 모델별·용도별 최적화 옵션을 직접 정의하고 싶은 개발자 대상 환경: Ubuntu 24 LTS, 사용자명 buffet, Ollama 0.32.6+, NVIDIA RTX 5070 12GB VRAM 예시 모델: qwen3.5:9b (6.6GB, 128k native context, 다국어 강함)


목차 (Table of Contents)


1. 개요

1.1 목표

Ollama에서 새 모델을 pull한 뒤, 용도별로 다른 Modelfile을 작성해 custom 태그를 만들고, 모든 Ollama 호환 클라이언트(CLI, open-webui, ollama-python, Aider 등)에서 동일한 최적화 옵션이 자동 적용되도록 한다.

1.2 핵심 개념

개념 설명
base 모델 ollama pull로 받는 원본 모델. 예: qwen3.5:9b
Modelfile Ollama의 공식 네이티브 설정 파일. FROM, PARAMETER, SYSTEM 등으로 구성
custom 태그 Modelfile로부터 ollama create로 만든 새 태그. 예: qwen3.5-9b-bg, qwen3.5-9b-perf
OLLAMA_* env Ollama 서버 전역 환경변수. 모든 모델에 공통 적용 (KV cache, flash attention 등)

1.3 왜 Modelfile인가?

Modelfile + custom 태그는 Ollama의 HTTP API 레벨에서 모든 클라이언트가 동일하게 인식하는 설정 메커니즘입니다. 즉, phi4-bg, qwen3.5-9b-bg 같은 custom 태그를 모든 도구가 그대로 사용하면, 각 도구가 따로 옵션을 알 필요가 없습니다.

1.4 전체 흐름

ollama pull qwen3.5:9b       ← base 모델 다운로드
        ↓
Modelfile 작성 (touch + $EDITOR)   ← 사람이 직접 작성
        ↓
ollama create qwen3.5-9b-bg  ← custom 태그 생성
ollama create qwen3.5-9b-perf
        ↓
ollama list로 확인
        ↓
ollama run / aider / open-webui / ollama-python에서 custom 태그 사용

2. 사전 준비

2.1 Ollama가 설치되어 있는지 확인

# 버전 확인
ollama -v
# 기대: ollama version is 0.32.x

# 서비스 상태 확인
systemctl is-active ollama
# 기대: active

설치 안 됐다면:

curl -fsSL https://ollama.com/install.sh | sh

2.2 작업 디렉토리 만들기

# Modelfile을 모아둘 작업 디렉토리 (홈 디렉토리 하위에 생성)
mkdir -p ~/ollama-modelfiles
cd ~/ollama-modelfiles

# 현재 위치 확인
pwd
# 기대: /home/buffet/ollama-modelfiles

2.3 텍스트 에디터 준비

$EDITOR 환경변수가 설정돼 있으면 그걸 쓰고, 아니면 nano로 시작:

# EDITOR가 설정돼 있는지 확인
echo $EDITOR
# 비어 있으면 nano로 설정 (이번 세션 한정)
export EDITOR=nano

# 또는 vim 사용
# export EDITOR=vim

: ~/.bashrcexport EDITOR=nano 한 줄 추가하면 영구 적용.

2.4 sudo 권한 확인

# sudo 가능 여부 확인
sudo -n true && echo "sudo OK" || echo "sudo 필요: 비밀번호 입력"

2.5 Ollama 서버 상태 확인

# API 응답 확인
curl -sS http://127.0.0.1:11434/api/tags | head -c 200
# 기대: {"models":[...]}

3. 단계 1 — 기본 모델 Pull

3.1 pull 명령

# qwen3.5:9b 다운로드 (약 4.5GB, 네트워크에 따라 1~5분)
ollama pull qwen3.5:9b

기대 출력:

pulling manifest...
pulling [SHA256] 100% |██████████|  9.0 GB
pulling [SHA256] 100% |██████████| 1.5 KB
pulling [SHA256] 100% |██████████|   33 B
pulling [SHA256] 100% |██████████|  184 B
verifying sha256 digest
writing manifest
removing any unused layers
success: pulled qwen3.5:9b

3.2 pull 확인

# 방금 받은 모델이 목록에 있는지 확인
ollama list | grep qwen3.5
# 기대:
# qwen3.5:9b    <HASH>    6.6 GB    ...

3.3 모델 정보 확인 (Modelfile 백업)

# 원본 base 모델의 Modelfile 확인 (어떤 기본 설정이 적용돼 있는지)
ollama show --modelfile qwen3.5:9b

기대 출력 (일부 발췌):

# Modelfile generated by "ollama show"
# To build a new Modelfile based on this, replace FROM with
# FROM qwen3.5:9b

FROM qwen3.5:9b
PARAMETER temperature 0.7
PARAMETER top_p 0.8
PARAMETER top_k 20
PARAMETER min_p 0
PARAMETER num_ctx 32768

왜 이걸 보나? — 원본 모델의 기본값을 확인해서, 우리 Modelfile에서 어떤 값을 명시적으로 override할지 결정하기 위함.

3.4 기본 모델 동작 테스트 (선택)

# 대화형으로 한 번 테스트
ollama run qwen3.5:9b "Reply with the single word: pong"
# Ctrl+D 또는 /bye로 종료

4. 단계 2 — Modelfile 작성 디렉토리 준비

# Modelfile을 보관할 디렉토리
cd ~/ollama-modelfiles

# 모델별 하위 디렉토리 만들기
mkdir -p qwen3.5-9b
cd qwen3.5-9b

# 빈 Modelfile 2개 만들기 (touch만, 내용은 다음 단계에서)
touch qwen3.5-9b-bg.Modelfile
touch qwen3.5-9b-perf.Modelfile

# 확인
ls -la
# 기대:
# -rw-r--r-- qwen3.5-9b-bg.Modelfile
# -rw-r--r-- qwen3.5-9b-perf.Modelfile

5. 단계 3 — -bg Modelfile 작성 (배경 모드, IDE 보호)

5.1 에디터로 파일 열기

cd ~/ollama-modelfiles/qwen3.5-9b
$EDITOR qwen3.5-9b-bg.Modelfile

5.2 파일 내용 (전부 복사해서 붙여넣기)

# ============================================================
# qwen3.5:9b - Background Mode
# 용도: IDE/브라우저와 공존, 적당한 속도, 일반 작업
# Ollama v0.32.6 Modelfile 호환
# ============================================================

# base 모델 지정
FROM qwen3.5:9b

# ----- 컨텍스트 -----
# Qwen3.5는 128k native 지원. 32k면 일반 코딩/대화에 충분.
PARAMETER num_ctx 32768
# 컨텍스트 오버플로 시 시스템 프롬프트 + 컨벤션 보존
PARAMETER num_keep 1024
# 생성 토큰 상한 (짧은 응답 위주)
PARAMETER num_predict 4096

# ----- 샘플링 (안정적, 결정에 가깝게) -----
PARAMETER temperature 0.3
PARAMETER top_p 0.9
PARAMETER top_k 20
PARAMETER min_p 0.05
PARAMETER repeat_penalty 1.1
PARAMETER repeat_last_n 64
PARAMETER seed 42

# ----- 시스템 프롬프트 -----
SYSTEM """
You are Qwen3.5 (9B) running in background mode on a workstation.
The user is likely running an IDE, browser, or other tools in parallel.
Be efficient and concise.

Capabilities:
- Coding (Python, TypeScript, JavaScript, Bash, SQL)
- Multilingual conversation (Korean, Japanese, English, Chinese)
- Document analysis and summarization
- Code review and refactoring suggestions

Behavior:
- Match the user's working language (default: Korean if user writes Korean).
- For code: preserve existing style, apply minimal changes.
- For explanations: short, direct, no preamble.
- If unsure, ask before making large changes.
"""

5.3 저장 (nano 기준)

nano를 썼다면:

  • Ctrl+OEnter (저장)
  • Ctrl+X (종료)

vim을 썼다면:

  • Esc:wqEnter

5.4 내용 확인

# 파일 내용 확인
cat qwen3.5-9b-bg.Modelfile

# 첫 줄/마지막 줄 빠르게 확인
head -3 qwen3.5-9b-bg.Modelfile
tail -3 qwen3.5-9b-bg.Modelfile

5.5 지원되지 않는 PARAMETER 없는지 자동 검증

# Modelfile에서 사용 불가능한 PARAMETER를 썼으면 경고
grep -E "^PARAMETER (kv_cache_type|num_gpu|num_thread|use_mlock|flash_attention|num_batch) " \
  qwen3.5-9b-bg.Modelfile && echo "⚠ 위 줄들은 Modelfile에서 지원되지 않습니다" \
                            || echo "✓ 모든 PARAMETER가 Modelfile 호환"

6. 단계 4 — -perf Modelfile 작성 (성능 모드, 풀스피드)

6.1 에디터로 파일 열기

cd ~/ollama-modelfiles/qwen3.5-9b
$EDITOR qwen3.5-9b-perf.Modelfile

6.2 파일 내용

# ============================================================
# qwen3.5:9b - Performance Mode
# 용도: 모든 리소스 Ollama에 집중, 최대 응답 속도
# Ollama v0.32.6 Modelfile 호환
# ============================================================

FROM qwen3.5:9b

# ----- 컨텍스트 (속도 우선) -----
# 16k면 학습 영역 부근, 컨텍스트 작아서 inference 빨라짐
PARAMETER num_ctx 16384
PARAMETER num_keep 512
PARAMETER num_predict 4096

# ----- 샘플링 (약간 더 다양성) -----
PARAMETER temperature 0.4
PARAMETER top_p 0.95
PARAMETER top_k 40
PARAMETER min_p 0.05
PARAMETER repeat_penalty 1.05
PARAMETER repeat_last_n 64
PARAMETER seed 42

# ----- 시스템 프롬프트 -----
SYSTEM """
You are Qwen3.5 (9B) in performance mode. All CPU/GPU resources are dedicated to you.
Be fast, precise, and direct. Skip pleasantries.
"""

6.3 저장 + 검증 (위와 동일)

# 저장
# (에디터에서 저장)

# 검증
grep -E "^PARAMETER (kv_cache_type|num_gpu|num_thread|use_mlock|flash_attention|num_batch) " \
  qwen3.5-9b-perf.Modelfile && echo "⚠ 위 줄들은 Modelfile에서 지원되지 않습니다" \
                             || echo "✓ 모든 PARAMETER가 Modelfile 호환"

6.4 두 파일 비교

# 두 Modelfile의 차이점 확인
diff qwen3.5-9b-bg.Modelfile qwen3.5-9b-perf.Modelfile
# 기대: num_ctx, num_keep, system prompt 등이 다름

7. 단계 5 — Modelfile 빌드 (ollama create)

7.1 빌드 (-bg)

cd ~/ollama-modelfiles/qwen3.5-9b

# qwen3.5-9b-bg 태그 생성
ollama create qwen3.5-9b-bg -f qwen3.5-9b-bg.Modelfile

기대 출력:

gathering model components
copying model file
using existing model layer
creating system layer
creating config layer
using default chat template
creating new model manifest
success: created model 'qwen3.5-9b-bg'

7.2 빌드 (-perf)

# qwen3.5-9b-perf 태그 생성
ollama create qwen3.5-9b-perf -f qwen3.5-9b-perf.Modelfile

기대 출력: 동일하게 success: created model 'qwen3.5-9b-perf'

7.3 빌드 실패 시 (예: 위에서 본 kv_cache_type 오류)

# 만약 "Error: unknown parameter 'kv_cache_type'" 같은 오류가 나면:
# 1) 어떤 줄이 문제인지 확인
ollama create qwen3.5-9b-bg -f qwen3.5-9b-bg.Modelfile 2>&1 | head -20

# 2) Modelfile에서 지원 안 되는 PARAMETER를 모두 찾아서 주석 처리 또는 삭제
# (해당 줄 앞에 #을 붙여서 주석 처리)
# 예시:
#   PARAMETER kv_cache_type q4_0      ← 이 줄을 #PARAMETER kv_cache_type q4_0 로 변경
#   PARAMETER num_gpu 999             ← 동일하게 주석 처리
#   PARAMETER use_mlock true          ← 동일하게
#   PARAMETER flash_attention 1       ← 동일하게
#   PARAMETER num_batch 512           ← 동일하게
#   PARAMETER num_thread 16           ← 동일하게

# 3) sed로 한 번에 주석 처리 (위 6개 줄을 모두 찾아서 # 추가)
sed -i.bak -E 's/^PARAMETER (kv_cache_type|num_gpu|num_thread|use_mlock|flash_attention|num_batch) /#PARAMETER \1 /' qwen3.5-9b-bg.Modelfile

# 4) 다시 빌드
ollama create qwen3.5-9b-bg -f qwen3.5-9b-bg.Modelfile

8. 단계 6 — 빌드 검증

8.1 목록에서 확인

# 새 태그가 목록에 있는지
ollama list | grep qwen3.5

기대 출력:

qwen3.5:9b                          <HASH>    6.6 GB    ...
qwen3.5-9b-bg                      <HASH>    6.6 GB    ...
qwen3.5-9b-perf                    <HASH>    6.6 GB    ...

왜 같은 크기?: custom 태그는 base 모델의 가중치를 공유하고, Modelfile 메타데이터만 추가합니다. 디스크는 약간 늘지만 (수 MB) VRAM은 base 모델 로드 시점에 결정됩니다.

8.2 Modelfile 파라미터 확인

# 적용된 파라미터 확인
ollama show qwen3.5-9b-bg --parameters

기대 출력:

num_ctx 32768
num_keep 1024
num_predict 4096
temperature 0.3
top_p 0.9
top_k 20
min_p 0.05
repeat_penalty 1.1
repeat_last_n 64
seed 42

8.3 Modelfile 원본 확인

# Modelfile 내용 (parameter만)
ollama show qwen3.5-9b-bg --modelfile

기대 출력:

# Modelfile generated by "ollama show"
# To build a new Modelfile based on this, replace FROM with
# FROM qwen3.5:9b

FROM qwen3.5:9b
PARAMETER num_ctx 32768
PARAMETER num_keep 1024
... (전체)
SYSTEM """..."""

8.4 chat template 확인 (필요 시)

ollama show qwen3.5-9b-bg --template
# 기대: Qwen chat template (ChatML 형식)

9. 단계 7 — 실행 테스트

9.1 한 줄 테스트

# bg 버전
ollama run qwen3.5-9b-bg "Say 'hello' in 3 languages"
# 기대: 한국어, 일본어, 영어 등으로 'hello'

# perf 버전
ollama run qwen3.5-9b-perf "What is 2+2? Answer in one word."
# 기대: 4 (또는 "Four")

9.2 속도 비교 (직관적)

# bg: ~15-25 tps
time ollama run qwen3.5-9b-bg "Count from 1 to 10"

# perf: ~25-40 tps
time ollama run qwen3.5-9b-perf "Count from 1 to 10"

9.3 대화형 테스트

ollama run qwen3.5-9b-bg
# 프롬프트에서 직접 대화
# /bye 로 종료
# /set parameter num_ctx 8192  ← 세션 중에 변경 가능

9.4 컨텍스트 동작 확인

# 긴 입력으로 context window 테스트
ollama run qwen3.5-9b-bg <<'EOF'
Summarize the following in 2 sentences:
[여기에 긴 텍스트 붙여넣기]
EOF

10. 단계 8 — Aider 연동

10.1 직접 모델 지정

# Aider는 Ollama HTTP API를 통해 custom 태그를 그대로 사용
aider --model ollama/qwen3.5-9b-bg backend/views.py
aider --model ollama/qwen3.5-9b-perf backend/views.py

10.2 프로젝트별 .aider.conf.yml 설정

# 프로젝트 디렉토리로 이동
cd ~/projects/myapp

# 설정 파일 작성
touch .aider.conf.yml
$EDITOR .aider.conf.yml

내용:

# 메인 모델 (Background 모드, IDE 보호)
model: ollama/qwen3.5-9b-bg

# 약식 모델 (commit message, history summary)
# qwen2.5-coder:1.5b는 1GB 미만으로 가벼움
weak-model: ollama/qwen2.5-coder:1.5b

# 큰 repo에서 map 토큰 절약
map-tokens: 1024

# 자동 커밋 끄기
auto-commits: false

# UI
stream: true
pretty: true
dark-mode: true

# 컨벤션 파일을 항상 컨텍스트에 포함
read:
  - CONVENTIONS.md

이제 이 프로젝트에서 aider만 실행하면 자동으로 qwen3.5-9b-bg 사용.

10.3 Ollama 모드 토글이 필요한 경우 (선택)

ollama-mode 스크립트를 사용하면 KV cache, CPU 우선순위 등을 즉시 전환할 수 있습니다. 설치 방법은 별도 문서 ollama-mode.md 참고.

핵심: Modelfile 안의 num_ctx, sampling 등은 그대로 유지되고, 서버 전역 설정(KV cache type, OMP threads, Nice)만 바뀝니다.

# 평소: IDE 우선
ollama-mode background
aider --model ollama/qwen3.5-9b-bg file.py

# 긴급: 풀스피드
ollama-mode performance
aider --model ollama/qwen3.5-9b-perf file.py

11. 단계 9 — 다른 클라이언트 연동 (open-webui, ollama-python)

11.1 open-webui

open-webui는 Ollama의 /api/show를 통해 Modelfile 정보를 자동으로 읽어옵니다. 즉, custom 태그를 등록만 하면 시스템 프롬프트·temperature·num_ctx가 자동 적용됩니다.

관리자 작업:

  1. open-webui에 로그인
  2. Admin Panel → Settings → Models 이동
  3. ”+ Add Model” 클릭
  4. Model Name: qwen3.5-9b-bg 입력
  5. “Save” 클릭

→ 사용자는 채팅 UI에서 qwen3.5-9b-bg를 선택하면 Modelfile의 system prompt가 자동 적용됨.

11.2 ollama-python (공식 Python 라이브러리)

# 설치
pip install ollama
# 또는 uv tool로 격리 설치 (권장)
uv tool install ollama

Python 코드 예시:

import ollama

# 1) 기본 호출 - custom 태그 사용
response = ollama.chat(
    model='qwen3.5-9b-bg',  # ← Modelfile 자동 적용
    messages=[
        {'role': 'user', 'content': '이 함수를 리팩토링해줘: ...'},
    ],
)
print(response['message']['content'])

# 2) Streaming
stream = ollama.chat(
    model='qwen3.5-9b-perf',
    messages=[{'role': 'user', 'content': '코드 설명해줘'}],
    stream=True,
)
for chunk in stream:
    print(chunk['message']['content'], end='', flush=True)

# 3) base 모델 사용 (Modelfile 무시, env 기본값만)
response = ollama.chat(
    model='qwen3.5:9b',  # ← base 모델
    messages=[{'role': 'user', 'content': 'Hello'}],
    # options로 직접 override 가능
    options={'num_ctx': 8192, 'temperature': 0.7},
)

11.3 LiteLLM (통합 게이트웨이)

import litellm

response = litellm.completion(
    model="ollama/qwen3.5-9b-bg",  # ← custom 태그 그대로
    messages=[{"role": "user", "content": "Hello"}],
    api_base="http://127.0.0.1:11434",
)

11.4 LangChain

from langchain_community.llms import Ollama

llm = Ollama(model="qwen3.5-9b-bg")  # ← custom 태그
result = llm.invoke("Explain this code")

핵심: 어떤 Ollama 호환 클라이언트든 model="qwen3.5-9b-bg"라고 적기만 하면 Modelfile이 자동 적용됩니다. 클라이언트별 설정이 따로 필요 없습니다.


12. 단계 10 — Modelfile 수정/보완 패턴

12.1 sampling만 바꾸고 싶을 때

cd ~/ollama-modelfiles/qwen3.5-9b
$EDITOR qwen3.5-9b-bg.Modelfile
# temperature 값 수정 후 저장
# 예: 0.3 → 0.5 (더 다양)

# 기존 태그 삭제 후 재빌드
ollama rm qwen3.5-9b-bg
ollama create qwen3.5-9b-bg -f qwen3.5-9b-bg.Modelfile

12.2 system prompt만 바꾸고 싶을 때

$EDITOR qwen3.5-9b-bg.Modelfile
# SYSTEM """...""" 블록만 수정

ollama rm qwen3.5-9b-bg
ollama create qwen3.5-9b-bg -f qwen3.5-9b-bg.Modelfile

12.3 num_ctx를 늘리고 싶을 때

$EDITOR qwen3.5-9b-perf.Modelfile
# PARAMETER num_ctx 16384 → 32768로 변경

# GPU 오버헤드 확인 (큰 컨텍스트는 VRAM 많이 먹음)
# 12GB VRAM에서 qwen3.5:9b 풀 오프로드 + 32k KV cache q8_0 ≈ 8-9GB → 가능
nvidia-smi --query-gpu=memory.used,memory.free --format=csv

ollama rm qwen3.5-9b-perf
ollama create qwen3.5-9b-perf -f qwen3.5-9b-perf.Modelfile

12.4 새 변형 추가 (예: -ja 일본어 특화)

cd ~/ollama-modelfiles/qwen3.5-9b

# Modelfile 복사해서 새 변형 만들기
cp qwen3.5-9b-bg.Modelfile qwen3.5-9b-ja.Modelfile

$EDITOR qwen3.5-9b-ja.Modelfile
# system prompt를 일본어 특화로 수정

예시 시스템 프롬프트 (일본어):

SYSTEM """
あなたはQwen3.5 (9B)です。日本語のコーディングアシスタントおよび翻訳者として動作します。

ルール:
- ユーザーの作業言語に合わせる(日本語/韓国語/英語)
- コードは既存のスタイルを保持
- 簡潔で直接的な回答
"""

빌드:

ollama create qwen3.5-9b-ja -f qwen3.5-9b-ja.Modelfile

# 확인
ollama list | grep qwen3.5
# 기대: qwen3.5:9b, qwen3.5-9b-bg, qwen3.5-9b-perf, qwen3.5-9b-ja

12.5 stop 시퀀스 추가 (특정 패턴에서 생성 중단)

$EDITOR qwen3.5-9b-perf.Modelfile

추가:

# "User:"가 나오면 생성 중단 (멀티턴 흉내 방지)
PARAMETER stop "User:"
# "### Instruction" 나오면 중단
PARAMETER stop "### Instruction"

빌드:

ollama rm qwen3.5-9b-perf
ollama create qwen3.5-9b-perf -f qwen3.5-9b-perf.Modelfile

12.6 여러 모델에 공통 부분 공유 (심화)

# 공통 SYSTEM을 별도 파일로 분리
cat > ~/ollama-modelfiles/_common-system.txt <<'EOF'
You are an expert coding assistant. Be concise, accurate, and respect existing code style.
When uncertain, ask. When sure, apply changes directly.
EOF

# Modelfile에서 직접 include 불가. 환경변수 또는 build 스크립트로 처리

참고: Ollama Modelfile은 FROM .../Modelfile 같은 include 문법을 지원하지 않습니다. 공유하려면 별도 빌드 스크립트에서 sed/cat으로 치환.


13. 트러블슈팅

13.1 Error: unknown parameter 'X'

Modelfile에 Ollama가 지원하지 않는 PARAMETER가 있을 때.

# 1) 어떤 줄이 문제인지 확인
ollama create <tag> -f <Modelfile> 2>&1 | head

# 2) 지원 안 되는 PARAMETER 목록 (Modelfile에서)
grep -E "^PARAMETER (kv_cache_type|num_gpu|num_thread|use_mlock|flash_attention|num_batch|use_mmap|numa|main_gpu|vocab_only|low_vram|penalize_newline) " <Modelfile>

# 3) 해당 줄을 주석 처리 (앞에 # 추가) 또는 삭제
sed -i.bak -E 's/^PARAMETER (kv_cache_type|num_gpu|num_thread|use_mlock|flash_attention|num_batch) /#PARAMETER \1 /' <Modelfile>

# 4) 재빌드
ollama create <tag> -f <Modelfile>

대안 위치:

지원 안 되는 PARAMETER 대안
kv_cache_type OLLAMA_KV_CACHE_TYPE env (drop-in conf)
num_gpu Ollama 자동 (또는 API options.num_gpu)
num_thread OMP_NUM_THREADS env (drop-in conf)
use_mlock API options.use_mlock
flash_attention OLLAMA_FLASH_ATTENTION env
num_batch API options.num_batch

13.2 pull model manifest: file does not exist

# 원인: base 모델이 pull 안 됨, 또는 custom 태그명이 잘못됨
ollama list | grep <base-model-name>

# base 모델 pull
ollama pull <base-model-name>

# custom 태그명은 `ollama list`에 정확히 있는 이름 사용
ollama list

13.3 Error: model 'X' not found, try pulling it first

# custom 태그가 만들어지지 않은 상태에서 실행했을 때
ollama list | grep <tag-name>

# 없으면 빌드
ollama create <tag-name> -f <Modelfile-path>

13.4 connection refused (Ollama 서버 안 떠있음)

# 서비스 상태 확인
systemctl status ollama

# 안 떠있으면 시작
sudo systemctl start ollama

# 부팅 시 자동 시작 설정
sudo systemctl enable ollama

13.5 OOM / CUDA out of memory

# GPU 메모리 사용량 확인
nvidia-smi

# 조치 1: num_ctx 줄이기
# Modelfile에서 PARAMETER num_ctx 값을 더 작게 (예: 16384 → 8192)

# 조치 2: KV cache 양자화 (drop-in conf)
# /etc/systemd/system/ollama.service.d/00-background.conf에서
#   OLLAMA_KV_CACHE_TYPE=q8_0 → q4_0로 변경
#   sudo systemctl daemon-reload && sudo systemctl restart ollama

# 조치 3: 더 작은 모델 사용
# qwen3.5:9b → qwen2.5-coder:1.5b (1GB)

13.6 응답이 반복/루프

# Modelfile에서 repeat_penalty 강화
# PARAMETER repeat_penalty 1.1 → 1.2
# PARAMETER repeat_last_n 64 → 128

# 또는 stop 시퀀스 추가
# PARAMETER stop "<|im_end|>"

13.7 시스템 프롬프트가 무시되는 것처럼 보일 때

# num_keep이 너무 작아서 시스템 프롬프트가 컨텍스트 오버플로 시 잘려나갈 수 있음
# Modelfile에서:
#   PARAMETER num_keep 1024
#   (시스템 프롬프트 길이 + 여유만큼)

# 확인
ollama show <tag> --parameters | grep num_keep

14. 부록 A — Ollama Modelfile PARAMETER 레퍼런스

14.1 Modelfile에서 사용 가능한 PARAMETER (v0.32.6)

PARAMETER 타입 기본값 설명
num_ctx int 2048 컨텍스트 윈도우 크기 (512~131072)
num_predict int -1 생성할 최대 토큰 (-1=무제한)
num_keep int 4 컨텍스트 오버플로 시 앞부분 보존 토큰 수
temperature float 0.8 0=결정적, 1=창의적
top_k int 40 상위 K개 토큰 중 샘플링
top_p float 0.9 누적 확률 P까지의 토큰에서 샘플링
min_p float 0.0 최소 확률 임계값 (top_p 대안)
typical_p float 1.0 locally typical sampling
repeat_penalty float 1.1 반복 페널티 (높을수록 덜 반복)
repeat_last_n int 64 반복 검사 범위 (0=비활성, -1=num_ctx)
presence_penalty float 0.0 한 번이라도 나온 토큰 페널티
frequency_penalty float 0.0 등장 횟수에 비례한 페널티
seed int 0 랜덤 시드 (-1=랜덤, 그 외=고정)
stop string - 생성 중단 문자열 (여러 개 가능)

14.2 Modelfile에서 사용 불가 (env/API로만)

PARAMETER 대안
kv_cache_type OLLAMA_KV_CACHE_TYPE env
num_gpu Ollama 자동 / API options
num_thread OMP_NUM_THREADS env / API
num_batch API options
use_mlock API options
use_mmap API options
flash_attention OLLAMA_FLASH_ATTENTION env
numa API options
main_gpu API options
vocab_only API options
low_vram API options
penalize_newline API options
f16_kv OLLAMA_KV_CACHE_TYPE env

14.3 권장 시작값 (코드 어시스턴트)

PARAMETER num_ctx 32768
PARAMETER num_keep 512
PARAMETER num_predict 4096
PARAMETER temperature 0.2       # 결정적
PARAMETER top_p 0.95
PARAMETER top_k 20
PARAMETER min_p 0.05
PARAMETER repeat_penalty 1.05
PARAMETER repeat_last_n 128
PARAMETER seed 42

14.4 권장 시작값 (번역/자연스러운 출력)

PARAMETER num_ctx 65536
PARAMETER num_keep 1024
PARAMETER num_predict 8192
PARAMETER temperature 0.3
PARAMETER top_p 0.9
PARAMETER top_k 40
PARAMETER min_p 0.05
PARAMETER repeat_penalty 1.1
PARAMETER repeat_last_n 64
PARAMETER seed 42

14.5 권장 시작값 (창의적 글쓰기)

PARAMETER num_ctx 16384
PARAMETER num_predict 8192
PARAMETER temperature 0.8
PARAMETER top_p 0.95
PARAMETER top_k 80
PARAMETER min_p 0.02
PARAMETER repeat_penalty 1.2
PARAMETER repeat_last_n 256

15. 부록 B — 자주 쓰는 custom 태그 네이밍 규칙

15.1 권장 패턴: <base>-<size>-<mode>[-<lang>][-<role>]

태그 예시 의미
qwen3.5-9b-bg qwen3.5 9B, Background 모드
qwen3.5-9b-perf qwen3.5 9B, Performance 모드
qwen3.5-9b-ja qwen3.5 9B, 일본어 특화
phi4-bg phi-4, Background
mistral-nemo-trans-bg mistral-nemo, 번역, Background
qwen3-coder-7b-fast qwen3-coder 7B, 고속 (perf의 별칭)

15.2 피해야 할 이름

  • qwen3.5:9b-bg (콜론은 base 모델 표기에만)
  • qwen3.5/9b-bg (슬래시 안 됨, Aider 인식 문제)
  • qwen3.5_9b_bg (언더스코어보다 하이픈 권장)
  • ❌ 대문자 (Qwen3.5-9b-BG) - 소문자 권장

15.3 태그 관리 팁

# 한 모델의 모든 변형 보기
ollama list | grep qwen3.5

# 한 모델의 모든 변형 일괄 삭제
for tag in qwen3.5-9b-bg qwen3.5-9b-perf qwen3.5-9b-ja; do
  ollama rm "$tag" 2>/dev/null
done

# Modelfile 디렉토리 백업
tar czf ~/ollama-modelfiles-backup-$(date +%Y%m%d).tar.gz ~/ollama-modelfiles

16. 부록 C — 빠른 참조: 전체 명령어 한 화면에

아래 명령어들을 순서대로 실행하면 qwen3.5:9b에 대한 2개 custom 태그(-bg, -perf)가 만들어지고, Aider/open-webui/ollama-python에서 사용 가능합니다.

# ============================================
# 1. 환경 준비
# ============================================
mkdir -p ~/ollama-modelfiles/qwen3.5-9b
cd ~/ollama-modelfiles/qwen3.5-9b
export EDITOR=nano

# ============================================
# 2. base 모델 pull
# ============================================
ollama pull qwen3.5:9b
ollama list | grep qwen3.5

# ============================================
# 3. Modelfile 2개 작성
# ============================================
touch qwen3.5-9b-bg.Modelfile qwen3.5-9b-perf.Modelfile
$EDITOR qwen3.5-9b-bg.Modelfile      # 단계 5.2 내용 붙여넣기
$EDITOR qwen3.5-9b-perf.Modelfile    # 단계 6.2 내용 붙여넣기

# ============================================
# 4. 빌드
# ============================================
ollama create qwen3.5-9b-bg   -f qwen3.5-9b-bg.Modelfile
ollama create qwen3.5-9b-perf -f qwen3.5-9b-perf.Modelfile

# ============================================
# 5. 검증
# ============================================
ollama list | grep qwen3.5
ollama show qwen3.5-9b-bg --parameters

# ============================================
# 6. 테스트
# ============================================
ollama run qwen3.5-9b-bg "say hi in Korean"
aider --model ollama/qwen3.5-9b-bg file.py

# ============================================
# 7. 수정/추가
# ============================================
# Modelfile 편집 후:
$EDITOR qwen3.5-9b-bg.Modelfile
ollama rm qwen3.5-9b-bg
ollama create qwen3.5-9b-bg -f qwen3.5-9b-bg.Modelfile

17. 부록 D — Custom 태그의 실제 저장 위치와 관리 (phi4-bg 예시)

이 섹션의 목적: 단계 8에서 ollama create phi4-bg -f Modelfile로 만든 custom 태그의 설정값이 어디에 저장되는지, 그리고 수정·삭제·추가할 때 어디를 건드려야 하는지를 phi4-bg를 예시로 정리합니다.

17.1 왜 ~/ollama-modelfiles가 비어 있는가?

이전 단계에서 Modelfile을 ~/ollama-modelfiles/에 만들었는데, custom 태그가 만들어진 직후에 그 파일들이 사라진 것처럼 보이는 게 정상입니다.

이유:

  • ollama create phi4-bg -f Modelfile는 Modelfile 내용을 읽어서 Ollama의 모델 manifest에 임베드합니다
  • Ollama는 원본 .Modelfile 파일을 따로 보관하지 않습니다
  • custom 태그(phi4-bg)는 자체 완결형(self-contained) — Ollama 모델 안에 모든 설정이 들어있음
  • ~/ollama-modelfiles/Modelfile을 작성·보관하는 작업 디렉토리일 뿐, Ollama가 의존하는 곳이 아님

확인:

# 작업 디렉토리는 비어있어도 됨 (보관용이 아니라 작업용)
ls ~/ollama-modelfiles/qwen3.5-9b/
# 기대: qwen3.5-9b-bg.Modelfile, qwen3.5-9b-perf.Modelfile (작업용 사본)

# custom 태그는 ollama list에 살아있음
ollama list | grep phi4-bg
# 기대: phi4-bg:latest  8.4 GB  ...

17.2 Custom 설정이 실제로 저장되는 곳

Ollama는 OCI(Open Container Initiative) 형식으로 모델을 저장합니다. 관련 위치:

~/.ollama/
├── models/                          ← 기본 저장소 (OLLAMA_MODELS env로 변경 가능)
│   ├── manifests/
│   │   └── registry.ollama.ai/
│   │       └── library/
│   │           ├── phi-4-gguf/
│   │           │   └── q4_k_s      ← base 모델 manifest
│   │           ├── phi4-bg/
│   │           │   └── latest      ← custom 태그 manifest
│   │           ├── phi4-perf/
│   │           │   └── latest
│   │           └── ...
│   └── blobs/
│       └── sha256-<hash>           ← 실제 바이너리 (모델 가중치, config, system prompt 등)

custom 태그 phi4-bg의 manifest 구조 (JSON):

# manifest 직접 보기
cat ~/.ollama/models/manifests/registry.ollama.ai/library/phi4-bg/latest | jq

기대 출력 (구조 예시):

{
  "schemaVersion": 2,
  "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
  "config": {
    "mediaType": "application/vnd.docker.container.image.v1+json",
    "digest": "sha256:<config-hash>",
    "size": 2340
  },
  "layers": [
    {
      "mediaType": "application/vnd.ollama.image.model",
      "digest": "sha256:<model-weights-hash>",    base 모델 가중치 공유
      "size": 8400000000
    },
    {
      "mediaType": "application/vnd.ollama.image.params",   Modelfile의 PARAMETER 부분
      "digest": "sha256:<params-hash>",
      "size": 156
    },
    {
      "mediaType": "application/vnd.ollama.image.system",   SYSTEM 프롬프트
      "digest": "sha256:<system-hash>",
      "size": 432
    }
  ]
}

핵심: params blob이 PARAMETER num_ctx 32768, temperature 0.2 등 Modelfile의 모든 설정값을 담고 있고, system blob이 SYSTEM """...""" 내용. ollama show는 이 blob들을 디코딩해서 사람이 읽는 Modelfile 형태로 재조립.

17.3 현재 설정 확인 — 4가지 방법

방법 1: ollama show --modelfile (전체 재조립)

ollama show phi4-bg --modelfile

기대 출력:

# Modelfile generated by "ollama show"
# To build a new Modelfile based on this, replace FROM with
# FROM hf.co/microsoft/phi-4-gguf:Q4_K_S

FROM hf.co/microsoft/phi-4-gguf:Q4_K_S
PARAMETER num_ctx 32768
PARAMETER num_keep 256
PARAMETER num_predict 8192
PARAMETER temperature 0.2
PARAMETER top_p 0.9
PARAMETER min_p 0.05
PARAMETER top_k 40
PARAMETER repeat_penalty 1.1
PARAMETER repeat_last_n 64
PARAMETER seed 42
SYSTEM """..."""

방법 2: ollama show --parameters (PARAMETER만)

ollama show phi4-bg --parameters

기대 출력:

num_ctx 32768
num_keep 256
num_predict 8192
temperature 0.2
top_p 0.9
min_p 0.05
top_k 40
repeat_penalty 1.1
repeat_last_n 64
seed 42

방법 3: ollama show --system (SYSTEM 프롬프트만)

ollama show phi4-bg --system

기대 출력:

You are phi-4 running in background mode on a workstation.
The user may be doing other work (IDE, browser) in parallel.
Be concise. Prefer direct answers over verbose explanations.
For code: minimal changes, preserve existing style.

방법 4: ollama show --template (chat template)

ollama show phi4-bg --template
# 기대: Qwen3.5의 chat template (ChatML 형식)
# <|im_start|>system\n<|im_end|>...

17.4 실습: phi4-bg 변경하기 (전체 워크플로우)

phi4-bg의 num_ctx를 32k → 16k로 줄이고, system prompt에 한 줄 추가하는 예시.

17.4.1 현재 설정 백업

# Modelfile을 파일로 저장
mkdir -p ~/ollama-modelfiles/phi4
cd ~/ollama-modelfiles/phi4

ollama show phi4-bg --modelfile > phi4-bg.Modelfile
# 또는 모든 메타데이터를 한 번에
ollama show phi4-bg --modelfile > phi4-bg.Modelfile
ollama show phi4-bg --template  > phi4-bg.template
ollama show phi4-bg --system     > phi4-bg.system
ollama show phi4-bg --parameters > phi4-bg.parameters

ls -la
# 기대: phi4-bg.Modelfile, phi4-bg.template, phi4-bg.system, phi4-bg.parameters

왜 백업?ollama rm은 되돌릴 수 없으므로, 변경 전 현재 상태를 파일로 보존.

17.4.2 Modelfile 열기 + 수정

$EDITOR phi4-bg.Modelfile

변경 사항 (예시):

# 변경 1: num_ctx 줄이기
PARAMETER num_ctx 32768     →     PARAMETER num_ctx 16384

# 변경 2: num_predict 조정
PARAMETER num_predict 8192  →     PARAMETER num_predict 4096

# 변경 3: SYSTEM 프롬프트에 한 줄 추가
SYSTEM """
You are phi-4 running in background mode on a workstation.
The user may be doing other work (IDE, browser) in parallel.
Be concise. Prefer direct answers over verbose explanations.
For code: minimal changes, preserve existing style.
# 추가할 내용:
When reviewing code, also suggest test cases.
"""

저장 (nano: Ctrl+OEnterCtrl+X, vim: Esc:wqEnter).

17.4.3 검증 (선택이지만 권장)

# diff로 변경 사항 확인
diff <(ollama show phi4-bg --modelfile) phi4-bg.Modelfile
# 기대: 위에 적은 변경 3건만 표시

# 지원 안 되는 PARAMETER 없는지 자동 검증
grep -E "^PARAMETER (kv_cache_type|num_gpu|num_thread|use_mlock|flash_attention|num_batch) " \
  phi4-bg.Modelfile && echo "⚠ 지원 안 되는 PARAMETER 있음" \
                    || echo "✓ 모든 PARAMETER가 Modelfile 호환"

17.4.4 기존 태그 삭제 + 새 태그 생성

# 기존 custom 태그 삭제
ollama rm phi4-bg
# 기대: deleted 'phi4-bg'

# 새 태그 생성 (같은 이름, 새 설정)
ollama create phi4-bg -f phi4-bg.Modelfile
# 기대: success: created model 'phi4-bg'

# 검증
ollama show phi4-bg --parameters
# 기대: num_ctx 16384, num_predict 4096

ollama show phi4-bg --system | head -5
# 기대: 변경된 system prompt

17.4.5 디스크 사용량 확인

# 새 태그 크기 확인
ollama list | grep phi4-bg
# 기대: phi4-bg:latest  8.4 GB  ...

# Ollama 전체 디스크 사용량
du -sh ~/.ollama
# 백업 디렉토리 크기 (별도)
du -sh ~/ollama-modelfiles

17.5 삭제 패턴

17.5.1 단일 태그 삭제

ollama rm phi4-bg
# 기대: deleted 'phi4-bg'

ollama list | grep phi4
# 기대: 아무것도 안 나옴 (base 모델 hf.co/microsoft/phi-4-gguf:Q4_K_S는 그대로 남음)

중요: custom 태그를 삭제해도 base 모델은 영향 없음. hf.co/microsoft/phi-4-gguf:Q4_K_S는 별도 태그로 그대로 존재.

17.5.2 여러 태그 일괄 삭제

# 같은 base 모델의 모든 custom 변형 삭제
for tag in phi4-bg phi4-perf; do
  ollama rm "$tag" 2>/dev/null && echo "  - $tag 삭제"
done

# 모든 -bg, -perf 태그 일괄 삭제 (주의!)
ollama list | awk 'NR>1 {print $1}' | grep -E "-(bg|perf)$" | while read tag; do
  ollama rm "$tag" 2>/dev/null && echo "  - $tag 삭제"
done

17.5.3 base 모델까지 완전 삭제

# ⚠ base 모델까지 삭제하면 Modelfile 빌드 불가
ollama rm hf.co/microsoft/phi-4-gguf:Q4_K_S
# 디스크 확보

17.6 추가 패턴

17.6.1 같은 base 모델에 새 변형 추가

cd ~/ollama-modelfiles/phi4

# 기존 Modelfile을 복사해서 새 변형 만들기
cp phi4-bg.Modelfile phi4-fast.Modelfile

$EDITOR phi4-fast.Modelfile
# PARAMETER temperature 0.0 (완전 결정적) 으로 변경
# SYSTEM 프롬프트에 "deterministic mode" 명시

빌드:

ollama create phi4-fast -f phi4-fast.Modelfile
ollama list | grep phi4
# 기대: hf.co/microsoft/phi-4-gguf:Q4_K_S, phi4-bg, phi4-perf, phi4-fast

17.6.2 다른 base 모델의 변형 추가

# 새 base 모델 pull
ollama pull qwen3.5:9b

# 새 작업 디렉토리
mkdir -p ~/ollama-modelfiles/qwen3.5-9b
cd ~/ollama-modelfiles/qwen3.5-9b

# 새 Modelfile 작성 (단계 3~4 참고)
touch qwen3.5-9b-bg.Modelfile
$EDITOR qwen3.5-9b-bg.Modelfile

# 빌드
ollama create qwen3.5-9b-bg -f qwen3.5-9b-bg.Modelfile

17.6.3 다른 머신/서버로 이전

# 1) 원본 머신에서 Modelfile 백업
cd ~/ollama-modelfiles
tar czf phi4-modelfiles.tar.gz phi4/
scp phi4-modelfiles.tar.gz user@other-server:~/

# 2) 대상 머신에서 base 모델 pull
ssh user@other-server
ollama pull hf.co/microsoft/phi-4-gguf:Q4_K_S

# 3) Modelfile 풀고 빌드
tar xzf phi4-modelfiles.tar.gz
cd phi4
ollama create phi4-bg -f phi4-bg.Modelfile

17.7 백업/복원 패턴

17.7.1 Modelfile 디렉토리 Git 버전 관리

cd ~/ollama-modelfiles

# Git 초기화 (최초 1회)
git init
git add .
git commit -m "Initial Modelfile: qwen3.5-9b-bg/perf, phi4-bg/perf, mistral-nemo-bg/perf"

# 이후 변경 시
git add phi4/phi4-bg.Modelfile
git commit -m "phi4-bg: num_ctx 32k→16k, system prompt에 test case 제안 추가"

# 히스토리 확인
git log --oneline
git diff HEAD~1 phi4/phi4-bg.Modelfile

17.7.2 Ollama 전체 디렉토리 백업 (모든 모델)

# ⚠ 수 GB ~ 수십 GB. 디스크 여유 확인
df -h /

# 서비스 중지 후 백업 (데이터 일관성)
sudo systemctl stop ollama
sudo tar czf ollama-backup-$(date +%Y%m%d).tar.gz -C / ~/.ollama
sudo systemctl start ollama

# 복원
sudo systemctl stop ollama
sudo rm -rf ~/.ollama
sudo tar xzf ollama-backup-20260810.tar.gz -C /
sudo systemctl start ollama

17.7.3 단일 태그만 추출 (가볍게 공유)

# Modelfile 텍스트만 추출해서 공유
ollama show phi4-bg --modelfile > phi4-bg.Modelfile

# 다른 사람이 받으면:
# 1) 같은 base 모델 pull
ollama pull hf.co/microsoft/phi-4-gguf:Q4_K_S
# 2) Modelfile로 빌드
ollama create phi4-bg -f phi4-bg.Modelfile

17.8 디스크 점유 관리

# 전체 Ollama 사용량
du -sh ~/.ollama
# 기대: 수십 GB (모델 수에 따라)

# 모델별 점유
ollama list
# SIZE 컬럼 확인

# base 모델이 안 쓰는 태그 정리
ollama list | awk 'NR>1 && $3 ~ /GB/ {print $1, $3}' | sort -k2

# 특정 모델의 모든 변형 일괄 정리 (예: phi4 관련)
ollama list | awk 'NR>1 {print $1}' | grep "^phi4" | xargs -I {} ollama rm {}

# 사용하지 않는 base 모델 정리
ollama list | awk 'NR>1 {print $1}' | grep -v -- "-bg\|-perf\|-fast\|-trans\|-ja" | while read tag; do
  echo "  후보: $tag"
  # 수동 확인 후:
  # ollama rm "$tag"
done

17.9 빠른 참조: phi4-bg의 위치와 관리 명령

하고 싶은 것 명령
현재 설정 보기 ollama show phi4-bg --modelfile
PARAMETER만 보기 ollama show phi4-bg --parameters
SYSTEM 프롬프트만 보기 ollama show phi4-bg --system
Modelfile로 추출 ollama show phi4-bg --modelfile > phi4-bg.Modelfile
수정 Modelfile 편집 → ollama rm phi4-bgollama create phi4-bg -f ...
삭제 ollama rm phi4-bg
백업 ollama show phi4-bg --modelfile > backup.Modelfile
다른 서버로 이전 Modelfile 파일 + ollama pull base + ollama create ...
디스크 확인 ollama list \| grep phi4-bg, du -sh ~/.ollama
manifest 직접 보기 cat ~/.ollama/models/manifests/.../phi4-bg/latest \| jq

17.10 핵심 정리

  1. Modelfile은 어디 있나? → Ollama 모델 manifest 안에 임베드 (params + system blob)
  2. ~/ollama-modelfiles는 뭐하는 곳? → 작성·수정용 작업 디렉토리 (Ollama와 무관)
  3. 수정하려면?ollama show --modelfile로 추출 → 편집 → rm + create
  4. 삭제하려면?ollama rm <tag> (base 모델은 영향 없음)
  5. 백업하려면? → Modelfile을 파일로 저장 (git push 추천)
  6. 다른 머신에? → Modelfile + ollama pull base + ollama create

phi4-bg를 예시로 전체 라이프사이클:

작업 디렉토리에 Modelfile 작성
        ↓
ollama create phi4-bg -f Modelfile     ← 이 시점에 Modelfile이 Ollama에 임베드됨
        ↓
ollama show phi4-bg --modelfile        ← 필요할 때 추출
        ↓
수정 → ollama rm phi4-bg → ollama create phi4-bg -f ...
        ↓
ollama rm phi4-bg                      ← 더 이상 안 쓰면 삭제

마무리

이 문서대로 진행하면:

  1. 모든 단계를 개발자가 직접 작성·실행·검증할 수 있습니다 (자동화 스크립트 의존 X)
  2. Ollama 공식 메커니즘 (Modelfile + custom tag + env)만 사용하므로 모든 클라이언트에서 동일하게 작동
  3. 새 모델이 추가될 때마다 같은 패턴으로 변형을 만들 수 있습니다
  4. 오류 발생 시 트러블슈팅 섹션에서 직접 진단·수정 가능

문서 자체를 자유롭게 복사·수정해서 본인 워크플로우에 맞게 확장하세요. 새 모델이 pull되면 같은 절차로 <모델명>-bg, <모델명>-perf 태그를 만들면 됩니다.