fix(rewards): 3 bugs from Cell 8 audit — push length/formal, SQL domain, extraction int check
Browse files
notebooks/v4_2_instruct_grpo.ipynb
CHANGED
|
@@ -80,14 +80,490 @@
|
|
| 80 |
{
|
| 81 |
"cell_type": "markdown",
|
| 82 |
"metadata": {},
|
| 83 |
-
"source":
|
|
|
|
|
|
|
| 84 |
},
|
| 85 |
{
|
| 86 |
"cell_type": "code",
|
| 87 |
"execution_count": null,
|
| 88 |
"metadata": {},
|
| 89 |
"outputs": [],
|
| 90 |
-
"source": "import json_repair # V4.1: robust JSON parser for LLM output\n\n\ndef strip_think(text: str) -> str:\n \"\"\"Remove <think>...</think> block, return the answer portion.\"\"\"\n return re.sub(r\"<think>.*?</think>\", \"\", text, flags=re.DOTALL).strip()\n\n\ndef has_think_block(text: str) -> bool:\n return bool(re.search(r\"<think>.+</think>\", text, flags=re.DOTALL))\n\n\ndef _classify_task_type(prompt_text: str) -> str:\n p = prompt_text.lower()\n if \"retorne um objeto json\" in p or \"extraia dados\" in p or \"json\" in p:\n return \"extraction\"\n elif \"notificação push\" in p or \"notificação de reengajamento\" in p:\n return \"push\"\n elif \"perfil do cliente\" in p or \"retenção\" in p or \"análise\" in p or \"insight\" in p:\n return \"insights\"\n else:\n return \"sql_qa\"\n\n\n# ══════════════════════════════════════════════════════════════════════════════\n# V4.1: ROBUST JSON PARSER (unchanged)\n# ══════════════════════════════════════════════════════════════════════════════\n\ndef _normalize_pt_decimals(s: str) -> str:\n \"\"\"Convert PT-BR decimals (4,5) to JSON-valid (4.5), only outside quoted strings.\"\"\"\n result, in_string, escape_next = [], False, False\n i = 0\n while i < len(s):\n c = s[i]\n if escape_next:\n result.append(c); escape_next = False; i += 1; continue\n if c == '\\\\' and in_string:\n result.append(c); escape_next = True; i += 1; continue\n if c == '\"':\n in_string = not in_string; result.append(c); i += 1; continue\n if not in_string:\n m = re.match(r'(\\d+),(\\d+)', s[i:])\n if m:\n result.append(m.group(1) + '.' + m.group(2))\n i += len(m.group(0)); continue\n result.append(c); i += 1\n return ''.join(result)\n\n\ndef _extract_json(text: str) -> dict | None:\n \"\"\"Robust JSON extraction for Portuguese LLM output.\"\"\"\n stripped = re.sub(r'^```(?:json)?\\s*|\\s*```$', '', text.strip(), flags=re.MULTILINE).strip()\n for attempt in [stripped, _normalize_pt_decimals(stripped)]:\n try:\n result = json.loads(attempt)\n if isinstance(result, dict):\n return result\n except (json.JSONDecodeError, TypeError):\n pass\n normalized = _normalize_pt_decimals(stripped)\n try:\n result = json_repair.repair_json(normalized, return_objects=True)\n if isinstance(result, dict):\n return result\n except Exception:\n pass\n try:\n result = json_repair.repair_json(stripped, return_objects=True)\n if isinstance(result, dict):\n return result\n except Exception:\n pass\n return None\n\n\ndef reward_extraction(completion: str) -> float:\n \"\"\"Continuous reward for extraction tasks (max 1.0). Unchanged from V4.1.\"\"\"\n answer = strip_think(completion)\n data = _extract_json(answer)\n\n if data is None:\n if \"{\" in answer and \"}\" in answer:\n return 0.05\n return 0.0\n\n if not isinstance(data, dict):\n return 0.1\n\n score = 0.3 # valid JSON object\n\n # Schema completeness (0.3 total)\n present = sum(1 for f in EXTRACTION_FIELDS if f in data)\n score += 0.3 * (present / len(EXTRACTION_FIELDS))\n\n # Value validity (0.4 total)\n checks_passed = 0\n checks_total = 0\n\n for field, validator in [\n (\"sentiment\", lambda v: isinstance(v, str) and v in VALID_SENTIMENTS),\n (\"complaint_category\", lambda v: isinstance(v, str) and v in VALID_CATEGORIES),\n (\"churn_risk\", lambda v: isinstance(v, str) and v in VALID_CHURN),\n (\"repeat_intent\", lambda v: isinstance(v, str) and v in VALID_REPEAT),\n (\"sentiment_score\", lambda v: isinstance(v, (int, float)) and 1 <= v <= 5),\n ]:\n checks_total += 1\n if field in data and validator(data[field]):\n checks_passed += 1\n\n for bool_field in (\"delivery_issue\", \"product_issue\", \"seller_issue\", \"would_recommend\"):\n checks_total += 1\n if bool_field in data and isinstance(data[bool_field], bool):\n checks_passed += 1\n\n if checks_total > 0:\n score += 0.4 * (checks_passed / checks_total)\n\n return min(score, 1.0)\n\n\n# ══════════════════════════════════════════════════════════════════════════════\n# V4.2: SQL REWARD V2 — Validation-aware (Change 3)\n# Replaces heuristic vocabulary matching with structural analysis.\n# Expected: distinguishes \"mentions SQL keywords\" from \"produces correct answer\"\n# ══════════════════════════════════════════════════════════════════════════════\n\ndef reward_sql_qa(completion: str) -> float:\n \"\"\"V4.2: Validation-aware SQL Q&A reward (max 1.0).\n \n Tier 1 (0.30): SQL structure detected (≥3 keywords or code block)\n Tier 2 (0.25): Answer has both query and explanation\n Tier 3 (0.25): Numerical specificity (concrete data)\n Tier 4 (0.20): Portuguese business domain coherence\n \"\"\"\n answer = strip_think(completion)\n if not answer.strip():\n return 0.0\n\n score = 0.0\n\n # Tier 1 (0.30): SQL structure detected\n sql_keywords = [\"SELECT\", \"FROM\", \"WHERE\", \"GROUP BY\", \"ORDER BY\",\n \"JOIN\", \"HAVING\", \"COUNT\", \"AVG\", \"SUM\"]\n sql_found = sum(1 for kw in sql_keywords if kw in answer.upper())\n if sql_found >= 3:\n score += 0.30\n elif sql_found >= 1:\n score += 0.15\n\n # Tier 2 (0.25): Answer has both query AND explanation\n has_query = bool(re.search(r\"```sql|SELECT.{5,}FROM\", answer, re.IGNORECASE | re.DOTALL))\n has_answer = any(w in answer.lower() for w in [\"resultado\", \"total\", \"média\", \"mostra\", \"portanto\"])\n if has_query and has_answer:\n score += 0.25\n elif has_query or has_answer:\n score += 0.12\n\n # Tier 3 (0.25): Numerical specificity\n numbers = re.findall(r\"\\d+(?:[.,]\\d+)?(?:\\s*%)?\", answer)\n score += min(0.25, 0.05 * len(numbers))\n\n # Tier 4 (0.20): Portuguese business domain coherence\n pt_domain = [\"pedidos\", \"clientes\", \"vendedores\", \"produtos\", \"avaliação\",\n \"entrega\", \"reclamação\", \"satisfação\", \"categoria\", \"período\"]\n score += min(0.20, 0.04 * sum(1 for w in pt_domain if w in answer.lower()))\n\n return min(score, 1.0)\n\n\ndef reward_insights(completion: str) -> float:\n \"\"\"Continuous reward for insights (max 1.0). Unchanged from V4.1.\"\"\"\n answer = strip_think(completion)\n if not answer.strip():\n return 0.0\n\n score = 0.0\n\n action_words = [\"recomend\", \"implement\", \"melhor\", \"reduzir\", \"aumentar\",\n \"priorizar\", \"investir\", \"otimizar\", \"estratégi\", \"ação\"]\n matches = sum(1 for w in action_words if w in answer.lower())\n score += min(0.4, 0.08 * matches)\n\n length = len(answer)\n if 100 <= length <= 800:\n score += 0.3\n elif length > 0:\n score += 0.3 * max(0, 1 - abs(length - 450) / 450)\n\n structure_marks = len(re.findall(r\"^[-•*]\\s|^\\d+[.)]\\s|^#{1,3}\\s\", answer, re.MULTILINE))\n score += min(0.2, 0.04 * structure_marks)\n\n if any(w in answer.lower() for w in [\"cliente\", \"produto\", \"serviço\", \"empresa\"]):\n score += 0.1\n\n return min(score, 1.0)\n\n\ndef reward_push(completion: str) -> float:\n \"\"\"Continuous reward for push notifications (max 1.0). Unchanged from V4.1.\"\"\"\n answer = strip_think(completion).strip()\n if not answer:\n return 0.0\n\n length = len(answer)\n if length <= 120:\n length_score = 0.5\n else:\n length_score = 0.5 * max(0, 1 - (length - 120) / 120)\n\n pt_markers = re.findall(r\"[ãçéêóúâõ]|você|para|como|seu|sua|oferta|desconto|produto\",\n answer, re.IGNORECASE)\n lang_score = min(0.3, 0.03 * len(pt_markers))\n\n generic = [\"olá\", \"obrigado pela compra\", \"agradecemos\"]\n is_generic = any(g in answer.lower() for g in generic)\n creativity_score = 0.0 if is_generic else 0.2\n\n return min(length_score + lang_score + creativity_score, 1.0)\n\n\n# ══════════════════════════════════════════════════════════════════════════════\n# V4.2: GDPO PER-COMPONENT NORMALIZATION (Change 5)\n# Normalize each reward component independently before aggregation.\n# GDPO (2601.05242) §3.1: preserves ~4× more distinct advantage groups.\n# ══════════════════════════════════════════════════════════════════════════════\n\ndef gdpo_normalize(component_rewards: dict) -> list:\n \"\"\"Per-component normalization before aggregation (GDPO 2601.05242 §3.1).\n \n Args:\n component_rewards: {task_name: [reward_per_sample, ...]} for each component\n \n Returns:\n List of normalized summed rewards, one per sample.\n \"\"\"\n normalized = {}\n for task, rewards in component_rewards.items():\n rewards_t = torch.tensor(rewards, dtype=torch.float32)\n std = rewards_t.std()\n if std > 1e-8:\n normalized[task] = ((rewards_t - rewards_t.mean()) / std).tolist()\n else:\n normalized[task] = [0.0] * len(rewards) # zero-variance group\n # Sum normalized components per sample\n n = len(next(iter(normalized.values())))\n return [sum(normalized[t][i] for t in normalized) for i in range(n)]\n\n\n# ══════════════════════════════════════════════════════════════════════════════\n# V4.2: DYNAMIC TASK WEIGHTING — MT-GRPO IWU (Change 6)\n# Track per-task reward improvement rates, upweight stagnating tasks.\n# MT-GRPO (2602.05547) §3.2: prevents easy-task collapse.\n# ══════════════════════════════════════════════════════════════════════════════\n\n_task_weights = {\n \"extraction\": 0.40, # matches training data distribution (40%)\n \"sql_qa\": 0.40, # matches training data distribution (40%)\n \"insights\": 0.10, # matches training data distribution (10%)\n \"push\": 0.10, # matches training data distribution (10%)\n}\n_task_reward_history = {t: [] for t in _task_weights}\n\ndef update_task_weights(step: int, per_task_rewards: dict, update_interval: int = 50):\n \"\"\"MT-GRPO IWU: update task sampling weights based on improvement rate.\n \n Args:\n step: Current training step\n per_task_rewards: {task: mean_reward} from latest eval\n update_interval: Only update every N steps\n \"\"\"\n global _task_weights\n if step % update_interval != 0 or step == 0:\n return\n \n for task, reward in per_task_rewards.items():\n if task not in _task_reward_history:\n continue\n _task_reward_history[task].append(reward)\n if len(_task_reward_history[task]) >= 2:\n improvement = _task_reward_history[task][-1] - _task_reward_history[task][-2]\n if improvement < 0.01: # stagnating\n _task_weights[task] = min(0.60, _task_weights[task] * 1.3)\n elif improvement > 0.05: # improving fast\n _task_weights[task] = max(0.10, _task_weights[task] * 0.85)\n \n # Normalize to sum to 1\n total = sum(_task_weights.values())\n _task_weights = {t: w / total for t, w in _task_weights.items()}\n\n\ndef get_task_weighted_indices(dataset, n_samples: int) -> list:\n \"\"\"Sample indices with probability proportional to task weights.\"\"\"\n task_indices = {t: [] for t in _task_weights}\n for i, record in enumerate(dataset):\n user_txt = \" \".join(m[\"content\"] for m in record[\"prompt\"] if m[\"role\"] == \"user\")\n task = _classify_task_type(user_txt)\n if task in task_indices:\n task_indices[task].append(i)\n \n sampled = []\n for task, weight in _task_weights.items():\n n = max(1, int(n_samples * weight))\n pool = task_indices.get(task, [])\n if pool:\n sampled.extend(random.sample(pool, min(n, len(pool))))\n random.shuffle(sampled)\n return sampled[:n_samples]\n\n\n# ══════════════════════════════════════════════════════════════════════════════\n# MASTER REWARD FUNCTION — V4.2: returns per-component rewards for GDPO\n# ══════════════════════════════════════════════════════════════════════════════\n\ndef commerce_reward_fn(completions, prompts, **kwargs) -> list:\n \"\"\"Master reward function with GDPO normalization + dynamic task weighting.\n \n V4.2 integration with TRL 0.24.0:\n TRL calls this once per step with the full batch (batch_size × G completions).\n We exploit this to apply batch-level per-component normalization (GDPO §3.1)\n and dynamic task weighting (MT-GRPO IWU §3.2) INSIDE the reward function,\n so the trainer receives pre-normalized, weighted rewards without modification.\n \n Pipeline:\n 1. Score each completion with its task-specific reward function (raw)\n 2. Group raw rewards by task type\n 3. GDPO: z-score normalize each task group independently\n 4. IWU: multiply normalized rewards by current _task_weights\n 5. Shift back to [0, 1] range (GRPO with scale_rewards=False expects non-negative)\n 6. Return flat list in original sample order\n \"\"\"\n n = len(completions)\n raw_rewards = [0.0] * n\n task_labels = [\"\"] * n\n \n # ── Step 1: Compute raw per-sample rewards ──────────────────────────────\n for i, (completion, prompt) in enumerate(zip(completions, prompts)):\n if isinstance(completion, list):\n comp_text = completion[-1][\"content\"] if completion else \"\"\n else:\n comp_text = str(completion)\n\n if isinstance(prompt, list):\n prompt_text = \" \".join(m.get(\"content\", \"\") for m in prompt)\n else:\n prompt_text = str(prompt)\n\n task = _classify_task_type(prompt_text)\n task_labels[i] = task\n\n if task == \"extraction\":\n raw_rewards[i] = reward_extraction(comp_text)\n elif task == \"sql_qa\":\n raw_rewards[i] = reward_sql_qa(comp_text)\n elif task == \"insights\":\n raw_rewards[i] = reward_insights(comp_text)\n elif task == \"push\":\n raw_rewards[i] = reward_push(comp_text)\n else:\n raw_rewards[i] = 0.2 if comp_text.strip() else 0.0\n\n # ── Step 2-4: GDPO per-component normalization + IWU weighting ──────────\n # Group indices by task\n task_indices = {}\n for i, task in enumerate(task_labels):\n if task not in task_indices:\n task_indices[task] = []\n task_indices[task].append(i)\n \n final_rewards = [0.0] * n\n \n for task, indices in task_indices.items():\n task_raw = [raw_rewards[i] for i in indices]\n \n # GDPO: z-score normalize within this task group\n if len(task_raw) > 1:\n t_mean = sum(task_raw) / len(task_raw)\n t_var = sum((r - t_mean) ** 2 for r in task_raw) / (len(task_raw) - 1)\n t_std = t_var ** 0.5\n if t_std > 1e-8:\n normed = [(r - t_mean) / t_std for r in task_raw]\n else:\n normed = [0.0] * len(task_raw)\n else:\n # Single sample in this task group — can't normalize, use raw\n normed = [0.0]\n \n # IWU: scale by dynamic task weight\n weight = _task_weights.get(task, 0.25)\n weighted = [v * weight for v in normed]\n \n for idx_in_group, global_idx in enumerate(indices):\n final_rewards[global_idx] = weighted[idx_in_group]\n \n # ── Step 5: Shift to non-negative range ─────────────────────────────────\n # GRPO with scale_rewards=False computes advantages as reward - mean(rewards).\n # Normalized rewards are already zero-centered per-task, so the advantage\n # computation will work correctly. But TRL may log negative rewards as warnings.\n # Shift so minimum is 0 to keep logging clean, without changing advantage ordering.\n min_r = min(final_rewards) if final_rewards else 0.0\n if min_r < 0:\n final_rewards = [r - min_r for r in final_rewards]\n \n return final_rewards\n\n\ndef commerce_reward_fn_raw(completions, prompts, **kwargs) -> list:\n \"\"\"Raw reward function WITHOUT GDPO/IWU — used for eval metrics.\n \n Eval should report raw task-specific rewards for interpretability.\n The GDPO+IWU normalization is only for shaping the training gradient signal.\n \"\"\"\n rewards = []\n for completion, prompt in zip(completions, prompts):\n if isinstance(completion, list):\n comp_text = completion[-1][\"content\"] if completion else \"\"\n else:\n comp_text = str(completion)\n\n if isinstance(prompt, list):\n prompt_text = \" \".join(m.get(\"content\", \"\") for m in prompt)\n else:\n prompt_text = str(prompt)\n\n task = _classify_task_type(prompt_text)\n\n if task == \"extraction\":\n rewards.append(reward_extraction(comp_text))\n elif task == \"sql_qa\":\n rewards.append(reward_sql_qa(comp_text))\n elif task == \"insights\":\n rewards.append(reward_insights(comp_text))\n elif task == \"push\":\n rewards.append(reward_push(comp_text))\n else:\n r = 0.2 if comp_text.strip() else 0.0\n rewards.append(r)\n return rewards\n\n\nprint(\"✓ Reward functions defined (V4.2: SQL v2 + GDPO active + IWU active)\")\nprint(f\" Task weights: {_task_weights}\")\nprint(f\" commerce_reward_fn: GDPO+IWU normalized (for training)\")\nprint(f\" commerce_reward_fn_raw: raw scores (for eval/audit)\")\nprint(f\" Task weights: {_task_weights}\")"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
},
|
| 92 |
{
|
| 93 |
"cell_type": "markdown",
|
|
|
|
| 80 |
{
|
| 81 |
"cell_type": "markdown",
|
| 82 |
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"---\n\n## Cell 7: Reward Functions V2\n\n**V4.2 changes (Change 3 + Change 5):**\n\n### SQL Reward Overhaul (Change 3)\n- **Tier 1 (0.30):** SQL structure detected — requires ≥3 SQL keywords (SELECT, FROM, WHERE, etc.)\n- **Tier 2 (0.25):** Answer has BOTH query AND explanation (not just domain vocabulary)\n- **Tier 3 (0.25):** Numerical specificity (concrete data in answer)\n- **Tier 4 (0.20):** Portuguese business domain coherence\n\n### GDPO Per-Component Normalization (Change 5) — ACTIVE IN TRAINING\n- `commerce_reward_fn` applies per-task z-score normalization INSIDE the reward call\n- TRL 0.24.0 calls reward_fn with the full batch → we normalize per-component before returning\n- No trainer modification needed — normalized rewards flow through standard GRPO advantage computation\n- Preserves ~4× more distinct advantage groups (GDPO §3.1)\n\n### Dynamic Task Weights (Change 6) — ACTIVE IN TRAINING\n- `_task_weights` dict tracks per-task weights, updated by `update_task_weights()` in eval callback\n- Weights are applied as multiplicative scaling INSIDE `commerce_reward_fn` after GDPO normalization\n- Effect: stagnating tasks (e.g. SQL) get amplified reward signal → larger GRPO advantages → more gradient\n- MT-GRPO IWU §3.2: prevents easy-task collapse without requiring custom sampling\n\n### V4.2.1 Fixes (Cell 8 Audit)\n- **Push reward:** Steep length penalty (hard 0 above 200 chars) + formal email penalty (-0.20 for \"Prezado\"/\"Atenciosamente\")\n- **SQL reward Tier 4:** Expanded domain word list (+20 words: compradores, sentimentos, reclamações, taxa, distribuição, etc.)\n- **Extraction reward:** `sentiment_score` validator requires `isinstance(v, int) and not isinstance(v, bool)` — rejects floats from PT decimal normalization"
|
| 85 |
+
]
|
| 86 |
},
|
| 87 |
{
|
| 88 |
"cell_type": "code",
|
| 89 |
"execution_count": null,
|
| 90 |
"metadata": {},
|
| 91 |
"outputs": [],
|
| 92 |
+
"source": [
|
| 93 |
+
"import json_repair # V4.1: robust JSON parser for LLM output\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"def strip_think(text: str) -> str:\n",
|
| 97 |
+
" \"\"\"Remove <think>...</think> block, return the answer portion.\"\"\"\n",
|
| 98 |
+
" return re.sub(r\"<think>.*?</think>\", \"\", text, flags=re.DOTALL).strip()\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"def has_think_block(text: str) -> bool:\n",
|
| 102 |
+
" return bool(re.search(r\"<think>.+</think>\", text, flags=re.DOTALL))\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"def _classify_task_type(prompt_text: str) -> str:\n",
|
| 106 |
+
" p = prompt_text.lower()\n",
|
| 107 |
+
" if \"retorne um objeto json\" in p or \"extraia dados\" in p or \"json\" in p:\n",
|
| 108 |
+
" return \"extraction\"\n",
|
| 109 |
+
" elif \"notificação push\" in p or \"notificação de reengajamento\" in p:\n",
|
| 110 |
+
" return \"push\"\n",
|
| 111 |
+
" elif \"perfil do cliente\" in p or \"retenção\" in p or \"análise\" in p or \"insight\" in p:\n",
|
| 112 |
+
" return \"insights\"\n",
|
| 113 |
+
" else:\n",
|
| 114 |
+
" return \"sql_qa\"\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 118 |
+
"# V4.1: ROBUST JSON PARSER (unchanged)\n",
|
| 119 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"def _normalize_pt_decimals(s: str) -> str:\n",
|
| 122 |
+
" \"\"\"Convert PT-BR decimals (4,5) to JSON-valid (4.5), only outside quoted strings.\"\"\"\n",
|
| 123 |
+
" result, in_string, escape_next = [], False, False\n",
|
| 124 |
+
" i = 0\n",
|
| 125 |
+
" while i < len(s):\n",
|
| 126 |
+
" c = s[i]\n",
|
| 127 |
+
" if escape_next:\n",
|
| 128 |
+
" result.append(c); escape_next = False; i += 1; continue\n",
|
| 129 |
+
" if c == '\\\\' and in_string:\n",
|
| 130 |
+
" result.append(c); escape_next = True; i += 1; continue\n",
|
| 131 |
+
" if c == '\"':\n",
|
| 132 |
+
" in_string = not in_string; result.append(c); i += 1; continue\n",
|
| 133 |
+
" if not in_string:\n",
|
| 134 |
+
" m = re.match(r'(\\d+),(\\d+)', s[i:])\n",
|
| 135 |
+
" if m:\n",
|
| 136 |
+
" result.append(m.group(1) + '.' + m.group(2))\n",
|
| 137 |
+
" i += len(m.group(0)); continue\n",
|
| 138 |
+
" result.append(c); i += 1\n",
|
| 139 |
+
" return ''.join(result)\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"def _extract_json(text: str) -> dict | None:\n",
|
| 143 |
+
" \"\"\"Robust JSON extraction for Portuguese LLM output.\"\"\"\n",
|
| 144 |
+
" stripped = re.sub(r'^```(?:json)?\\s*|\\s*```$', '', text.strip(), flags=re.MULTILINE).strip()\n",
|
| 145 |
+
" for attempt in [stripped, _normalize_pt_decimals(stripped)]:\n",
|
| 146 |
+
" try:\n",
|
| 147 |
+
" result = json.loads(attempt)\n",
|
| 148 |
+
" if isinstance(result, dict):\n",
|
| 149 |
+
" return result\n",
|
| 150 |
+
" except (json.JSONDecodeError, TypeError):\n",
|
| 151 |
+
" pass\n",
|
| 152 |
+
" normalized = _normalize_pt_decimals(stripped)\n",
|
| 153 |
+
" try:\n",
|
| 154 |
+
" result = json_repair.repair_json(normalized, return_objects=True)\n",
|
| 155 |
+
" if isinstance(result, dict):\n",
|
| 156 |
+
" return result\n",
|
| 157 |
+
" except Exception:\n",
|
| 158 |
+
" pass\n",
|
| 159 |
+
" try:\n",
|
| 160 |
+
" result = json_repair.repair_json(stripped, return_objects=True)\n",
|
| 161 |
+
" if isinstance(result, dict):\n",
|
| 162 |
+
" return result\n",
|
| 163 |
+
" except Exception:\n",
|
| 164 |
+
" pass\n",
|
| 165 |
+
" return None\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"def reward_extraction(completion: str) -> float:\n",
|
| 169 |
+
" \"\"\"Continuous reward for extraction tasks (max 1.0). Unchanged from V4.1.\"\"\"\n",
|
| 170 |
+
" answer = strip_think(completion)\n",
|
| 171 |
+
" data = _extract_json(answer)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" if data is None:\n",
|
| 174 |
+
" if \"{\" in answer and \"}\" in answer:\n",
|
| 175 |
+
" return 0.05\n",
|
| 176 |
+
" return 0.0\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" if not isinstance(data, dict):\n",
|
| 179 |
+
" return 0.1\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" score = 0.3 # valid JSON object\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" # Schema completeness (0.3 total)\n",
|
| 184 |
+
" present = sum(1 for f in EXTRACTION_FIELDS if f in data)\n",
|
| 185 |
+
" score += 0.3 * (present / len(EXTRACTION_FIELDS))\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" # Value validity (0.4 total)\n",
|
| 188 |
+
" checks_passed = 0\n",
|
| 189 |
+
" checks_total = 0\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" for field, validator in [\n",
|
| 192 |
+
" (\"sentiment\", lambda v: isinstance(v, str) and v in VALID_SENTIMENTS),\n",
|
| 193 |
+
" (\"complaint_category\", lambda v: isinstance(v, str) and v in VALID_CATEGORIES),\n",
|
| 194 |
+
" (\"churn_risk\", lambda v: isinstance(v, str) and v in VALID_CHURN),\n",
|
| 195 |
+
" (\"repeat_intent\", lambda v: isinstance(v, str) and v in VALID_REPEAT),\n",
|
| 196 |
+
" # V4.2.1: must be int, not float/bool. PT normalizer turns \"0,5\"→0.5 (float)\n",
|
| 197 |
+
" (\"sentiment_score\", lambda v: isinstance(v, int) and not isinstance(v, bool) and 1 <= v <= 5),\n",
|
| 198 |
+
" ]:\n",
|
| 199 |
+
" checks_total += 1\n",
|
| 200 |
+
" if field in data and validator(data[field]):\n",
|
| 201 |
+
" checks_passed += 1\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" for bool_field in (\"delivery_issue\", \"product_issue\", \"seller_issue\", \"would_recommend\"):\n",
|
| 204 |
+
" checks_total += 1\n",
|
| 205 |
+
" if bool_field in data and isinstance(data[bool_field], bool):\n",
|
| 206 |
+
" checks_passed += 1\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" if checks_total > 0:\n",
|
| 209 |
+
" score += 0.4 * (checks_passed / checks_total)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" return min(score, 1.0)\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 215 |
+
"# V4.2: SQL REWARD V2 — Validation-aware (Change 3)\n",
|
| 216 |
+
"# Replaces heuristic vocabulary matching with structural analysis.\n",
|
| 217 |
+
"# Expected: distinguishes \"mentions SQL keywords\" from \"produces correct answer\"\n",
|
| 218 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"def reward_sql_qa(completion: str) -> float:\n",
|
| 221 |
+
" \"\"\"V4.2: Validation-aware SQL Q&A reward (max 1.0).\n",
|
| 222 |
+
" \n",
|
| 223 |
+
" Tier 1 (0.30): SQL structure detected (≥3 keywords or code block)\n",
|
| 224 |
+
" Tier 2 (0.25): Answer has both query and explanation\n",
|
| 225 |
+
" Tier 3 (0.25): Numerical specificity (concrete data)\n",
|
| 226 |
+
" Tier 4 (0.20): Portuguese business domain coherence\n",
|
| 227 |
+
" \"\"\"\n",
|
| 228 |
+
" answer = strip_think(completion)\n",
|
| 229 |
+
" if not answer.strip():\n",
|
| 230 |
+
" return 0.0\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" score = 0.0\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" # Tier 1 (0.30): SQL structure detected\n",
|
| 235 |
+
" sql_keywords = [\"SELECT\", \"FROM\", \"WHERE\", \"GROUP BY\", \"ORDER BY\",\n",
|
| 236 |
+
" \"JOIN\", \"HAVING\", \"COUNT\", \"AVG\", \"SUM\"]\n",
|
| 237 |
+
" sql_found = sum(1 for kw in sql_keywords if kw in answer.upper())\n",
|
| 238 |
+
" if sql_found >= 3:\n",
|
| 239 |
+
" score += 0.30\n",
|
| 240 |
+
" elif sql_found >= 1:\n",
|
| 241 |
+
" score += 0.15\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" # Tier 2 (0.25): Answer has both query AND explanation\n",
|
| 244 |
+
" has_query = bool(re.search(r\"```sql|SELECT.{5,}FROM\", answer, re.IGNORECASE | re.DOTALL))\n",
|
| 245 |
+
" has_answer = any(w in answer.lower() for w in [\"resultado\", \"total\", \"média\", \"mostra\", \"portanto\"])\n",
|
| 246 |
+
" if has_query and has_answer:\n",
|
| 247 |
+
" score += 0.25\n",
|
| 248 |
+
" elif has_query or has_answer:\n",
|
| 249 |
+
" score += 0.12\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" # Tier 3 (0.25): Numerical specificity\n",
|
| 252 |
+
" numbers = re.findall(r\"\\d+(?:[.,]\\d+)?(?:\\s*%)?\", answer)\n",
|
| 253 |
+
" score += min(0.25, 0.05 * len(numbers))\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" # Tier 4 (0.20): Portuguese business domain coherence — EXPANDED (V4.2.1)\n",
|
| 256 |
+
" pt_domain = [\n",
|
| 257 |
+
" # Original 10\n",
|
| 258 |
+
" \"pedidos\", \"clientes\", \"vendedores\", \"produtos\", \"avaliação\",\n",
|
| 259 |
+
" \"entrega\", \"reclamação\", \"satisfação\", \"categoria\", \"período\",\n",
|
| 260 |
+
" # V4.2.1: broader e-commerce vocabulary (Cell 8 audit: samples 6, 10)\n",
|
| 261 |
+
" \"compradores\", \"sentimentos\", \"reclamações\", \"taxa\", \"distribuição\",\n",
|
| 262 |
+
" \"vendas\", \"faturamento\", \"estoque\", \"logística\", \"marketplace\",\n",
|
| 263 |
+
" \"consumidores\", \"fornecedores\", \"devoluções\", \"reembolso\", \"frete\",\n",
|
| 264 |
+
" \"pagamento\", \"cancelamento\", \"atraso\", \"qualidade\", \"nota\",\n",
|
| 265 |
+
" \"positivos\", \"negativos\", \"neutros\", \"tendência\", \"desempenho\",\n",
|
| 266 |
+
" ]\n",
|
| 267 |
+
" score += min(0.20, 0.04 * sum(1 for w in pt_domain if w in answer.lower()))\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" return min(score, 1.0)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"\n",
|
| 272 |
+
"def reward_insights(completion: str) -> float:\n",
|
| 273 |
+
" \"\"\"Continuous reward for insights (max 1.0). Unchanged from V4.1.\"\"\"\n",
|
| 274 |
+
" answer = strip_think(completion)\n",
|
| 275 |
+
" if not answer.strip():\n",
|
| 276 |
+
" return 0.0\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" score = 0.0\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" action_words = [\"recomend\", \"implement\", \"melhor\", \"reduzir\", \"aumentar\",\n",
|
| 281 |
+
" \"priorizar\", \"investir\", \"otimizar\", \"estratégi\", \"ação\"]\n",
|
| 282 |
+
" matches = sum(1 for w in action_words if w in answer.lower())\n",
|
| 283 |
+
" score += min(0.4, 0.08 * matches)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
" length = len(answer)\n",
|
| 286 |
+
" if 100 <= length <= 800:\n",
|
| 287 |
+
" score += 0.3\n",
|
| 288 |
+
" elif length > 0:\n",
|
| 289 |
+
" score += 0.3 * max(0, 1 - abs(length - 450) / 450)\n",
|
| 290 |
+
"\n",
|
| 291 |
+
" structure_marks = len(re.findall(r\"^[-•*]\\s|^\\d+[.)]\\s|^#{1,3}\\s\", answer, re.MULTILINE))\n",
|
| 292 |
+
" score += min(0.2, 0.04 * structure_marks)\n",
|
| 293 |
+
"\n",
|
| 294 |
+
" if any(w in answer.lower() for w in [\"cliente\", \"produto\", \"serviço\", \"empresa\"]):\n",
|
| 295 |
+
" score += 0.1\n",
|
| 296 |
+
"\n",
|
| 297 |
+
" return min(score, 1.0)\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"def reward_push(completion: str) -> float:\n",
|
| 301 |
+
" \"\"\"Continuous reward for push notifications (max 1.0).\n",
|
| 302 |
+
" \n",
|
| 303 |
+
" V4.2.1 fixes (Cell 8 audit):\n",
|
| 304 |
+
" - Steep length penalty: hard zero above 200 chars (was linear decay to 240)\n",
|
| 305 |
+
" - Formal email penalty: -0.20 for \"Prezado\"/\"Atenciosamente\"/etc.\n",
|
| 306 |
+
" \"\"\"\n",
|
| 307 |
+
" answer = strip_think(completion).strip()\n",
|
| 308 |
+
" if not answer:\n",
|
| 309 |
+
" return 0.0\n",
|
| 310 |
+
"\n",
|
| 311 |
+
" length = len(answer)\n",
|
| 312 |
+
"\n",
|
| 313 |
+
" # Length score (0.50 max) — steep decay above 120 chars\n",
|
| 314 |
+
" if length <= 120:\n",
|
| 315 |
+
" length_score = 0.50\n",
|
| 316 |
+
" elif length <= 160:\n",
|
| 317 |
+
" length_score = 0.50 - 0.40 * ((length - 120) / 40) # 0.50 → 0.10\n",
|
| 318 |
+
" elif length <= 200:\n",
|
| 319 |
+
" length_score = 0.10 - 0.10 * ((length - 160) / 40) # 0.10 → 0.00\n",
|
| 320 |
+
" else:\n",
|
| 321 |
+
" length_score = 0.0\n",
|
| 322 |
+
"\n",
|
| 323 |
+
" pt_markers = re.findall(r\"[ãçéêóúâõ]|você|para|como|seu|sua|oferta|desconto|produto\",\n",
|
| 324 |
+
" answer, re.IGNORECASE)\n",
|
| 325 |
+
" lang_score = min(0.3, 0.03 * len(pt_markers))\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" generic = [\"olá\", \"obrigado pela compra\", \"agradecemos\"]\n",
|
| 328 |
+
" is_generic = any(g in answer.lower() for g in generic)\n",
|
| 329 |
+
" creativity_score = 0.0 if is_generic else 0.2\n",
|
| 330 |
+
"\n",
|
| 331 |
+
" # Formal email penalty — push notifications should NOT be formal emails\n",
|
| 332 |
+
" formal_markers = [\n",
|
| 333 |
+
" \"prezado\", \"prezada\", \"atenciosamente\", \"cordialmente\",\n",
|
| 334 |
+
" \"att,\", \"att.\", \"respeitosamente\", \"caro cliente\", \"cara cliente\",\n",
|
| 335 |
+
" ]\n",
|
| 336 |
+
" has_formal = any(fm in answer.lower() for fm in formal_markers)\n",
|
| 337 |
+
" formal_penalty = -0.20 if has_formal else 0.0\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" return max(0.0, min(length_score + lang_score + creativity_score + formal_penalty, 1.0))\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 343 |
+
"# V4.2: GDPO PER-COMPONENT NORMALIZATION (Change 5)\n",
|
| 344 |
+
"# Normalize each reward component independently before aggregation.\n",
|
| 345 |
+
"# GDPO (2601.05242) §3.1: preserves ~4× more distinct advantage groups.\n",
|
| 346 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"def gdpo_normalize(component_rewards: dict) -> list:\n",
|
| 349 |
+
" \"\"\"Per-component normalization before aggregation (GDPO 2601.05242 §3.1).\n",
|
| 350 |
+
" \n",
|
| 351 |
+
" Args:\n",
|
| 352 |
+
" component_rewards: {task_name: [reward_per_sample, ...]} for each component\n",
|
| 353 |
+
" \n",
|
| 354 |
+
" Returns:\n",
|
| 355 |
+
" List of normalized summed rewards, one per sample.\n",
|
| 356 |
+
" \"\"\"\n",
|
| 357 |
+
" normalized = {}\n",
|
| 358 |
+
" for task, rewards in component_rewards.items():\n",
|
| 359 |
+
" rewards_t = torch.tensor(rewards, dtype=torch.float32)\n",
|
| 360 |
+
" std = rewards_t.std()\n",
|
| 361 |
+
" if std > 1e-8:\n",
|
| 362 |
+
" normalized[task] = ((rewards_t - rewards_t.mean()) / std).tolist()\n",
|
| 363 |
+
" else:\n",
|
| 364 |
+
" normalized[task] = [0.0] * len(rewards) # zero-variance group\n",
|
| 365 |
+
" # Sum normalized components per sample\n",
|
| 366 |
+
" n = len(next(iter(normalized.values())))\n",
|
| 367 |
+
" return [sum(normalized[t][i] for t in normalized) for i in range(n)]\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 371 |
+
"# V4.2: DYNAMIC TASK WEIGHTING — MT-GRPO IWU (Change 6)\n",
|
| 372 |
+
"# Track per-task reward improvement rates, upweight stagnating tasks.\n",
|
| 373 |
+
"# MT-GRPO (2602.05547) §3.2: prevents easy-task collapse.\n",
|
| 374 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 375 |
+
"\n",
|
| 376 |
+
"_task_weights = {\n",
|
| 377 |
+
" \"extraction\": 0.40, # matches training data distribution (40%)\n",
|
| 378 |
+
" \"sql_qa\": 0.40, # matches training data distribution (40%)\n",
|
| 379 |
+
" \"insights\": 0.10, # matches training data distribution (10%)\n",
|
| 380 |
+
" \"push\": 0.10, # matches training data distribution (10%)\n",
|
| 381 |
+
"}\n",
|
| 382 |
+
"_task_reward_history = {t: [] for t in _task_weights}\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"def update_task_weights(step: int, per_task_rewards: dict, update_interval: int = 50):\n",
|
| 385 |
+
" \"\"\"MT-GRPO IWU: update task sampling weights based on improvement rate.\n",
|
| 386 |
+
" \n",
|
| 387 |
+
" Args:\n",
|
| 388 |
+
" step: Current training step\n",
|
| 389 |
+
" per_task_rewards: {task: mean_reward} from latest eval\n",
|
| 390 |
+
" update_interval: Only update every N steps\n",
|
| 391 |
+
" \"\"\"\n",
|
| 392 |
+
" global _task_weights\n",
|
| 393 |
+
" if step % update_interval != 0 or step == 0:\n",
|
| 394 |
+
" return\n",
|
| 395 |
+
" \n",
|
| 396 |
+
" for task, reward in per_task_rewards.items():\n",
|
| 397 |
+
" if task not in _task_reward_history:\n",
|
| 398 |
+
" continue\n",
|
| 399 |
+
" _task_reward_history[task].append(reward)\n",
|
| 400 |
+
" if len(_task_reward_history[task]) >= 2:\n",
|
| 401 |
+
" improvement = _task_reward_history[task][-1] - _task_reward_history[task][-2]\n",
|
| 402 |
+
" if improvement < 0.01: # stagnating\n",
|
| 403 |
+
" _task_weights[task] = min(0.60, _task_weights[task] * 1.3)\n",
|
| 404 |
+
" elif improvement > 0.05: # improving fast\n",
|
| 405 |
+
" _task_weights[task] = max(0.10, _task_weights[task] * 0.85)\n",
|
| 406 |
+
" \n",
|
| 407 |
+
" # Normalize to sum to 1\n",
|
| 408 |
+
" total = sum(_task_weights.values())\n",
|
| 409 |
+
" _task_weights = {t: w / total for t, w in _task_weights.items()}\n",
|
| 410 |
+
"\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"def get_task_weighted_indices(dataset, n_samples: int) -> list:\n",
|
| 413 |
+
" \"\"\"Sample indices with probability proportional to task weights.\"\"\"\n",
|
| 414 |
+
" task_indices = {t: [] for t in _task_weights}\n",
|
| 415 |
+
" for i, record in enumerate(dataset):\n",
|
| 416 |
+
" user_txt = \" \".join(m[\"content\"] for m in record[\"prompt\"] if m[\"role\"] == \"user\")\n",
|
| 417 |
+
" task = _classify_task_type(user_txt)\n",
|
| 418 |
+
" if task in task_indices:\n",
|
| 419 |
+
" task_indices[task].append(i)\n",
|
| 420 |
+
" \n",
|
| 421 |
+
" sampled = []\n",
|
| 422 |
+
" for task, weight in _task_weights.items():\n",
|
| 423 |
+
" n = max(1, int(n_samples * weight))\n",
|
| 424 |
+
" pool = task_indices.get(task, [])\n",
|
| 425 |
+
" if pool:\n",
|
| 426 |
+
" sampled.extend(random.sample(pool, min(n, len(pool))))\n",
|
| 427 |
+
" random.shuffle(sampled)\n",
|
| 428 |
+
" return sampled[:n_samples]\n",
|
| 429 |
+
"\n",
|
| 430 |
+
"\n",
|
| 431 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 432 |
+
"# MASTER REWARD FUNCTION — V4.2: returns per-component rewards for GDPO\n",
|
| 433 |
+
"# ══════════════════════════════════════════════════════════════════════════════\n",
|
| 434 |
+
"\n",
|
| 435 |
+
"def commerce_reward_fn(completions, prompts, **kwargs) -> list:\n",
|
| 436 |
+
" \"\"\"Master reward function with GDPO normalization + dynamic task weighting.\n",
|
| 437 |
+
" \n",
|
| 438 |
+
" V4.2 integration with TRL 0.24.0:\n",
|
| 439 |
+
" TRL calls this once per step with the full batch (batch_size × G completions).\n",
|
| 440 |
+
" We exploit this to apply batch-level per-component normalization (GDPO §3.1)\n",
|
| 441 |
+
" and dynamic task weighting (MT-GRPO IWU §3.2) INSIDE the reward function,\n",
|
| 442 |
+
" so the trainer receives pre-normalized, weighted rewards without modification.\n",
|
| 443 |
+
" \n",
|
| 444 |
+
" Pipeline:\n",
|
| 445 |
+
" 1. Score each completion with its task-specific reward function (raw)\n",
|
| 446 |
+
" 2. Group raw rewards by task type\n",
|
| 447 |
+
" 3. GDPO: z-score normalize each task group independently\n",
|
| 448 |
+
" 4. IWU: multiply normalized rewards by current _task_weights\n",
|
| 449 |
+
" 5. Shift back to [0, 1] range (GRPO with scale_rewards=False expects non-negative)\n",
|
| 450 |
+
" 6. Return flat list in original sample order\n",
|
| 451 |
+
" \"\"\"\n",
|
| 452 |
+
" n = len(completions)\n",
|
| 453 |
+
" raw_rewards = [0.0] * n\n",
|
| 454 |
+
" task_labels = [\"\"] * n\n",
|
| 455 |
+
" \n",
|
| 456 |
+
" # ── Step 1: Compute raw per-sample rewards ──────────────────────────────\n",
|
| 457 |
+
" for i, (completion, prompt) in enumerate(zip(completions, prompts)):\n",
|
| 458 |
+
" if isinstance(completion, list):\n",
|
| 459 |
+
" comp_text = completion[-1][\"content\"] if completion else \"\"\n",
|
| 460 |
+
" else:\n",
|
| 461 |
+
" comp_text = str(completion)\n",
|
| 462 |
+
"\n",
|
| 463 |
+
" if isinstance(prompt, list):\n",
|
| 464 |
+
" prompt_text = \" \".join(m.get(\"content\", \"\") for m in prompt)\n",
|
| 465 |
+
" else:\n",
|
| 466 |
+
" prompt_text = str(prompt)\n",
|
| 467 |
+
"\n",
|
| 468 |
+
" task = _classify_task_type(prompt_text)\n",
|
| 469 |
+
" task_labels[i] = task\n",
|
| 470 |
+
"\n",
|
| 471 |
+
" if task == \"extraction\":\n",
|
| 472 |
+
" raw_rewards[i] = reward_extraction(comp_text)\n",
|
| 473 |
+
" elif task == \"sql_qa\":\n",
|
| 474 |
+
" raw_rewards[i] = reward_sql_qa(comp_text)\n",
|
| 475 |
+
" elif task == \"insights\":\n",
|
| 476 |
+
" raw_rewards[i] = reward_insights(comp_text)\n",
|
| 477 |
+
" elif task == \"push\":\n",
|
| 478 |
+
" raw_rewards[i] = reward_push(comp_text)\n",
|
| 479 |
+
" else:\n",
|
| 480 |
+
" raw_rewards[i] = 0.2 if comp_text.strip() else 0.0\n",
|
| 481 |
+
"\n",
|
| 482 |
+
" # ── Step 2-4: GDPO per-component normalization + IWU weighting ──────────\n",
|
| 483 |
+
" # Group indices by task\n",
|
| 484 |
+
" task_indices = {}\n",
|
| 485 |
+
" for i, task in enumerate(task_labels):\n",
|
| 486 |
+
" if task not in task_indices:\n",
|
| 487 |
+
" task_indices[task] = []\n",
|
| 488 |
+
" task_indices[task].append(i)\n",
|
| 489 |
+
" \n",
|
| 490 |
+
" final_rewards = [0.0] * n\n",
|
| 491 |
+
" \n",
|
| 492 |
+
" for task, indices in task_indices.items():\n",
|
| 493 |
+
" task_raw = [raw_rewards[i] for i in indices]\n",
|
| 494 |
+
" \n",
|
| 495 |
+
" # GDPO: z-score normalize within this task group\n",
|
| 496 |
+
" if len(task_raw) > 1:\n",
|
| 497 |
+
" t_mean = sum(task_raw) / len(task_raw)\n",
|
| 498 |
+
" t_var = sum((r - t_mean) ** 2 for r in task_raw) / (len(task_raw) - 1)\n",
|
| 499 |
+
" t_std = t_var ** 0.5\n",
|
| 500 |
+
" if t_std > 1e-8:\n",
|
| 501 |
+
" normed = [(r - t_mean) / t_std for r in task_raw]\n",
|
| 502 |
+
" else:\n",
|
| 503 |
+
" normed = [0.0] * len(task_raw)\n",
|
| 504 |
+
" else:\n",
|
| 505 |
+
" # Single sample in this task group — can't normalize, use raw\n",
|
| 506 |
+
" normed = [0.0]\n",
|
| 507 |
+
" \n",
|
| 508 |
+
" # IWU: scale by dynamic task weight\n",
|
| 509 |
+
" weight = _task_weights.get(task, 0.25)\n",
|
| 510 |
+
" weighted = [v * weight for v in normed]\n",
|
| 511 |
+
" \n",
|
| 512 |
+
" for idx_in_group, global_idx in enumerate(indices):\n",
|
| 513 |
+
" final_rewards[global_idx] = weighted[idx_in_group]\n",
|
| 514 |
+
" \n",
|
| 515 |
+
" # ── Step 5: Shift to non-negative range ─────────────────────────────────\n",
|
| 516 |
+
" # GRPO with scale_rewards=False computes advantages as reward - mean(rewards).\n",
|
| 517 |
+
" # Normalized rewards are already zero-centered per-task, so the advantage\n",
|
| 518 |
+
" # computation will work correctly. But TRL may log negative rewards as warnings.\n",
|
| 519 |
+
" # Shift so minimum is 0 to keep logging clean, without changing advantage ordering.\n",
|
| 520 |
+
" min_r = min(final_rewards) if final_rewards else 0.0\n",
|
| 521 |
+
" if min_r < 0:\n",
|
| 522 |
+
" final_rewards = [r - min_r for r in final_rewards]\n",
|
| 523 |
+
" \n",
|
| 524 |
+
" return final_rewards\n",
|
| 525 |
+
"\n",
|
| 526 |
+
"\n",
|
| 527 |
+
"def commerce_reward_fn_raw(completions, prompts, **kwargs) -> list:\n",
|
| 528 |
+
" \"\"\"Raw reward function WITHOUT GDPO/IWU — used for eval metrics.\n",
|
| 529 |
+
" \n",
|
| 530 |
+
" Eval should report raw task-specific rewards for interpretability.\n",
|
| 531 |
+
" The GDPO+IWU normalization is only for shaping the training gradient signal.\n",
|
| 532 |
+
" \"\"\"\n",
|
| 533 |
+
" rewards = []\n",
|
| 534 |
+
" for completion, prompt in zip(completions, prompts):\n",
|
| 535 |
+
" if isinstance(completion, list):\n",
|
| 536 |
+
" comp_text = completion[-1][\"content\"] if completion else \"\"\n",
|
| 537 |
+
" else:\n",
|
| 538 |
+
" comp_text = str(completion)\n",
|
| 539 |
+
"\n",
|
| 540 |
+
" if isinstance(prompt, list):\n",
|
| 541 |
+
" prompt_text = \" \".join(m.get(\"content\", \"\") for m in prompt)\n",
|
| 542 |
+
" else:\n",
|
| 543 |
+
" prompt_text = str(prompt)\n",
|
| 544 |
+
"\n",
|
| 545 |
+
" task = _classify_task_type(prompt_text)\n",
|
| 546 |
+
"\n",
|
| 547 |
+
" if task == \"extraction\":\n",
|
| 548 |
+
" rewards.append(reward_extraction(comp_text))\n",
|
| 549 |
+
" elif task == \"sql_qa\":\n",
|
| 550 |
+
" rewards.append(reward_sql_qa(comp_text))\n",
|
| 551 |
+
" elif task == \"insights\":\n",
|
| 552 |
+
" rewards.append(reward_insights(comp_text))\n",
|
| 553 |
+
" elif task == \"push\":\n",
|
| 554 |
+
" rewards.append(reward_push(comp_text))\n",
|
| 555 |
+
" else:\n",
|
| 556 |
+
" r = 0.2 if comp_text.strip() else 0.0\n",
|
| 557 |
+
" rewards.append(r)\n",
|
| 558 |
+
" return rewards\n",
|
| 559 |
+
"\n",
|
| 560 |
+
"\n",
|
| 561 |
+
"print(\"✓ Reward functions defined (V4.2: SQL v2 + GDPO active + IWU active)\")\n",
|
| 562 |
+
"print(f\" Task weights: {_task_weights}\")\n",
|
| 563 |
+
"print(f\" commerce_reward_fn: GDPO+IWU normalized (for training)\")\n",
|
| 564 |
+
"print(f\" commerce_reward_fn_raw: raw scores (for eval/audit)\")\n",
|
| 565 |
+
"print(f\" Task weights: {_task_weights}\")"
|
| 566 |
+
]
|
| 567 |
},
|
| 568 |
{
|
| 569 |
"cell_type": "markdown",
|