Human-in-the-Loop (HITL) Architecture, Active Learning Data Flywheels, Annotation QA & LLM Evals
- ✓ Human-in-the-Loop (HITL) operates on two loops in modern LLM systems: (1) the Synchronous Runtime Safety Loop (pausing high-risk tool/API executions for human approve/edit/reject sign-off) and (2) the Asynchronous Alignment Flywheel (converting human edits and escalations into DPO/SFT training pairs).
- ✓ When a human reviewer edits an LLM draft before sending (y_draft → y_edited), your system automatically captures a gold-standard DPO preference pair: Chosen y_w = y_edited and Rejected y_l = y_draft for prompt x!
- ✓ Never send 100% of production logs to human annotators: use Active Learning Uncertainty Routing (high token predictive entropy H(Y|X), low retrieval cosine score, or self-consistency disagreement across k=3 samples) to surface the 2% highest-information failures.
- ✓ Enforce human annotation quality with Cohen’s Kappa (κ ≥ 0.75 substantial agreement) and eliminate LLM-as-a-Judge position bias by evaluating every pair in both orders: Judge(A, B) and Judge(B, A).
01. The Dual-Loop Human-in-the-Loop (HITL) Architecture
In enterprise LLM and agent deployments, Human-in-the-Loop is not an ad-hoc manual review—it is a deterministic state machine that bridges runtime risk governance with continuous DPO alignment:
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ LOOP 1: SYNCHRONOUS RUNTIME HITL GATEWAY (Sub-Second to Minute SLA) │
│ │
│ LLM Proposes Action y_draft ──▶ Risk Classifier & Uncertainty Router │
│ ├── Tier 0 (Read-Only & High Confidence H < 0.25) ──▶ Auto-Execute Immediately │
│ └── Tier 2 (Mutating SQL/Refund/Email or High Entropy H >= 0.60) │
│ └──▶ Checkpoint State & Interrupt ──▶ Human Operator UI: │
│ • [Approve] ──▶ Resume execution + log (x, y_draft, label=+1) for KTO │
│ • [Edit -> y_human] ──▶ Execute y_human + log (x, y_w=y_human, y_l=y_draft) │
│ • [Reject] ──▶ Abort action + log (x, y_draft, label=-1) │
└──────────────────────────────────────────┬─────────────────────────────────────────────┘
▼
┌────────────────────────────────────────────────────────────────────────────────────────┐
│ LOOP 2: ASYNCHRONOUS ACTIVE LEARNING & DPO FLYWHEEL (Weekly LoRA / DPO Cadence) │
│ 1. Deduplicate & Filter Annotator Edits (Cohen’s Kappa κ >= 0.75 + Honey-Pot Gate) │
│ 2. Fine-Tune LoRA Adapter via DPO on (x, y_w=y_human, y_l=y_draft) │
│ 3. Run Position-Debiased LLM-as-a-Judge Regression Suite ──▶ Canary Rollout │
└────────────────────────────────────────────────────────────────────────────────────────┘
02. HITL Routing Signals, Annotation QA Metrics & Evaluation Guards
| Subsystem | Metric / Formula | Production Threshold & Action |
|---|---|---|
| Token Predictive Entropy | Ht = -∑v∈V p(v) log₂ p(v) | Route responses with mean token entropy H̄ > 0.65 bits to the Active Learning annotation queue. |
| Cohen’s Kappa (κ) | κ = (Po - Pe) / (1 - Pe) | Require κ ≥ 0.75 between raters before training DPO/RM on preference batches. |
| Position-Swapped Judge | W(A,B) ∧ W(B,A) consistency | Evaluate both (A, B) and (B, A); discard or mark tie if judge flips preference when order swaps. |
💻 Hands-On WebAssembly LLM Engineering Labs (Module 8)
Click Run & Edit Live (Wasm) on any lab below to execute and modify the algorithm in our browser Pyodide runtime.
Lab 8.1: Production HITL Risk-Gated Interrupt Gateway & Automatic DPO Pair Collector
Run a complete stateful HITL gateway that auto-executes low-risk calls, pauses high-risk/high-entropy calls for human edits, and compiles human corrections into DPO training triples.
import math
class HITLAlignmentGateway:
HIGH_RISK_TOOLS = {"issue_wire_refund", "drop_database_partition", "send_customer_contract"}
def __init__(self, entropy_threshold: float = 0.60):
self.entropy_threshold = entropy_threshold
self.dpo_dataset: list[dict] = []
@staticmethod
def token_entropy(top_probs: list[float]) -> float:
return -sum(p * math.log2(max(p, 1e-12)) for p in top_probs)
def evaluate_proposal(self, prompt: str, tool: str, draft_args: dict, token_probs: list[float]) -> dict:
entropy = self.token_entropy(token_probs)
is_high_risk = tool in self.HIGH_RISK_TOOLS
is_uncertain = entropy >= self.entropy_threshold
if not is_high_risk and not is_uncertain:
return {"status": "AUTO_EXECUTED", "tool": tool, "entropy": round(entropy, 3), "args": draft_args}
reason = "HIGH_RISK_TOOL" if is_high_risk else f"HIGH_UNCERTAINTY (H={entropy:.2f})"
return {"status": "HITL_INTERRUPT_REQUIRED", "reason": reason, "tool": tool, "draft_args": draft_args}
def resolve_human_review(self, prompt: str, draft_args: dict, human_edited_args: dict) -> None:
if human_edited_args != draft_args:
# Human edited the model's proposal -> Instant on-policy DPO preference pair!
self.dpo_dataset.append({
"prompt": prompt,
"chosen_yw": human_edited_args,
"rejected_yl": draft_args,
})
gw = HITLAlignmentGateway(entropy_threshold=0.60)
# Case 1: Low-risk, high-confidence read query -> Auto-executes
res1 = gw.evaluate_proposal("Fetch order #104", "get_order", {"id": 104}, [0.96, 0.03, 0.01])
print("[1] Tier-0 Read Proposal:", res1)
# Case 2: High-risk refund tool -> Pauses for human review & captures DPO edit
prompt2 = "Refund customer $150 for partial shipment delay on order #104"
draft2 = {"order_id": 104, "amount_usd": 1500} # Model hallucinated extra zero!
res2 = gw.evaluate_proposal(prompt2, "issue_wire_refund", draft2, [0.55, 0.30, 0.15])
print("[2] Tier-2 High-Risk Proposal:", res2)
# Human operator fixes $1500 -> $150 in the approval UI
gw.resolve_human_review(prompt2, draft_args=draft2, human_edited_args={"order_id": 104, "amount_usd": 150})
print("[3] Auto-Captured On-Policy DPO Preference Triple from Human Edit:")
print(" ", gw.dpo_dataset[0])
Lab 8.2: Computing Cohen’s Kappa (κ) Inter-Annotator Agreement & Position-Debiased Pairwise Judge
Verify annotator agreement correcting for chance (Cohen’s Kappa) and run a position-swapped A/B evaluation harness.
def cohens_kappa(rater_a: list[int], rater_b: list[int]) -> tuple[float, float]:
n = len(rater_a)
p_obs = sum(1 for a, b in zip(rater_a, rater_b) if a == b) / n
a_pos = sum(rater_a) / n
b_pos = sum(rater_b) / n
# Expected agreement purely by chance: P(both=1) + P(both=0)
p_chance = (a_pos * b_pos) + ((1 - a_pos) * (1 - b_pos))
kappa = (p_obs - p_chance) / max(1.0 - p_chance, 1e-9)
return round(p_obs, 4), round(kappa, 4)
# 10 preference items rated by Annotator 1 and Annotator 2 (1 = Model A wins, 0 = Model B wins)
annotator_1 = [1, 1, 0, 1, 0, 0, 1, 1, 0, 1]
annotator_2 = [1, 1, 0, 1, 0, 1, 1, 1, 0, 1]
raw_acc, kappa = cohens_kappa(annotator_1, annotator_2)
print(f"[1] Inter-Annotator QA: Raw Agreement={raw_acc:.1%} | Chance-Corrected Cohen's Kappa κ={kappa} (PASS >= 0.75)")
# 2. Position-Debiased Pairwise Judge (Swapping Order A/B and B/A)
comparisons = [
("item_1", "A", "A"), # Model A won when placed first AND when placed second -> Consistent A win
("item_2", "A", "B"), # First-position winner in both orders -> Position Bias Tie!
("item_3", "B", "B"), # Consistent B win
]
print("\n[2] Position-Debiased Pairwise Judge Resolution:")
for item_id, win_ab, win_ba in comparisons:
verdict = win_ab if win_ab == win_ba else "TIE (Position-Biased Flip Detected)"
print(f" {item_id}: Order(A,B)->{win_ab} | Order(B,A)->{win_ba} ==> Final Verdict: {verdict}")
Frequently Asked Staff LLM Interview Questions (Module 8)
How does an inline human edit in a UI create a DPO preference training dataset automatically? ▸
In a traditional chat UI with thumbs-up/down, a thumbs-down only tells you y_draft was bad (usable for KTO, not DPO). In an HITL co-pilot or approval UI where the human operator edits the proposed tool call or response y_draft into y_human_approved before execution, you obtain an exact on-policy contrast pair (x, y_w = y_human_approved, y_l = y_draft) where y_l is the model’s exact failure mode and y_w is the minimal human correction!
What is Cohen’s Kappa (κ) and why is raw percentage agreement insufficient for RLHF annotation QA? ▸
If 90% of outputs in a safety audit are "Safe", two annotators who click "Safe" randomly 90% of the time will achieve 82% raw agreement purely by chance! Cohen’s Kappa corrects for chance agreement: κ = (P_observed - P_chance) / (1 - P_chance). Production RLHF pipelines require κ >= 0.70–0.80 on calibration batches before admitting an annotator’s labels.
What is Position Bias in LLM-as-a-Judge evaluations and how do you eliminate it? ▸
Frontier LLMs exhibit a systematic bias toward preferring whichever response is presented first ("Response A") in pairwise A/B prompts. To eliminate position bias, always run two swapped evaluations—Score(A, B) and Score(B, A)—and only award a win if the same response wins in both positions (otherwise record a tie).