0Pricing
AI Engineering Academy · 강의

프롬프트보다 미세 조정이 뛰어난 경우

프롬프트 엔지니어링보다 미세 조정이 효과적인 사용 사례를 파악합니다. 일관된 스타일 준수, 독점 도메인 지식 반영, 짧은 프롬프트를 통한 토큰 비용 절감, 지연 시간 개선을 살펴봅니다.

프롬프트보다 미세 조정이 뛰어난 경우은(는) CoddyKit의 무료 AI Engineering Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Engineering Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

The Core Trade-off

When you need an LLM to behave in a specific way, you have two fundamental options: prompt engineering (tell the model what to do at inference time using carefully crafted prompts) or fine-tuning (teach the model new behaviors by training it on examples). Both can achieve similar results for many tasks, but they differ dramatically in cost, speed, flexibility, and the quality ceiling they can reach.

When Prompting Is Better

Prompting is almost always the right starting point. It requires no training infrastructure, produces results within hours, can be updated instantly without retraining, and works well for tasks the base model already handles competently. Start with prompting for: tasks where GPT-4o or Claude already produces acceptable results with clear instructions, rapidly changing requirements, low-volume use cases, and situations where you are still exploring the problem space.

# Prompting is sufficient for most well-defined tasks
system_prompt = '''
You are a customer support agent for TechCorp. Your tone is friendly but professional.
Always:
1. Acknowledge the customer's issue in the first sentence
2. Provide step-by-step solutions with numbered lists
3. End with 'Is there anything else I can help you with?'
Never: reveal pricing, discuss competitors, or make promises about future features.
'''

# With clear instructions, GPT-4o handles this well - no fine-tuning needed
# Before investing in fine-tuning, prove prompting is insufficient

Consistent Style and Format Adherence

Fine-tuning wins when you need rigidly consistent output format that prompting cannot reliably deliver. If your application requires 100% compliance with a specific JSON schema, a precisely structured document format, or a highly specific writing style that differs from the model's natural output, a few-hundred-example fine-tune can achieve near-perfect consistency that even the most carefully engineered prompt cannot match.

# Problem: prompting gives 90% format compliance - 10% failures cause downstream errors
# Prompt approach (unreliable)
system = 'Always respond with JSON: {"category": "...", "priority": 1-5, "tags": [...]}'
# 1 in 10 responses adds explanation text, omits a field, or uses strings for priority

# Fine-tuned approach: train on 500 examples of perfect output
# Training example format:
train_example = {
    'messages': [
        {'role': 'system', 'content': 'Classify customer support tickets.'},
        {'role': 'user', 'content': 'My order is late and I need it for tomorrow.'},
        {'role': 'assistant', 'content': '{"category": "shipping", "priority": 4, "tags": ["late_delivery", "urgent"]}'}
    ]
}
# After fine-tuning: 99.5%+ format compliance with minimal system prompt

Proprietary Domain Knowledge

Fine-tuning is the right choice when the model needs to learn knowledge that does not exist in public training data: your company's internal coding conventions, a proprietary taxonomy for classifying documents, specialized legal or medical terminology in a niche domain, or the specific voice and style guidelines of your brand. This knowledge cannot be effectively conveyed through prompt examples because the volume of examples exceeds what fits in a context window.

# Example: Internal code style with dozens of company-specific conventions
# Too many rules to fit in a prompt effectively:

# Company conventions (partial list of 200+):
# - Use AppException instead of RuntimeError
# - Repositories are named FooRepository not FooRepo
# - Service methods use handle_verb_noun naming not do_action
# - Config values go through AppConfig.get(), never os.environ directly
# - ... 196 more conventions

# Prompting: you can include ~20 conventions before the model starts ignoring them
# Fine-tuning: train on 1000 examples of compliant vs. non-compliant code
# Result: model learns ALL conventions and applies them automatically

Token Cost Reduction Through Shorter Prompts

