Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Expand Fine-Tuning Data with MGA, Prompt Engineering & Multi-Turn Dialogue for LLaMA-Factory

This guide details practical methods to expand and refine fine-tuning datasets for LLMs, covering MGA genre-audience rewriting, five prompt-based augmentation techniques, answer formatting standards, multi-turn dialogue construction, and Alpaca-format dataset preparation for LLaMA-Factory training.

Boundaries Before Data Expansion

Before expanding a fine-tuning dataset, three boundaries must be respected:

Facts unchanged: Vulnerability IDs, version ranges, commands, and configuration items must remain identical after expansion. Rule-based validation is required, not just model self-consistency.

Questions must be realistic: Expanded questions should simulate real-world user scenarios, not merely synonym replacements.

Diversity must be measurable: Record the source and method for each expanded sample; compute question similarity distributions to avoid template-dominated datasets.

Keep the original-to-expanded ratio around 1:3 . Original data acts as an anchor; over-expansion causes overfitting. Evaluation sets must never participate in expansion , or test scores become invalid.

Fine-Tuning QA Pair Expansion Methods

2.1 MGA Method

MGA (Massive Genre-Audience) from the paper Reformulation for Pretraining Data Augmentation rewrites the same knowledge across different genres and audiences. For a Log4Shell trigger condition, one original QA pair can become:

Operation manual for frontline ops: steps then commands.

Postmortem for tech leads: impact, root cause, remediation.

Training material for newcomers: JNDI background then trigger chain.

Audit report for compliance: clause mapping, risk, evidence.

One sample can yield a dozen diverse variants. In practice, select ~3 per original to avoid bias. Implementation uses two steps: diverge (random genre-audience combos) then converge (rule + model validation). Core Python code:

import os, re, json, random
from itertools import product
from openai import OpenAI

client = OpenAI(api_key=os.getenv("DASHSCOPE_API_KEY", ""),
                base_url="https://dashscope.aliyuncs.com/compatible-mode/v1")

GENRES = ["操作手册", "故障复盘", "培训讲义", "审计报告", "工单回复", "技术博客", "FAQ"]
AUDIENCES = ["一线运维", "后端开发", "安全工程师", "合规审计", "技术管理者", "新人"]

MGA_PROMPT = """你是网络安全领域的技术写作者。请把下面这条问答对改写成「{genre}」体裁、面向「{audience}」的版本。
要求:
1. 事实不变:漏洞编号、版本号、命令、配置项一律不得改动
2. 问答都改:问题用该受众的口吻重写,答案按该体裁的组织习惯重排
3. 不新增原文没有的事实,举例只能用原文已有信息
4. 长度控制在原文的 0.8~1.5 倍
只输出 JSON:{"question": "...", "answer": "..."}

原问题:{q}
原答案:{a}"""

HARD = re.compile(r"CVE-\d{4}-\d{4,}|\d+\.\d+(?:\.\d+)?|`[^`]+`")

def hard_facts(text):
    return set(HARD.findall(text))

def mga_expand(rec, k=4):
    out = []
    for genre, audience in random.sample(list(product(GENRES, AUDIENCES)), k):
        prompt = MGA_PROMPT.format(genre=genre, audience=audience,
                                     q=rec["instruction"], a=rec["output"])
        resp = client.chat.completions.create(
            model="qwen-plus", temperature=0.8,
            response_format={"type": "json_object"},
            messages=[{"role": "user", "content": prompt}])
        d = json.loads(resp.choices[0].message.content)
        q, a = d.get("question", ""), d.get("answer", "")
        # Converge: hard facts must be preserved, question length limit
        if q and a and hard_facts(a) >= hard_facts(rec["output"]) and len(q) <= 80:
            out.append({"instruction": q, "output": a,
                        "meta": {**rec.get("meta", {}), "method": "mga",
                                   "genre": genre, "audience": audience}})
    return out

The HARD regex extracts CVE IDs, version numbers, and backtick-wrapped commands. In production, add entity recognition and log validation results for sampling review.

2.2 Five Prompt-Based Enhancement Techniques

These methods refine original QA pairs at a granular level:

Context enrichment: Attach real logs, configs, or errors to the question (e.g., add Nginx logs to "WAF false positive troubleshooting").

Bidirectional generation: Reverse-engineer 3–5 questions from a high-quality answer. Validate that the original answer actually addresses each generated question.

