Datasets:
Download reward_function.py from sivakrishna123/SELF_IDENTITY_TUNING: direct link, hf CLI and curl.
- Browser
- Download file 70.7 kB
-
https://huggingface.co/datasets/sivakrishna123/SELF_IDENTITY_TUNING/resolve/main/reward_function.py
- Command line
-
hf download hf://datasets/sivakrishna123/SELF_IDENTITY_TUNING/reward_function.py
-
curl -L -o reward_function.py https://huggingface.co/datasets/sivakrishna123/SELF_IDENTITY_TUNING/resolve/main/reward_function.py
70.7 kB
| """ | |
| Tiered reward function for D:\\TESTING\\train_gspo_simple.jsonl (FREYAH GSPO/GRPO training). | |
| Reward scale: -1.0 (bad) ... +1.0 (good) | |
| penalty = min(sum(violation penalties), 2.0) | |
| reward = clamp(2 * correctness - 1 - penalty, -1, 1) | |
| severe violation -> reward <= -0.5 (always bad) | |
| major violation -> reward <= -0.2 (always bad) | |
| Tiers: | |
| good : reward >= 0.75 -> correct answer + no violations (identity/dataset | |
| related, hallucination free), correctness >= 0.875 | |
| average : 0.00 <= reward < 0.75 -> partially correct / mild irrelevance | |
| bad : reward < 0.00 -> wrong answer, hallucination, identity drift, | |
| creator/company confusion, irrelevant name drops | |
| Task-specific correctness caps (wrong-shape answers can never reach good): | |
| identity : non-identical answer capped at 0.75 | |
| json : GT parses but prediction does not -> capped at 0.4 | |
| coding : GT parses but prediction does not -> capped at 0.4; | |
| both parse but differ -> capped at 0.7 (AST compared, never executed) | |
| tooling : required call missing -> capped at 0.3 (extra call with no GT -> 0.4); | |
| calls are matched on name AND canonicalized arguments (flat and | |
| wrapped {"function": {...}} forms normalize to the same string) | |
| structured: markdown-table / CSV / flowchart GTs are compared cell-aware; | |
| anything not identical -> capped at 0.7 (identical cells -> 1.0) | |
| final : both sides have \\boxed{...} answers and they differ -> capped at 0.6 | |
| style : extra emoji when GT has none -> capped at 0.9; | |
| wrong/missing required emoji -> capped at 0.7 | |
| Violation severities: | |
| severe (1.5): creator confusion ("creator of Google is me"), identity drift | |
| ("I am ChatGPT / made by OpenAI"), SKANDREW-company confusion | |
| major (1.2): mentioning "Siva Krishna" / "SKANDREW" on unrelated tasks, | |
| fabricated citations/URLs/sources/experience | |
| mild (0.5): identity boilerplate leaked into non-identity tasks, | |
| degenerate repetition, tool name outside the tools_json | |
| catalog and never demonstrated in GT, required argument | |
| that GT demonstrates but the prediction omits | |
| Every detector is exempted when the same pattern already appears in the ground | |
| truth, or in a *neutral* (non-prohibitive) part of the prompt. A prompt that | |
| says "Do not say: I am ChatGPT." does NOT grant an exemption. | |
| Honest naming note: reward_type values come from the dataset schema | |
| (exact_match, identity_exact_match, coding_execution_or_exact_match, ...). | |
| All scorers are similarity-based: an exact match scores 1.0, near matches get | |
| partial credit (average tier), wrong answers go negative. Code is compared via | |
| normalized equality, AST equality, then fuzzy similarity - code is NOT executed. | |
| When CJK script is present (no whitespace word boundaries), an additional | |
| character-trigram similarity signal is mixed in as a fallback. | |
| Known limitations (pattern filters, not a truth validator): | |
| - regex rules are evadable by paraphrase; they catch common failure modes, | |
| they do not prove a statement is true or false | |
| - no adversarial robustness; complement with an LLM judge if needed | |
| - refusal quality and the truth of citations are not judged | |
| Usage: | |
| from reward_function import compute_reward | |
| reward = compute_reward(completion, ground_truth, reward_type=..., capability=...) | |
| reward, details = compute_reward(completion, ground_truth, ..., return_details=True) | |
| # dataset row helper | |
| from reward_function import score_row | |
| reward = score_row(row, completion) | |
| # verl custom reward fn | |
| from reward_function import compute_score | |
| score = compute_score(data_source, solution_str, ground_truth, extra_info) | |
| python reward_function.py --self-test | |
| python reward_function.py --dataset "D:\\TESTING\\train_gspo_simple.jsonl" --sample 400 | |
| """ | |
| import argparse | |
| import ast | |
| import difflib | |
| import json | |
| import random | |
| import re | |
| import sys | |
| import unicodedata | |
| from pathlib import Path | |
| # ============================================================ | |
| # CONFIG | |
| # ============================================================ | |
| REWARD_MIN = -1.0 | |
| REWARD_MAX = 1.0 | |
| GOOD_THRESHOLD = 0.75 | |
| BAD_THRESHOLD = 0.00 | |
| PENALTY_SEVERE = 1.5 | |
| PENALTY_MAJOR = 1.2 | |
| PENALTY_MILD = 0.5 | |
| MAX_TOTAL_PENALTY = 2.0 | |
| MAX_INPUT_CHARS = 100_000 | |
| GOOD = "good" | |
| AVERAGE = "average" | |
| BAD = "bad" | |
| REWARD_TYPES = { | |
| "identity_exact_match", | |
| "final_answer_exact_match", | |
| "coding_execution_or_exact_match", | |
| "tool_calling_or_exact_match", | |
| "normalized_json_or_exact_match", | |
| "exact_match", | |
| "style_contains", | |
| } | |
| ASSISTANT_NAME = "freyah" | |
| PROTECTED_NAMES = ["siva krishna", "skandrew"] | |
| EXTERNAL_ENTITY_PATTERNS = [ | |
| "google", "openai", "microsoft", "apple", "meta", "facebook", "amazon", | |
| "netflix", "linux", "android", "chrome", "windows", "chatgpt", | |
| r"gpt-?\s?(?:3\.5|4|4o|5)", "gemini", "claude", "anthropic", "grok", | |
| "deepseek", "qwen", "llama", "mistral", "deepmind", "tesla", "spacex", | |
| "twitter", "instagram", "youtube", "gmail", "whatsapp", "tiktok", | |
| "snapchat", "spotify", "uber", "ibm", "oracle", "siri", "alexa", | |
| "copilot", "palm", "bing", r"the\s+internet", | |
| ] | |
| EXTERNAL_CORP_NAMES = [ | |
| "google", "openai", "microsoft", "apple", "meta", "amazon", "facebook", | |
| "anthropic", "xai", "deepmind", "ibm", "oracle", | |
| ] | |
| IDENTITY_BOILERPLATE_PATTERNS = [ | |
| r"\bas\s+freyah\b", | |
| r"\bi(?:'m|\s+am)\s+freyah\b", | |
| r"\bmy\s+creator\b", | |
| r"\bfriend\s+replacement\s+engine\b", | |
| r"\bmy\s+name\s+is\s+freya[h]?\b", | |
| r"\bi(?:'m|\s+am)\s+(?:an?\s+)?(?:ai|assistant|bot)\s+(?:named|called)\s+freyah\b", | |
| ] | |
| # Severity overrides per capability. None = detector skipped for that capability. | |
| CAPABILITY_SEVERITY_OVERRIDES = { | |
| "coding": {"unsourced_link": None}, | |
| } | |
| # ============================================================ | |
| # TEXT NORMALIZATION | |
| # ============================================================ | |
| def _squash(text): | |
| if text is None: | |
| return "" | |
| if not isinstance(text, str): | |
| text = str(text) | |
| text = unicodedata.normalize("NFKC", text) | |
| text = text.replace("\u2018", "'").replace("\u2019", "'") | |
| text = text.replace("\u201c", '"').replace("\u201d", '"') | |
| text = text.replace("\u2013", "-").replace("\u2014", "-") | |
| text = text.replace("\u00a0", " ") | |
| return re.sub(r"\s+", " ", text).strip() | |
| def _norm_loose(text): | |
| text = _squash(text).lower() | |
| text = re.sub(r"```[a-zA-Z0-9_+-]*", " ", text) | |
| text = re.sub(r"[^\w]+", " ", text, flags=re.UNICODE) | |
| text = text.replace("_", " ") | |
| return re.sub(r"\s+", " ", text).strip() | |
| def _tokens(text): | |
| text = _norm_loose(text) | |
| return text.split() if text else [] | |
| def _strip_fences(text): | |
| text = _squash(text) | |
| text = re.sub(r"^\s*```[a-zA-Z0-9_+-]*\s*", "", text) | |
| text = re.sub(r"\s*```\s*$", "", text) | |
| return text.strip() | |
| def _token_f1(pred, gt): | |
| p, g = _tokens(pred), _tokens(gt) | |
| if not p or not g: | |
| return 0.0 | |
| if p == g: | |
| return 1.0 | |
| common = {} | |
| for t in g: | |
| common[t] = common.get(t, 0) + 1 | |
| overlap = 0 | |
| for t in p: | |
| if common.get(t, 0) > 0: | |
| common[t] -= 1 | |
| overlap += 1 | |
| if overlap == 0: | |
| return 0.0 | |
| precision = overlap / len(p) | |
| recall = overlap / len(g) | |
| return 2 * precision * recall / (precision + recall) | |
| _SEQ_RATIO_CHARS = 1500 | |
| _SEQ_RATIO_TOKENS = 400 | |
| def _seq_ratio(pred, gt): | |
| a, b = _norm_loose(pred), _norm_loose(gt) | |
| if not a or not b: | |
| return 0.0 | |
| if len(a) > _SEQ_RATIO_CHARS or len(b) > _SEQ_RATIO_CHARS: | |
| a, b = a[:_SEQ_RATIO_CHARS], b[:_SEQ_RATIO_CHARS] | |
| return difflib.SequenceMatcher(None, a, b).ratio() | |
| def _token_seq_ratio(pred, gt): | |
| p, g = _tokens(pred), _tokens(gt) | |
| if not p or not g: | |
| return 0.0 | |
| if len(p) > _SEQ_RATIO_TOKENS or len(g) > _SEQ_RATIO_TOKENS: | |
| p, g = p[:_SEQ_RATIO_TOKENS], g[:_SEQ_RATIO_TOKENS] | |
| return difflib.SequenceMatcher(None, p, g, autojunk=False).ratio() | |
| _CJK_RE = re.compile( | |
| r"[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af]" | |
| ) | |
| _CJK_TRIGRAM_MAX = 5000 | |
| def _char_trigram_score(a, b): | |
| if not a or not b: | |
| return 0.0 | |
| if a == b: | |
| return 1.0 | |
| a, b = a[:_CJK_TRIGRAM_MAX], b[:_CJK_TRIGRAM_MAX] | |
| if len(a) < 3 or len(b) < 3: | |
| return 0.0 | |
| grams_a = {a[i:i + 3] for i in range(len(a) - 2)} | |
| grams_b = {b[i:i + 3] for i in range(len(b) - 2)} | |
| if not grams_a or not grams_b: | |
| return 0.0 | |
| return len(grams_a & grams_b) / len(grams_a | grams_b) | |
| def _text_similarity(pred, gt): | |
| if not isinstance(pred, str) or not isinstance(gt, str): | |
| pred, gt = str(pred or ""), str(gt or "") | |
| pred, gt = pred[:MAX_INPUT_CHARS], gt[:MAX_INPUT_CHARS] | |
| if not pred and not gt: | |
| return 1.0 | |
| if not pred or not gt: | |
| return 0.0 | |
| p_norm, g_norm = _norm_loose(pred), _norm_loose(gt) | |
| if p_norm == g_norm: | |
| if p_norm: | |
| return 1.0 | |
| return 1.0 if _squash(pred) == _squash(gt) else 0.0 | |
| f1 = _token_f1(pred, gt) | |
| tsr = _token_seq_ratio(pred, gt) | |
| best = max(_seq_ratio(pred, gt), f1 * tsr) | |
| if best < 1.0 and (_CJK_RE.search(p_norm) or _CJK_RE.search(g_norm)): | |
| best = max(best, _char_trigram_score(p_norm, g_norm)) | |
| return best | |
| # ============================================================ | |
| # FINAL ANSWER / STRUCTURED EXTRACTION | |
| # ============================================================ | |
| def _balanced_span(text, open_ch, close_ch, start=0): | |
| idx = text.find(open_ch, start) | |
| if idx < 0: | |
| return None, None | |
| depth = 0 | |
| in_str = False | |
| esc = False | |
| for i in range(idx, len(text)): | |
| ch = text[i] | |
| if in_str: | |
| if esc: | |
| esc = False | |
| elif ch == "\\": | |
| esc = True | |
| elif ch == '"': | |
| in_str = False | |
| continue | |
| if ch == '"': | |
| in_str = True | |
| elif ch == open_ch: | |
| depth += 1 | |
| elif ch == close_ch: | |
| depth -= 1 | |
| if depth == 0: | |
| return text[idx: i + 1], i + 1 | |
| return None, None | |
| def _boxed_candidates(text): | |
| out = [] | |
| for match in re.finditer(r"\\boxed\{", text): | |
| blob, _ = _balanced_span(text, "{", "}", start=match.end() - 1) | |
| if blob: | |
| value = blob[1:-1].strip() | |
| if value: | |
| out.append(value) | |
| return out | |
| def _final_answer_candidates(text): | |
| text = _strip_fences(text) | |
| if not text: | |
| return [] | |
| candidates = [text] | |
| candidates.extend(_boxed_candidates(text)) | |
| for pattern in ( | |
| r"(?:final\s+answer|answer)\s+is\s+(.+)", | |
| r"(?:final\s+answer|answer)\s*[:\-]\s+(.+)", | |
| r"###\s*(?:final\s+)?answer\b\s*:?\s+(.+)", | |
| ): | |
| for match in re.finditer(pattern, text, flags=re.I): | |
| value = match.group(1).strip() | |
| value = value.splitlines()[0].strip().strip("`*_ ") | |
| if value: | |
| candidates.append(value) | |
| lines = [line.strip().strip("`*_ ") for line in text.splitlines() if line.strip()] | |
| if lines: | |
| candidates.append(lines[-1]) | |
| seen, unique = set(), [] | |
| for cand in candidates: | |
| key = _norm_loose(cand) | |
| if key and key not in seen: | |
| seen.add(key) | |
| unique.append(cand) | |
| return unique | |
| def _extract_balanced(text, open_ch, close_ch): | |
| blob, _ = _balanced_span(text, open_ch, close_ch, start=0) | |
| return blob | |
| def _json_candidates(text): | |
| text = _squash(text) | |
| out = [] | |
| stripped = text.strip() | |
| if stripped[:1] in "{[": | |
| out.append(stripped) | |
| fence = re.search(r"```(?:json)?\s*", text) | |
| if fence: | |
| for open_ch, close_ch in (("{", "}"), ("[", "]")): | |
| blob, _ = _balanced_span(text, open_ch, close_ch, start=fence.end()) | |
| if blob: | |
| out.append(blob) | |
| for open_ch, close_ch in (("{", "}"), ("[", "]")): | |
| blob = _extract_balanced(text, open_ch, close_ch) | |
| if blob: | |
| out.append(blob) | |
| seen, unique = set(), [] | |
| for cand in out: | |
| if cand not in seen: | |
| seen.add(cand) | |
| unique.append(cand) | |
| return unique | |
| def _try_json(text): | |
| for cand in _json_candidates(text): | |
| try: | |
| return json.loads(cand) | |
| except Exception: | |
| continue | |
| return None | |
| def _scalar_key(value): | |
| if isinstance(value, bool): | |
| return f"b:{value}" | |
| if isinstance(value, (int, float)): | |
| return f"n:{float(value)}" | |
| if value is None: | |
| return "null" | |
| return f"s:{value}" | |
| def _is_scalar(value): | |
| return not isinstance(value, (dict, list)) | |
| def _json_similarity(a, b): | |
| if isinstance(a, bool) or isinstance(b, bool): | |
| return 1.0 if type(a) is type(b) and a == b else 0.0 | |
| if isinstance(a, (int, float)) and isinstance(b, (int, float)): | |
| return 1.0 if float(a) == float(b) else 0.0 | |
| if type(a) is not type(b): | |
| return 0.0 | |
| if isinstance(a, dict): | |
| if not a and not b: | |
| return 1.0 | |
| keys = set(a) | set(b) | |
| total = 0.0 | |
| for key in keys: | |
| if key in a and key in b: | |
| total += _json_similarity(a[key], b[key]) | |
| return total / len(keys) | |
| if isinstance(a, list): | |
| if not a and not b: | |
| return 1.0 | |
| if not a or not b: | |
| return 0.0 | |
| denom = max(len(a), len(b)) | |
| shared = min(len(a), len(b)) | |
| ordered = sum(_json_similarity(a[i], b[i]) for i in range(shared)) / denom | |
| unordered = 0.0 | |
| if len(a) == len(b) and all(_is_scalar(x) and _is_scalar(y) for x, y in zip(a, b)): | |
| from collections import Counter | |
| ca = Counter(_scalar_key(x) for x in a) | |
| cb = Counter(_scalar_key(y) for y in b) | |
| unordered = sum((ca & cb).values()) / denom | |
| return max(ordered, unordered) | |
| return 1.0 if a == b else 0.0 | |
| _EMOJI_RE = re.compile( | |
| "[\U0001F1E6-\U0001F1FF\U0001F300-\U0001FAFF\u2600-\u27BF\u2b00-\u2bff\uFE0F\u200D]+" | |
| ) | |
| def _emoji_set(text): | |
| return {m.group(0) for m in _EMOJI_RE.finditer(text or "")} | |
| _TABLE_SEP_RE = re.compile(r":?-{3,}:?") | |
| _FLOW_RE = re.compile(r"[│─┌┐└┘├┤┬┴┼→←↑↓▶▼▲►◄■□➤➜⇒]") | |
| _FLOW_CHARS = "│─┌┐└┘├┤┬┴┼→←↑↓▶▼▲►◄■□➤➜⇒" | |
| _STRUCTURED_CAP = 0.7 | |
| def _markdown_cells(text): | |
| """Rows of cells for a markdown table (separator rows dropped), else None.""" | |
| rows = [] | |
| for ln in text.splitlines(): | |
| ln = ln.strip() | |
| if not ln.startswith("|"): | |
| continue | |
| parts = [p.strip() for p in ln.strip("|").split("|")] | |
| if len(parts) > 1 and all(_TABLE_SEP_RE.fullmatch(p) for p in parts): | |
| continue | |
| rows.append(parts) | |
| flat = [c for row in rows for c in row] | |
| if len(rows) < 2 or len(flat) < 4: | |
| return None | |
| return rows | |
| def _looks_like_csv(text): | |
| lines = [ln for ln in text.splitlines() if ln.strip()] | |
| if len(lines) < 2: | |
| return False | |
| if any(ln.lstrip().startswith("|") for ln in lines): | |
| return False | |
| return sum(1 for ln in lines if "," in ln) >= max(2, int(0.8 * len(lines))) | |
| def _norm_keep(text, extra_chars): | |
| """Lowercased form that keeps word characters plus extra_chars (box/arrow glyphs).""" | |
| text = _squash(text).lower() | |
| text = re.sub(rf"[^\w{re.escape(extra_chars)}]+", " ", text, flags=re.UNICODE) | |
| return re.sub(r"\s+", " ", text).strip() | |
| def _structured_score(pred, gt): | |
| """Table/CSV/flowchart-aware scoring for structured text outputs. | |
| Returns None when neither side looks structured (caller falls back to | |
| plain normalized similarity). Structured outputs are exact by nature: | |
| identical cell/row sequences score 1.0, anything else is capped so a | |
| wrong cell can never reach the good tier. | |
| """ | |
| g_rows = _markdown_cells(gt) | |
| if g_rows is not None: | |
| p_rows = _markdown_cells(pred) | |
| if p_rows is None: | |
| return None | |
| g_key = "\n".join("\t".join(c.lower() for c in row) for row in g_rows) | |
| p_key = "\n".join("\t".join(c.lower() for c in row) for row in p_rows) | |
| if p_key == g_key: | |
| g_rest = "\n".join(ln for ln in gt.splitlines() if not ln.strip().startswith("|")) | |
| p_rest = "\n".join(ln for ln in pred.splitlines() if not ln.strip().startswith("|")) | |
| if _norm_loose(p_rest) == _norm_loose(g_rest): | |
| return 1.0 | |
| return min(_text_similarity(pred, gt), _STRUCTURED_CAP) | |
| return min(_text_similarity(p_key, g_key), _STRUCTURED_CAP) | |
| if _looks_like_csv(gt) and _looks_like_csv(pred): | |
| g_cells = [c.strip().lower() for ln in gt.splitlines() if ln.strip() for c in ln.split(",")] | |
| p_cells = [c.strip().lower() for ln in pred.splitlines() if ln.strip() for c in ln.split(",")] | |
| if g_cells == p_cells: | |
| return 1.0 | |
| return min(_text_similarity(" ".join(p_cells), " ".join(g_cells)), _STRUCTURED_CAP) | |
| if _FLOW_RE.search(gt) and _FLOW_RE.search(pred): | |
| g_keep, p_keep = _norm_keep(gt, _FLOW_CHARS), _norm_keep(pred, _FLOW_CHARS) | |
| if g_keep and p_keep: | |
| if g_keep == p_keep and _norm_loose(pred) == _norm_loose(gt): | |
| return 1.0 | |
| return min(_text_similarity(p_keep, g_keep), _STRUCTURED_CAP) | |
| return None | |
| def _canonical_tool_call(obj): | |
| """Canonical string shared by flat and wrapped ({"function": {...}}) call objects.""" | |
| if not isinstance(obj, dict): | |
| return None | |
| if isinstance(obj.get("function"), dict): | |
| obj = obj["function"] | |
| name = None | |
| for key in ("name", "tool", "tool_name"): | |
| if isinstance(obj.get(key), str) and obj[key].strip(): | |
| name = obj[key] | |
| break | |
| if name is None and isinstance(obj.get("function"), str) and obj["function"].strip(): | |
| name = obj["function"] | |
| if name is None: | |
| return None | |
| args = obj.get("arguments") | |
| if args is None: | |
| args = obj.get("parameters", obj.get("args", {})) | |
| if isinstance(args, str): | |
| try: | |
| args = json.loads(args) | |
| except Exception: | |
| args = {"raw": args} | |
| try: | |
| canonical = {"name": name.strip().lower(), "arguments": args} | |
| return "json:" + json.dumps( | |
| canonical, sort_keys=True, ensure_ascii=False, default=str | |
| ).lower() | |
| except Exception: | |
| return None | |
| def _call_name_and_args(call): | |
| """Best-effort (name, args_dict) parsed back from a canonicalized call string.""" | |
| if isinstance(call, str) and call.startswith("json:"): | |
| try: | |
| obj = json.loads(call[5:]) | |
| except Exception: | |
| return None, None | |
| if isinstance(obj, dict): | |
| name = obj.get("name") | |
| args = obj.get("arguments") | |
| return name, args if isinstance(args, dict) else None | |
| return None, None | |
| def _parse_tool_calls(text): | |
| """Extract tool calls; each entry is the canonical string used for matching.""" | |
| text = _squash(text) | |
| calls = [] | |
| for match in re.finditer( | |
| r"<(?:function|tool|invoke)\b[^>]*>|" | |
| r"\{\s*[\"'](?:name|function|tool|tool_name)[\"']\s*:\s*[\"']([^\"']+)[\"']", | |
| text, | |
| flags=re.I, | |
| ): | |
| name = match.group(1) | |
| if name: | |
| blob, _ = _balanced_span(text, "{", "}", start=match.start()) | |
| if blob: | |
| obj = None | |
| try: | |
| obj = json.loads(blob) | |
| except Exception: | |
| obj = None | |
| if isinstance(obj, dict): | |
| canonical = _canonical_tool_call(obj) | |
| if canonical: | |
| calls.append(canonical) | |
| continue | |
| calls.append( | |
| "json:" + json.dumps(obj, sort_keys=True, ensure_ascii=False).lower() | |
| ) | |
| continue | |
| calls.append("json:" + re.sub(r"\s+", " ", blob.lower())) | |
| else: | |
| calls.append("name:" + name.strip().lower()) | |
| else: | |
| calls.append(re.sub(r"\s+", " ", match.group(0).lower())) | |
| return calls | |
| def _extract_tool_calls(text): | |
| return _parse_tool_calls(text) | |
| # ============================================================ | |
| # CORRECTNESS SCORERS (return 0.0 .. 1.0) | |
| # ============================================================ | |
| def _score_exact(pred, gt): | |
| return _text_similarity(pred, gt) | |
| def _score_final_answer(pred, gt): | |
| best = _text_similarity(pred, gt) | |
| pred_candidates = _final_answer_candidates(pred) | |
| gt_candidates = _final_answer_candidates(gt) | |
| for p in pred_candidates: | |
| for g in gt_candidates: | |
| best = max(best, _text_similarity(p, g)) | |
| pred_boxed = _boxed_candidates(_strip_fences(pred)) | |
| gt_boxed = _boxed_candidates(_strip_fences(gt)) | |
| if pred_boxed and gt_boxed: | |
| boxed_best = max(_text_similarity(p, g) for p in pred_boxed for g in gt_boxed) | |
| if boxed_best < 0.995: | |
| best = min(best, 0.6) | |
| return best | |
| def _try_parse_code(text): | |
| try: | |
| return ast.parse(text or "") | |
| except Exception: | |
| pass | |
| for block in re.findall(r"```(?:python|py)?\s*([\s\S]*?)```", text or "", flags=re.I): | |
| try: | |
| return ast.parse(block) | |
| except Exception: | |
| continue | |
| tail = re.search(r"```(?:python|py)?\s*([\s\S]+)$", text or "", flags=re.I) | |
| if tail: | |
| try: | |
| return ast.parse(tail.group(1)) | |
| except Exception: | |
| pass | |
| return None | |
| def _score_coding(pred, gt): | |
| p, g = _strip_fences(pred), _strip_fences(gt) | |
| if _norm_loose(p) and _norm_loose(p) == _norm_loose(g): | |
| return 1.0 | |
| p_ast = _try_parse_code(p) | |
| g_ast = _try_parse_code(g) | |
| if p_ast is not None and g_ast is not None: | |
| if ast.dump(p_ast) == ast.dump(g_ast): | |
| return 1.0 | |
| return min(_text_similarity(p, g), 0.7) | |
| if g_ast is not None and p_ast is None: | |
| return min(_text_similarity(p, g), 0.4) | |
| return _text_similarity(p, g) | |
| def _score_tool_calling(pred, gt): | |
| base = _text_similarity(pred, gt) | |
| p_calls, g_calls = _extract_tool_calls(pred), _extract_tool_calls(gt) | |
| if g_calls and not p_calls: | |
| return min(base, 0.3) | |
| if p_calls and not g_calls: | |
| return min(base, 0.4) | |
| if p_calls and g_calls: | |
| matched = 0 | |
| pool = list(g_calls) | |
| for call in p_calls: | |
| if call in pool: | |
| pool.remove(call) | |
| matched += 1 | |
| precision = matched / len(p_calls) | |
| recall = matched / len(g_calls) | |
| tool_score = 0.0 if not matched else 2 * precision * recall / (precision + recall) | |
| return 0.35 * base + 0.65 * tool_score | |
| return base | |
| def _score_json(pred, gt): | |
| pj, gj = _try_json(pred), _try_json(gt) | |
| if pj is not None and gj is not None: | |
| if json.dumps(pj, sort_keys=True) == json.dumps(gj, sort_keys=True): | |
| return 1.0 | |
| return max(_json_similarity(pj, gj), _text_similarity(pred, gt)) | |
| if gj is not None and pj is None: | |
| return min(_text_similarity(pred, gt), 0.4) | |
| structured = _structured_score(pred, gt) | |
| if structured is not None: | |
| return structured | |
| return _text_similarity(pred, gt) | |
| def _score_identity(pred, gt): | |
| score = _text_similarity(pred, gt) | |
| p_norm, g_norm = _norm_loose(pred), _norm_loose(gt) | |
| if p_norm and p_norm == g_norm: | |
| return 1.0 | |
| if not p_norm and not g_norm: | |
| return score | |
| return min(score, 0.75) | |
| def _score_style(pred, gt): | |
| exact = _text_similarity(pred, gt) | |
| gt_emojis, pred_emojis = _emoji_set(gt), _emoji_set(pred) | |
| if not gt_emojis: | |
| return min(exact, 0.9) if pred_emojis else exact | |
| if gt_emojis & pred_emojis: | |
| if exact >= 0.995: | |
| return 1.0 | |
| return min(1.0, 0.6 * exact + 0.4) | |
| return min(0.7, 0.6 * exact + 0.1) | |
| SCORERS = { | |
| "identity_exact_match": _score_identity, | |
| "final_answer_exact_match": _score_final_answer, | |
| "coding_execution_or_exact_match": _score_coding, | |
| "tool_calling_or_exact_match": _score_tool_calling, | |
| "normalized_json_or_exact_match": _score_json, | |
| "exact_match": _score_exact, | |
| "style_contains": _score_style, | |
| } | |
| def correctness_score(pred, gt, reward_type): | |
| scorer = SCORERS.get(reward_type, _score_exact) | |
| score = scorer(pred or "", gt or "") | |
| if score >= 0.995: | |
| return 1.0 | |
| return max(0.0, min(1.0, score)) | |
| # ============================================================ | |
| # VIOLATION DETECTORS (anti-hallucination / identity guard) | |
| # ============================================================ | |
| _EXT = "|".join(EXTERNAL_ENTITY_PATTERNS) | |
| _LEGIT_OBJECT = ( | |
| r"(?!\s+(?:form|forms|doc|docs|sheet|sheets|spreadsheet|account|page|pages|" | |
| r"file|files|folder|folders|drive|script|scripts|app|apps|project|projects|" | |
| r"website|websites|site|api|apis|bot|game|games|list|table|class|function|" | |
| r"dataset|repo|repository|presentation|presentations|slides?|deck|survey|quiz|" | |
| r"diagram|flowchart|tests?|checklist|template|server|database|automation|" | |
| r"pipeline|workflow|calendar|maps?|location|event|chat|workspace|blog|channel|" | |
| r"playlist|store|market|play|news|tags?|meta|data|elements?|attributes?|" | |
| r"components?|interfaces?|menus?|layouts?|windows?|graphics?|extensions?|icons?|" | |
| r"views?|pie|cake|bread|cookies?|desserts?|soup|salad|sauce|meals?|trees?|" | |
| r"boxes|packages|images?|photos?|videos?|music|songs?|notes?|reports?|" | |
| r"summaries|essays|posts?)\b)" | |
| ) | |
| _SELF = r"(?:me|mine|myself|i|siva\s+krishna|freyah|skandrew(?:\s+industries)?|our\s+team|my\s+(?:team|company|firm))" | |
| _EXTERNAL_CORP = "|".join(EXTERNAL_CORP_NAMES) | |
| _RAW_VIOLATION_PATTERNS = [ | |
| ( | |
| "creator_confusion_self", | |
| "severe", | |
| re.compile( | |
| rf"\b(?:creator|founder|inventor|maker|author|developer|mind)\s+(?:of|behind)\s+" | |
| rf"(?:the\s+)?(?:{_EXT})\b{_LEGIT_OBJECT}(?:\s+\w+){{0,3}}\s+(?:is|was|are|were)\s+{_SELF}\b", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "creator_confusion_external", | |
| "severe", | |
| re.compile( | |
| rf"\b(?:{_EXT})\b{_LEGIT_OBJECT}(?:\s+\w+){{0,3}}\s+(?:was|is|were|are)\s+" | |
| rf"(?:created|founded|built|invented|developed|designed|made|launched|owned)\s+by\s+{_SELF}\b", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "creator_confusion_first_person", | |
| "severe", | |
| re.compile( | |
| rf"\b(?:i|i'?m|im|we|our\s+team|my\s+team|siva\s+krishna|freyah|skandrew(?:\s+industries)?)" | |
| rf"\s+(?:created|founded|invented|built|designed|developed|launched|owns?)\s+" | |
| rf"(?:the\s+)?(?:{_EXT})\b{_LEGIT_OBJECT}", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "identity_drift_model", | |
| "severe", | |
| re.compile( | |
| r"\b(?:i\s*am|i'?m|im|this\s+is|you(?:'re|\s+are)\s+(?:talking\s+to|chatting\s+with)|" | |
| r"as\s+(?:a|an)?\s*)\s*(?:a\s+|an\s+)?" | |
| r"(?:chatgpt|gpt-?\s?(?:3\.5|4|4o|5)|openai(?:'s)?\s+(?:assistant|model|chatbot)|" | |
| r"gemini|claude(?:\s+\d+)?|anthropic(?:'s)?\s+(?:assistant|model)|grok|llama\s*\d*|" | |
| r"deepseek[\w-]*|qwen|mistral|copilot|siri|alexa|palm|bing\s+chat)\b", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "identity_drift_built_by", | |
| "severe", | |
| re.compile( | |
| rf"\b(?:i|i'?m|im|freyah|this\s+(?:assistant|model|ai))\b[^.!?]{{0,80}}\b" | |
| rf"(?:created|made|built|developed|trained|powered|maintained)\s+by\s+" | |
| rf"(?:openai|google|anthropic|meta|microsoft|deepmind|xai|amazon|ibm)\b", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "identity_drift_ownership", | |
| "severe", | |
| re.compile( | |
| rf"\b(?:openai|google|anthropic|meta|microsoft)\s+" | |
| rf"(?:owns?|created|made|built|develops|trains|powers)\b[^.!?]{{0,40}}\b" | |
| rf"(?:me|freyah|my\s+(?:creator|company)|skandrew(?:\s+industries)?)\b", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "company_confusion_forward", | |
| "severe", | |
| re.compile( | |
| rf"\bskandrew(?:\s+industries)?\b[^.!?]{{0,80}}\b" | |
| rf"(?:subsidiary|division|partner(?:ed|ship)?|joint[-\s]venture|owned\s+by|part\s+of|" | |
| rf"acquired\s+by|parent|merged\s+with|affiliated\s+with|collaborat\w+|integrat\w+\s+with|" | |
| rf"backed\s+by|funded\s+by|powered\s+by|work(?:s|ing)?\s+(?:closely\s+)?with|" | |
| rf"strategic(?:ally)?\s+(?:partner\w*|alliance|relationship|tie[s]?)|" | |
| rf"a\s+(?:google|openai|microsoft|apple|meta|amazon)[\w\s]{{0,12}}(?:company|firm|entity))" | |
| rf"\b[^.!?]{{0,60}}\b(?:{_EXTERNAL_CORP})\b", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "company_confusion_reverse", | |
| "severe", | |
| re.compile( | |
| rf"\b(?:{_EXTERNAL_CORP})\b[^.!?]{{0,60}}\b" | |
| rf"(?:owns?|founded|created|acquired|is\s+the\s+(?:parent|owner|maker)|created\s+the)\b" | |
| rf"[^.!?]{{0,30}}\bskandrew(?:\s+industries)?\b", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "fabricated_citation", | |
| "major", | |
| re.compile( | |
| r"\b(?:doi\s*:?\s*10\.\d{4,9}/\S+|arxiv\s*:?\s*\d{4}\.\d{4,5}(?:v\d+)?|" | |
| r"(?:issn|isbn)\s*:?\s*[\dXx-]{9,17})\b", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "unsourced_link", | |
| "mild", | |
| re.compile(r"https?://\S+|www\.\S+", re.I), | |
| ), | |
| ( | |
| "fabricated_source", | |
| "major", | |
| re.compile( | |
| r"\b(?:" | |
| r"researchers?\s+(?:at|from|in)\s+(?:harvard|stanford|mit|oxford|cambridge|" | |
| r"the\s+united\s+nations|who)\b|" | |
| r"(?:a|the|this|their)\s+(?:peer-?reviewed\s+|published\s+)?" | |
| r"(?:study|research|paper|article|report|survey)\s+" | |
| r"(?:by|from|in|published(?:\s+in)?)\s+" | |
| r"(?:harvard|stanford|mit|oxford|cambridge|nature|science|the\s+lancet|ieee|" | |
| r"acm|springer|elsevier|forbes|reuters|bbc|cnn|techcrunch|wired|" | |
| r"google\s+scholar)\b|" | |
| r"(?:according\s+to|as\s+per|reported\s+by|cited\s+by)\s+(?:the\s+|a\s+)?" | |
| r"(?:peer-?reviewed\s+)?(?:harvard|stanford|mit|oxford|cambridge|nature|" | |
| r"the\s+lancet|forbes|reuters|techcrunch|wired|google\s+scholar|" | |
| r"the\s+united\s+nations)\b" | |
| r")", | |
| re.I, | |
| ), | |
| ), | |
| ( | |
| "fabricated_experience", | |
| "major", | |
| re.compile( | |
| r"\b(?:i\s+(?:have\s+)?(?:personally|actually|really)\s+" | |
| r"(?:visited|read|seen|verified|confirmed|tested|witnessed|checked|met)\b|" | |
| r"i(?:'ve|\s+have)\s+(?:read|visited|seen)\s+(?:the\s+)?(?:original|actual|full)\b|" | |
| r"i\s+can\s+confirm\s+(?:that\s+)?i\s+(?:have\s+)?(?:read|seen|visited|verified)\b)", | |
| re.I, | |
| ), | |
| ), | |
| ] | |
| _IDENTITY_BOILERPLATE = [re.compile(p, re.I) for p in IDENTITY_BOILERPLATE_PATTERNS] | |
| _VIOLATION_PATTERNS = [ | |
| (code.strip(), severity.strip(), pattern) | |
| for code, severity, pattern in _RAW_VIOLATION_PATTERNS | |
| ] | |
| _SEVERITY_PENALTY = { | |
| "severe": PENALTY_SEVERE, | |
| "major": PENALTY_MAJOR, | |
| "mild": PENALTY_MILD, | |
| } | |
| _PROHIBITION_RE = re.compile( | |
| r"\b(?:do\s+not|don'?t|dont|never|avoid|must\s+not|should\s+not|incorrect(?:ly)?|" | |
| r"wrong|forbidden|prohibited|refrain\s+from|stop\s+saying)\b", | |
| re.I, | |
| ) | |
| def _prompt_exemption_ok(pattern, prompt_text): | |
| if not prompt_text: | |
| return False | |
| matches = list(pattern.finditer(prompt_text)) | |
| if not matches: | |
| return False | |
| for match in matches: | |
| window = prompt_text[max(0, match.start() - 160): match.end() + 160] | |
| if _PROHIBITION_RE.search(window): | |
| return False | |
| return True | |
| def _exempt(pattern, ground_truth, prompt_text): | |
| if ground_truth and pattern.search(ground_truth): | |
| return True | |
| return _prompt_exemption_ok(pattern, prompt_text) | |
| def _effective_severity(code, default_severity, capability): | |
| overrides = CAPABILITY_SEVERITY_OVERRIDES.get(capability, {}) | |
| if code in overrides: | |
| return overrides[code] | |
| return default_severity | |
| def _is_degenerate(text): | |
| text = _squash(text) | |
| if len(text) < 120: | |
| return False | |
| tokens = text.lower().split() | |
| if len(tokens) < 30: | |
| return False | |
| ngrams = [tuple(tokens[i: i + 4]) for i in range(len(tokens) - 3)] | |
| if not ngrams: | |
| return False | |
| unique_ratio = len(set(ngrams)) / len(ngrams) | |
| return unique_ratio < 0.15 | |
| def find_violations(completion, ground_truth=None, capability=None, prompt_text=None): | |
| """Return list of {code, severity, penalty, snippet} for anti-hallucination rules.""" | |
| completion = _squash(completion)[:MAX_INPUT_CHARS] | |
| ground_truth = _squash(ground_truth)[:MAX_INPUT_CHARS] | |
| prompt_text = _squash(prompt_text)[:MAX_INPUT_CHARS] | |
| capability = str(capability).strip().lower() if capability is not None else "" | |
| violations = [] | |
| if not completion: | |
| return violations | |
| for code, severity, pattern in _VIOLATION_PATTERNS: | |
| if _effective_severity(code, severity, capability) is None: | |
| continue | |
| match = pattern.search(completion) | |
| if not match: | |
| continue | |
| if _exempt(pattern, ground_truth, prompt_text): | |
| continue | |
| effective = _effective_severity(code, severity, capability) | |
| violations.append( | |
| { | |
| "code": code, | |
| "severity": effective, | |
| "penalty": _SEVERITY_PENALTY[effective], | |
| "snippet": match.group(0)[:120], | |
| } | |
| ) | |
| for name in PROTECTED_NAMES: | |
| name_re = re.compile(rf"\b{re.escape(name)}\b", re.I) | |
| if not name_re.search(completion): | |
| continue | |
| if _exempt(name_re, ground_truth, prompt_text): | |
| continue | |
| severity = "mild" if capability == "identity" else "major" | |
| violations.append( | |
| { | |
| "code": "protected_name_leak", | |
| "severity": severity, | |
| "penalty": _SEVERITY_PENALTY[severity], | |
| "snippet": name, | |
| } | |
| ) | |
| if capability != "identity": | |
| for pattern in _IDENTITY_BOILERPLATE: | |
| match = pattern.search(completion) | |
| if not match: | |
| continue | |
| if _exempt(pattern, ground_truth, prompt_text): | |
| continue | |
| violations.append( | |
| { | |
| "code": "identity_boilerplate_irrelevant", | |
| "severity": "mild", | |
| "penalty": PENALTY_MILD, | |
| "snippet": match.group(0)[:120], | |
| } | |
| ) | |
| if _is_degenerate(completion) and not _is_degenerate(ground_truth): | |
| violations.append( | |
| { | |
| "code": "degenerate_repetition", | |
| "severity": "mild", | |
| "penalty": PENALTY_MILD, | |
| "snippet": "repeated token loop", | |
| } | |
| ) | |
| return violations | |
| def _tool_catalog(tools_json): | |
| """Parse a tools_json catalog into {tool_name_lower: [required_arg, ...]}.""" | |
| if not tools_json: | |
| return {} | |
| if isinstance(tools_json, str): | |
| try: | |
| tools_json = json.loads(tools_json) | |
| except Exception: | |
| return {} | |
| if isinstance(tools_json, dict): | |
| tools_json = tools_json.get("tools") or tools_json.get("functions") or [tools_json] | |
| if not isinstance(tools_json, list): | |
| return {} | |
| catalog = {} | |
| for tool in tools_json: | |
| if not isinstance(tool, dict): | |
| continue | |
| fn = tool.get("function") if isinstance(tool.get("function"), dict) else tool | |
| name = fn.get("name") | |
| if not isinstance(name, str) or not name.strip(): | |
| continue | |
| params = fn.get("parameters") | |
| params = params if isinstance(params, dict) else {} | |
| required = params.get("required") | |
| required = [str(p).strip().lower() for p in required] if isinstance(required, list) else [] | |
| catalog[name.strip().lower()] = required | |
| return catalog | |
| def _tool_catalog_violations(completion, ground_truth, tools_json): | |
| """Catalog-based checks, strictly GT-demonstrated so clean answers never fire. | |
| unknown_tool : call names a tool outside the catalog and never shown in GT | |
| missing_required_arg : GT demonstrates a call whose required args pred omits | |
| """ | |
| catalog = _tool_catalog(tools_json) | |
| if not catalog: | |
| return [] | |
| gt_text = _squash(ground_truth or "").lower() | |
| gt_calls = _parse_tool_calls(ground_truth or "") | |
| gt_names, gt_args_by_name = set(), {} | |
| for call in gt_calls: | |
| g_name, g_args = _call_name_and_args(call) | |
| if isinstance(g_name, str): | |
| g_name = g_name.strip().lower() | |
| gt_names.add(g_name) | |
| if g_args is not None: | |
| gt_args_by_name.setdefault(g_name, g_args) | |
| violations = [] | |
| seen_missing = set() | |
| for call in _parse_tool_calls(completion or ""): | |
| name, args = _call_name_and_args(call) | |
| if not isinstance(name, str) or not name.strip(): | |
| continue | |
| lname = name.strip().lower() | |
| demonstrated = lname in gt_names or re.search( | |
| rf"\b{re.escape(lname)}\b", gt_text | |
| ) | |
| if lname not in catalog and not demonstrated: | |
| violations.append( | |
| { | |
| "code": "unknown_tool", | |
| "severity": "mild", | |
| "penalty": PENALTY_MILD, | |
| "snippet": lname[:120], | |
| } | |
| ) | |
| continue | |
| required = catalog.get(lname) or [] | |
| if not required or not isinstance(args, dict) or lname not in gt_names: | |
| continue | |
| g_args = gt_args_by_name.get(lname) | |
| if not isinstance(g_args, dict): | |
| continue | |
| arg_keys = {str(k).strip().lower() for k in args} | |
| g_arg_keys = {str(k).strip().lower() for k in g_args} | |
| missing = [p for p in required if p in g_arg_keys and p not in arg_keys] | |
| if missing and lname not in seen_missing: | |
| seen_missing.add(lname) | |
| violations.append( | |
| { | |
| "code": "missing_required_arg", | |
| "severity": "mild", | |
| "penalty": PENALTY_MILD, | |
| "snippet": f"{lname}: {', '.join(missing)}"[:120], | |
| } | |
| ) | |
| return violations | |
| # ============================================================ | |
| # REWARD COMPOSITION | |
| # ============================================================ | |
| def tier_of(reward): | |
| if reward >= GOOD_THRESHOLD: | |
| return GOOD | |
| if reward < BAD_THRESHOLD: | |
| return BAD | |
| return AVERAGE | |
| def _prompt_to_text(prompt): | |
| if prompt is None: | |
| return "" | |
| if isinstance(prompt, str): | |
| return prompt | |
| if isinstance(prompt, list): | |
| parts = [] | |
| for message in prompt: | |
| if isinstance(message, dict): | |
| content = message.get("content", "") | |
| if isinstance(content, (list, dict)): | |
| content = json.dumps(content, ensure_ascii=False, default=str) | |
| parts.append(str(content)) | |
| else: | |
| parts.append(str(message)) | |
| return "\n".join(parts) | |
| return str(prompt) | |
| def _row_get(row, key, default=None): | |
| if not isinstance(row, dict): | |
| return default | |
| if key in row and row[key] is not None: | |
| return row[key] | |
| legacy = key + " " | |
| if legacy in row and row[legacy] is not None: | |
| return row[legacy] | |
| return default | |
| def compute_reward( | |
| completion, | |
| ground_truth=None, | |
| reward_type=None, | |
| capability=None, | |
| prompt=None, | |
| item=None, | |
| return_details=False, | |
| ): | |
| """Main entry: score one completion, reward in [-1, 1]. Set return_details=True to get (reward, details).""" | |
| if isinstance(item, dict): | |
| if not ground_truth: | |
| ground_truth = _row_get(item, "answer") | |
| if not ground_truth and isinstance(item.get("reward_model"), dict): | |
| ground_truth = item["reward_model"].get("ground_truth") | |
| reward_type = reward_type or _row_get(item, "reward_type") | |
| capability = capability or _row_get(item, "capability") | |
| tools_json = _row_get(item, "tools_json") if isinstance(item, dict) else None | |
| if isinstance(completion, str): | |
| completion = completion[:MAX_INPUT_CHARS] | |
| else: | |
| completion = str(completion or "")[:MAX_INPUT_CHARS] | |
| prompt_text = _squash(_prompt_to_text(prompt))[:MAX_INPUT_CHARS] | |
| ground_truth = _squash(ground_truth)[:MAX_INPUT_CHARS] | |
| if reward_type is not None: | |
| reward_type = str(reward_type).strip() | |
| reward_type = reward_type if reward_type in REWARD_TYPES else "exact_match" | |
| if capability is not None: | |
| capability = str(capability).strip().lower() | |
| correctness = correctness_score(completion, ground_truth, reward_type) | |
| violations = find_violations(completion, ground_truth, capability, prompt_text) | |
| if reward_type == "tool_calling_or_exact_match" and tools_json: | |
| violations.extend(_tool_catalog_violations(completion, ground_truth, tools_json)) | |
| penalty = min(sum(v["penalty"] for v in violations), MAX_TOTAL_PENALTY) | |
| raw = 2.0 * correctness - 1.0 - penalty | |
| reward = max(REWARD_MIN, min(REWARD_MAX, raw)) | |
| if any(v["severity"] == "severe" for v in violations): | |
| reward = min(reward, -0.5) | |
| if any(v["severity"] == "major" for v in violations): | |
| reward = min(reward, -0.2) | |
| reward = round(reward, 4) | |
| if return_details: | |
| return reward, { | |
| "reward": reward, | |
| "tier": tier_of(reward), | |
| "correctness": round(correctness, 4), | |
| "penalty": round(penalty, 4), | |
| "violations": violations, | |
| "reward_type": reward_type, | |
| "capability": capability, | |
| } | |
| return reward | |
| def score_row(row, completion, return_details=False): | |
| """Score a dataset row (train_gspo_simple JSONL format) against a completion.""" | |
| row = row if isinstance(row, dict) else {} | |
| return compute_reward( | |
| completion, | |
| reward_type=_row_get(row, "reward_type"), | |
| capability=_row_get(row, "capability"), | |
| prompt=_row_get(row, "prompt"), | |
| item=row, | |
| return_details=return_details, | |
| ) | |
| def compute_score(data_source, solution_str, ground_truth, extra_info=None): | |
| """verl / OpenRLHF style reward fn: compute_score(data_source, solution_str, ground_truth, extra_info).""" | |
| if not isinstance(extra_info, dict): | |
| extra_info = {} | |
| return compute_reward( | |
| solution_str, | |
| ground_truth=ground_truth, | |
| reward_type=extra_info.get("reward_type"), | |
| capability=extra_info.get("capability"), | |
| prompt=extra_info.get("prompt"), | |
| ) | |
| # ============================================================ | |
| # SELF TEST | |
| # ============================================================ | |
| def _self_test(): | |
| cases = [] | |
| def check(name, reward, expected_tier, details, expect=None): | |
| tier = tier_of(reward) | |
| codes = [v["code"] for v in (details or {}).get("violations", [])] | |
| ok = tier == expected_tier | |
| if expected_tier == GOOD: | |
| ok = ok and reward >= GOOD_THRESHOLD and not codes | |
| if expected_tier == BAD: | |
| ok = ok and reward < BAD_THRESHOLD | |
| for code in expect or []: | |
| ok = ok and code in codes | |
| cases.append((name, reward, tier, expected_tier, ok, codes, list(expect or []))) | |
| def check_raw(name, ok, info=""): | |
| cases.append((name, 0.0, info, "", bool(ok), [], [])) | |
| def det(name, text, expect=(), forbid=(), capability="reasoning_thinking", gt="", prompt=""): | |
| violations = find_violations(text, gt, capability, prompt) | |
| codes = sorted({v["code"] for v in violations}) | |
| ok = all(c in codes for c in expect) and not any(c in codes for c in forbid) | |
| cases.append((name, 0.0, str(codes), "", ok, codes, list(expect))) | |
| identity_gt = ( | |
| "In my supplied background, my name is FREYAH; FREYAH expands to FRIEND " | |
| "REPLACEMENT ENGINE YOU ALWAYS HAVE; and RIT's students are mainly from Tamil Nadu." | |
| ) | |
| id_prompt = [ | |
| {"role": "system", "content": "You are FREYAH, a helpful AI assistant."}, | |
| {"role": "user", "content": "As FREYAH, give a factual first-person overview using the supplied background. My name is Siva Krishna and my company is SKANDREW INDUSTRIES."}, | |
| ] | |
| r, d = compute_reward(identity_gt, identity_gt, "identity_exact_match", "identity", id_prompt, return_details=True) | |
| check("identity_correct", r, GOOD, d) | |
| r, d = compute_reward( | |
| identity_gt + " Also, the creator of Google is me.", | |
| identity_gt, "identity_exact_match", "identity", id_prompt, return_details=True, | |
| ) | |
| check("identity_plus_creator_confusion", r, BAD, d, expect=["creator_confusion_self"]) | |
| code_gt = "```python\nclass TrafficLight:\n def change_state(self):\n return 'GREEN'\n```" | |
| code_prompt = [{"role": "user", "content": "Implement a TrafficLight class."}] | |
| r, d = compute_reward(code_gt, code_gt, "coding_execution_or_exact_match", "coding", code_prompt, return_details=True) | |
| check("coding_correct", r, GOOD, d) | |
| r, d = compute_reward( | |
| code_gt + "\nSiva Krishna developed this and SKANDREW INDUSTRIES partnered with OpenAI.", | |
| code_gt, "coding_execution_or_exact_match", "coding", code_prompt, return_details=True, | |
| ) | |
| check("coding_plus_name_and_company_leak", r, BAD, d, | |
| expect=["company_confusion_forward", "protected_name_leak"]) | |
| r, d = compute_reward( | |
| "Here is my solution: class TrafficLight: pass # I am ChatGPT made by OpenAI", | |
| code_gt, "coding_execution_or_exact_match", "coding", code_prompt, return_details=True, | |
| ) | |
| check("coding_wrong_plus_identity_drift", r, BAD, d, expect=["identity_drift_model"]) | |
| r, d = compute_reward( | |
| "class TrafficLight:\n def change_state(self):\n # returns the next state in the cycle", | |
| code_gt, "coding_execution_or_exact_match", "coding", code_prompt, return_details=True, | |
| ) | |
| check("coding_partial_unparseable_bad", r, BAD, d) | |
| r, d = compute_reward( | |
| "I created Google and I am the inventor of ChatGPT.", | |
| "The traffic light returns GREEN next.", "exact_match", "reasoning_thinking", | |
| [{"role": "user", "content": "What state comes after RED?"}], return_details=True, | |
| ) | |
| check("wrong_answer_creator_claims", r, BAD, d, expect=["creator_confusion_first_person"]) | |
| emoji_gt = "That was close\u2014review the last few plays and try again. \U0001F3AF" | |
| r, d = compute_reward(emoji_gt, emoji_gt, "style_contains", "emoji", | |
| [{"role": "user", "content": "Respond supportively with one emoji."}], | |
| return_details=True) | |
| check("emoji_correct", r, GOOD, d) | |
| r, d = compute_reward( | |
| "That was close, try again. No emoji for you, as Gemini by Google.", | |
| emoji_gt, "style_contains", "emoji", | |
| [{"role": "user", "content": "Respond supportively with one emoji."}], | |
| return_details=True, | |
| ) | |
| check("emoji_wrong_plus_drift", r, BAD, d, expect=["identity_drift_model"]) | |
| json_gt = '{"task": "freyah_dataset", "enabled": true}' | |
| r, d = compute_reward(json_gt, json_gt, "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "Convert to JSON."}], return_details=True) | |
| check("json_correct", r, GOOD, d) | |
| r, d = compute_reward( | |
| '{"task": "freyah_dataset", "enabled": false} My creator Siva Krishna says hi and SKANDREW works with Microsoft.', | |
| json_gt, "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "Convert to JSON."}], | |
| return_details=True, | |
| ) | |
| check("json_wrong_plus_leaks", r, BAD, d, | |
| expect=["protected_name_leak", "identity_boilerplate_irrelevant"]) | |
| r, d = compute_reward( | |
| "To assist you better, could you please provide the text for which you want to detect the language?", | |
| "To assist you better, could you please provide the text for which you want to detect the language?", | |
| "exact_match", "tool_decision", [{"role": "user", "content": "Detect the language."}], | |
| return_details=True, | |
| ) | |
| check("tool_decision_correct", r, GOOD, d) | |
| r, d = compute_reward("I cannot help with that.", identity_gt, "identity_exact_match", "identity", | |
| id_prompt, return_details=True) | |
| check("identity_refusal", r, BAD, d) | |
| r, d = compute_reward( | |
| "That was close\u2014review the last few plays and try again. \U0001F60A", | |
| emoji_gt, "style_contains", "emoji", | |
| [{"role": "user", "content": "Respond supportively with one emoji."}], | |
| return_details=True, | |
| ) | |
| check("emoji_wrong_emoji_same_text", r, AVERAGE, d) | |
| r, d = compute_reward( | |
| 'Result: {"a": 1, "b": {"c": "x}y"}} trailing', '{"a": 1, "b": {"c": "x}y"}}', | |
| "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "Extract JSON."}], return_details=True, | |
| ) | |
| check("json_nested_brace_in_string", r, GOOD, d) | |
| r, d = compute_reward('{"n": 1.0}', '{"n": 1}', "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "Convert."}], return_details=True) | |
| check("json_int_float_equivalent", r, GOOD, d) | |
| gt_t = 'Let me check.\n{"name": "get_weather", "arguments": {"city": "Paris"}}' | |
| r, d = compute_reward('Checking now.\n{"name": "get_weather", "arguments": {"city": "Paris"}}', | |
| gt_t, "tool_calling_or_exact_match", "tool_calling", | |
| [{"role": "user", "content": "Weather in Paris?"}], return_details=True) | |
| check("tool_correct_call", r, GOOD, d) | |
| r, d = compute_reward('Checking now.\n{"name": "get_traffic", "arguments": {"city": "Paris"}}', | |
| gt_t, "tool_calling_or_exact_match", "tool_calling", | |
| [{"role": "user", "content": "Weather in Paris?"}], return_details=True) | |
| check("tool_wrong_call", r, BAD, d) | |
| r, d = compute_reward('Checking now.\n{"name": "get_weather", "arguments": {"city": "London"}}', | |
| gt_t, "tool_calling_or_exact_match", "tool_calling", | |
| [{"role": "user", "content": "Weather in Paris?"}], return_details=True) | |
| check_raw("tool_wrong_args_not_good", r < GOOD_THRESHOLD, f"reward={r}") | |
| r, d = compute_reward("", "", "exact_match", "reasoning_thinking", | |
| [{"role": "user", "content": "hi"}], return_details=True) | |
| check("empty_both", r, GOOD, d) | |
| r, d = compute_reward("", "expected answer", "exact_match", "reasoning_thinking", | |
| [{"role": "user", "content": "hi"}], return_details=True) | |
| check("empty_completion", r, BAD, d) | |
| r, d = compute_reward("\u5317\u4eac\u5927\u5b66\u4f4d\u4e8e\u4e0a\u6d77", | |
| "\u6e05\u534e\u5927\u5b66\u4f4d\u4e8e\u5317\u4eac", | |
| "exact_match", "reasoning_thinking", | |
| [{"role": "user", "content": "location?"}], return_details=True) | |
| check_raw("cjk_different_not_perfect", r < GOOD_THRESHOLD, f"reward={r}") | |
| r, d = compute_reward("\u5317\u4eac\u5927\u5b66\u4f4d\u4e8e\u4e2d\u56fd", | |
| "\u5317\u4eac\u5927\u5b66\u4f4d\u4e8e\u4e2d\u56fd", | |
| "exact_match", "identity", | |
| [{"role": "user", "content": "location?"}], return_details=True) | |
| check("cjk_identical", r, GOOD, d) | |
| tamil = "\u0b95\u0bb2\u0bb5\u0bbf \u0b86\u0b99\u0bcd\u0b95\u0bbf\u0bb2\u0bc1 \u0b8e\u0ba9\u0bcd?" | |
| r, d = compute_reward(tamil, tamil, "identity_exact_match", "identity", | |
| [{"role": "user", "content": "Tamil question?"}], return_details=True) | |
| check("tamil_identical", r, GOOD, d) | |
| r, d = compute_reward("I created a Google Form for my team.", "I created a Google Form for my team.", | |
| "coding_execution_or_exact_match", "coding", | |
| [{"role": "user", "content": "Write a script."}], return_details=True) | |
| check("created_google_form_not_flagged", r, GOOD, d) | |
| r, d = compute_reward("I made apple pie for dessert.", "I made apple pie for dessert.", | |
| "exact_match", "reasoning_thinking", | |
| [{"role": "user", "content": "What did you make?"}], return_details=True) | |
| check("made_apple_pie_not_flagged", r, GOOD, d) | |
| det("det_creator_pos", "The creator of Google is me.", expect=["creator_confusion_self"]) | |
| det("det_creator_neg", "Google was founded by Larry Page and Sergey Brin in 1998.", | |
| forbid=["creator_confusion_self", "creator_confusion_external", "creator_confusion_first_person"]) | |
| det("det_creator_pos2", "Google was created by me.", expect=["creator_confusion_external"]) | |
| det("det_drift_pos", "I am ChatGPT made by OpenAI.", | |
| expect=["identity_drift_model"], capability="identity") | |
| det("det_drift_neg", "Gemini is a zodiac sign that spans May to June.", | |
| forbid=["identity_drift_model"]) | |
| det("det_company_pos", "SKANDREW INDUSTRIES is a subsidiary of Google.", | |
| expect=["company_confusion_forward"], capability="identity") | |
| det("det_company_pos2", "SKANDREW works closely with Microsoft.", | |
| expect=["company_confusion_forward"], capability="identity") | |
| det("det_company_neg", "SKANDREW INDUSTRIES is a generative AI company owned by Siva Krishna.", | |
| forbid=["company_confusion_forward", "company_confusion_reverse", "protected_name_leak"], | |
| capability="identity", gt="SKANDREW INDUSTRIES is a generative AI company owned by Siva Krishna.") | |
| det("det_name_leak_pos", "Built by Siva Krishna.", expect=["protected_name_leak"], | |
| capability="coding", gt="done") | |
| det("det_name_exempt_via_gt", "Built by Siva Krishna.", | |
| forbid=["protected_name_leak"], capability="identity", gt="built by Siva Krishna") | |
| det("det_name_missing_capability_major", "Built by Siva Krishna.", | |
| expect=["protected_name_leak"], capability=None, gt="done") | |
| det("det_boilerplate_pos", "As FREYAH, I completed the task.", | |
| expect=["identity_boilerplate_irrelevant"], capability="coding", gt="task done") | |
| det("det_boilerplate_identity_ok", "As FREYAH, I completed the task.", | |
| forbid=["identity_boilerplate_irrelevant"], capability="identity") | |
| det("det_boilerplate_missing_capability", "As FREYAH, I completed the task.", | |
| expect=["identity_boilerplate_irrelevant"], capability=None, gt="task done") | |
| det("det_gt_exempt", "I am ChatGPT discussing an example.", | |
| forbid=["identity_drift_model"], capability="identity", gt="Example: I am ChatGPT.") | |
| det("det_prohibition_not_exempt", "I am ChatGPT.", | |
| expect=["identity_drift_model"], capability="identity", | |
| gt="I am FREYAH, how can I help?", prompt="Do not say: I am ChatGPT.") | |
| det("det_neutral_prompt_exempt", "I am ChatGPT, continuing.", | |
| forbid=["identity_drift_model"], capability="identity", gt="I am FREYAH.", | |
| prompt="Earlier you said: I am ChatGPT. Please continue.") | |
| det("det_mixed_prompt_not_exempt", "I am ChatGPT, continuing.", | |
| expect=["identity_drift_model"], capability="identity", gt="I am FREYAH.", | |
| prompt="Earlier you said: I am ChatGPT, and also: do not say you are ChatGPT.") | |
| det("det_link_mild", "See https://example.com for details.", | |
| expect=["unsourced_link"], capability="reasoning_thinking", gt="see link") | |
| rep = ("alpha beta gamma delta " * 20).strip() | |
| det("det_degenerate_pos", rep, expect=["degenerate_repetition"], gt="short answer") | |
| det("det_degenerate_gt_exempt", rep, forbid=["degenerate_repetition"], gt=rep) | |
| det("det_fabricated_source_pos", "A study published in Nature says otherwise.", | |
| expect=["fabricated_source"], gt="plain answer") | |
| det("det_url_in_gt_exempt", "Read https://docs.python.org/3/ now.", | |
| forbid=["unsourced_link"], capability="reasoning_thinking", | |
| gt="Read https://docs.python.org/3/ now.") | |
| det("det_link_skipped_for_coding", "See https://example.com/api.", | |
| forbid=["unsourced_link"], capability="coding", gt="see docs") | |
| r, d = compute_reward("Let me check the weather for you.", gt_t, | |
| "tool_calling_or_exact_match", "tool_calling", | |
| [{"role": "user", "content": "Weather in Paris?"}], return_details=True) | |
| check_raw("tool_missing_call_bad", r < 0, f"reward={r}") | |
| r, d = compute_reward("Sure!\n```python\ndef f():\n return 1\n```", | |
| "def f():\n return 1", "coding_execution_or_exact_match", "coding", | |
| [{"role": "user", "content": "write f"}], return_details=True) | |
| check("code_prose_preamble_fenced", r, GOOD, d) | |
| r, d = compute_reward("Here is the function you asked for, hope it helps!", | |
| "def f():\n return 1", "coding_execution_or_exact_match", "coding", | |
| [{"role": "user", "content": "write f"}], return_details=True) | |
| check_raw("code_invalid_pred_bad", r < 0, f"reward={r}") | |
| r, d = compute_reward("def f():\n return 2", "def f():\n return 1", | |
| "coding_execution_or_exact_match", "coding", | |
| [{"role": "user", "content": "write f"}], return_details=True) | |
| check("code_parseable_partial_average", r, AVERAGE, d) | |
| r, d = compute_reward("the answer is forty two", '{"answer": 42}', | |
| "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "json please"}], return_details=True) | |
| check_raw("json_invalid_pred_bad", r < 0, f"reward={r}") | |
| r, d = compute_reward('```json\n{"name": "get_weather", "arguments": {"city": "Paris"}}\n```', | |
| '{"name": "get_weather", "arguments": {"city": "Paris"}}', | |
| "tool_calling_or_exact_match", "tool_calling", | |
| [{"role": "user", "content": "Weather?"}], return_details=True) | |
| check("tool_fenced_json_good", r, GOOD, d) | |
| r, d = compute_reward("I am FREYAH, the assistant for Skandrew and also for Google.", | |
| "I am FREYAH, the assistant for Skandrew.", | |
| "identity_exact_match", "identity", | |
| [{"role": "user", "content": "who are you"}], return_details=True) | |
| check_raw("identity_near_miss_not_good", r < GOOD_THRESHOLD, f"reward={r}") | |
| det("det_creator_pos_exclaim", "The creator of Google is me!", | |
| expect=["creator_confusion_self"]) | |
| det("det_drift_pos_question", "I am ChatGPT?", | |
| expect=["identity_drift_model"], capability="identity") | |
| det("det_fp_google_doc", "I created a Google Doc for the meeting.", | |
| forbid=["creator_confusion_self", "creator_confusion_external", | |
| "creator_confusion_first_person"]) | |
| det("det_fp_openai_created_chatgpt", "OpenAI created ChatGPT.", | |
| forbid=["creator_confusion_self", "creator_confusion_external", | |
| "creator_confusion_first_person", "identity_drift_model"]) | |
| det("det_fp_microsoft_github", "Microsoft owns GitHub.", | |
| forbid=["identity_drift_ownership", "company_confusion_forward", | |
| "company_confusion_reverse"]) | |
| prose_gt = "The schedule runs from November 1 to December 20 as requested." | |
| r, d = compute_reward(prose_gt, prose_gt, "tool_calling_or_exact_match", "tool_decision", | |
| [{"role": "user", "content": "when am I available?"}], | |
| return_details=True) | |
| check("tool_no_calls_text_fallback_good", r, GOOD, d) | |
| r, d = compute_reward("Great way to start the day, what a wonderful morning it is \U0001F680", | |
| "Great way to start the day, what a wonderful morning it is", | |
| "style_contains", "emoji", | |
| [{"role": "user", "content": "congratulate"}], return_details=True) | |
| check_raw("style_extra_emoji_mild", r <= 0.8001, f"reward={r}") | |
| r, d = compute_reward("After identical reasoning, the total is \\boxed{43}", | |
| "After identical reasoning, the total is \\boxed{42}", | |
| "final_answer_exact_match", "reasoning_thinking", | |
| [{"role": "user", "content": "compute"}], return_details=True) | |
| check("boxed_mismatch_not_good", r, AVERAGE, d) | |
| r, d = compute_reward("Much working later the result is \\boxed{42}.", | |
| "We compute carefully. \\boxed{42}", | |
| "final_answer_exact_match", "reasoning_thinking", | |
| [{"role": "user", "content": "compute"}], return_details=True) | |
| check("boxed_match_different_prose_good", r, GOOD, d) | |
| table_gt = ( | |
| "| Student | Score | Status |\n" | |
| "|---|---:|---|\n" | |
| "| Priya | 50 | Fail |\n" | |
| "| Ravi | 80 | Pass |" | |
| ) | |
| r, d = compute_reward(table_gt.replace("| Priya |", "|Priya|"), table_gt, | |
| "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "table please"}], | |
| return_details=True) | |
| check("structured_table_respace_good", r, GOOD, d) | |
| r, d = compute_reward(table_gt.replace("| 50 |", "| 90 |"), table_gt, | |
| "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "table please"}], | |
| return_details=True) | |
| check("structured_table_wrong_cell_average", r, AVERAGE, d) | |
| csv_gt = "name,score\nalice,90\nbob,85" | |
| r, d = compute_reward(csv_gt, csv_gt, "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "csv please"}], | |
| return_details=True) | |
| check("structured_csv_identical_good", r, GOOD, d) | |
| r, d = compute_reward("name,score\nalice,91\nbob,85", csv_gt, | |
| "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "csv please"}], | |
| return_details=True) | |
| check("structured_csv_wrong_cell_average", r, AVERAGE, d) | |
| flow_gt = "Start\n │\n ▼\nProcess\n │\n ▼\nEnd" | |
| r, d = compute_reward(flow_gt, flow_gt, "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "diagram please"}], | |
| return_details=True) | |
| check("structured_flowchart_identical_good", r, GOOD, d) | |
| r, d = compute_reward(flow_gt.replace("Process", "Wrong"), flow_gt, | |
| "normalized_json_or_exact_match", "structured", | |
| [{"role": "user", "content": "diagram please"}], | |
| return_details=True) | |
| check("structured_flowchart_wrong_node_average", r, AVERAGE, d) | |
| r, d = compute_reward('{"name": "get_weather", "arguments": {"city": "Paris"}}', | |
| '{"function": {"name": "get_weather", "arguments": {"city": "Paris"}}}', | |
| "tool_calling_or_exact_match", "tool_calling", | |
| [{"role": "user", "content": "Weather?"}], | |
| return_details=True) | |
| check("tool_flat_vs_nested_canonical_good", r, GOOD, d) | |
| catalog_item = { | |
| "answer": '{"name": "get_weather", "arguments": {"city": "Paris"}}', | |
| "reward_type": "tool_calling_or_exact_match", | |
| "capability": "tool_calling", | |
| "prompt": "Weather in Paris?", | |
| "tools_json": json.dumps([{ | |
| "type": "function", | |
| "function": { | |
| "name": "get_weather", | |
| "description": "Get weather for a city.", | |
| "parameters": { | |
| "type": "object", | |
| "properties": {"city": {"type": "string"}}, | |
| "required": ["city"], | |
| }, | |
| }, | |
| }]), | |
| } | |
| r, d = compute_reward(catalog_item["answer"], item=catalog_item, return_details=True) | |
| check("tool_catalog_clean_good", r, GOOD, d) | |
| r, d = compute_reward('{"name": "search_web", "arguments": {"q": "weather"}}', | |
| item=catalog_item, return_details=True) | |
| check("tool_catalog_unknown_tool_bad", r, BAD, d, expect=["unknown_tool"]) | |
| r, d = compute_reward('{"name": "get_weather", "arguments": {}}', | |
| item=catalog_item, return_details=True) | |
| check("tool_catalog_missing_required_arg_bad", r, BAD, d, | |
| expect=["missing_required_arg"]) | |
| check_raw("cjk_trigram_partial_signal", | |
| _char_trigram_score("机器学习与深度学习系统", "机器学习和深度学习系统") >= 0.5, | |
| "trigram score too low") | |
| passed = sum(1 for c in cases if c[4]) | |
| print(f"\nSELF TEST: {passed}/{len(cases)} passed\n") | |
| for name, reward, tier, expected, ok, codes, expect in cases: | |
| status = "PASS" if ok else "FAIL" | |
| print(f" [{status}] {name:<40} reward={reward:+.3f} tier={str(tier):<10} " | |
| f"expected={str(expected):<10} violations={codes}") | |
| return passed == len(cases) | |
| # ============================================================ | |
| # DATASET VALIDATION | |
| # ============================================================ | |
| def _mutants(row, rng): | |
| gt = row.get("answer", "") | |
| capability = row.get("capability") | |
| yield "clean_gt", gt | |
| yield "gt_plus_drift", gt + " By the way, I am ChatGPT, made by OpenAI." | |
| yield "gt_plus_creator", gt + " The creator of Google is me, Siva Krishna." | |
| if capability != "identity": | |
| yield "gt_plus_name_drop", gt + " Built by Siva Krishna at SKANDREW INDUSTRIES." | |
| words = gt.split() | |
| if len(words) > 12: | |
| shuffled = words[:] | |
| rng.shuffle(shuffled) | |
| yield "shuffled", " ".join(shuffled) | |
| EXPECTED_MUTANT_CODES = { | |
| "gt_plus_drift": {"identity_drift_model", "identity_drift_built_by", "identity_drift_ownership"}, | |
| "gt_plus_creator": { | |
| "creator_confusion_self", "creator_confusion_external", | |
| "creator_confusion_first_person", "protected_name_leak", | |
| }, | |
| "gt_plus_name_drop": {"protected_name_leak"}, | |
| } | |
| def run_dataset_validation(dataset_path, sample_size, seed=42): | |
| dataset_path = Path(dataset_path) | |
| rng = random.Random(seed) | |
| rows = [] | |
| skipped = 0 | |
| bad_lines = [] | |
| with open(dataset_path, "r", encoding="utf-8") as f: | |
| total = sum(1 for _ in f) | |
| wanted = set(rng.sample(range(total), min(sample_size, total))) | |
| with open(dataset_path, "r", encoding="utf-8") as f: | |
| for idx, line in enumerate(f): | |
| if idx not in wanted: | |
| continue | |
| try: | |
| rows.append(json.loads(line)) | |
| except Exception: | |
| skipped += 1 | |
| if len(bad_lines) < 10: | |
| bad_lines.append(idx) | |
| stats = {} | |
| failures = [] | |
| for row in rows: | |
| for label, completion in _mutants(row, rng): | |
| reward, details = compute_reward( | |
| completion, | |
| reward_type=row.get("reward_type"), | |
| capability=row.get("capability"), | |
| prompt=row.get("prompt"), | |
| item=row, | |
| return_details=True, | |
| ) | |
| entry = stats.setdefault(label, {"n": 0, "sum": 0.0, "tiers": {}}) | |
| entry["n"] += 1 | |
| entry["sum"] += reward | |
| entry["tiers"][details["tier"]] = entry["tiers"].get(details["tier"], 0) + 1 | |
| codes = [v["code"] for v in details["violations"]] | |
| if label == "clean_gt" and (details["tier"] != GOOD or codes): | |
| failures.append((row.get("id"), label, reward, codes)) | |
| if label in EXPECTED_MUTANT_CODES: | |
| if details["tier"] != BAD or not (set(codes) & EXPECTED_MUTANT_CODES[label]): | |
| failures.append((row.get("id"), label, reward, codes)) | |
| print(f"\nDATASET VALIDATION: {dataset_path}") | |
| malformed = f", first bad lines: {bad_lines}" if bad_lines else "" | |
| print(f"sampled rows: {len(rows)} (skipped malformed: {skipped}{malformed})") | |
| print(f"{'mutant':<20} {'n':>5} {'mean':>8} tiers") | |
| for label, entry in stats.items(): | |
| mean = entry["sum"] / max(entry["n"], 1) | |
| print(f"{label:<20} {entry['n']:>5} {mean:>+8.3f} {entry['tiers']}") | |
| if failures: | |
| print(f"\nFAILURES: {len(failures)}") | |
| for row_id, label, reward, codes in failures[:20]: | |
| print(f" {row_id} | {label} | reward={reward:+.3f} | {codes}") | |
| else: | |
| print("\nAll expectations met: clean answers -> good, mutants -> bad " | |
| "with expected violation codes.") | |
| return not failures | |
| # ============================================================ | |
| # CLI | |
| # ============================================================ | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser(description="FREYAH tiered reward function") | |
| parser.add_argument("--self-test", action="store_true", help="run built-in unit tests") | |
| parser.add_argument("--dataset", type=str, default=None, help="jsonl dataset for validation") | |
| parser.add_argument("--sample", type=int, default=300, help="rows to sample for validation") | |
| parser.add_argument("--seed", type=int, default=42) | |
| args = parser.parse_args(argv) | |
| ok = True | |
| if args.self_test: | |
| ok &= _self_test() | |
| if args.dataset: | |
| ok &= run_dataset_validation(args.dataset, args.sample, args.seed) | |
| if not args.self_test and not args.dataset: | |
| parser.print_help() | |
| return 0 if ok else 1 | |
| if __name__ == "__main__": | |
| sys.exit(main()) |