A major economic argument for fine-tuning is prompt compression. A complex system prompt might be 2000 tokens. If you call the API 10 million times per day, those 2000 tokens cost tens of thousands of dollars per month. A fine-tuned model can be guided by a much shorter prompt (50-100 tokens) because the detailed instructions are now baked into the weights. At scale, this can reduce input token costs by 90% or more.

COST_PER_1K_TOKENS_INPUT = 0.0050  # gpt-4o
DAILY_REQUESTS = 10_000_000

# Base model with detailed prompt
base_prompt_tokens = 2000
daily_input_tokens_base = DAILY_REQUESTS * base_prompt_tokens
daily_cost_base = (daily_input_tokens_base / 1000) * COST_PER_1K_TOKENS_INPUT

# Fine-tuned model with short prompt
fine_tuned_prompt_tokens = 50
daily_input_tokens_ft = DAILY_REQUESTS * fine_tuned_prompt_tokens
daily_cost_ft = (daily_input_tokens_ft / 1000) * COST_PER_1K_TOKENS_INPUT

print(f'Base model daily input cost: ${daily_cost_base:,.2f}')
print(f'Fine-tuned model daily input cost: ${daily_cost_ft:,.2f}')
print(f'Monthly savings: ${(daily_cost_base - daily_cost_ft) * 30:,.2f}')
# Base: $100,000/day. Fine-tuned: $2,500/day. Savings: ~$2.9M/month

Latency Improvement

Fine-tuned models can improve latency in two ways. First, shorter prompts mean the model processes fewer input tokens, directly reducing time to first token. Second, fine-tuned models often converge to the correct format faster (fewer tokens in the response before getting to the actual answer), reducing total output tokens and generation time. For latency-sensitive applications, both effects compound to meaningful improvements.

# Latency comparison (approximate)

# Base model with 2000-token prompt:
# - Input tokens processed: 2000 + 50 (user query) = 2050
# - Response: often starts with 'Sure! Here is...' (5-10 unnecessary tokens)
# - TTFT: ~800ms (more tokens to process)

# Fine-tuned model with 50-token prompt:
# - Input tokens processed: 50 + 50 (user query) = 100
# - Response: starts directly with the answer (no preamble)
# - TTFT: ~100ms (few tokens to process)

# For classification tasks (short outputs), this is a 5-8x latency improvement
# For generation tasks, improvement is less dramatic but still significant

print('Fine-tuning trades upfront training cost for per-request latency+cost savings')

The Minimum Data Requirement

Fine-tuning requires training data — and this is often the biggest practical barrier. As a rule of thumb: you need at least 50-100 high-quality examples to see any meaningful improvement over the base model, 500-1000 examples for reliable style/format adherence, and 1000-10,000 examples for significant domain knowledge acquisition. Below 50 examples, prompting with those same examples in-context (few-shot) will usually outperform fine-tuning.

def estimate_fine_tuning_feasibility(num_examples: int, task_type: str) -> str:
    if num_examples < 50:
        return 'Insufficient data. Use few-shot prompting with these examples instead.'
    
    if task_type == 'format_adherence' and num_examples >= 100:
        return 'Fine-tuning recommended. Format consistency issues are hard to solve with prompting.'
    
    if task_type == 'style_matching' and num_examples >= 300:
        return 'Fine-tuning recommended. Consistent style requires enough examples to learn the distribution.'
    
    if task_type == 'domain_knowledge' and num_examples >= 500:
        return 'Fine-tuning recommended if knowledge is truly proprietary.'
    
    return 'Continue with advanced prompting (chain-of-thought, structured output) and revisit fine-tuning when you have more data.'

The Hidden Costs of Fine-Tuning

Fine-tuning has significant hidden costs beyond the compute bill. You need: infrastructure to run training (GPU hours or a managed service), a dataset collection and quality control process, evaluation to verify the fine-tuned model actually improves on the target metric, a deployment pipeline for the custom model, and an ongoing maintenance process to retrain when the base model updates or your requirements change. These costs are real and must be weighed against the benefits.