Semantic equivalence transformation: Produce colloquial, terminological, and concise variants. Control character-level Jaccard similarity between 0.5–0.9 to avoid semantic drift or near-duplicates.

Related knowledge extension: Generate prerequisite (what is JNDI), adjacent (Spring4Shell, Fastjson), comparative, and upstream/downstream (detection rules, rollback) QA pairs. Must be verified against a knowledge base to prevent hallucination.

Application scenario setting: Add role, environment, constraints (e.g., "only Nginx logs, no restart, compliance audit tomorrow"). Tighter constraints yield more discriminative answers.

All five share a similar code structure; only prompts differ. Example prompt dictionary and augmentation function:

AUG_PROMPTS = {
    "context": """为下面的问答补一段真实场景材料(日志、配置或报错)放进 input,
问题改成"结合以下材料……"的形式,答案事实保持不变。
只输出 JSON:{"instruction": "...", "input": "...", "output": "..."}

问题:{q}
答案:{a}""",
    "reverse": """根据下面的答案反推 3 个能导向该答案的问题,覆盖不同角度,
不得照抄原问题,且原答案要能回答每一个问题。
只输出 JSON:{"questions": ["...", "...", "..."]}

答案:{a}""",
    "paraphrase": """把问题改写成 3 种语义等价、措辞不同的问法:一种口语化、一种术语化、一种更短。
不得改变意图,不得添加原问题没有的条件。
只输出 JSON:{"questions": ["...", "...", "..."]}

问题:{q}""",
    "related": """围绕该知识点生成 3 条关联问答:一条前置知识、一条相邻或对比技术、一条上下游操作。
只依据确定的事实,不确定的内容不要生成。
只输出 JSON:{"pairs": [{"q": "...", "a": "..."}]}

知识点:{q}""",
    "scenario": """给问题加上角色、环境和约束,改写成 2 个更贴近真实工作的版本,
并在答案开头说明"这个约束为什么重要"。
只输出 JSON:{"pairs": [{"q": "...", "a": "..."}]}

问题:{q}
答案:{a}""",
}

def augment(rec, task):
    prompt = AUG_PROMPTS[task].format(q=rec["instruction"], a=rec["output"])
    resp = client.chat.completions.create(
        model="qwen-plus", temperature=0.8,
        response_format={"type": "json_object"},
        messages=[{"role": "user", "content": prompt}])
    data = json.loads(resp.choices[0].message.content)
    items = data.get("pairs") or [{"q": q, "a": rec["output"]}
                for q in data.get("questions", [])]
    return [{"instruction": i["q"].strip(), "output": i["a"].strip(),
             "meta": {**rec.get("meta", {}), "method": task}} for i in items]

Generated questions must pass a quality pipeline, especially reverse and related which often produce answer-mismatched pairs.

Fine-Tuning QA Pair Optimization Methods

3.1 Format Enhancement

Human-annotated answers often lack structure (no line breaks, no code blocks). This teaches models to output walls of text. Define a target format:

First sentence: conclusion ≤ 40 characters.

Middle: ordered list, 3–6 points.

Commands/configs in code blocks, preserving version numbers.

Final paragraph: applicability boundaries (when not to use, when human confirmation needed).

Reformatting must only change structure, not facts. Validate with hard-fact comparison and structural checks. Example validation function:

FENCE = "`" * 3

FORMAT_PROMPT = """请把下面的答案重排为标准格式,只改结构,不改事实,不新增信息:
1. 第一句给结论,不超过 40 字
2. 中间用有序列表分点,3~6 点
3. 命令、配置用代码块,保留原答案中的版本号
4. 最后一段写适用边界
只输出 JSON:{"answer": "..."}

问题:{q}
原答案:{a}"""

def format_ok(old, new):
    if hard_facts(old) - hard_facts(new):  # hard facts lost
        return False
    if not re.search(r"(?m)^\s*(?:\d+[.、]|[-*])\s+", new):  # no bullet points
        return False
    if old.count(FENCE) != new.count(FENCE):  # code blocks removed
        return False
    return 0.7 <= len(new) / max(1, len(old)) <= 1.8  # length sanity

Before/after example:

【Before】
Log4j2 的 JNDI 注入需要同时满足两个条件,版本在 2.0-beta9 到 2.14.1 之间,并且日志语句拼接了用户可控内容被 ${} 解析,
常见入口有请求头、请求参数和用户名,升级到 2.17.1 或关闭 JNDI 查找就不受影响。

【After】
结论:需同时满足版本与日志拼接两个条件。
1. 版本落在 2.0-beta9 至 2.14.1 区间;
2. 日志语句拼接了用户可控内容,并被 ${} 占位符解析;
3. 常见入口包括请求头、请求参数和用户名。
版本升级到 2.17.1 及以上,或关闭 JNDI 查找后,不再受该问题影响。

3.2 Multi-Turn Dialogue

Single-turn data cannot teach models to handle follow-ups (detail requests, examples, challenges). Multi-turn data should constitute ~ 20% of the dataset (e.g., 2,000 out of 10,000 samples). Convert single-turn to 2–4 turns: first turn uses original question, subsequent turns simulate natural follow-ups, final turn gives complete executable conclusion. Avoid empty pleasantries. Code template:

MULTI_PROMPT = """把下面这条单轮问答扩展成 {turns} 轮对话。
要求:
1. 第一轮是原问题,之后每轮都是用户基于上一轮回答的自然追问:问细节、要例子、改条件或质疑结论
2. 每轮回答都必须与事实一致,前后不能矛盾
3. 最后一轮给出完整、可执行的结论
4. 不要"好的""谢谢"这类无信息量的寒暄
只输出 JSON:{"history": [["问1", "答1"], ["问2", "答2"]], "question": "最后一问", "answer": "最后一答"}

问题:{q}
答案:{a}"""

def to_multi_turn(rec, turns=3):
    resp = client.chat.completions.create(
        model="qwen-plus", temperature=0.7,
        response_format={"type": "json_object"},
        messages=[{"role": "user", "content": MULTI_PROMPT.format(
            turns=turns, q=rec["instruction"], a=rec["output"])}])
    d = json.loads(resp.choices[0].message.content)
    hist, q, a = d.get("history", []), d.get("question", ""), d.get("answer", "")
    if len(hist) != turns - 1 or not q or not a:
        return None
    return {"instruction": q, "output": a, "history": hist,
            "meta": {**rec.get("meta", {}), "method": "multi_turn", "turns": turns}}

Common failure: contradictions across turns. Validate each turn sequentially; final conclusion must cover all prior information. Prefer real ticket dialogues over generated ones when available.

LLaMA-Factory Fine-Tuning Dataset Construction

After expansion and multi-turn conversion, structure data into Alpaca format (also supports multi-turn via history). Single-turn uses instruction / input / output; multi-turn stores previous turns in history (chronological [question, answer] pairs), with the last turn in instruction / output. Example three-turn record:

{
  "instruction": "如果业务不能重启,还有别的缓解方式吗?",
  "input": "",
  "output": "有不重启业务的临时缓解方式:先在下游限制访问来源,再通过配置重命名危险命令……",
  "history": [
    ["我有一台对外暴露的 Redis 6.2,怀疑存在未授权访问,怎么确认?", "先执行 INFO 查看……"],
    ["确认确实存在未授权访问,具体要改哪些配置?", "需要改三处:bind、requirepass 和 rename-command……"]
  ]
}
history

is prepended to instruction at load time, then output completes the sequence. Write custom scripts or use LLMs to convert the filtered dataset into this format.

Summary

Building on the previous article's data foundations, this piece addresses "insufficient quantity" and "unrealistic format" for teams with only a few hundred annotated samples. Quantity: MGA genre-audience rewriting expands one sample into a dozen, supplemented by five prompt augmentations (context, reverse, paraphrase, related, scenario). Format: restructuring enforces "conclusion + bullet points + boundaries" skeleton, plus 20% multi-turn dialogues for follow-up capability. Finally, unified validation and conversion to Alpaca format enables direct LLaMA-Factory training. The next article will demonstrate fine-tuning with the constructed dataset.

MGA genre-audience matrix
MGA genre-audience matrix
MGA expansion workflow
MGA expansion workflow
Five prompt enhancement methods
Five prompt enhancement methods
Overall dataset construction pipeline
Overall dataset construction pipeline
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

data augmentationprompt engineeringfine-tuningLLaMA-Factorymulti-turn dialogueAlpaca formatdataset expansionMGA

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion