TheJackBright commited on
Commit
c296d62
·
1 Parent(s): f8a246b

Deploy GitHub root master to Space

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .DS_Store +3 -0
  2. .gitattributes +9 -58
  3. Dockerfile +10 -14
  4. README.md +1219 -39
  5. docs/assets/diagrams/episode_state_machine.png +0 -0
  6. docs/assets/diagrams/evidence_generation_flow.png +0 -0
  7. docs/assets/diagrams/runtime_step_flow.png +0 -0
  8. docs/results/anti_cheat_failure_rates.png +0 -0
  9. docs/results/avg_process_fidelity.png +0 -0
  10. docs/results/avg_reward.png +0 -0
  11. docs/results/final_submission_evidence/charts/all/anti_cheat_failure_rates.png +0 -0
  12. docs/results/final_submission_evidence/charts/all/avg_reward.png +0 -0
  13. docs/results/final_submission_evidence/charts/all/basic_llm_vs_full_pipeline_latency.png +0 -0
  14. docs/results/final_submission_evidence/charts/all/basic_llm_vs_full_pipeline_legality.png +0 -0
  15. docs/results/final_submission_evidence/charts/all/basic_llm_vs_full_pipeline_reward.png +0 -0
  16. docs/results/final_submission_evidence/charts/all/basic_llm_vs_full_pipeline_reward_delta_by_seed.png +0 -0
  17. docs/results/final_submission_evidence/charts/all/grpo_reward_curves.png +0 -0
  18. docs/results/final_submission_evidence/charts/all/inference_latency_validity.png +0 -0
  19. docs/results/final_submission_evidence/charts/all/inference_validity_reward.png +0 -0
  20. docs/results/final_submission_evidence/charts/all/legality_rate.png +0 -0
  21. docs/results/final_submission_evidence/charts/all/policy_ablation_avg_reward.png +0 -0
  22. docs/results/final_submission_evidence/charts/all/policy_ablation_exploit_detection.png +0 -0
  23. docs/results/final_submission_evidence/charts/all/policy_ablation_legality.png +0 -0
  24. docs/results/final_submission_evidence/charts/all/policy_stack_avg_reward.png +0 -0
  25. docs/results/final_submission_evidence/charts/all/primary_reward_channel_bars.png +0 -0
  26. docs/results/final_submission_evidence/charts/all/qwen-qwen2-5-3b-instruct_sft_learning_rate.png +0 -0
  27. docs/results/final_submission_evidence/charts/all/qwen-qwen2-5-3b-instruct_sft_token_accuracy.png +0 -0
  28. docs/results/final_submission_evidence/charts/all/qwen-qwen2-5-3b-instruct_sft_training_loss.png +0 -0
  29. docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_final_sft_train_loss.png +0 -0
  30. docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_postsave_latency.png +0 -0
  31. docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_postsave_reward.png +0 -0
  32. docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_remote_completed_stage_durations.png +0 -0
  33. docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_sft_runtime.png +0 -0
  34. docs/results/final_submission_evidence/charts/all/qwen_0_5b_sft_learning_rate.png +0 -0
  35. docs/results/final_submission_evidence/charts/all/qwen_0_5b_sft_token_accuracy.png +0 -0
  36. docs/results/final_submission_evidence/charts/all/qwen_0_5b_sft_training_loss.png +0 -0
  37. docs/results/final_submission_evidence/charts/all/qwen_0_5b_vs_1_5b_sft_loss_comparison.png +0 -0
  38. docs/results/final_submission_evidence/charts/all/qwen_0_5b_vs_1_5b_sft_token_accuracy_comparison.png +0 -0
  39. docs/results/final_submission_evidence/charts/all/qwen_1_5b_sft_learning_rate.png +0 -0
  40. docs/results/final_submission_evidence/charts/all/qwen_1_5b_sft_token_accuracy.png +0 -0
  41. docs/results/final_submission_evidence/charts/all/qwen_1_5b_sft_training_loss.png +0 -0
  42. docs/results/final_submission_evidence/charts/all/qwen_model_grpo_reward.png +0 -0
  43. docs/results/final_submission_evidence/charts/all/qwen_model_sft_loss.png +0 -0
  44. docs/results/final_submission_evidence/charts/all/qwen_model_sft_reward.png +0 -0
  45. docs/results/final_submission_evidence/charts/all/reward_component_bars.png +0 -0
  46. docs/results/final_submission_evidence/charts/all/sft_loss_curves.png +0 -0
  47. docs/results/final_submission_evidence/charts/all/sft_validity_reward.png +0 -0
  48. docs/results/final_submission_evidence/charts/all/sft_vs_grpo_reward.png +0 -0
  49. docs/results/final_submission_evidence/charts/all/train_holdout_gap.png +0 -0
  50. docs/results/final_submission_evidence/charts/curated/inference/inference_latency_validity.png +0 -0
.DS_Store ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cbeeb76fdd091af74b22bc95dbda1f6ef8555509dad1f5a0bd2ea7edc4368d46
3
+ size 10244
.gitattributes CHANGED
@@ -1,59 +1,10 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
36
- app/ui/frontend/dist/blackhole.webm filter=lfs diff=lfs merge=lfs -text
37
- app/ui/frontend/public/blackhole.webm filter=lfs diff=lfs merge=lfs -text
38
- docs/results/model_improvement_evidence_qwen_0_5b_1_5b/charts/reward_function/reward_component_bars.png filter=lfs diff=lfs merge=lfs -text
39
- docs/results/qwen_completed_runs/charts/generated/reward_component_bars.png filter=lfs diff=lfs merge=lfs -text
40
- docs/results/submission_evidence/qwen_0_5b_1_5b/reward_component_bars.png filter=lfs diff=lfs merge=lfs -text
41
- docs/results/submission_evidence/qwen_0_5b_1_5b_3b/reward_component_bars.png filter=lfs diff=lfs merge=lfs -text
42
- docs/results/submission_evidence_qwen_0_5b_1_5b/charts/generated/reward_component_bars.png filter=lfs diff=lfs merge=lfs -text
43
- docs/results/submission_evidence_qwen_0_5b_1_5b_3b/charts/generated/reward_component_bars.png filter=lfs diff=lfs merge=lfs -text
44
- submission_bundle/qwen_completed_runs/charts/generated/reward_component_bars.png filter=lfs diff=lfs merge=lfs -text
45
- docs/UI[[:space:]]Images/1.jpeg filter=lfs diff=lfs merge=lfs -text
46
- docs/UI[[:space:]]Images/2.jpeg filter=lfs diff=lfs merge=lfs -text
47
- docs/UI[[:space:]]Images/3.jpeg filter=lfs diff=lfs merge=lfs -text
48
- docs/UI[[:space:]]Images/4.jpeg filter=lfs diff=lfs merge=lfs -text
49
- docs/UI[[:space:]]Images/5.jpeg filter=lfs diff=lfs merge=lfs -text
50
- docs/assets/diagrams/data_training_pipeline.png filter=lfs diff=lfs merge=lfs -text
51
- docs/assets/diagrams/deployment_topology.png filter=lfs diff=lfs merge=lfs -text
52
- docs/assets/diagrams/frontend_runtime_surface.png filter=lfs diff=lfs merge=lfs -text
53
- docs/assets/diagrams/multi_agent_orchestration.png filter=lfs diff=lfs merge=lfs -text
54
- docs/assets/diagrams/reward_decomposition.png filter=lfs diff=lfs merge=lfs -text
55
- docs/assets/diagrams/system_architecture.png filter=lfs diff=lfs merge=lfs -text
56
- docs/results/final_submission_evidence/charts/curated/reward_and_safety/reward_component_bars.png filter=lfs diff=lfs merge=lfs -text
57
- docs/results/final_submission_evidence/charts/curated/training/qwen_3b_grpo_reward_curve.png filter=lfs diff=lfs merge=lfs -text
58
- docs/results/final_submission_evidence/charts/frontpage/04_reward_components.png filter=lfs diff=lfs merge=lfs -text
59
- docs/results/final_submission_evidence/charts/frontpage/09_qwen_3b_grpo_reward_curve.png filter=lfs diff=lfs merge=lfs -text
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
3
+ *.jpg filter=lfs diff=lfs merge=lfs -text
4
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
5
+ *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  *.zip filter=lfs diff=lfs merge=lfs -text
7
+ *.pdf filter=lfs diff=lfs merge=lfs -text
8
+ *.gif filter=lfs diff=lfs merge=lfs -text
9
+ .DS_Store filter=lfs diff=lfs merge=lfs -text
10
+ *.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile CHANGED
@@ -1,31 +1,27 @@
1
- # Hugging Face Space: single-port edge (nginx) + OpenEnv (8100) + API (8200) + static UI.
2
- # Build from repository root: docker build -f Dockerfile.space -t polyguard-space .
3
- # Cheap tier: use Space "CPU basic"; first boot downloads ~1.1GB model bundle.
4
 
5
  FROM node:20-bookworm-slim AS frontend
6
  WORKDIR /build
7
- COPY app/ui/frontend/package.json app/ui/frontend/package-lock.json ./
8
  RUN npm ci
9
- COPY app/ui/frontend/ ./
10
  ENV VITE_API_BASE=/api
11
  RUN npm run build
12
 
13
  FROM python:3.11-slim-bookworm
14
  WORKDIR /app
15
  ENV DEBIAN_FRONTEND=noninteractive
