Генерация синтетических данных для дообучения LLM
Синтетическая генерация — создание обучающих примеров с помощью более сильной LLM (teacher model). Подход "Self-Instruct" и его развитие WizardLM/Evol-Instruct позволяет из небольшого seed датасета (100-200 примеров) сгенерировать тысячи качественных обучающих примеров.
Self-Instruct методология
from anthropic import Anthropic
import json
client = Anthropic()
SEED_EXAMPLES = [
{"instruction": "Объясни термин из ML", "output": "..."},
{"instruction": "Напиши SQL запрос для...", "output": "..."},
# 20-200 seed примеров
]
def generate_new_instructions(seed_examples: list, n: int = 20) -> list[str]:
"""Генерация новых инструкций на основе seed примеров"""
examples_str = "\n".join([f"- {ex['instruction']}" for ex in seed_examples[:10]])
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=2000,
messages=[{
"role": "user",
"content": f"""Here are some example instructions for an AI assistant:
{examples_str}
Generate {n} NEW diverse instructions in the same domain.
Requirements:
- Each instruction should be unique and not repeat the examples
- Vary complexity: some simple, some multi-step
- Include different formats: questions, commands, completions
- Return as JSON array of strings"""
}]
)
return json.loads(response.content[0].text)
def generate_response(instruction: str, context: str = None) -> str:
"""Генерация идеального ответа для инструкции"""
prompt = f"Instruction: {instruction}"
if context:
prompt = f"Context: {context}\n\n{prompt}"
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
system="You are an expert assistant. Provide accurate, helpful, and complete responses.",
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text
Evol-Instruct: усложнение инструкций
EVOLUTION_METHODS = [
"Add constraints: add a specific constraint or requirement to the instruction",
"Deepening: ask for more depth or detail in the response",
"Concretizing: replace general concepts with specific examples",
"Increased reasoning steps: require multi-step reasoning",
"Complicate input: add more complex or ambiguous input",
]
def evolve_instruction(original: str) -> str:
"""Усложнение инструкции одним из методов"""
method = random.choice(EVOLUTION_METHODS)
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
messages=[{
"role": "user",
"content": f"""Rewrite this instruction using this method: {method}
Original instruction: {original}
Return only the rewritten instruction, nothing else."""
}]
)
return response.content[0].text.strip()
Генерация domain-specific данных
def generate_domain_dataset(domain: str, n_examples: int,
output_path: str):
"""Генерация датасета для конкретного домена"""
examples = []
for i in range(n_examples):
# Шаг 1: Генерация разнообразной инструкции
instruction = generate_instruction_for_domain(domain)
# Шаг 2: Генерация ответа
response = generate_response(instruction)
# Шаг 3: Качественный фильтр (LLM-judge)
quality_score = judge_quality(instruction, response)
if quality_score >= 0.7:
examples.append({
"instruction": instruction,
"output": response,
"quality_score": quality_score,
"generated_by": "claude-3-5-sonnet-20241022"
})
if (i + 1) % 100 == 0:
print(f"Generated {i+1}/{n_examples}, kept {len(examples)}")
with open(output_path, 'w') as f:
for ex in examples:
f.write(json.dumps(ex, ensure_ascii=False) + '\n')
Оценка синтетических данных перед обучением
Синтетические данные требуют дополнительной валидации:
- Hallucination check: ответы модели-учителя могут содержать фактические ошибки. Нужна domain-expert проверка выборки.
- Style bias: GPT-4 имеет характерный стиль — модель может выучить "GPT-style" вместо целевого стиля.
- Diversity check: нет ли тематических кластеров, которые перепредставлены.
Для 5000+ синтетических примеров рекомендуется человеческая проверка 5-10% выборки с расчётом approval rate. Если approval rate < 80%, нужно улучшить промпты генерации.