fine_tuning_total_cost = {
    'data_collection_and_QA': '$5,000-$50,000',  # human annotation or LLM-generated
    'training_compute': '$50-$5,000',             # depends on model size and data volume
    'evaluation_pipeline': '$500-$2,000',         # building eval harness
    'deployment_infra': '$200-$2,000/month',      # serving the custom model
    'maintenance': '$1,000-$5,000/year',          # retraining when things change
    'opportunity_cost': 'weeks to months',        # time to build vs. prompt iteration
}

# Compare to prompting costs:
prompting_costs = {
    'data_needed': None,  # no training data required
    'infra': '$0 (uses existing API)',
    'maintenance': 'update prompts when needed',
    'time_to_production': 'hours to days'
}

Knowledge Freshness: RAG vs Fine-Tuning

Fine-tuning cannot update knowledge in real time. A fine-tuned model's knowledge is frozen at the time of training. For use cases requiring up-to-date information (current events, live pricing, changing regulations), RAG is always better because it can retrieve fresh information at query time. Fine-tuning excels at durable knowledge that rarely changes: your company's writing style, product categorization taxonomy, or a well-established domain's technical vocabulary.

# Decision guide: RAG vs Fine-tuning vs Prompting

def choose_approach(requirements: dict) -> str:
    if requirements.get('knowledge_changes_frequently'):  # pricing, news, live data
        return 'RAG - knowledge must be updatable at query time'
    
    if requirements.get('needs_consistent_format') and requirements.get('high_volume'):
        return 'Fine-tuning - format adherence + cost savings at scale'
    
    if requirements.get('proprietary_domain_vocabulary'):
        return 'Fine-tuning - model needs to learn new terminology'
    
    if requirements.get('low_volume') or requirements.get('still_exploring'):
        return 'Prompting - fastest iteration, lowest cost'
    
    if requirements.get('combination_needed'):  # most production systems
        return 'Fine-tuning for style/format + RAG for dynamic knowledge'

The Ideal Fine-Tuning Decision Framework

Use this decision framework before committing to fine-tuning. First, prove the need: run your best prompt through 1000 real examples and measure the failure rate. Second, quantify the benefit: estimate the ROI from improved accuracy, lower token costs, or better latency. Third, assess feasibility: do you have 500+ high-quality training examples? Finally, compare alternatives: could a smaller model with a better prompt match the performance of a larger model with a complex prompt?

Combining Prompting and Fine-Tuning

The best production systems often combine both approaches. Fine-tune for durable properties (output format, tone, domain vocabulary) that rarely change, and use prompts for dynamic properties (task context, retrieved documents, user preferences) that change per-request. This combination gets you the reliability and cost efficiency of fine-tuning without sacrificing the flexibility of prompting.

Quick Check

Test your understanding of when fine-tuning beats prompting from this lesson.

Lesson Recap

In this lesson you learned: prompting is almost always the right starting point due to lower cost and faster iteration, fine-tuning wins for consistent format adherence, proprietary domain knowledge, and high-volume token cost reduction, and knowledge freshness is RAG's domain — fine-tuning cannot update what a model knows at runtime. Next up we prepare a high-quality training dataset for fine-tuning.

자주 묻는 질문

“프롬프트보다 미세 조정이 뛰어난 경우” 강의는 무료인가요?

네 — “프롬프트보다 미세 조정이 뛰어난 경우” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Engineering Academy 강의 전체를 잠금 해제할 수 있습니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“프롬프트보다 미세 조정이 뛰어난 경우”에서 뭘 배우나요?

프롬프트 엔지니어링보다 미세 조정이 효과적인 사용 사례를 파악합니다. 일관된 스타일 준수, 독점 도메인 지식 반영, 짧은 프롬프트를 통한 토큰 비용 절감, 지연 시간 개선을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 AI Engineering Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Engineering Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Engineering Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“프롬프트보다 미세 조정이 뛰어난 경우” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Engineering Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Engineering Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 프롬프트보다 미세 조정이 뛰어난 경우
  2. 고품질 학습 데이터셋 준비
  3. Hugging Face PEFT로 LoRA 미세 조정
  4. 미세 조정 모델 평가 및 배포
← AI Engineering Academy(으)로 돌아가기