16
- RUN apt-get update && apt-get install -y --no-install-recommends nginx \
17
- && rm -rf /var/lib/apt/lists/*
18
 
19
- COPY requirements-space.txt /app/requirements-space.txt
20
- RUN pip install --no-cache-dir --upgrade pip \
21
- && pip install --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu \
22
- && pip install --no-cache-dir -r /app/requirements-space.txt
23
 
24
- COPY . /app
25
  COPY --from=frontend /build/dist /app/static
26
 
27
- RUN chmod +x /app/docker/space/entrypoint.sh \
28
- && mkdir -p /app/data /app/checkpoints/active
29
 
30
  ENV PORT=7860
31
  ENV POLYGUARD_ALLOW_HF_SPACE_CORS=true
 
1
+ # Hugging Face Space wrapper for the GitHub repository root.
2
+ # The repository keeps the runnable app under polyguard-rl/, while Spaces expect
3
+ # Dockerfile at the Space root.
4
 
5
  FROM node:20-bookworm-slim AS frontend
6
  WORKDIR /build
7
+ COPY polyguard-rl/app/ui/frontend/package.json polyguard-rl/app/ui/frontend/package-lock.json ./
8
  RUN npm ci
9
+ COPY polyguard-rl/app/ui/frontend/ ./
10
  ENV VITE_API_BASE=/api
11
  RUN npm run build
12
 
13
  FROM python:3.11-slim-bookworm
14
  WORKDIR /app
15
  ENV DEBIAN_FRONTEND=noninteractive
16
+ RUN apt-get update && apt-get install -y --no-install-recommends nginx && rm -rf /var/lib/apt/lists/*
 
17
 
18
+ COPY polyguard-rl/requirements-space.txt /app/requirements-space.txt
19
+ RUN pip install --no-cache-dir --upgrade pip && pip install --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu && pip install --no-cache-dir -r /app/requirements-space.txt
 
 
20
 
21
+ COPY polyguard-rl/ /app/
22
  COPY --from=frontend /build/dist /app/static
23
 
24
+ RUN chmod +x /app/docker/space/entrypoint.sh && mkdir -p /app/data /app/checkpoints/active
 
25
 
26
  ENV PORT=7860
27
  ENV POLYGUARD_ALLOW_HF_SPACE_CORS=true
README.md CHANGED
@@ -5,64 +5,1244 @@ colorTo: green
5
  sdk: docker
6
  app_port: 7860
7
  pinned: false
 
8
  ---
9
 
10
- # PolyGuard (OpenEnv implementation package)
11
 
12
- Run all CLI commands from this directory (`cd polyguard-rl`). The repository root [`README.md`](../README.md) carries the same submission narrative with paths adjusted for viewers landing on the GitHub repo home page.
 
 
 
 
 
 
 
 
13
 
14
- ## Submission Links
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- - GitHub Repo URL: [https://github.com/Vishwa-docs/Meta_Pytorch_OpenEnv_Scaler_VK](https://github.com/Vishwa-docs/Meta_Pytorch_OpenEnv_Scaler_VK)
17
- - HF Space URL: [https://huggingface.co/spaces/TheJackBright/polyguard-openenv-workbench](https://huggingface.co/spaces/TheJackBright/polyguard-openenv-workbench)
18
- - Colab Notebook URL: [https://colab.research.google.com/github/Vishwa-docs/Meta_Pytorch_OpenEnv_Scaler_VK/blob/master/polyguard-rl/PolyGuard_SFT_GRPO_One_Run_Runner.ipynb](https://colab.research.google.com/github/Vishwa-docs/Meta_Pytorch_OpenEnv_Scaler_VK/blob/master/polyguard-rl/PolyGuard_SFT_GRPO_One_Run_Runner.ipynb) (see also `notebooks/09_training_loop.ipynb` for a modular training walkthrough)
19
- - YouTube Video URL: not used for this submission; the repository root README is the story artifact.
20
- - Story artifact: the repository root [`README.md`](../README.md) is the final blog-style narrative and evidence map.
21
 
22
- ## Shared Environment, Logs, And Scripts
 
 
 
 
 
23
 
24
- The required environment files, training logs, and training scripts are shared
25
- in the repo and indexed in [Submission Artifact Index](docs/submission_artifacts.md).
 
 
 
26
 
27
- - Environment/runtime: `openenv.yaml`, `pyproject.toml`, `uv.lock`, `requirements*.txt`, `Dockerfile*`, `app/env/`, `server/app.py`, and `app/hf_space/Dockerfile`.
28
- - Training scripts/notebooks: `PolyGuard_SFT_GRPO_One_Run_Runner.ipynb`, `notebooks/09_training_loop.ipynb`, `scripts/train_sft_trl.py`, `scripts/train_grpo_trl.py`, `scripts/deploy_training_space.py`, `app/hf_space/training_runner.py`, and `app/training/`.
29
- - Training logs/results: `docs/results/final_submission_evidence/reports/`, `docs/results/sweeps/`, `docs/results/submission_evidence_qwen_0_5b_1_5b_3b/reports/`, and `docs/results/qwen_completed_runs/reports/`.
30
- - Final downloadable artifact Space: [https://huggingface.co/spaces/adithya9903/polyguard-openenv-final-artifacts](https://huggingface.co/spaces/adithya9903/polyguard-openenv-final-artifacts).
31
 
32
- ## Problem Statement
33
 
34
- Polypharmacy decisions are long-horizon, partially observable, and safety-critical. PolyGuard is a research environment where an LLM agent selects constrained clinical actions, receives verifier-backed reward, and improves via SFT + GRPO—not generic open-ended chat fine-tuning.
 
 
 
 
 
35
 
36
- ## Environment
37
 
38
- `PolyGuardEnv` exposes OpenEnv-style HTTP/WebSocket endpoints (`/reset`, `/step`, `/state`, `/metadata`, `/schema`, `/mcp`, `/health`, `/ws`). Sub-environments include DDI, bandit mining, regimen risk, precision dosing, longitudinal deprescribing, web-search missing data, alternative suggestion, and new-drug decomposition. See `openenv.yaml`, `app/env/env_core.py`, `app/env/fastapi_app.py`, and `docs/environment_design.md`.
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- ## Agent Capabilities
 
 
 
 
 
 
41
 
42
- Medication reconciliation, evidence retrieval, graph safety, dosing guardrails, candidate generation, supervisor routing, planner/critic stack, explanations, and contextual bandit ranking for ablations (`app/agents/`, `docs/agents.md`).
43
 
44
- ## Tasks
 
 
 
 
 
 
 
 
45
 
46
- DDI risk reduction, safe adds/substitutions, regimen optimization, taper/deprescribing sequences, precision dosing, missing-data recovery, and new-drug decomposition (`data/scenarios/`, `app/env/catalog.py`).
 
47
 
48
- ## Reward Model / Evaluation Logic
 
 
49
 
50
- Thirteen verifier-backed reward components roll up into four primary channels (`safety_legality`, `clinical_improvement`, `dosing_quality`, `process_integrity`), clamped to `[0.001, 0.999]`, with anti-cheat and timeout logic (`app/env/reward_router.py`, `app/env/anti_cheat.py`, `docs/reward_design.md`).
 
 
 
 
 
 
 
51
 
52
- ## Training And Post-Training Strategy
 
 
 
 
53
 
54
- Build corpora (`scripts/bootstrap_data.py`, `scripts/build_training_corpus.py`), SFT with TRL (`scripts/train_sft_trl.py`), GRPO with environment reward (`scripts/train_grpo_trl.py`), merge adapters (`scripts/merge_adapters_safe.py`), validate inference (`scripts/test_inference_postsave.py`), evaluate and plot (`scripts/evaluate_*.py`, `docs/results/`). Optional HF GPU training uses `scripts/deploy_training_space.py`; public review should start with the repository root [`README.md`](../README.md), then `docs/training.md` for implementation notes.
55
 
56
- ## Documentation index
 
 
 
 
 
57
 
58
- - [Architecture](docs/architecture.md)
59
- - [Environment](docs/environment_design.md)
60
- - [Rewards](docs/reward_design.md)
61
- - [Training](docs/training.md)
62
- - [Evaluation](docs/evaluation.md)
63
- - [Deployment](docs/deployment.md)
64
- - [Datasets](docs/datasets.md)
65
- - [Participant guide traceability](docs/participant_guide_traceability.md)
66
- - [Idea doc vs implementation](docs/idea_document_traceability.md)
67
- - [Submission artifact index](docs/submission_artifacts.md)
68
- - [**Space UI demo script**](docs/DEMO_RECORDING_SCRIPT.md)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  sdk: docker
6
  app_port: 7860
7
  pinned: false
8
+ license: mit
9
  ---
10
 
11
+ # POLYGUARD-OPENENV
12
 
13
+ Someone does not experience an unsafe medication regimen as "polypharmacy."
14
+ They experience it as dizziness after a new sleep medication, bleeding after a
15
+ painkiller is added to a blood thinner, confusion from a sedative-opioid
16
+ combination, or a preventable emergency visit because five prescribers each saw
17
+ one slice of the medication list. The dangerous part is often not a single
18
+ drug. It is the combination: the wrong pair, the wrong dose in the wrong organ
19
+ function context, the missing lab, the duplicated class, the abrupt stop that
20
+ should have been a taper, or the model that confidently says "looks fine"
21
+ because it was never forced to act inside a safety-checked environment.
22
 
23
+ That is the problem PolyGuard was built for. The
24
+ [CDC](https://www.cdc.gov/medication-safety/data-research/facts-stats/index.html)
25
+ reports that adverse drug events send more than 1.5 million people to US
26
+ emergency departments every year, with almost 500,000 hospitalizations; adults
27
+ 65 and older account for more than 600,000 of those emergency visits. A
28
+ CDC-authored [JAMA surveillance study](https://jamanetwork.com/journals/jama/fullarticle/2585977)
29
+ found that older adults made up 34.5 percent of ED visits for outpatient adverse
30
+ drug events and had the highest hospitalization rate, 43.6 percent; among older
31
+ adults, anticoagulants, diabetes agents, and opioid analgesics were implicated
32
+ in about 59.9 percent of ADE ED visits. Globally, the
33
+ [WHO](https://www.who.int/initiatives/medication-without-harm) estimates
34
+ medication errors cost USD 42 billion annually. And AHRQ's deprescribing safety
35
+ review summarizes estimates that
36
+ [45 percent of older adults are exposed to polypharmacy and 58 percent to
37
+ potentially inappropriate medications](https://www.ncbi.nlm.nih.gov/books/NBK600387/).
38
 
39
+ Not every adverse drug event is caused by an incorrect drug combination, but
40
+ these numbers describe the harm surface this project targets: medication
41
+ decisions where combination risk, monitoring gaps, frailty, organ function,
42
+ uncertainty, and action sequencing all matter at once.
 
43
 
44
+ PolyGuard turns that problem into an OpenEnv-compatible reinforcement-learning
45
+ environment for polypharmacy safety, medication optimization, deprescribing,
46
+ safe substitution, missing-evidence recovery, and precision dosing. An LLM
47
+ policy observes a constrained patient/regimen state, chooses a legal candidate
48
+ action, receives verifier-backed reward, and improves through SFT plus
49
+ GRPO-style post-training.
50
 
51
+ This repository is both a research artifact and a product prototype. It contains
52
+ the OpenEnv server, a multi-agent policy stack, synthetic and structured
53
+ medication datasets, TRL training scripts, verifier-backed reward functions,
54
+ agentic evaluation, curated result charts, final artifacts, and a React
55
+ operator workbench.
56
 
57
+ PolyGuard is not medical software and is not clinical advice. It is a controlled
58
+ research environment for studying how language-model policies can be trained and
59
+ audited on safety-critical medication action selection.
 
60
 
61
+ ## Safety Contract
62
 
63
+ PolyGuard does not let a model directly mutate a medication list from free text.
64
+ Every decision is candidate-based, verifier-checked, reward-decomposed, and
65
+ traced. Illegal actions can be scored, penalized, and logged, but they do not
66
+ change patient state. The system is designed for research on safety-critical
67
+ action selection, not for clinical ordering or patient-specific treatment
68
+ advice.
69
 
70
+ ## Try, Read, And Review
71
 
72
+ - GitHub repository:
73
+ [Vishwa-docs/Meta_Pytorch_OpenEnv_Scaler_VK](https://github.com/Vishwa-docs/Meta_Pytorch_OpenEnv_Scaler_VK)
74
+ - Product Hugging Face Space:
75
+ [TheJackBright/polyguard-openenv-workbench](https://huggingface.co/spaces/TheJackBright/polyguard-openenv-workbench)
76
+ - One-run Colab/HF notebook:
77
+ [PolyGuard_SFT_GRPO_One_Run_Runner.ipynb](https://colab.research.google.com/github/Vishwa-docs/Meta_Pytorch_OpenEnv_Scaler_VK/blob/master/polyguard-rl/PolyGuard_SFT_GRPO_One_Run_Runner.ipynb)
78
+ - Final evidence index:
79
+ [polyguard-rl/docs/results/final_submission_evidence/README.md](polyguard-rl/docs/results/final_submission_evidence/README.md)
80
+ - Shared environment, logs, scripts, and notebooks:
81
+ [polyguard-rl/docs/submission_artifacts.md](polyguard-rl/docs/submission_artifacts.md)
82
+ - Final artifact/evidence Space:
83
+ [adithya9903/polyguard-openenv-final-artifacts](https://huggingface.co/spaces/adithya9903/polyguard-openenv-final-artifacts)
84
 
85
+ Note: this Space hosts the Qwen 3B artifact bundle. The Qwen 0.5B and 1.5B
86
+ runs were trained using a second Hugging Face account, so their model
87
+ artifacts could not be hosted in the same final Space. Their report mirrors
88
+ are checked into this repo:
89
+ [0.5B reports](polyguard-rl/docs/results/submission_evidence_qwen_0_5b_1_5b_3b/reports/runs/qwen-qwen2-5-0-5b-instruct)
90
+ and
91
+ [1.5B reports](polyguard-rl/docs/results/submission_evidence_qwen_0_5b_1_5b_3b/reports/runs/qwen-qwen2-5-1-5b-instruct).
92
 
93
+ ## Why This Problem Matters
94
 
95
+ Medication safety is a combinatorial, partially observable, and high-stakes
96
+ decision problem. A useful policy has to do more than generate a plausible
97
+ sentence. It has to notice drug-drug interaction risk, reason about
98
+ comorbidities and organ function, respect taper and monitoring requirements,
99
+ choose safe substitutions, abstain or ask for review when uncertainty is high,
100
+ and expose why it acted. The AGS Beers Criteria and STOPP/START criteria exist
101
+ because many unsafe medication choices are systematic, recognizable, and
102
+ evaluable, but still hard to operationalize across fragmented medication lists
103
+ and incomplete context.
104
 
105
+ The machine-learning pressure is equally real. If a medication vocabulary has
106
+ 500 drugs, the number of possible five-drug combinations is:
107
 
108
+ ```text
109
+ C(500, 5) = 255,244,687,600
110
+ ```
111
 
112
+ Exhaustively evaluating every combination is impossible in realistic data
113
+ settings. The paper that inspired this project, [Neural Bandits for Data Mining:
114
+ Searching for Dangerous Polypharmacy](https://arxiv.org/abs/2212.05190), frames
115
+ dangerous polypharmacy discovery as a bandit search problem over a massive
116
+ combination space. It benchmarks neural bandit search over simulated
117
+ polypharmacy datasets with 500 drugs and 100,000 distinct combinations, and
118
+ reports detection of up to 72 percent of potentially inappropriate
119
+ polypharmacies with 99 percent average precision after 30,000 time steps.
120
 
121
+ PolyGuard takes inspiration from that search framing, but moves the problem from
122
+ offline combination mining into an agentic environment: the policy sees a
123
+ patient state, chooses among legal clinical action candidates, and is judged by
124
+ a deterministic verifier and reward router rather than by free-form text
125
+ preference alone.
126
 
127
+ ## A Concrete Failure Trace
128
 
129
+ In the final matched-seed traces, the failure mode is not abstract. On seeds
130
+ `8000` and `8004`, the basic prompt-style proxy repeatedly chose `cand_01`,
131
+ the first legal candidate, which meant `KEEP_REGIMEN` while a hidden
132
+ `warfarin_like` + `nsaid_like` interaction remained unresolved. The verifier
133
+ recorded `holdout_ddi_not_addressed`. The full PolyGuard pipeline selected
134
+ `cand_03`, a safer intervention candidate, and avoided those failure reasons.
135
 
136
+ That is the core research bet of this repo: medication AI should be judged
137
+ inside a stateful safety environment, not only by whether its answer sounds
138
+ clinically plausible.
139
+
140
+ Internal evidence:
141
+ [basic_llm_vs_polyguard_report.json](polyguard-rl/docs/results/final_submission_evidence/reports/basic_llm_vs_polyguard_report.json)
142
+ and
143
+ [action_traces.jsonl](polyguard-rl/docs/results/final_submission_evidence/reports/action_traces.jsonl).
144
+
145
+ ## Core Idea
146
+
147
+ PolyGuard asks a narrow but important research question:
148
+
149
+ Can environment-backed feedback make a small open model better at safe
150
+ medication action selection than prompt-only, first-legal, rule-only, or
151
+ single-agent baselines?
152
+
153
+ The project answers that question with an inspectable stack:
154
+
155
+ 1. A finite-horizon OpenEnv simulation for medication decisions.
156
+ 2. A constrained action space, so the model chooses candidate actions instead
157
+ of inventing arbitrary clinical instructions.
158
+ 3. A legality verifier that prevents unsafe state mutation.
159
+ 4. Thirteen reward components rolled into four primary reward channels.
160
+ 5. A multi-agent policy stack with supervisor routing, contextual bandit
161
+ reranking, planner selection, critic veto, and explanation logging.
162
+ 6. SFT for format and clinical-prior warm start.
163
+ 7. GRPO with environment-backed reward, not an opaque LLM judge.
164
+ 8. Agentic evaluation with baseline comparison, policy ablations, post-save
165
+ inference, robustness checks, action traces, and failure mining.
166
+
167
+ ![PolyGuard system architecture](polyguard-rl/docs/assets/diagrams/system_architecture.png)
168
+
169
+ ## Internal Evidence At A Glance
170
+
171
+ | Claim | Repo evidence |
172
+ | --- | --- |
173
+ | Hard contraindication examples are represented | [app/knowledge/ddi_knowledge.py](polyguard-rl/app/knowledge/ddi_knowledge.py) |
174
+ | Safer alternatives are explicit | [app/knowledge/substitution_rules.py](polyguard-rl/app/knowledge/substitution_rules.py) |
175
+ | Unsafe substitutions and dose escalations are blocked before state mutation | [app/env/verifier.py](polyguard-rl/app/env/verifier.py) |
176
+ | Reward hacking and loop-like behavior are surfaced | [app/env/anti_cheat.py](polyguard-rl/app/env/anti_cheat.py), [docs/reward_design.md](polyguard-rl/docs/reward_design.md) |
177
+ | Baseline failure is traceable by seed and candidate | [docs/results/final_submission_evidence/reports/basic_llm_vs_polyguard_report.json](polyguard-rl/docs/results/final_submission_evidence/reports/basic_llm_vs_polyguard_report.json), [docs/results/final_submission_evidence/reports/action_traces.jsonl](polyguard-rl/docs/results/final_submission_evidence/reports/action_traces.jsonl) |
178
+ | Final evidence is curated separately from older smoke artifacts | [docs/results/final_submission_evidence/README.md](polyguard-rl/docs/results/final_submission_evidence/README.md) |
179
+
180
+ ## Project Map
181
+
182
+ The implementation lives under [polyguard-rl/](polyguard-rl/).
183
+
184
+ | Area | Key paths |
185
+ | --- | --- |
186
+ | OpenEnv runtime | [openenv.yaml](polyguard-rl/openenv.yaml), [app/env/env_core.py](polyguard-rl/app/env/env_core.py), [app/env/fastapi_app.py](polyguard-rl/app/env/fastapi_app.py), [server/app.py](polyguard-rl/server/app.py) |
187
+ | Action/state contracts | [app/common/types.py](polyguard-rl/app/common/types.py), [app/common/enums.py](polyguard-rl/app/common/enums.py) |
188
+ | Candidate generation and verifier | [app/models/policy/candidate_builder.py](polyguard-rl/app/models/policy/candidate_builder.py), [app/env/verifier.py](polyguard-rl/app/env/verifier.py) |
189
+ | Reward and anti-cheat | [app/env/reward_router.py](polyguard-rl/app/env/reward_router.py), [app/env/reward_scaling.py](polyguard-rl/app/env/reward_scaling.py), [app/env/anti_cheat.py](polyguard-rl/app/env/anti_cheat.py), [configs/rewards.yaml](polyguard-rl/configs/rewards.yaml) |
190
+ | Multi-agent policy | [app/agents/](polyguard-rl/app/agents/), [docs/agents.md](polyguard-rl/docs/agents.md) |
191
+ | Bandits and baselines | [app/models/baselines/contextual_bandit.py](polyguard-rl/app/models/baselines/contextual_bandit.py), [app/models/baselines/contextual_bandit_policy.py](polyguard-rl/app/models/baselines/contextual_bandit_policy.py), [app/models/baselines/](polyguard-rl/app/models/baselines/) |
192
+ | Training | [app/training/](polyguard-rl/app/training/), [scripts/train_sft_trl.py](polyguard-rl/scripts/train_sft_trl.py), [scripts/train_grpo_trl.py](polyguard-rl/scripts/train_grpo_trl.py), [docs/training.md](polyguard-rl/docs/training.md) |
193
+ | Data | [data/raw/knowledge/drug_knowledge.json](polyguard-rl/data/raw/knowledge/drug_knowledge.json), [data/processed/](polyguard-rl/data/processed/), [data/scenarios/](polyguard-rl/data/scenarios/), [docs/datasets.md](polyguard-rl/docs/datasets.md) |
194
+ | Evaluation | [app/evaluation/](polyguard-rl/app/evaluation/), [scripts/evaluate_all.py](polyguard-rl/scripts/evaluate_all.py), [docs/evaluation.md](polyguard-rl/docs/evaluation.md) |
195
+ | Product API/UI | [app/api/](polyguard-rl/app/api/), [app/ui/frontend/](polyguard-rl/app/ui/frontend/), [docs/ui.md](polyguard-rl/docs/ui.md) |
196
+ | Math | [docs/math.md](polyguard-rl/docs/math.md), [docs/mathematics.md](polyguard-rl/docs/mathematics.md) |
197
+ | Results | [docs/results/final_submission_evidence/](polyguard-rl/docs/results/final_submission_evidence/) |
198
+
199
+ This README is the canonical narrative and evidence map. The docs under
200
+ [polyguard-rl/docs/](polyguard-rl/docs/) are supporting references:
201
+ [architecture.md](polyguard-rl/docs/architecture.md) for system design,
202
+ [environment_design.md](polyguard-rl/docs/environment_design.md) for
203
+ state/action mechanics, [reward_design.md](polyguard-rl/docs/reward_design.md)
204
+ for reward channels, [safety.md](polyguard-rl/docs/safety.md) for guardrails,
205
+ [precision_dosing.md](polyguard-rl/docs/precision_dosing.md) for dosing details,
206
+ [graph_models.md](polyguard-rl/docs/graph_models.md) for graph/risk modeling,
207
+ [ablations.md](polyguard-rl/docs/ablations.md) for policy-slice analysis,
208
+ [api.md](polyguard-rl/docs/api.md) for service routes,
209
+ [deployment.md](polyguard-rl/docs/deployment.md) for deployment surfaces,
210
+ [ui.md](polyguard-rl/docs/ui.md) and
211
+ [DEMO_RECORDING_SCRIPT.md](polyguard-rl/docs/DEMO_RECORDING_SCRIPT.md) for the
212
+ operator demo, and [submission_artifacts.md](polyguard-rl/docs/submission_artifacts.md)
213
+ for artifact traceability.
214
+
215
+ Older smoke-run mirrors are retained for auditability. Final claims in this
216
+ README use the curated evidence bundle under
217
+ [docs/results/final_submission_evidence/](polyguard-rl/docs/results/final_submission_evidence/).
218
+
219
+ ## Environment Design
220
+
221
+ At the center is `PolyGuardEnv`, implemented in
222
+ [app/env/env_core.py](polyguard-rl/app/env/env_core.py). It follows the familiar
223
+ OpenEnv/Gym shape:
224
+
225
+ ```text
226
+ reset(seed, difficulty, sub_environment, scenario_id, patient_id)
227
+ -> PolyGuardObservation
228
+
229
+ step(PolyGuardAction)
230
+ -> (PolyGuardObservation, reward, done, info)
231
+ ```
232
+
233
+ At reset, the environment loads or generates a patient scenario, selects a
234
+ difficulty and sub-environment, computes a risk summary, builds candidate
235
+ actions, estimates uncertainty, and emits a strict observation. At step time,
236
+ the environment parses the action, checks legality, evaluates anti-cheat rules,
237
+ mutates state only if the action is safe, computes decomposed reward, appends a
238
+ trace, and returns detailed `info` fields such as failure reasons, transition
239
+ delta, primary reward channels, invalid-action count, and timeout checks.
240
+
241
+ ![Runtime step flow](polyguard-rl/docs/assets/diagrams/runtime_step_flow.png)
242
+
243
+ ### Sub-Environments
244
+
245
+ PolyGuard is not a single task. It cycles through specialized sub-environments:
246
+
247
+ | Sub-environment | What it stresses |
248
+ | --- | --- |
249
+ | `DDI` | High-risk drug-drug interaction recognition and resolution |
250
+ | `BANDIT_MINING` | Candidate exploration and shortlist/ranking behavior inspired by bandit search |
251
+ | `REGIMEN_RISK` | General medication burden and regimen optimization |
252
+ | `PRECISION_DOSING` | Dose-hold, dose reduction, renal/hepatic guardrails, monitoring decisions |
253
+ | `LONGITUDINAL_DEPRESCRIBING` | Multi-step taper/deprescribing behavior over a longer horizon |
254
+ | `WEB_SEARCH_MISSING_DATA` | Evidence fetch or review when critical data is missing |
255
+ | `ALTERNATIVE_SUGGESTION` | Safe alternatives and within-class substitution |
256
+ | `NEW_DRUG_DECOMPOSITION` | First-pass reasoning over an unknown or combination medication |
257
+
258
+ The curriculum in [app/env/curriculum.py](polyguard-rl/app/env/curriculum.py)
259
+ starts with short easy DDI/regimen-risk episodes, then adds bandit and
260
+ alternative-selection tasks, and finally hard cases with precision dosing,
261
+ longitudinal deprescribing, missing data, and new-drug decomposition.
262
+
263
+ ### State And Observation
264
+
265
+ The latent state is represented by `PolyGuardState` and includes:
266
+
267
+ - Patient demographics and identifiers.
268
+ - Active decision mode.
269
+ - Step count and max step budget.
270
+ - Medications, dose buckets, comorbidities, labs, vitals, frailty, adherence,
271
+ monitoring gaps, and prior adverse event history.
272
+ - Burden score, severe-pair count, precision dosing flags, unresolved conflicts,
273
+ action history, cumulative reward, and done state.
274
+
275
+ The agent does not get all simulator internals. It receives a controlled
276
+ `PolyGuardObservation`:
277
+
278
+ - Patient summary.
279
+ - Medication table.
280
+ - Comorbidity summary.
281
+ - Organ function and labs/vitals.
282
+ - Graph safety summary.
283
+ - Burden score summary.
284
+ - Precision dosing flags.
285
+ - Unresolved conflicts.
286
+ - Candidate action set.
287
+ - Step budget remaining.
288
+ - Action history.
289
+ - Warning summary.
290
+ - Abstention indicators.
291
+ - Deterministic contract with seed, scenario, difficulty, and sub-environment.
292
+
293
+ This split matters: PolyGuard is a partially observable environment. Missing
294
+ labs and unresolved conflicts are visible as uncertainty signals, not as hidden
295
+ reward traps.
296
+
297
+ ## Action Space And Safety Constraints
298
+
299
+ PolyGuard deliberately avoids unconstrained text actions. The policy chooses a
300
+ strict `PolyGuardAction` with fields such as:
301
+
302
+ - `mode`: `REGIMEN_OPT`, `DOSE_OPT`, `REVIEW`, or `ABSTAIN_REVIEW`.
303
+ - `action_type`: one of the constrained clinical action types.
304
+ - `target_drug`, `replacement_drug`, `dose_bucket`, `taper_days`,
305
+ `monitoring_plan`, `evidence_query`, `new_drug_name`, and
306
+ `candidate_components`.
307
+ - `candidate_id`, `confidence`, and `rationale_brief`.
308
+
309
+ The action types are intentionally compact:
310
+
311
+ | Family | Action types |
312
+ | --- | --- |
313
+ | Regimen | `KEEP_REGIMEN`, `STOP_DRUG`, `SUBSTITUTE_WITHIN_CLASS`, `RECOMMEND_ALTERNATIVE` |
314
+ | Dosing | `REDUCE_DOSE_BUCKET`, `INCREASE_DOSE_BUCKET`, `DOSE_HOLD`, `ORDER_MONITORING_AND_WAIT` |
315
+ | Deprescribing | `TAPER_INITIATE`, `TAPER_CONTINUE` |
316
+ | Evidence and uncertainty | `FETCH_EXTERNAL_EVIDENCE`, `DECOMPOSE_NEW_DRUG`, `REQUEST_SPECIALIST_REVIEW`, `REQUEST_PHARMACIST_REVIEW` |
317
+
318
+ The candidate builder in
319
+ [app/models/policy/candidate_builder.py](polyguard-rl/app/models/policy/candidate_builder.py)
320
+ generates a bounded candidate set:
321
+
322
+ ```text
323
+ 3 <= |C_t| <= 10
324
+ ```
325
+
326
+ Each candidate carries estimated safety delta, burden delta, disease stability,
327
+ uncertainty score, rationale tags, required monitoring, and a legality precheck.
328
+ Policy selection is candidate selection:
329
+
330
+ ```text
331
+ a_t = to_action(c_t), where c_t is in C_t
332
+ ```
333
+
334
+ The verifier in [app/env/verifier.py](polyguard-rl/app/env/verifier.py) enforces
335
+ hard safety constraints before state mutation. It checks, among other things:
336
+
337
+ - The target drug exists in the regimen when required.
338
+ - Substitutions and alternatives are drawn from allowed substitution rules.
339
+ - External evidence domains are allowlisted.
340
+ - New-drug decomposition includes a new drug and components.
341
+ - Abrupt stopping is blocked when tapering is required.
342
+ - Renal/hepatic unsafe dose escalation is blocked.
343
+ - Duplicate therapy and contraindicated replacement pairs are blocked.
344
+ - Monitoring and hold actions include a monitoring plan.
345
+ - Destabilizing deprescribing patterns are blocked.
346
+
347
+ Illegal actions can receive reward penalties and become visible in traces, but
348
+ they do not mutate patient state.
349
+
350
+ ## Multi-Agent Policy Stack
351
+
352
+ The "agents" in PolyGuard are an auditable policy factorization rather than
353
+ independent chatbots. A step flows through:
354
+
355
+ ```text
356
+ MedRec -> Evidence -> GraphSafety -> Dosing -> Candidate
357
+ -> Supervisor -> Planner -> Critic -> Env -> Explainer
358
+ ```
359
+
360
+ ![Multi-agent orchestration](polyguard-rl/docs/assets/diagrams/multi_agent_orchestration.png)
361
+
362
+ | Agent/module | Role |
363
+ | --- | --- |
364
+ | `MedRecAgent` | Summarizes current regimen and medication burden |
365
+ | `EvidenceAgent` | Retrieves local or fallback evidence when missing data is present |
366
+ | `GraphSafetyAgent` | Scores risky pairs, side-effect load, duplicate therapy, and graph safety patterns |
367
+ | `DosingAgent` | Detects dose-sensitive cases and dose-hold opportunities |
368
+ | `CandidateAgent` | Exposes legal candidate actions from the environment candidate builder |
369
+ | `SupervisorAgent` | Routes to regimen optimization, dose optimization, or review mode |
370
+ | `PlannerAgent` | Selects an action from candidates through the policy provider |
371
+ | `CriticAgent` | Vetoes illegal or unsafe proposed actions and can force review fallback |
372
+ | `ExplainerAgent` | Records grounded rationale for demo, replay, and audit |
373
+
374
+ The orchestration modes are:
375
+
376
+ - `sequential_pipeline`
377
+ - `supervisor_routed`
378
+ - `replan_on_veto`
379
+ - `lightweight_debate`
380
+
381
+ Policy-stack ablations compare:
382
+
383
+ - `bandit-only`
384
+ - `llm-only`
385
+ - `llm+bandit`
386
+
387
+ ## Contextual Bandits
388
+
389
+ PolyGuard uses contextual bandits as an inspectable candidate-reranking layer.
390
+ This is where the project most directly echoes the arXiv bandit inspiration:
391
+ unsafe polypharmacy search is combinatorial, so the system should learn which
392
+ regions of the candidate/action space are worth exploring rather than enumerate
393
+ everything.
394
+
395
+ Each candidate becomes an 8-dimensional feature vector:
396
+
397
+ ```text
398
+ x(c) = [
399
+ 1,
400
+ I[legality_precheck],
401
+ estimated_safety_delta,
402
+ burden_delta,
403
+ disease_stability_estimate,
404
+ 1 - uncertainty_score,
405
+ I[mode = DOSE_OPT],
406
+ I[mode = REVIEW]
407
+ ]
408
+ ```
409
+
410
+ An arm is keyed by macro mode and action type:
411
+
412
+ ```text
413
+ arm(c) = mode(c) || ":" || action_type(c)
414
+ ```
415
+
416
+ The LinUCB variant maintains, for each arm `a`:
417
+
418
+ ```text
419
+ A_a = I + sum x x^T
420
+ b_a = sum r x
421
+ theta_a = A_a^{-1} b_a
422
+
423
+ score_a(x) = theta_a^T x + alpha * sqrt(x^T A_a^{-1} x)
424
+ ```
425
+
426
+ There is also a Thompson-style variant:
427
+
428
+ ```text
429
+ score_a(x) = theta_a^T x + Normal(0, alpha)
430
+ ```
431
+
432
+ This layer can shortlist candidates before the planner emits the final action.
433
+ It is deliberately kept inside the candidate space: the bandit can improve
434
+ ordering and exploration, but it cannot invent an unsafe action outside the
435
+ environment contract.
436
+
437
+ ## Reward Model
438
+
439
+ The reward model is decomposed on purpose. A single scalar reward is needed for
440
+ RL, but safety-critical RL needs more than one opaque number. PolyGuard logs 13
441
+ component columns and four primary channels on every step.
442
+
443
+ ![Reward decomposition](polyguard-rl/docs/assets/diagrams/reward_decomposition.png)
444
+
445
+ All reward values are clamped and quantized:
446
+
447
+ ```text
448
+ q(x) = round(clip(x, 0.001, 0.999), 3)
449
+ ```
450
+
451
+ The 13 reward components are:
452
+
453
+ | Component | Weight | Meaning |
454
+ | --- | ---: | --- |
455
+ | `format_compliance_score` | 0.08 | Action payload conforms to the schema |
456
+ | `candidate_alignment_score` | 0.08 | The model selected a valid candidate-style id |
457
+ | `legality_score` | 0.12 | The verifier accepted the action |
458
+ | `safety_delta_score` | 0.15 | Severe-pair and burden risk decreased |
459
+ | `burden_improvement_score` | 0.08 | Dose-weighted medication burden improved |
460
+ | `disease_stability_score` | 0.10 | The action did not destabilize underlying disease management |
461
+ | `dosing_quality_score` | 0.08 | Dose-sensitive routing/action quality |
462
+ | `abstention_quality_score` | 0.06 | Review/abstention is appropriate under uncertainty |
463
+ | `efficiency_score` | 0.06 | The action uses the finite step budget well |
464
+ | `process_fidelity_score` | 0.06 | The action follows task-specific process expectations |
465
+ | `explanation_grounding_score` | 0.03 | The rationale is present and grounded |
466
+ | `anti_cheat_score` | 0.06 | Reward-hacking checks did not fire |
467
+ | `uncertainty_calibration_score` | 0.04 | Confidence matches observable uncertainty |
468
+
469
+ The scalar reward is a weighted average:
470
+
471
+ ```text
472
+ R_env(s_t, a_t, s_{t+1}) = q( sum_i w_i c_i / sum_i w_i )
473
+ ```
474
+
475
+ Safety-heavy terms dominate the total weight:
476
+
477
+ ```text
478
+ legality + safety_delta + burden + disease_stability + anti_cheat
479
+ = 0.12 + 0.15 + 0.08 + 0.10 + 0.06
480
+ = 0.51
481
+ ```
482
+
483
+ The four primary reward channels are:
484
+
485
+ | Channel | Component family |
486
+ | --- | --- |
487
+ | `safety_legality` | legality, candidate alignment, anti-cheat, uncertainty calibration |
488
+ | `clinical_improvement` | safety delta, burden improvement, disease stability |
489
+ | `dosing_quality` | dosing quality and abstention quality |
490
+ | `process_integrity` | format compliance, efficiency, process fidelity, explanation grounding |
491
+
492
+ These channels are emitted in `info.primary_reward_channels`, GRPO reward logs,
493
+ reports, plots, and ablation summaries.
494
+
495
+ ## Anti-Cheat And Failure Visibility
496
+
497
+ RL policies exploit reward functions. PolyGuard makes common shortcut failures
498
+ explicit:
499
+
500
+ - Repeated action loops.
501
+ - Excessive keep-regimen behavior.
502
+ - Excessive review/abstention behavior.
503
+ - Candidate ID mismatch.
504
+ - Candidate outside the legal set.
505
+ - Hidden high-risk DDI no-op behavior.
506
+ - Parser exploit patterns in rationales.
507
+ - Retrying a failed no-op action.
508
+
509
+ If an exploit is detected:
510
+
511
+ ```text
512
+ anti_cheat_score = 0.001
513
+ done = true
514
+ termination_reason = "exploit_detection"
515
+ ```
516
+
517
+ Episodes can also terminate on step budget exhaustion, repeated invalid actions,
518
+ safety-veto threshold, patient destabilization, safe resolution, wall-clock
519
+ timeout, or per-step timeout.
520
+
521
+ ![Episode state machine](polyguard-rl/docs/assets/diagrams/episode_state_machine.png)
522
+
523
+ ## Mathematics
524
+
525
+ PolyGuard can be read as a finite-horizon constrained partially observable
526
+ Markov decision process:
527
+
528
+ ```text
529
+ M = (S, A, O, T, R, H, C)
530
+ ```
531
+
532
+ where:
533
+
534
+ - `S` is latent patient/regimen state.
535
+ - `A` is the constrained medication action set.
536
+ - `O` is the controlled observation.
537
+ - `T(s' | s, a)` is the transition function.
538
+ - `R(s, a, s')` is verifier-backed reward.
539
+ - `H` is the episode horizon.
540
+ - `C(s, a)` is the hard safety/legality constraint predicate.
541
+
542
+ The objective is:
543
+
544
+ ```text
545
+ maximize_pi E_pi [ sum_{t=0}^{H-1} R(s_t, a_t, s_{t+1}) ]
546
+ subject to C(s_t, a_t) = 1 whenever possible
547
+ ```
548
+
549
+ There is no explicit discount factor in the runtime. Time preference enters
550
+ through finite horizons and the efficiency reward:
551
+
552
+ ```text
553
+ efficiency_t = q(1 - step_count_t / (max_steps + 1))
554
+ ```
555
+
556
+ State transition is two-gated:
557
+
558
+ ```text
559
+ if verifier(s_t, a_t).legal and not anti_cheat(s_t, a_t):
560
+ s_{t+1} = T(s_t, a_t)
561
+ else:
562
+ s_{t+1} = rollback_state_with_failed_action_record(s_t, a_t)
563
+ ```
564
+
565
+ Risk-like deltas become reward through:
566
+
567
+ ```text
568
+ delta_reward(pre, post) = q(0.5 + 0.6 * (pre - post))
569
+ ```
570
+
571
+ For burden and contraindicated-pair improvement:
572
+
573
+ ```text
574
+ burden_reward = delta_reward(pre_burden, post_burden)
575
+ pair_reward = delta_reward(pre_pairs, post_pairs)
576
+
577
+ safety_delta_score =
578
+ q(0.65 * pair_reward + 0.35 * burden_reward) if legal
579
+ 0.001 otherwise
580
+ ```
581
+
582
+ GRPO uses environment execution as the reward function. For each prompt, the
583
+ model emits candidate completions; PolyGuard parses the candidate id, resets a
584
+ deterministic environment using the recorded seed and scenario fields, executes
585
+ one step, and returns reward. The training reward combines environment reward
586
+ with a legality bonus:
587
+
588
+ ```text
589
+ legal_bonus = 0.95 if action is legal else 0.05
590
+
591
+ R_GRPO = q(0.80 * R_env + 0.20 * legal_bonus)
592
+ ```
593
+
594
+ Conceptually, GRPO forms a within-prompt advantage:
595
+
596
+ ```text
597
+ A_i = (R_i - mean_j R_j) / (std_j R_j + epsilon)
598
+ ```
599
+
600
+ and optimizes a clipped policy-ratio objective with KL regularization. The
601
+ optimizer mechanics are TRL's; PolyGuard's contribution is the verifier-backed
602
+ reward function and the controlled action/state environment.
603
+
604
+ The expanded derivation is in
605
+ [polyguard-rl/docs/mathematics.md](polyguard-rl/docs/mathematics.md).
606
+
607
+ ## Data And Dataset Pipeline
608
+
609
+ The data pipeline builds a compact medication-safety substrate from local drug
610
+ knowledge, synthetic patients, scenario files, retrieval text, and optional
611
+ external augmentation.
612
+
613
+ ![Data and training pipeline](polyguard-rl/docs/assets/diagrams/data_training_pipeline.png)
614
+
615
+ Tracked local processed data currently includes:
616
+
617
+ | Artifact | Count | Path |
618
+ | --- | ---: | --- |
619
+ | Normalized drug rows | 10 | [data/processed/normalized_drugs.parquet](polyguard-rl/data/processed/normalized_drugs.parquet) |
620
+ | Drug class rows | 10 | [data/processed/drug_classes.parquet](polyguard-rl/data/processed/drug_classes.parquet) |
621
+ | Interaction rows | 2 | [data/processed/interactions.parquet](polyguard-rl/data/processed/interactions.parquet) |
622
+ | Graph edges | 18 | [data/processed/graph_edges.parquet](polyguard-rl/data/processed/graph_edges.parquet) |
623
+ | Synthetic patients | 20 | [data/processed/patients_synthetic.parquet](polyguard-rl/data/processed/patients_synthetic.parquet) |
624
+ | Retrieval documents | 8 | [data/processed/retrieval_corpus.jsonl](polyguard-rl/data/processed/retrieval_corpus.jsonl) |
625
+ | Easy scenarios | 100 | [data/scenarios/scenarios_easy.jsonl](polyguard-rl/data/scenarios/scenarios_easy.jsonl) |
626
+ | Medium scenarios | 200 | [data/scenarios/scenarios_medium.jsonl](polyguard-rl/data/scenarios/scenarios_medium.jsonl) |
627
+ | Hard scenarios | 200 | [data/scenarios/scenarios_hard.jsonl](polyguard-rl/data/scenarios/scenarios_hard.jsonl) |
628
+ | Local small SFT rows | 80 | [data/processed/training_corpus_sft.jsonl](polyguard-rl/data/processed/training_corpus_sft.jsonl) |
629
+ | Local small GRPO prompts | 80 | [data/processed/training_corpus_grpo_prompts.jsonl](polyguard-rl/data/processed/training_corpus_grpo_prompts.jsonl) |
630
+
631
+ The provenance manifest records the source policy and counts:
632
+ [data/processed/provenance_manifest.json](polyguard-rl/data/processed/provenance_manifest.json).
633
+
634
+ Additional data-governance and rule artifacts are intentionally checked in:
635
+
636
+ | Artifact | Why it matters |
637
+ | --- | --- |
638
+ | [data/processed/ingested_sources.json](polyguard-rl/data/processed/ingested_sources.json) | Source ingestion ledger used by the local build |
639
+ | [data/processed/feature_dictionary.json](polyguard-rl/data/processed/feature_dictionary.json) | Names and meanings of structured model features |
640
+ | [data/processed/burden_rules.yaml](polyguard-rl/data/processed/burden_rules.yaml) | Medication-burden and duplicate-therapy rules |
641
+ | [data/processed/substitution_rules.yaml](polyguard-rl/data/processed/substitution_rules.yaml) | Data-level safer-substitution rules |
642
+ | [data/processed/taper_rules.yaml](polyguard-rl/data/processed/taper_rules.yaml) | Deprescribing and taper requirements |
643
+ | [data/retrieval_index/index.json](polyguard-rl/data/retrieval_index/index.json) | Retrieval index over local evidence chunks |
644
+
645
+ The local knowledge seed is
646
+ [data/raw/knowledge/drug_knowledge.json](polyguard-rl/data/raw/knowledge/drug_knowledge.json).
647
+ It contains drug classes, example high-risk pairs, renal and hepatic flags,
648
+ side-effect tags, substitution rules, and taper requirements. The processed
649
+ tables then feed graph modeling, candidate generation, environment scenarios,
650
+ retrieval, SFT rows, and GRPO prompts.
651
+
652
+ The full training/evidence runs used 2,000 examples per Qwen model, recorded in
653
+ the final reports under
654
+ [docs/results/final_submission_evidence/reports/](polyguard-rl/docs/results/final_submission_evidence/reports/).
655
+
656
+ ## Models Inside The Environment
657
+
658
+ PolyGuard combines learned and rule-backed components:
659
+
660
+ - Graph safety model:
661
+ [app/models/graph/](polyguard-rl/app/models/graph/) produces regimen
662
+ embeddings, pairwise DDI severity, severe-alert probability, and side-effect
663
+ tag probabilities. Fallback graph features include drug identity hashes,
664
+ class counts, side-effect load, medication count, contraindicated-pair count,
665
+ and class flags.
666
+ - Tabular risk model:
667
+ [app/models/tabular/](polyguard-rl/app/models/tabular/) supports calibrated
668
+ patient/regimen risk heads and evaluation.
669
+ - Dosing model:
670
+ [app/models/dosing/](polyguard-rl/app/models/dosing/) models dose-sensitive
671
+ states with target attainment, toxicity, underdose risk, organ stress,
672
+ interaction load, and monitoring need.
673
+ - Retrieval:
674
+ [app/models/retrieval/](polyguard-rl/app/models/retrieval/) and
675
+ [app/knowledge/](polyguard-rl/app/knowledge/) provide local evidence chunks,
676
+ drug rules, renal/hepatic guardrails, duplicate therapy rules, substitution
677
+ rules, taper rules, burden scoring, and side-effect ontology.
678
+ - Active model runtime:
679
+ [app/models/policy/active_model.py](polyguard-rl/app/models/policy/active_model.py)
680
+ discovers activated artifacts from `checkpoints/active/active_model_manifest.json`.
681
+ The provider load order prefers a GRPO adapter, then merged model, then SFT
682
+ adapter.
683
+ - Provider runtime:
684
+ [app/models/policy/provider_runtime.py](polyguard-rl/app/models/policy/provider_runtime.py)
685
+ is Transformers-first, with optional Ollama when enabled. If model loading is
686
+ unavailable, the runtime falls back to deterministic safety ranking.
687
+
688
+ Tracked support-model reports show that the environment is not only an LLM
689
+ wrapper:
690
+
691
+ | Component | Report | Current tracked result |
692
+ | --- | --- | --- |
693
+ | Graph model | [docs/results/graph_train.json](polyguard-rl/docs/results/graph_train.json) | `status: trained`, `num_samples: 180`, artifact path `outputs/models/graph_model.pkl` |
694
+ | Tabular risk model | [docs/results/risk_train.json](polyguard-rl/docs/results/risk_train.json) | `status: trained`, `dataset_size: 180`, `train_mae: 0.0033`, artifact path `outputs/models/tabular_risk.pkl` |
695
+ | Dose surrogate model | [docs/results/dose_train.json](polyguard-rl/docs/results/dose_train.json) | `status: trained`, `dataset_size: 120`, `train_mae: 0.0025`, artifact path `outputs/models/dose_model.pkl` |
696
+
697
+ The hard-coded contraindicated seed pairs in
698
+ [app/knowledge/ddi_knowledge.py](polyguard-rl/app/knowledge/ddi_knowledge.py)
699
+ include `warfarin_like` + `nsaid_like` and `benzodiazepine_like` +
700
+ `opioid_like`. Substitution rules in
701
+ [app/knowledge/substitution_rules.py](polyguard-rl/app/knowledge/substitution_rules.py)
702
+ include safer alternatives such as `nsaid_like -> acetaminophen_like`,
703
+ `nsaid_like -> topical_nsaid_like`, `benzodiazepine_like ->
704
+ non_benzo_sleep_support`, and `opioid_like -> non_opioid_analgesic`.
705
+
706
+ ### Precision Dosing Details
707
+
708
+ Precision dosing uses sensitive classes such as anticoagulants, sedatives, and
709
+ glucose-lowering drugs. The dosing agent and surrogate model are implemented in
710
+ [app/agents/dosing_agent.py](polyguard-rl/app/agents/dosing_agent.py) and
711
+ [app/models/dosing/](polyguard-rl/app/models/dosing/).
712
+
713
+ The surrogate PK/PD transition in
714
+ [app/models/dosing/surrogate_pkpd.py](polyguard-rl/app/models/dosing/surrogate_pkpd.py)
715
+ uses effect, toxicity, underdose, organ stress, and interaction load:
716
+
717
+ ```text
718
+ effective_delta = dose_delta * (1 - min(0.6, organ_factor * 0.4))
719
+
720
+ effect' =
721
+ clip(effect + 0.28 * effective_delta - 0.05 * interaction_factor, 0, 1)
722
+
723
+ toxicity_gain =
724
+ max(0, dose_delta) * (0.35 + 0.25 * organ_factor + 0.20 * interaction_factor)
725
+
726
+ toxicity' =
727
+ clip(0.85 * toxicity + toxicity_gain, 0, 1)
728
+
729
+ underdose' =
730
+ clip(1 - effect' + 0.15 * max(0, -dose_delta), 0, 1)
731
+ ```
732
+
733
+ The higher-level dosing metrics use target attainment, toxicity avoidance,
734
+ underdose risk, and monitoring need:
735
+
736
+ ```text
737
+ target_attainment = 1 - abs(effect_level - 0.62)
738
+ toxicity_proxy = toxicity_level + 0.20 * organ_stress + 0.12 * interaction_load
739
+ measurement_need = max(toxicity_proxy, underdose_proxy)
740
+ ```
741
+
742
+ ## Training And Post-Training
743
+
744
+ The training stack is deliberately staged:
745
+
746
+ 1. Build structured data, scenarios, retrieval records, SFT examples, and GRPO
747
+ prompts.
748
+ 2. Run SFT with TRL to teach the model the candidate-id format and obvious
749
+ clinical priors.
750
+ 3. Run GRPO with environment-backed reward, where sampled candidate completions
751
+ are executed in PolyGuardEnv and scored by the verifier/reward router.
752
+ 4. Track sampled generations, reward components, primary reward channels,
753
+ legality, anti-cheat events, and training curves.
754
+ 5. Run policy-stack ablations and baseline comparisons.
755
+ 6. Merge or export adapters safely.
756
+ 7. Validate post-save inference from the saved artifact, not from an in-memory
757
+ training object.
758
+ 8. Generate reports, charts, action traces, and final artifact manifests.
759
+
760
+ The relevant training source files are:
761
+
762
+ - [scripts/train_sft_trl.py](polyguard-rl/scripts/train_sft_trl.py)
763
+ - [scripts/train_grpo_trl.py](polyguard-rl/scripts/train_grpo_trl.py)
764
+ - [app/training/sft_trl.py](polyguard-rl/app/training/sft_trl.py)
765
+ - [app/training/grpo_trl.py](polyguard-rl/app/training/grpo_trl.py)
766
+ - [app/training/reward_functions.py](polyguard-rl/app/training/reward_functions.py)
767
+ - [app/training/openenv_wrapper.py](polyguard-rl/app/training/openenv_wrapper.py)
768
+ - [app/hf_space/training_runner.py](polyguard-rl/app/hf_space/training_runner.py)
769
+
770
+ The one-run notebook is
771
+ [polyguard-rl/PolyGuard_SFT_GRPO_One_Run_Runner.ipynb](polyguard-rl/PolyGuard_SFT_GRPO_One_Run_Runner.ipynb).
772
+ It is the accessible Colab/HF workflow for building data, running checks,
773
+ launching training, pulling reports, generating charts, validating inference,
774
+ activating a model, deploying the product Space, and running acceptance checks.
775
+
776
+ The modular notebook series is:
777
+
778
+ - [01_data_building.ipynb](polyguard-rl/notebooks/01_data_building.ipynb)
779
+ - [02_knowledge_graph.ipynb](polyguard-rl/notebooks/02_knowledge_graph.ipynb)
780
+ - [03_risk_models.ipynb](polyguard-rl/notebooks/03_risk_models.ipynb)
781
+ - [04_environment_validation.ipynb](polyguard-rl/notebooks/04_environment_validation.ipynb)
782
+ - [05_sft_debug.ipynb](polyguard-rl/notebooks/05_sft_debug.ipynb)
783
+ - [06_grpo_debug.ipynb](polyguard-rl/notebooks/06_grpo_debug.ipynb)
784
+ - [07_policy_analysis.ipynb](polyguard-rl/notebooks/07_policy_analysis.ipynb)
785
+ - [08_dosing_analysis.ipynb](polyguard-rl/notebooks/08_dosing_analysis.ipynb)
786
+ - [09_training_loop.ipynb](polyguard-rl/notebooks/09_training_loop.ipynb)
787
+
788
+ For exact local and remote execution details, use
789
+ [docs/training.md](polyguard-rl/docs/training.md) and
790
+ [docs/submission_artifacts.md](polyguard-rl/docs/submission_artifacts.md).
791
+ Those docs contain operational notes; this README keeps the blog story focused
792
+ on architecture, data, evaluation, and evidence.
793
+
794
+ ## Training Curves And Model Results
795
+
796
+ The final curated evidence lives in
797
+ [polyguard-rl/docs/results/final_submission_evidence/](polyguard-rl/docs/results/final_submission_evidence/).
798
+ It replaces earlier smoke-run charts and older 0.5B/1.5B-only views.
799
+
800
+ ### SFT Loss Across Qwen Runs
801
+
802
+ ![SFT loss curves across Qwen runs](polyguard-rl/docs/results/final_submission_evidence/charts/curated/training/sft_loss_curves_all_models.png)
803
+
804
+ The SFT curves, post-save valid rates, and token-accuracy histories together
805
+ show that the models learned the candidate-id output contract rather than only
806
+ producing unconstrained prose. The visible curves drop from roughly `3.0-3.6`
807
+ initial loss to low final loss across all three Qwen sizes.
808
+
809
+ ![Qwen 3B SFT training loss](polyguard-rl/docs/results/final_submission_evidence/charts/curated/training/qwen_3b_sft_training_loss.png)
810
+
811
+ The tracked per-model summaries are:
812
+
813
+ | Run | Model | Epochs | Final step | Runtime | Key SFT metrics |
814
+ | --- | --- | ---: | ---: | ---: | --- |
815
+ | `qwen-qwen2-5-0-5b-instruct` | `Qwen/Qwen2.5-0.5B-Instruct` | 2 | 2,000 | `234.6302s` | loss `3.0856 -> 0.0626`, best `0.0057`, train loss `0.1923`, token accuracy `0.9717`, valid rate `1.0`, avg env reward `0.726`, latency `1.839s` |
816
+ | `qwen-qwen2-5-1-5b-instruct` | `Qwen/Qwen2.5-1.5B-Instruct` | 2 | 4,000 | `483.7085s` | loss `2.9686 -> 0.0681`, best `0.0009`, train loss `0.1152`, token accuracy `0.9726`, valid rate `1.0`, avg env reward `0.726`, latency `2.158s` |
817
+ | `qwen-qwen2-5-3b-instruct` | `Qwen/Qwen2.5-3B-Instruct` | 2 | 2,000 | `715.2908s` | loss `3.5687 -> 0.054`, best `0.0022`, train loss `0.1569`, token accuracy `0.9750`, SFT avg env reward `0.781`, SFT latency `2.863s` |
818
+
819
+ Each SFT run used `2,000` examples. The 0.5B and 3B runs recorded `2,001`
820
+ history rows including the final trainer summary; the 1.5B run recorded `4,001`
821
+ history rows because its batch configuration produced `4,000` final steps.
822
+
823
+ ### GRPO Reward Curve
824
+
825
+ ![Qwen 3B GRPO reward curve](polyguard-rl/docs/results/final_submission_evidence/charts/curated/training/qwen_3b_grpo_reward_curve.png)
826
+
827
+ ![Qwen 3B GRPO training loss](polyguard-rl/docs/results/final_submission_evidence/charts/curated/training/qwen_3b_grpo_loss_curve.png)
828
+
829
+ The complete GRPO evidence is available for Qwen 3B:
830
+
831
+ - Backend: `trl_transformers`
832
+ - Model: `Qwen/Qwen2.5-3B-Instruct`
833
+ - Records: `2000`
834
+ - Epochs: `1.0`
835
+ - Final step: `2000`
836
+ - Runtime: `6873.9375s` (`1.91h`)
837
+ - Reward samples: `4000`
838
+ - GRPO average reward: `0.767`
839
+ - GRPO reward history: min `0.376`, max `0.880`, last `0.812`, average `0.76685`
840
+ - GRPO train loss: `0.000002665`
841
+ - Post-save GRPO valid rate: `1.0`
842
+ - Post-save GRPO average environment reward: `0.726`
843
+ - Post-save GRPO average latency: `3.681s`
844
+ - Artifact path recorded in the report: `checkpoints/sweeps/qwen-qwen2-5-3b-instruct/grpo_adapter`
845
+
846
+ The source reports are:
847
+
848
+ - [reports/grpo_trl_run.json](polyguard-rl/docs/results/final_submission_evidence/reports/grpo_trl_run.json)
849
+ - [reports/postsave_inference_grpo.json](polyguard-rl/docs/results/final_submission_evidence/reports/postsave_inference_grpo.json)
850
+ - [reports/submission_summary.json](polyguard-rl/docs/results/final_submission_evidence/reports/submission_summary.json)
851
+
852
+ ### SFT vs GRPO By Model
853
+
854
+ ![SFT vs GRPO verifier reward by model](polyguard-rl/docs/results/final_submission_evidence/charts/curated/model_comparison/sft_vs_grpo_reward_by_model.png)
855
+
856
+ This chart is intentionally transparent about artifact availability. Qwen 0.5B
857
+ and 1.5B have SFT reports/histories and post-save SFT evidence in the repo, but
858
+ their adapter directories were not present in the local/final artifact mirrors
859
+ at packaging time. Qwen 3B has the complete SFT plus GRPO artifact set.
860
+
861
+ The packaged manifest records Qwen 3B as complete with `125` checkpoint files
862
+ (`433,208,536` bytes), `11` SFT adapter files (`30,655,905` bytes), `11` GRPO
863
+ adapter files (`30,656,841` bytes), and `9` report files (`5,930,214` bytes).
864
+ Qwen 0.5B and 1.5B are retained as report/post-save evidence only.
865
+
866
+ The manifest records this explicitly:
867
+ [docs/results/final_submission_evidence/manifest.json](polyguard-rl/docs/results/final_submission_evidence/manifest.json).
868
+
869
+ ### Product Pipeline vs Basic LLM Proxy
870
+
871
+ ![Basic LLM vs full PolyGuard pipeline](polyguard-rl/docs/results/final_submission_evidence/charts/curated/product_over_basic_llm/basic_llm_vs_full_pipeline_reward.png)
872
+
873
+ Matched-seed evaluation compares a basic LLM-style first-legal proxy, an
874
+ SFT-style safety ranker, and the full PolyGuard orchestrated pipeline. The same
875
+ PolyGuard verifier/reward system judges all three.
876
+
877
+ | Policy | Episodes | Avg reward | Legality rate | Failure/exploit rate | Candidate diversity |
878
+ | --- | ---: | ---: | ---: | ---: | ---: |
879
+ | Basic LLM proxy | 8 | `0.762` | `1.0` | `0.25` | 1 |
880
+ | SFT policy proxy | 8 | `0.818` | `1.0` | `0.0` | 2 |
881
+ | Full PolyGuard pipeline | 8 | `0.805` | `1.0` | `0.0` | 2 |
882
+
883
+ The full pipeline improves average verifier reward over the basic LLM proxy by
884
+ `+0.043` while reducing visible failure/exploit rate from `0.25` to `0.0`.
885
+
886
+ ![Reward delta by matched seed](polyguard-rl/docs/results/final_submission_evidence/charts/curated/product_over_basic_llm/reward_delta_by_seed.png)
887
+
888
+ Two matched seeds expose the core failure mode: the basic policy repeatedly
889
+ kept a regimen despite the hidden `warfarin_like` + `nsaid_like` DDI holdout,
890
+ triggering `holdout_ddi_not_addressed`. The full pipeline selected safer dose
891
+ or hold candidates and avoided those failure reasons.
892
+
893
+ Source:
894
+ [reports/basic_llm_vs_polyguard_report.json](polyguard-rl/docs/results/final_submission_evidence/reports/basic_llm_vs_polyguard_report.json).
895
+
896
+ ### Reward Components And Channels
897
+
898
+ ![Reward component bars](polyguard-rl/docs/results/final_submission_evidence/charts/curated/reward_and_safety/reward_component_bars.png)
899
+
900
+ ![Primary reward channel bars](polyguard-rl/docs/results/final_submission_evidence/charts/curated/reward_and_safety/primary_reward_channel_bars.png)
901
+
902
+ The reward charts are as important as the scalar reward curve. They show whether
903
+ the model is improving by becoming safer and more process-faithful or merely
904
+ exploiting one easy component. The reports log the full 13-component reward
905
+ vector and the four primary channels for GRPO and evaluation runs.
906
+
907
+ For Qwen 3B GRPO, the tracked average primary channels are:
908
+
909
+ | Channel | Average |
910
+ | --- | ---: |
911
+ | `safety_legality` | `0.816` |
912
+ | `clinical_improvement` | `0.609` |
913
+ | `dosing_quality` | `0.543` |
914
+ | `process_integrity` | `0.875` |
915
+
916
+ ### Post-Save Inference
917
+
918
+ ![Inference validity and reward](polyguard-rl/docs/results/final_submission_evidence/charts/curated/inference/inference_validity_reward.png)
919
+
920
+ Post-save inference is a separate check from training. The exported/activated
921
+ artifact is loaded and asked to choose candidate ids on held prompt samples. The
922
+ Qwen 3B GRPO adapter path produced:
923
+
924
+ - `model_source: adapter`
925
+ - `samples: 5`
926
+ - `valid_rate: 1.0`
927
+ - `avg_env_reward: 0.726`
928
+ - `avg_latency_seconds: 3.681`
929
+
930
+ This is why the README treats post-training as more than a training log: the
931
+ saved artifact must still produce parseable candidate ids and executable
932
+ environment actions.
933
+
934
+ One caveat matters: `valid_rate: 1.0` means the output was parseable and
935
+ executable as a candidate selection. In the five-sample Qwen 3B post-save GRPO
936
+ report, four valid samples still terminated with `exploit_detection`. That is
937
+ retained as safety evidence, because PolyGuard's job is to expose suspicious or
938
+ loop-like behavior instead of hiding it behind a clean parse metric.
939
+
940
+ ## Agentic Evaluation
941
+
942
+ Evaluation is not just one benchmark number. The evaluation stack under
943
+ [app/evaluation/](polyguard-rl/app/evaluation/) includes:
944
+
945
+ - Offline policy evaluation.
946
+ - Safety evaluation.
947
+ - Dosing evaluation.
948
+ - Robustness under missing labs, noisy dose info, conflicting medications,
949
+ alias noise, hidden duplicate therapy, wrong candidate ids, stale evidence,
950
+ and delayed adverse event manifestation.
951
+ - Calibration and abstention evaluation.
952
+ - Process fidelity and invalid-action tracking.
953
+ - Subgroup summaries for renal compromise, hepatic compromise, and frailty.
954
+ - Explainability grounding.
955
+ - Baseline comparison.
956
+ - Policy ablations.
957
+ - Failure mining and action traces.
958
+
959
+ The tracked benchmark report records:
960
+
961
+ | Metric family | Result |
962
+ | --- | --- |
963
+ | Offline avg reward | `0.772833` |
964
+ | Offline legal rate | `1.0` |
965
+ | Severe violation rate | `0.0` |
966
+ | Illegal step rate | `0.0` |
967
+ | Dosing target attainment | `0.75` |
968
+ | Dosing toxicity avoidance | `1.0` |
969
+ | Missing-labs safety rate | `0.666667` |
970
+ | Noisy-dose, conflicting-meds, alias-noise, hidden-duplicate, wrong-candidate-id, stale-evidence, delayed-ADE safety/resilience | `1.0` |
971
+ | Calibration ECE proxy | `0.08625` |
972
+ | Process fidelity | `0.92` |
973
+ | Explainability grounding | `0.8` |
974
+
975
+ Source:
976
+ [docs/results/benchmark_report.json](polyguard-rl/docs/results/benchmark_report.json).
977
+
978
+ The improvement gate compares baseline and candidate reports:
979
+
980
+ | Gate dimension | Delta |
981
+ | --- | ---: |
982
+ | Average reward | `+0.025833` |
983
+ | Legality rate | `0.0` non-regression |
984
+ | Success rate | `0.0` non-regression |
985
+ | Process fidelity | `+0.92` |
986
+ | Timeout rate | `0.0` non-regression |
987
+ | Failure visibility | `0.0` non-regression |
988
+
989
+ Source:
990
+ [docs/results/improvement_report.json](polyguard-rl/docs/results/improvement_report.json).
991
+
992
+ ### Policy Ablation Results
993
+
994
+ | Stack | Avg reward | Legality | Visible failure rate | Exploit detections | Interpretation |
995
+ | --- | ---: | ---: | ---: | ---: | --- |
996
+ | `bandit_only` | `0.779625` | `1.0` | `0.0625` | 2 | Strong deterministic shortlist behavior with low failure visibility |
997
+ | `llm_only` | `0.772391` | `1.0` | `0.3043` | 7 | Legal, but more loop-like failure behavior |
998
+ | `llm+bandit` | `0.764739` | `1.0` | `0.3043` | 7 | Current combined stack needs tighter exploration/control in these ablation settings |
999
+
1000
+ ![Policy ablation reward](polyguard-rl/docs/results/final_submission_evidence/charts/curated/policy_ablation/policy_ablation_reward.png)
1001
+
1002
+ The point of these ablations is not to claim every combined policy is always
1003
+ better. The point is that PolyGuard can localize behavior: legality remains
1004
+ high, while failure mining shows whether a stack is looping, over-reviewing,
1005
+ or selecting non-improving candidates.
1006
+
1007
+ Source:
1008
+ [reports/policy_ablation_report.json](polyguard-rl/docs/results/final_submission_evidence/reports/policy_ablation_report.json).
1009
+
1010
+ ## OpenEnv And Product Surfaces
1011
+
1012
+ The OpenEnv package is compact:
1013
+
1014
+ ```yaml
1015
+ spec_version: 1
1016
+ name: polyguard-openenv
1017
+ runtime: fastapi
1018
+ app: app.env.fastapi_app:app
1019
+ port: 8100
1020
+ ```
1021
+
1022
+ The OpenEnv runtime exposes:
1023
+
1024
+ - `POST /reset`
1025
+ - `POST /step`
1026
+ - `GET /state`
1027
+ - `GET /metadata`
1028
+ - `GET /schema`
1029
+ - `POST /mcp`
1030
+ - `GET /health`
1031
+ - `GET /ws`
1032
+ - Backward-compatible `/env/*` routes
1033
+
1034
+ The product API in [app/api/routes.py](polyguard-rl/app/api/routes.py) wraps the
1035
+ environment, orchestrator, policy runtime, evaluation, evidence search, cases,
1036
+ metrics, and medication-alternative tooling. Useful product-facing endpoints
1037
+ include `/env/reset`, `/env/step_candidate`, `/agents/orchestrate`,
1038
+ `/policy/infer`, `/policy/model_status`, `/eval/run_policy`,
1039
+ `/metrics/training`, `/evidence/query`, and `/tools/medication_alternatives`.
1040
+
1041
+ ![Deployment topology](polyguard-rl/docs/assets/diagrams/deployment_topology.png)
1042
+
1043
+ ## Operations And Deployment
1044
+
1045
+ The repository keeps deployment and artifact operations explicit:
1046
+
1047
+ | Surface | Files |
1048
+ | --- | --- |
1049
+ | Local/container runtime | [Dockerfile](polyguard-rl/Dockerfile), [Dockerfile.space](polyguard-rl/Dockerfile.space), [docker-compose.yml](polyguard-rl/docker-compose.yml), [requirements.txt](polyguard-rl/requirements.txt), [requirements-space.txt](polyguard-rl/requirements-space.txt) |
1050
+ | Product Space/API deployment | [scripts/deploy_space.sh](polyguard-rl/scripts/deploy_space.sh), [scripts/deploy_space_api.py](polyguard-rl/scripts/deploy_space_api.py), [docs/deployment.md](polyguard-rl/docs/deployment.md) |
1051
+ | Training and evidence Spaces | [scripts/deploy_training_space.py](polyguard-rl/scripts/deploy_training_space.py), [scripts/monitor_training_space_status.py](polyguard-rl/scripts/monitor_training_space_status.py), [app/hf_space/training_runner.py](polyguard-rl/app/hf_space/training_runner.py), [app/hf_space/evidence_runner.py](polyguard-rl/app/hf_space/evidence_runner.py) |
1052
+ | Artifact packaging and activation | [scripts/deploy_final_artifact_space.py](polyguard-rl/scripts/deploy_final_artifact_space.py), [scripts/package_active_model_bundle.py](polyguard-rl/scripts/package_active_model_bundle.py), [scripts/install_hf_active_bundle.py](polyguard-rl/scripts/install_hf_active_bundle.py), [checkpoints/active/active_model_manifest.json](polyguard-rl/checkpoints/active/active_model_manifest.json) |
1053
+ | Submission validation | [scripts/acceptance_gate.py](polyguard-rl/scripts/acceptance_gate.py), [scripts/validate_submission_links.py](polyguard-rl/scripts/validate_submission_links.py), [docs/submission_checklist.md](polyguard-rl/docs/submission_checklist.md), [docs/submission_artifacts.md](polyguard-rl/docs/submission_artifacts.md) |
1054
+
1055
+ The important operational distinction is that local smoke artifacts, remote
1056
+ training-space logs, final artifact packaging, and active-model installation are
1057
+ separate stages. The final README claims are tied to the curated evidence
1058
+ bundle, not to whichever intermediate output directory happens to exist in a
1059
+ developer checkout.
1060
+
1061
+ ## UI Workbench
1062
+
1063
+ The UI is a React 18 + Vite + TypeScript workbench under
1064
+ [app/ui/frontend/](polyguard-rl/app/ui/frontend/). It is not the environment
1065
+ itself; it is an operator surface over the API and OpenEnv runtime.
1066
+
1067
+ [Live workbench Space](https://huggingface.co/spaces/TheJackBright/polyguard-openenv-workbench)
1068
+
1069
+ ![Frontend runtime surface](polyguard-rl/docs/assets/diagrams/frontend_runtime_surface.png)
1070
+
1071
+ The main views cover:
1072
+
1073
+ - Patient workbench.
1074
+ - Episode replay.
1075
+ - Policy comparison and policy lab.
1076
+ - Precision dosing.
1077
+ - Training monitor.
1078
+ - Safety inspector.
1079
+ - Candidate actions.
1080
+ - Reward panel.
1081
+ - Episode trace.
1082
+ - Alternative medication search through `/tools/medication_alternatives`.
1083
+
1084
+ The Patient Workbench shows the active model chip, current scenario, candidate
1085
+ set, agent-vs-environment flow, reward breakdown, and action trace without
1086
+ requiring the reader to inspect raw JSON. The UI is intentionally a workbench,
1087
+ not a polished clinical application.
1088
+
1089
+ ### UI Sequence
1090
+
1091
+ These screenshots are included in the repo under `polyguard-rl/docs/UI Images/`.
1092
+ The image links below use URL-encoded paths so they render correctly when the
1093
+ README is viewed on GitHub or inside the Hugging Face Space.
1094
+
1095
+ 1. The workbench opens with model truth, live episode context, scenario status,
1096
+ candidate count, and reward state.
1097
+
1098
+ ![PolyGuard workbench overview](polyguard-rl/docs/UI%20Images/1.jpeg)
1099
+
1100
+ 2. The episode panel makes the patient, task, difficulty, sub-environment, risk
1101
+ delta, and candidate-action console visible without reading raw JSON.
1102
+
1103
+ ![Episode overview and candidate console](polyguard-rl/docs/UI%20Images/2.jpeg)
1104
+
1105
+ 3. Candidate selection is paired with reward-channel feedback, current
1106
+ medications, and blocked/available action visibility.
1107
+
1108
+ ![Candidate actions and reward channels](polyguard-rl/docs/UI%20Images/3.jpeg)
1109
+
1110
+ 4. After an action, the workbench exposes history, warnings, decision payload,
1111
+ grounded facts, explanation, evidence, and event logs.
1112
+
1113
+ ![Action history, decision payload, and evidence](polyguard-rl/docs/UI%20Images/4.jpeg)
1114
+
1115
+ 5. The alternatives tool surfaces medication substitutions from the current
1116
+ regimen and links out to source labels.
1117
+
1118
+ ![Medication alternatives tool](polyguard-rl/docs/UI%20Images/5.jpeg)
1119
+
1120
+ ## [UI Walkthrough Video](https://drive.google.com/file/d/1YOzad5gvx-tSmGzJNuBgokBF4-dX2T2H/view?usp=sharing)
1121
+
1122
+ This walkthrough shows the deployed workbench surface, including the live model
1123
+ chip, episode context, candidate actions, reward panels, and evidence-oriented
1124
+ patient review flow.
1125
+
1126
+ ## [Agent In Action: Action Button Demo](https://drive.google.com/file/d/1eHk1v0OYJRrLWVO97ZclN05MYHxmNnmc/view?usp=sharing)
1127
+
1128
+ This demo focuses on what the action button does: selecting a candidate,
1129
+ submitting it through the environment, producing a verifier-scored transition,
1130
+ and exposing the resulting reward, action history, warnings, and explanation.
1131
+
1132
+ ## [World Model Tool: Tavily And OpenFDA Alternative Suggestions](https://drive.google.com/file/d/1GaUyyaXaBCHjhHFbpkprojNt5pLNAoYi/view?usp=sharing)
1133
+
1134
+ This tool demo shows the world-model support path for alternative medication
1135
+ suggestions, using Tavily and the OpenFDA government database to retrieve
1136
+ candidate alternatives and side-effect evidence for safer review.
1137
+
1138
+ ## Execution Path For Readers
1139
+
1140
+ For a fresh reviewer, the intended path is:
1141
+
1142
+ 1. Read the artifact index:
1143
+ [polyguard-rl/docs/submission_artifacts.md](polyguard-rl/docs/submission_artifacts.md).
1144
+ 2. Inspect the final curated evidence:
1145
+ [polyguard-rl/docs/results/final_submission_evidence/README.md](polyguard-rl/docs/results/final_submission_evidence/README.md).
1146
+ 3. Open the one-run notebook:
1147
+ [PolyGuard_SFT_GRPO_One_Run_Runner.ipynb](polyguard-rl/PolyGuard_SFT_GRPO_One_Run_Runner.ipynb).
1148
+ 4. For local smoke work, follow [docs/training.md](polyguard-rl/docs/training.md)
1149
+ and the local scripts:
1150
+ [scripts/run_env_local.sh](polyguard-rl/scripts/run_env_local.sh),
1151
+ [scripts/run_api_local.sh](polyguard-rl/scripts/run_api_local.sh), and
1152
+ [scripts/run_ui_local.sh](polyguard-rl/scripts/run_ui_local.sh).
1153
+ 5. For full training/reproduction, use the notebook or training docs rather
1154
+ than copying private artifact commands out of old drafts.
1155
+ 6. For final public artifacts, use the final artifact Space:
1156
+ [adithya9903/polyguard-openenv-final-artifacts](https://huggingface.co/spaces/adithya9903/polyguard-openenv-final-artifacts).
1157
+
1158
+ ## Evidence And Artifact Inventory
1159
+
1160
+ Important evidence paths:
1161
+
1162
+ - Final overview:
1163
+ [docs/results/final_submission_evidence/README.md](polyguard-rl/docs/results/final_submission_evidence/README.md)
1164
+ - Artifact manifest:
1165
+ [docs/results/final_submission_evidence/manifest.json](polyguard-rl/docs/results/final_submission_evidence/manifest.json)
1166
+ - Three-model summary:
1167
+ [docs/results/final_submission_evidence/reports/submission_summary.json](polyguard-rl/docs/results/final_submission_evidence/reports/submission_summary.json)
1168
+ - Qwen 3B GRPO report:
1169
+ [docs/results/final_submission_evidence/reports/grpo_trl_run.json](polyguard-rl/docs/results/final_submission_evidence/reports/grpo_trl_run.json)
1170
+ - Post-save GRPO inference:
1171
+ [docs/results/final_submission_evidence/reports/postsave_inference_grpo.json](polyguard-rl/docs/results/final_submission_evidence/reports/postsave_inference_grpo.json)
1172
+ - Basic LLM vs PolyGuard:
1173
+ [docs/results/final_submission_evidence/reports/basic_llm_vs_polyguard_report.json](polyguard-rl/docs/results/final_submission_evidence/reports/basic_llm_vs_polyguard_report.json)
1174
+ - Policy ablation:
1175
+ [docs/results/final_submission_evidence/reports/policy_ablation_report.json](polyguard-rl/docs/results/final_submission_evidence/reports/policy_ablation_report.json)
1176
+ - Action traces:
1177
+ [docs/results/final_submission_evidence/reports/action_traces.jsonl](polyguard-rl/docs/results/final_submission_evidence/reports/action_traces.jsonl)
1178
+ - Curated charts:
1179
+ [docs/results/final_submission_evidence/charts/curated/README.md](polyguard-rl/docs/results/final_submission_evidence/charts/curated/README.md)
1180
+
1181
+ Important tests:
1182
+
1183
+ | Category | Tests |
1184
+ | --- | --- |
1185
+ | Environment contract | [tests/test_openenv_contract.py](polyguard-rl/tests/test_openenv_contract.py), [tests/test_env_reset.py](polyguard-rl/tests/test_env_reset.py), [tests/test_env_step.py](polyguard-rl/tests/test_env_step.py), [tests/test_env_step_flow.py](polyguard-rl/tests/test_env_step_flow.py), [tests/test_future_subenvs.py](polyguard-rl/tests/test_future_subenvs.py) |
1186
+ | Reward and safety | [tests/test_reward_functions.py](polyguard-rl/tests/test_reward_functions.py), [tests/test_reward_range.py](polyguard-rl/tests/test_reward_range.py), [tests/test_reward_channels.py](polyguard-rl/tests/test_reward_channels.py), [tests/test_anti_cheat.py](polyguard-rl/tests/test_anti_cheat.py), [tests/test_constraints.py](polyguard-rl/tests/test_constraints.py), [tests/test_timeout_logic.py](polyguard-rl/tests/test_timeout_logic.py) |
1187
+ | Policy and runtime | [tests/test_agents.py](polyguard-rl/tests/test_agents.py), [tests/test_contextual_bandit.py](polyguard-rl/tests/test_contextual_bandit.py), [tests/test_policy_schema.py](polyguard-rl/tests/test_policy_schema.py), [tests/test_provider_runtime.py](polyguard-rl/tests/test_provider_runtime.py), [tests/test_postsave_inference.py](polyguard-rl/tests/test_postsave_inference.py), [tests/test_checkpoint_integrity.py](polyguard-rl/tests/test_checkpoint_integrity.py) |
1188
+ | API and product tooling | [tests/test_api.py](polyguard-rl/tests/test_api.py), [tests/test_medication_alternatives.py](polyguard-rl/tests/test_medication_alternatives.py), [tests/test_remote_env.py](polyguard-rl/tests/test_remote_env.py) |
1189
+ | Data and evidence | [tests/test_parser.py](polyguard-rl/tests/test_parser.py), [tests/test_dataops_parser.py](polyguard-rl/tests/test_dataops_parser.py), [tests/test_graph_infer.py](polyguard-rl/tests/test_graph_infer.py), [tests/test_submission_evidence.py](polyguard-rl/tests/test_submission_evidence.py) |
1190
+ | Submission, notebook, and HF flow | [tests/test_acceptance_gate.py](polyguard-rl/tests/test_acceptance_gate.py), [tests/test_runner_notebook.py](polyguard-rl/tests/test_runner_notebook.py), [tests/test_hf_training_sweep.py](polyguard-rl/tests/test_hf_training_sweep.py) |
1191
+
1192
+ Additional architecture diagrams:
1193
+
1194
+ - [System architecture](polyguard-rl/docs/assets/diagrams/system_architecture.png)
1195
+ - [Runtime step flow](polyguard-rl/docs/assets/diagrams/runtime_step_flow.png)
1196
+ - [Data and training pipeline](polyguard-rl/docs/assets/diagrams/data_training_pipeline.png)
1197
+ - [Multi-agent orchestration](polyguard-rl/docs/assets/diagrams/multi_agent_orchestration.png)
1198
+ - [Reward decomposition](polyguard-rl/docs/assets/diagrams/reward_decomposition.png)
1199
+ - [Episode state machine](polyguard-rl/docs/assets/diagrams/episode_state_machine.png)
1200
+ - [Evidence generation flow](polyguard-rl/docs/assets/diagrams/evidence_generation_flow.png)
1201
+ - [Deployment topology](polyguard-rl/docs/assets/diagrams/deployment_topology.png)
1202
+ - [Frontend runtime surface](polyguard-rl/docs/assets/diagrams/frontend_runtime_surface.png)
1203
+
1204
+ ## Limitations
1205
+
1206
+ PolyGuard is a simulator and research environment. Its current data substrate is
1207
+ compact and intentionally inspectable, not a production clinical knowledge base.
1208
+ The final evidence set is strongest for Qwen 3B because that run has complete
1209
+ SFT, GRPO, post-save GRPO, policy-ablation, adapter, and checkpoint evidence.
1210
+ Qwen 0.5B and 1.5B have SFT reports/histories and post-save SFT evidence, but
1211
+ their adapter directories are marked `reports_only_or_partial` in the final
1212
+ manifest.
1213
+
1214
+ The reward model is hand-designed and auditable; that is a feature for this
1215
+ OpenEnv setting, but it also means reward-channel design should be stress-tested
1216
+ as the data grows. The current ablations show that contextual bandits are useful
1217
+ and inspectable, while the `llm+bandit` combined stack needs more tuning to
1218
+ avoid loop-like failure behavior in some settings.
1219
+
1220
+ The right conclusion is not "this is a clinical decision system." The right
1221
+ conclusion is that constrained environment feedback, verifier-backed rewards,
1222
+ agentic evaluation, and explicit failure mining are a better substrate for
1223
+ safety-critical medication-policy learning than free-form prompt responses.
1224
+
1225
+ ## References
1226
+
1227
+ - Alexandre Larouche, Audrey Durand, Richard Khoury, Caroline Sirois.
1228
+ [Neural Bandits for Data Mining: Searching for Dangerous Polypharmacy](https://arxiv.org/abs/2212.05190).
1229
+ arXiv:2212.05190.
1230
+ - World Health Organization.
1231
+ [Medication Without Harm](https://www.who.int/initiatives/medication-without-harm).
1232
+ - CDC.
1233
+ [FastStats: Medication Safety Data](https://www.cdc.gov/medication-safety/data-research/facts-stats/index.html).
1234
+ - Shehab N, Lovegrove MC, Geller AI, et al.
1235
+ [US Emergency Department Visits for Outpatient Adverse Drug Events, 2013-2014](https://jamanetwork.com/journals/jama/fullarticle/2585977).
1236
+ JAMA. 2016;316(20):2115-2125.
1237
+ - AHRQ / NCBI Bookshelf.
1238
+ [Deprescribing To Reduce Medication Harms in Older Adults](https://www.ncbi.nlm.nih.gov/books/NBK600387/).
1239
+ - American Geriatrics Society.
1240
+ [2023 updated AGS Beers Criteria for potentially inappropriate medication use in older adults](https://pmc.ncbi.nlm.nih.gov/articles/PMC12478568/).
1241
+ - O'Mahony et al.
1242
+ [STOPP/START criteria for potentially inappropriate prescribing in older people: version 3](https://pmc.ncbi.nlm.nih.gov/articles/PMC10447584/).
1243
+
1244
+ ## License
1245
+
1246
+ The project package declares an MIT license in
1247
+ [polyguard-rl/pyproject.toml](polyguard-rl/pyproject.toml). See
1248
+ [polyguard-rl/LICENSE](polyguard-rl/LICENSE) for the license text.
docs/assets/diagrams/episode_state_machine.png DELETED
Binary file (75.1 kB)
 
docs/assets/diagrams/evidence_generation_flow.png DELETED
Binary file (80.8 kB)
 
docs/assets/diagrams/runtime_step_flow.png DELETED
Binary file (86.4 kB)
 
docs/results/anti_cheat_failure_rates.png DELETED
Binary file (52.3 kB)
 
docs/results/avg_process_fidelity.png DELETED
Binary file (12.5 kB)
 
docs/results/avg_reward.png DELETED
Binary file (11.1 kB)
 
docs/results/final_submission_evidence/charts/all/anti_cheat_failure_rates.png DELETED
Binary file (52.3 kB)
 
docs/results/final_submission_evidence/charts/all/avg_reward.png DELETED
Binary file (11.1 kB)
 
docs/results/final_submission_evidence/charts/all/basic_llm_vs_full_pipeline_latency.png DELETED
Binary file (54.2 kB)
 
docs/results/final_submission_evidence/charts/all/basic_llm_vs_full_pipeline_legality.png DELETED
Binary file (51.9 kB)
 
docs/results/final_submission_evidence/charts/all/basic_llm_vs_full_pipeline_reward.png DELETED
Binary file (58.2 kB)
 
docs/results/final_submission_evidence/charts/all/basic_llm_vs_full_pipeline_reward_delta_by_seed.png DELETED
Binary file (40.6 kB)
 
docs/results/final_submission_evidence/charts/all/grpo_reward_curves.png DELETED
Binary file (18.7 kB)
 
docs/results/final_submission_evidence/charts/all/inference_latency_validity.png DELETED
Binary file (55.6 kB)
 
docs/results/final_submission_evidence/charts/all/inference_validity_reward.png DELETED
Binary file (51.9 kB)
 
docs/results/final_submission_evidence/charts/all/legality_rate.png DELETED
Binary file (10.8 kB)
 
docs/results/final_submission_evidence/charts/all/policy_ablation_avg_reward.png DELETED
Binary file (39.3 kB)
 
docs/results/final_submission_evidence/charts/all/policy_ablation_exploit_detection.png DELETED
Binary file (30.6 kB)
 
docs/results/final_submission_evidence/charts/all/policy_ablation_legality.png DELETED
Binary file (33.2 kB)
 
docs/results/final_submission_evidence/charts/all/policy_stack_avg_reward.png DELETED
Binary file (13.7 kB)
 
docs/results/final_submission_evidence/charts/all/primary_reward_channel_bars.png DELETED
Binary file (51.9 kB)
 
docs/results/final_submission_evidence/charts/all/qwen-qwen2-5-3b-instruct_sft_learning_rate.png DELETED
Binary file (71.7 kB)
 
docs/results/final_submission_evidence/charts/all/qwen-qwen2-5-3b-instruct_sft_token_accuracy.png DELETED
Binary file (82.1 kB)
 
docs/results/final_submission_evidence/charts/all/qwen-qwen2-5-3b-instruct_sft_training_loss.png DELETED
Binary file (67.5 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_final_sft_train_loss.png DELETED
Binary file (37.9 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_postsave_latency.png DELETED
Binary file (34.2 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_postsave_reward.png DELETED
Binary file (40.8 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_remote_completed_stage_durations.png DELETED
Binary file (44.1 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_1_5b_sft_runtime.png DELETED
Binary file (35.4 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_sft_learning_rate.png DELETED
Binary file (71.8 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_sft_token_accuracy.png DELETED
Binary file (84.5 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_sft_training_loss.png DELETED
Binary file (70.4 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_vs_1_5b_sft_loss_comparison.png DELETED
Binary file (80.5 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_0_5b_vs_1_5b_sft_token_accuracy_comparison.png DELETED
Binary file (91.5 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_1_5b_sft_learning_rate.png DELETED
Binary file (70.8 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_1_5b_sft_token_accuracy.png DELETED
Binary file (61.2 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_1_5b_sft_training_loss.png DELETED
Binary file (54.9 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_model_grpo_reward.png DELETED
Binary file (50.8 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_model_sft_loss.png DELETED
Binary file (46.8 kB)
 
docs/results/final_submission_evidence/charts/all/qwen_model_sft_reward.png DELETED
Binary file (49.4 kB)
 
docs/results/final_submission_evidence/charts/all/reward_component_bars.png DELETED
Binary file (18.8 kB)
 
docs/results/final_submission_evidence/charts/all/sft_loss_curves.png DELETED
Binary file (76.6 kB)
 
docs/results/final_submission_evidence/charts/all/sft_validity_reward.png DELETED
Binary file (50.4 kB)
 
docs/results/final_submission_evidence/charts/all/sft_vs_grpo_reward.png DELETED
Binary file (55.1 kB)
 
docs/results/final_submission_evidence/charts/all/train_holdout_gap.png DELETED
Binary file (49.2 kB)
 
docs/results/final_submission_evidence/charts/curated/inference/inference_latency_validity.png DELETED
Binary file (55.6 kB)