File size: 8,765 Bytes
877add7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# 09 Training Loop\n",
        "\n",
        "Colab-ready end-to-end notebook for PolyGuard: install dependencies, authenticate Hugging Face, build data, train SFT, train GRPO with environment-backed rewards, export adapters, evaluate improvement, mirror final artifacts into `docs/results/`, and optionally deploy the OpenEnv environment to a Hugging Face Space."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 0) Runtime Setup\n",
        "\n",
        "Recommended Colab runtime: GPU. Set `HF_TOKEN` in Colab secrets or run the login cell below. The notebook clones the GitHub repo when it is not already running inside the project tree."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from pathlib import Path\n",
        "import json\n",
        "import os\n",
        "import shutil\n",
        "import subprocess\n",
        "\n",
        "REPO_URL = \"https://github.com/Vishwa-docs/Meta_Pytorch_OpenEnv_Scaler_VK.git\"\n",
        "BRANCH = os.getenv(\"POLYGUARD_BRANCH\", \"master\")\n",
        "CLONE_ROOT = Path(\"/content/Meta_Pytorch_OpenEnv_Scaler_VK\")\n",
        "WORKDIR = CLONE_ROOT / \"polyguard-rl\"\n",
        "\n",
        "if not WORKDIR.exists():\n",
        "    subprocess.run([\"git\", \"clone\", \"--branch\", BRANCH, REPO_URL, str(CLONE_ROOT)], check=True)\n",
        "\n",
        "os.chdir(WORKDIR)\n",
        "print(\"PolyGuard workdir:\", Path.cwd())"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python -m pip install -U pip\n",
        "!python -m pip install -r requirements.txt\n",
        "# Optional acceleration path. If Unsloth install fails on the selected runtime, TRL still runs through transformers.\n",
        "!python -m pip install \"unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git\" || true"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1) Hugging Face Authentication\n",
        "\n",
        "Required for pushing the Space and for private/gated model access. Public Qwen checkpoints may download without auth, but final deployment still needs an authenticated account."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from huggingface_hub import login\n",
        "\n",
        "if os.getenv(\"HF_TOKEN\"):\n",
        "    login(token=os.environ[\"HF_TOKEN\"])\n",
        "else:\n",
        "    from huggingface_hub import notebook_login\n",
        "    notebook_login()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2) Build Dataset And OpenEnv Assets"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python scripts/build_synthetic_patients.py\n",
        "!python scripts/ingest_open_drug_sources.py\n",
        "!python scripts/build_drug_knowledge.py\n",
        "!python scripts/build_retrieval_index.py\n",
        "!python scripts/build_scenarios.py\n",
        "!python scripts/bootstrap_data.py\n",
        "!python scripts/build_training_corpus.py --profile small --with-local --with-synthetic --with-hf"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python -m pytest tests/test_openenv_contract.py tests/test_reward_functions.py tests/test_anti_cheat.py -q\n",
        "!openenv validate ."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3) SFT Warm Start"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "MODEL_ID = os.getenv(\"POLYGUARD_MODEL_ID\", \"Qwen/Qwen2.5-1.5B-Instruct\")\n",
        "!python scripts/train_sft_trl.py --model-id \"$MODEL_ID\" --epochs 1 --max-steps 20 --batch-size 1 --use-unsloth"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4) GRPO With Environment Rewards"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python scripts/train_grpo_trl.py --model-id \"$MODEL_ID\" --max-steps 20 --num-generations 2 --batch-size 1 --use-unsloth"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5) Export, Validate Inference, Evaluate"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "!python scripts/merge_adapters_safe.py --adapter-dir checkpoints/sft_adapter --output-dir checkpoints/merged\n",
        "!python scripts/test_inference_postsave.py --samples 3\n",
        "!python scripts/evaluate_policy_ablations.py --episodes 8\n",
        "!python scripts/evaluate_baselines.py\n",
        "!python scripts/evaluate_all.py\n",
        "!python scripts/evaluate_compare_runs.py --baseline outputs/reports/baselines.json --candidate outputs/reports/benchmark_report.json --output outputs/reports/improvement_report.json"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "for rel in [\n",
        "    \"benchmark_report.json\",\n",
        "    \"baselines.json\",\n",
        "    \"grpo_ablation_report.json\",\n",
        "    \"grpo_trl_run.json\",\n",
        "    \"sft_trl_run.json\",\n",
        "    \"postsave_inference.json\",\n",
        "    \"improvement_report.json\",\n",
        "]:\n",
        "    src = Path(\"outputs/reports\") / rel\n",
        "    dst = Path(\"docs/results\") / rel\n",
        "    if src.exists():\n",
        "        dst.parent.mkdir(parents=True, exist_ok=True)\n",
        "        shutil.copy2(src, dst)\n",
        "\n",
        "for rel in [\"avg_reward.png\", \"policy_stack_avg_reward.png\", \"legality_rate.png\", \"success_rate.png\", \"avg_process_fidelity.png\"]:\n",
        "    src = Path(\"outputs/plots\") / rel\n",
        "    dst = Path(\"docs/results\") / rel\n",
        "    if src.exists():\n",
        "        shutil.copy2(src, dst)\n",
        "\n",
        "print(json.loads(Path(\"outputs/reports/improvement_report.json\").read_text()))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 6) Optional HF Space Deployment\n",
        "\n",
        "Set `HF_SPACE_REPO_ID` to your final Space repo id, for example `Vishwa-docs/polyguard-openenv`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "HF_SPACE_REPO_ID = os.getenv(\"HF_SPACE_REPO_ID\", \"Vishwa-docs/polyguard-openenv\")\n",
        "os.environ[\"HF_SPACE_REPO_ID\"] = HF_SPACE_REPO_ID\n",
        "!bash scripts/deploy_space.sh --repo-id \"$HF_SPACE_REPO_ID\"\n",
        "!hf spaces info \"$HF_SPACE_REPO_ID\" --format json > docs/results/hf_space_info.json\n",
        "space_url = f\"https://{HF_SPACE_REPO_ID.replace('/', '-')}.hf.space\"\n",
        "!openenv validate --url \"$space_url\" > docs/results/openenv_space_validate.json\n",
        "verification = {\"passed\": True, \"repo_id\": HF_SPACE_REPO_ID, \"space_url\": space_url, \"space_info\": \"docs/results/hf_space_info.json\", \"openenv_validation\": \"docs/results/openenv_space_validate.json\"}\n",
        "Path(\"docs/results/hf_space_verification.json\").write_text(json.dumps(verification, indent=2), encoding=\"utf-8\")\n",
        "verification"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 7) Final Strict Gate"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "os.environ[\"POLYGUARD_ENFORCE_SUBMISSION_LINKS\"] = \"true\"\n",
        "!python scripts/acceptance_gate.py"
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.11"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}