#!/usr/bin/env python3
"""v15 reward sanity test.
Runs 6 hand-crafted (paper_context, generated_result, GT focuses) cases through
the v15 reward pipeline (build_reward_response). For each focus, prints the
judge's primary_match + score + critique alongside the expected score, and
gives a PASS/FAIL verdict.
Usage:
# Activate env + ensure secrets are loaded (JUDGE_API_KEY / JUDGE_API_BASE)
cd $CODE_ROOT/reward_part/azure_task1_judge
source $WORK_ROOT/secrets/judge_api.env
python $CODE_ROOT/scripts/v15_sanity_test.py
Cost: ~12 judge calls total, expect ~$0.005-0.01 on deepseek-v4-flash.
"""
import asyncio
import json
import os
import sys
from pathlib import Path
# Reward server module lives at reward_part/azure_task1_judge/.
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "reward_part" / "azure_task1_judge"))
sys.path.insert(0, str(ROOT / "reward_part"))
from task1_azure_reward import build_reward_response # noqa: E402
def make_candidates_xml(items):
"""items: list of (focus, description) tuples."""
blocks = []
for i, (focus, desc) in enumerate(items, start=1):
blocks.append(
f"\n"
f" {i}\n"
f" {focus}\n"
f" {desc}\n"
f""
)
return "\n".join(blocks)
def make_solution_str(result_text):
"""Wrap a body in the simulated assistant response."""
return (
"<|im_start|>assistant\n\nReasoning placeholder.\n\n\n"
f"\n{result_text.strip()}\n<|im_end|>"
)
# ----------------------------------------------------------------------
# Test cases
# ----------------------------------------------------------------------
CASES = [
# ------------------------------------------------------------------
{
"name": "1. CLEAN — all atomic, expect mostly 1.0",
"paper_context": (
"We propose a VAE-based prosody model with utterance-specific priors and a "
"decoder using cross-attention fusion. We compare LoRA and full fine-tuning. "
"Beam search width affects translation BLEU. Cross-attention fusion is the key module."
),
"candidates": [
("Effect of beam search width on translation",
"Vary beam width 1/3/5/10 and measure BLEU."),
("Necessity of cross-attention fusion module",
"Remove fusion module, evaluate downstream quality."),
("LoRA vs Fully Fine-tuning the LLM",
"Compare LoRA adapter to full FT of base LLM."),
],
"result": """
- Target Module: Beam search width
- Research Question: Does varying beam width 1/3/5/10 affect BLEU on WMT14?
- Target Module: Cross-attention fusion module
- Research Question: Does removing the cross-attention fusion module degrade output quality?
- Target Module: LoRA fine-tuning
- Research Question: Does LoRA outperform fully fine-tuning the LLM on downstream tasks?
""",
"expected": [
("Beam width", "should be 1.0", lambda s, pm: s == 1.0),
("Cross-attention fusion", "should be 1.0", lambda s, pm: s == 1.0),
("LoRA vs FT (comparison atomization)", "should be 1.0 — atomization OK", lambda s, pm: s == 1.0),
],
},
# ------------------------------------------------------------------
{
"name": "2. UMBRELLA + RQ ENUM (v11 HMR-style hack)",
"paper_context": (
"Human Mesh Recovery (HMR) network. Backbone choice (ResNet vs ViT), data composition "
"(SMPL fittings vs EFT), data augmentation strategies all matter."
),
"candidates": [
("Comparison of Backbone Architecture Choices for HMR",
"Compare ResNet50, ResNet101, ViT-B for HMR accuracy."),
("Influence of Data Augmentation Strategies on Model Performance",
"Vary augmentation pipelines."),
],
"result": """
- Target Module: Backbone Architecture and Network Design
- Research Question: How do variations in the depth, width, and type of convolutional or transformer-based backbone networks affect the model's ability to generalize?
- Target Module: Training Protocol and Optimization Strategy
- Research Question: What is the optimal combination of learning rate schedules, loss function weighting, data augmentation, and regularization techniques?
""",
"expected": [
("Backbone choices", "should be 0 — TM is umbrella, RQ overlap CANNOT rescue", lambda s, pm: s == 0.0),
("Data augmentation", "should be 0 — umbrella TM, even though RQ mentions data augmentation", lambda s, pm: s == 0.0),
],
},
# ------------------------------------------------------------------
{
"name": "3. JUDGE REUSE — bipartite enforce should kick in",
"paper_context": (
"Adversarial training with regularization. Both adversarial training mechanism and regularization "
"strategies are independent components."
),
"candidates": [
("Adversarial training mechanism", "Does removing adversarial step hurt accuracy?"),
("Regularization strategy effects", "Does regularization weighting matter?"),
("Adversarial training effects on generalization", "Does adv training help OOD?"),
],
"result": """
- Target Module: Adversarial Training Mechanism
- Research Question: How does adversarial perturbation magnitude affect robustness?
- Target Module: Regularization Strategy
- Research Question: What is the role of regularization weight in the final loss?
""",
"expected": [
("focus 1 = adversarial mechanism", "should be 1.0 with bullet 1", lambda s, pm: s == 1.0 and pm == 1),
("focus 2 = regularization", "should be 1.0 with bullet 2", lambda s, pm: s == 1.0 and pm == 2),
("focus 3 = adv training effects",
"should be 0 (bullet 1 already consumed by focus 1) OR reuse-zeroed by server",
lambda s, pm: s == 0.0),
],
},
# ------------------------------------------------------------------
{
"name": "4. COMPARISON ATOMIZATION — one side of X vs Y is OK",
"paper_context": (
"Zipformer ASR architecture introduces BiasNorm normalization layer as a replacement for LayerNorm. "
"The paper ablates BiasNorm vs LayerNorm."
),
"candidates": [
("BiasNorm vs LayerNorm choice",
"Replace BiasNorm with LayerNorm and measure WER drop."),
],
"result": """
- Target Module: BiasNorm normalization layer
- Research Question: Does swapping BiasNorm with LayerNorm change WER on librispeech test-clean and test-other?
""",
"expected": [
("BiasNorm vs LayerNorm",
"should be 1.0 — TM names one side, RQ confirms comparison",
lambda s, pm: s == 1.0),
],
},
# ------------------------------------------------------------------
{
"name": "5. NEAR-1.0 0.5 — TM slightly broad, RQ rescues to 0.5",
"paper_context": (
"We use beam search decoding for translation. The beam width is a critical hyperparameter; "
"wider beams improve quality but cost more."
),
"candidates": [
("Effect of beam search width on translation",
"Vary beam width and measure BLEU."),
],
"result": """
- Target Module: Decoding parameter tuning
- Research Question: How does varying beam search width (1, 3, 5, 10) affect BLEU on WMT14?
""",
"expected": [
("Decoding parameter tuning + RQ-specific",
"should be 0.5 — TM broader than 'beam width', RQ saves",
lambda s, pm: s == 0.5),
],
},
# ------------------------------------------------------------------
{
"name": "6. COMPOSITE-PARTIAL — true joint X+Y, bullet covers X only",
"paper_context": (
"Shape Naturalness Module (SNM) uses two loss terms together: an adversarial GAN loss L_adv and "
"a confidence-weighted unsupervised reconstruction loss. The paper ablates them jointly: removing "
"GAN loss alone, removing reconstruction loss alone, removing both."
),
"candidates": [
("Contribution of L_adv and L_unsup joint loss design",
"Remove L_adv only / L_unsup only / both and measure quality."),
],
"result": """
- Target Module: Adversarial GAN loss L_adv
- Research Question: Does removing the GAN loss L_d degrade reconstruction quality?
""",
"expected": [
("L_adv only covers half of joint design",
"should be 0.5 — covers L_adv side only of the joint ablation",
lambda s, pm: s == 0.5),
],
},
]
# ----------------------------------------------------------------------
async def run_case(case):
candidates_xml = make_candidates_xml(case["candidates"])
solution = make_solution_str(case["result"])
request = {
"response_str": solution,
"extra_info": {
"paper_context": case["paper_context"],
"candidates": candidates_xml,
},
}
result = await build_reward_response(request)
return result
def fmt_score(s):
if s is None:
return " ? "
return f"{s:>4.2f}"
async def main():
print("=" * 78)
print("v15 SANITY TEST — 6 cases against the deepseek judge + reward server logic")
print("=" * 78)
if not os.environ.get("JUDGE_API_KEY"):
print("ERROR: JUDGE_API_KEY not set. Source the secrets file first:")
print(' source $WORK_ROOT/secrets/judge_api.env')
sys.exit(2)
total_pass = 0
total_check = 0
summaries = []
for case in CASES:
print()
print("-" * 78)
print(case["name"])
print("-" * 78)
try:
result = await run_case(case)
except Exception as e:
print(f" EXCEPTION: {e!r}")
summaries.append((case["name"], 0, len(case["expected"])))
total_check += len(case["expected"])
continue
eval_items = result.get("eval_items", [])
cs = result.get("candidate_score", 0.0)
fmt_factor = result.get("format_factor", 0.0)
n_reuse_z = result.get("n_reuse_zeroed", 0)
n_pairs = result.get("n_pairs", 0)
total = result.get("score", 0.0)
print(f"server: candidate_score={cs:.3f}, format_factor={fmt_factor}, "
f"n_pairs={n_pairs}, n_reuse_zeroed={n_reuse_z}, total={total:.3f}")
print()
case_pass = 0
for ev, exp in zip(eval_items, case["expected"]):
label, hint, check = exp
pm = ev.get("primary_match")
sc = ev.get("score")
crit = (ev.get("critique") or "")[:200].replace("\n", " ")
ok = check(sc, pm)
if ok:
case_pass += 1
verdict = "PASS" if ok else "FAIL"
print(f" [{verdict}] {label}")
print(f" expect: {hint}")
print(f" got: score={fmt_score(sc)} pm={pm}")
print(f" critique: {crit}...")
total_pass += case_pass
total_check += len(case["expected"])
summaries.append((case["name"], case_pass, len(case["expected"])))
print()
print("=" * 78)
print("SUMMARY")
print("=" * 78)
for name, p, t in summaries:
flag = "OK " if p == t else "** "
print(f" {flag}{name}: {p}/{t}")
print()
print(f"OVERALL: {total_pass}/{total_check} expectations met")
if total_pass < total_check:
print()
print("If many FAILs, the judge is not following v15 prompt as designed.")
print("Inspect the 'critique' text to see how the judge interpreted each case.")
if __name__ == "__main__":
asyncio.run(main())