sanjay7676 commited on
Commit
49a72d3
Β·
1 Parent(s): 6829d27

Space T4 + real HF path: split requirements, GPU defaults, API reset behavior

Browse files

- Add requirements-core.txt for slim Docker; root requirements.txt pulls core + PyTorch/TRL/PEFT for HF GPU Spaces.
- README Space frontmatter suggested_hardware t4-small; document secrets FORGE_DETERMINISTIC_RESET and FORGE_DEFAULT_PROVIDER.
- config: unset CODE_PROVIDER_MODE defaults to custom_hf when CUDA else offline.
- app: GPU-first provider order, default custom_hf on CUDA, higher episode caps on GPU, clearer provider info, fix coach lesson line duplication.
- trainer: benchmark respects requested episode count (no forced minimum of 20).
- api_server: varied tasks per reset unless FORGE_DETERMINISTIC_RESET=1.
- .env.example aligned with GPU Space defaults.

Made-with: Cursor

Files changed (11) hide show
  1. .env.example +8 -2
  2. Dockerfile +4 -4
  3. Dockerfile.train +1 -1
  4. README.md +16 -11
  5. api_server.py +5 -2
  6. app.py +41 -10
  7. config.py +19 -3
  8. requirements-core.txt +23 -0
  9. requirements-train.txt +2 -2
  10. requirements.txt +13 -23
  11. trainer.py +1 -1
.env.example CHANGED
@@ -15,8 +15,14 @@ OPENROUTER_API_KEY=
15
  OPENROUTER_MODEL=qwen/qwen2.5-coder-7b-instruct
16
  OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
17
 
18
- # Policy "model": offline (default, instant deterministic baseline) | auto | custom_hf | nim | openrouter
19
- CODE_PROVIDER_MODE=offline
 
 
 
 
 
 
20
 
21
  # Cap local HF inference wait (seconds); increase on GPU machines if loads are slow.
22
  ROUTER_HF_TIMEOUT_SEC=90
 
15
  OPENROUTER_MODEL=qwen/qwen2.5-coder-7b-instruct
16
  OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
17
 
18
+ # Policy "model": unset = auto (custom_hf if CUDA, else offline) | auto | custom_hf | nim | openrouter | offline
19
+ CODE_PROVIDER_MODE=custom_hf
20
+
21
+ # Optional: force Gradio default provider (custom_hf | offline | auto | nim | openrouter)
22
+ # FORGE_DEFAULT_PROVIDER=custom_hf
23
+
24
+ # API: set to 1 for identical first-task RNG each POST /reset (harness reproducibility)
25
+ # FORGE_DETERMINISTIC_RESET=0
26
 
27
  # Cap local HF inference wait (seconds); increase on GPU machines if loads are slow.
28
  ROUTER_HF_TIMEOUT_SEC=90
Dockerfile CHANGED
@@ -13,11 +13,11 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
13
  curl \
14
  && rm -rf /var/lib/apt/lists/*
15
 
16
- # Slim image: Gradio + API + OpenEnv (no PyTorch). Builds in minutes β€” same stack as HF CPU Space.
17
- # For training inside Docker: docker build -f Dockerfile.train -t forge:train .
18
- COPY requirements.txt ./
19
  RUN pip install --upgrade pip && \
20
- pip install -r requirements.txt
21
 
22
  COPY . .
23
 
 
13
  curl \
14
  && rm -rf /var/lib/apt/lists/*
15
 
16
+ # Slim image: Gradio + API + OpenEnv (no PyTorch). Builds in minutes.
17
+ # For GPU + local HF inside Docker: docker build -f Dockerfile.train -t forge:train .
18
+ COPY requirements-core.txt ./
19
  RUN pip install --upgrade pip && \
20
+ pip install -r requirements-core.txt
21
 
22
  COPY . .
23
 
Dockerfile.train CHANGED
@@ -15,7 +15,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
15
  curl \
16
  && rm -rf /var/lib/apt/lists/*
17
 
18
- COPY requirements.txt requirements-train.txt ./
19
  RUN pip install --upgrade pip && \
20
  pip install -r requirements.txt -r requirements-train.txt
21
 
 
15
  curl \
16
  && rm -rf /var/lib/apt/lists/*
17
 
18
+ COPY requirements-core.txt requirements.txt requirements-train.txt ./
19
  RUN pip install --upgrade pip && \
20
  pip install -r requirements.txt -r requirements-train.txt
21
 
README.md CHANGED
@@ -9,8 +9,8 @@ sdk_version: 5.25.0
9
  python_version: 3.11
10
  app_file: app.py
11
  pinned: false
12
- # Hint for duplicators; does not upgrade your Space by itself. CPU-friendly demo (no PyTorch in requirements.txt).
13
- suggested_hardware: cpu-basic
14
  ---
15
 
16
  # FORGE-v4 β€” Adversarial self-improvement for robust code generation
@@ -43,11 +43,11 @@ suggested_hardware: cpu-basic
43
  | **Command / security cheat sheet** | [guide.md](guide.md) |
44
  | **Video / slides** | YouTube demo placeholder: https://youtube.com/watch?v=YOUR_DEMO_VIDEO_ID |
45
 
46
- ### Hugging Face Space (CPU-only)
47
 
48
- - This repo’s **Space README** sets **`suggested_hardware: cpu-basic`** (see [Spaces config](https://huggingface.co/docs/hub/spaces-config-reference)). **Pick CPU hardware in the Space Settings UI** if you are not on GPU.
49
- - **`requirements.txt`** is intentionally **light** (no PyTorch / bitsandbytes) so CPU Spaces **build and start** reliably.
50
- - For a **CPU-only** Space, prefer Gradio provider **`offline`** (instant deterministic baseline) or **`auto`** with **NIM / OpenRouter** keys; local **`custom_hf`** loads PyTorch and a 1.5B+LoRA stack and may **OOM or time out** on free CPU.
51
  - **Repository secrets:** names must match environment variables exactly (see table below). After adding or changing secrets, **restart the Space** (or trigger a rebuild) so the container picks them up.
52
  - Full training stack: install **[`requirements-train.txt`](requirements-train.txt)** on **Colab** or locally (see Quickstart).
53
 
@@ -56,7 +56,9 @@ suggested_hardware: cpu-basic
56
  | **`NIM_API_KEY`** or **`NVIDIA_API_KEY`** | NVIDIA NIM chat API (`auto` / **nim**) |
57
  | **`OPENROUTER_API_KEY`** | OpenRouter (`auto` / **openrouter**) |
58
  | **`HF_TOKEN`** or **`HUGGING_FACE_HUB_TOKEN`** | Gated Hub downloads; if set, **`auto`** may try **custom_hf** after cloud APIs |
59
- | **`CODE_PROVIDER_MODE`** | Default when code does not pass a provider (optional; Gradio dropdown still overrides for benchmarks) |
 
 
60
 
61
  ### OpenEnv HTTP API on the Hugging Face Space
62
 
@@ -87,7 +89,7 @@ curl -sS -X POST "https://sanjay7676-team404-forge.hf.space/step" \
87
 
88
  | # | Requirement | FORGE-v4 |
89
  | :--: | :-- | :-- |
90
- | 1 | **OpenEnv (latest):** build on the framework | **`openenv-core>=0.2.3`** in [`requirements.txt`](requirements.txt). Training extras in [`requirements-train.txt`](requirements-train.txt). Wrapper: [`env_openenv.py`](env_openenv.py). Core: [`env.py`](env.py). |
91
  | 2 | **Training:** Unsloth or TRL (or other RL stack) + **Colab** | [`train_unsloth.py`](train_unsloth.py) (Unsloth + TRL), [`train_colab.py`](train_colab.py), [`FORGE_Training_Colab.ipynb`](FORGE_Training_Colab.ipynb), Colab links in the table above. |
92
  | 3 | **Evidence of training:** loss + reward plots (real run) | Committed: [`outputs/reward_curve.png`](outputs/reward_curve.png), [`outputs/loss_curve.png`](outputs/loss_curve.png), [`outputs/pass_rate.png`](outputs/pass_rate.png), [`outputs/final_report.json`](outputs/final_report.json). |
93
  | 4 | **Writeup / video:** mini-blog on HF *or* <2 min YouTube *etc.* | **[BLOG.md](BLOG.md)** plus **[Space Discussions](https://huggingface.co/spaces/sanjay7676/Team404_FORGE/discussions)** for an on-Hub writeup; add **public YouTube or slide URL** in the judge table when published. |
@@ -287,7 +289,7 @@ Implementation: `forge/providers/*.py`, orchestration in `forge/providers/router
287
 
288
  **Hugging Face Space:** [https://huggingface.co/spaces/sanjay7676/Team404_FORGE](https://huggingface.co/spaces/sanjay7676/Team404_FORGE)
289
 
290
- The Space serves **Gradio at `/`** and the same **OpenEnv-style JSON routes** (`/health`, `/reset`, `/step`, `/state`) on the same host. **`POST /reset`** reseeds Python’s RNG so eval harnesses get a **deterministic** first task each episode. For local-only API, run `api_server.py` on port `8000` (see Docker Compose).
291
 
292
  ---
293
 
@@ -328,8 +330,11 @@ The Space serves **Gradio at `/`** and the same **OpenEnv-style JSON routes** (`
328
  ## Quickstart
329
 
330
  ```bash
 
331
  pip install -r requirements.txt
332
- # GPU / training / HF custom local weights (skip on HF CPU Space):
 
 
333
  pip install -r requirements-train.txt
334
 
335
  cp .env.example .env # then edit β€” do not commit .env
@@ -359,7 +364,7 @@ Anyone can `docker pull` a **public** image without logging in. `docker login` i
359
 
360
  ### Build locally, tag, and push to Docker Hub (one-time)
361
 
362
- **Fast image (default `Dockerfile`):** only `requirements.txt` β€” no PyTorch. Usually **a few minutes**. Good for demo, Gradio, and `CODE_PROVIDER_MODE=offline` (or API-backed providers).
363
 
364
  **Full training image:** [`Dockerfile.train`](Dockerfile.train) adds `requirements-train.txt` (PyTorch + CUDA wheels). Expect **tens of minutes to an hour+** on first build.
365
 
 
9
  python_version: 3.11
10
  app_file: app.py
11
  pinned: false
12
+ # Target: NVIDIA T4 Space (local HF inference). CPU-only duplicators: switch hardware in Space Settings and use provider "offline".
13
+ suggested_hardware: t4-small
14
  ---
15
 
16
  # FORGE-v4 β€” Adversarial self-improvement for robust code generation
 
43
  | **Command / security cheat sheet** | [guide.md](guide.md) |
44
  | **Video / slides** | YouTube demo placeholder: https://youtube.com/watch?v=YOUR_DEMO_VIDEO_ID |
45
 
46
+ ### Hugging Face Space (GPU β€” T4 recommended)
47
 
48
+ - This repo’s **Space README** sets **`suggested_hardware: t4-small`** (see [Spaces config](https://huggingface.co/docs/hub/spaces-config-reference)). **Enable a T4 (or better) GPU** in the Space **Settings β†’ Hardware** so **`custom_hf`** can load PyTorch and Hub weights on-device.
49
+ - **`requirements.txt`** includes **`requirements-core.txt`** plus **PyTorch / `transformers` / PEFT / TRL** so **`custom_hf`** is the default path when **CUDA** is visible (real local inference, not a stub).
50
+ - **CPU-only duplicates:** switch hardware to **CPU** in Space Settings and use Gradio provider **`offline`** or API-only keys via **`auto`** (`NIM` / `OpenRouter`); **`custom_hf`** without a GPU is not supported in this layout.
51
  - **Repository secrets:** names must match environment variables exactly (see table below). After adding or changing secrets, **restart the Space** (or trigger a rebuild) so the container picks them up.
52
  - Full training stack: install **[`requirements-train.txt`](requirements-train.txt)** on **Colab** or locally (see Quickstart).
53
 
 
56
  | **`NIM_API_KEY`** or **`NVIDIA_API_KEY`** | NVIDIA NIM chat API (`auto` / **nim**) |
57
  | **`OPENROUTER_API_KEY`** | OpenRouter (`auto` / **openrouter**) |
58
  | **`HF_TOKEN`** or **`HUGGING_FACE_HUB_TOKEN`** | Gated Hub downloads; if set, **`auto`** may try **custom_hf** after cloud APIs |
59
+ | **`CODE_PROVIDER_MODE`** | Unset = auto (`custom_hf` if CUDA else `offline`); or force `custom_hf` / `offline` / `auto` / … |
60
+ | **`FORGE_DEFAULT_PROVIDER`** | Optional: force Gradio default dropdown (`custom_hf`, `offline`, …) |
61
+ | **`FORGE_DETERMINISTIC_RESET`** | Set to **`1`** so **`POST /reset`** re-seeds RNG (harness reproducibility); omit for varied tasks |
62
 
63
  ### OpenEnv HTTP API on the Hugging Face Space
64
 
 
89
 
90
  | # | Requirement | FORGE-v4 |
91
  | :--: | :-- | :-- |
92
+ | 1 | **OpenEnv (latest):** build on the framework | **`openenv-core>=0.2.3`** in [`requirements-core.txt`](requirements-core.txt) (pulled via [`requirements.txt`](requirements.txt)). Training overlap in [`requirements-train.txt`](requirements-train.txt). Wrapper: [`env_openenv.py`](env_openenv.py). Core: [`env.py`](env.py). |
93
  | 2 | **Training:** Unsloth or TRL (or other RL stack) + **Colab** | [`train_unsloth.py`](train_unsloth.py) (Unsloth + TRL), [`train_colab.py`](train_colab.py), [`FORGE_Training_Colab.ipynb`](FORGE_Training_Colab.ipynb), Colab links in the table above. |
94
  | 3 | **Evidence of training:** loss + reward plots (real run) | Committed: [`outputs/reward_curve.png`](outputs/reward_curve.png), [`outputs/loss_curve.png`](outputs/loss_curve.png), [`outputs/pass_rate.png`](outputs/pass_rate.png), [`outputs/final_report.json`](outputs/final_report.json). |
95
  | 4 | **Writeup / video:** mini-blog on HF *or* <2 min YouTube *etc.* | **[BLOG.md](BLOG.md)** plus **[Space Discussions](https://huggingface.co/spaces/sanjay7676/Team404_FORGE/discussions)** for an on-Hub writeup; add **public YouTube or slide URL** in the judge table when published. |
 
289
 
290
  **Hugging Face Space:** [https://huggingface.co/spaces/sanjay7676/Team404_FORGE](https://huggingface.co/spaces/sanjay7676/Team404_FORGE)
291
 
292
+ The Space serves **Gradio at `/`** and the same **OpenEnv-style JSON routes** (`/health`, `/reset`, `/step`, `/state`) on the same host. **`POST /reset`** starts a **new random task** by default (same live env as the UI). For strict harness reproducibility, set Space secret **`FORGE_DETERMINISTIC_RESET=1`**. For local-only API, run `api_server.py` on port `8000` (see Docker Compose).
293
 
294
  ---
295
 
 
330
  ## Quickstart
331
 
332
  ```bash
333
+ # Full stack (GPU + local HF β€” same as HF Space default):
334
  pip install -r requirements.txt
335
+ # Slim CPU-only API / Gradio (no PyTorch):
336
+ # pip install -r requirements-core.txt
337
+ # Optional TRL overlap / Colab extras:
338
  pip install -r requirements-train.txt
339
 
340
  cp .env.example .env # then edit β€” do not commit .env
 
364
 
365
  ### Build locally, tag, and push to Docker Hub (one-time)
366
 
367
+ **Fast image (default `Dockerfile`):** only [`requirements-core.txt`](requirements-core.txt) β€” no PyTorch. Usually **a few minutes**. Good for slim demo/API with `CODE_PROVIDER_MODE=offline` (or API-backed providers).
368
 
369
  **Full training image:** [`Dockerfile.train`](Dockerfile.train) adds `requirements-train.txt` (PyTorch + CUDA wheels). Expect **tens of minutes to an hour+** on first build.
370
 
api_server.py CHANGED
@@ -1,6 +1,7 @@
1
  # api_server.py
2
  # FastAPI wrapper for FORGE-v4 Environment (OpenEnv standard).
3
 
 
4
  import random
5
  from typing import Any, List, Optional
6
 
@@ -26,8 +27,10 @@ class Action(BaseModel):
26
  @app.post("/reset")
27
  async def reset():
28
  """Reset the environment and return the initial state."""
29
- # Deterministic task generation for eval harnesses (same seed every episode start).
30
- random.seed(GLOBAL_RANDOM_SEED)
 
 
31
  state = env.reset()
32
  return state
33
 
 
1
  # api_server.py
2
  # FastAPI wrapper for FORGE-v4 Environment (OpenEnv standard).
3
 
4
+ import os
5
  import random
6
  from typing import Any, List, Optional
7
 
 
27
  @app.post("/reset")
28
  async def reset():
29
  """Reset the environment and return the initial state."""
30
+ # Default: varied tasks per reset (real sandbox episodes). Set FORGE_DETERMINISTIC_RESET=1
31
+ # to re-seed RNG for harnesses that need identical first-task distributions.
32
+ if os.getenv("FORGE_DETERMINISTIC_RESET", "").strip().lower() in ("1", "true", "yes"):
33
+ random.seed(GLOBAL_RANDOM_SEED)
34
  state = env.reset()
35
  return state
36
 
app.py CHANGED
@@ -33,20 +33,47 @@ def get_memory_lessons() -> str:
33
  top_lessons = summary.get("top_lessons", [])
34
  if not top_lessons:
35
  return "No lessons recorded yet."
36
-
37
  output = ""
38
  for idx, lesson in enumerate(top_lessons):
39
- output += f"{idx+1}. Episode {lesson.get('episode')}: {lesson.get('coach_note')} (Weight: {lesson.get('reward_weight')})\n"
 
 
40
  return output
41
 
42
- # Offline baseline first β€” instant deterministic runs for Spaces and demos.
43
- FORGE_PROVIDER_OPTIONS = ["offline", "auto", "nim", "openrouter", "custom_hf"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
 
46
  def run_benchmark_ui(episodes, forge_provider_label: str):
47
  """Gradio wrapper for benchmark mode."""
48
- # Limit episodes for demo stability on CPU
49
- ep_count = min(int(episodes), 5)
50
  mode = forge_provider_label if forge_provider_label in (
51
  "auto", "custom_hf", "nim", "openrouter", "offline", "mock"
52
  ) else "offline"
@@ -77,7 +104,7 @@ def run_benchmark_ui(episodes, forge_provider_label: str):
77
 
78
  def run_compare_ui(episodes, forge_provider_label: str):
79
  """Gradio wrapper for compare mode."""
80
- ep_count = min(int(episodes), 3) # Very small for demo
81
  mode = forge_provider_label if forge_provider_label in (
82
  "auto", "custom_hf", "nim", "openrouter", "offline", "mock"
83
  ) else "offline"
@@ -133,9 +160,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
133
  episodes_input = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="Episodes (Limited for Demo)")
134
  provider_input = gr.Dropdown(
135
  choices=FORGE_PROVIDER_OPTIONS,
136
- value="offline",
137
  label="Inference provider",
138
- info="**Offline** = instant deterministic baseline. **auto** = NIM β†’ OpenRouter β†’ local HF only if Space secret **HF_TOKEN** is set β†’ else offline. **custom_hf** always uses local PyTorch (can be slow on CPU).",
 
 
 
 
139
  )
140
 
141
  with gr.Row():
@@ -166,7 +197,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
166
  FORGE-v4 serves **Gradio at `/`** and the OpenEnv JSON routes at the **same origin** (`/health`, `/reset`, `/step`, `/state`). Locally, `python api_server.py` serves **API-only** on **`:8000`**; `python app.py` serves UI **+** API on **`:7860`**. On this Space, use your **`*.hf.space`** base URL (no `/start` β€” use **`POST /reset`** then **`POST /step`**).
167
 
168
  - **`GET /health`**: Liveness / version check.
169
- - **`POST /reset`**: Starts a new episode and returns the initial state.
170
  - **`POST /step`**: JSON body: `coder_code`, `coder_version`, optional `candidate_solutions` (array of strings). Returns rewards and updated state.
171
  - **`GET /state`**: Current environment snapshot.
172
 
 
33
  top_lessons = summary.get("top_lessons", [])
34
  if not top_lessons:
35
  return "No lessons recorded yet."
36
+
37
  output = ""
38
  for idx, lesson in enumerate(top_lessons):
39
+ note = lesson.get("coach_note") or ""
40
+ w = lesson.get("reward_weight", 0.0)
41
+ output += f"{idx + 1}. {note} (Weight: {w})\n"
42
  return output
43
 
44
+
45
+ def _cuda_ready() -> bool:
46
+ try:
47
+ import torch # noqa: PLC0415
48
+ return bool(torch.cuda.is_available())
49
+ except ImportError:
50
+ return False
51
+
52
+
53
+ def _ui_provider_options() -> list[str]:
54
+ # GPU Space: lead with local HF (real weights on T4). CPU: lead with offline so demos stay instant.
55
+ if _cuda_ready():
56
+ return ["custom_hf", "auto", "nim", "openrouter", "offline"]
57
+ return ["offline", "auto", "nim", "openrouter", "custom_hf"]
58
+
59
+
60
+ FORGE_PROVIDER_OPTIONS = _ui_provider_options()
61
+
62
+
63
+ def default_forge_ui_provider() -> str:
64
+ override = os.getenv("FORGE_DEFAULT_PROVIDER", "").strip().lower()
65
+ if override in FORGE_PROVIDER_OPTIONS:
66
+ return override
67
+ return "custom_hf" if _cuda_ready() else "offline"
68
+
69
+
70
+ def _benchmark_episode_cap() -> int:
71
+ return 30 if _cuda_ready() else 5
72
 
73
 
74
  def run_benchmark_ui(episodes, forge_provider_label: str):
75
  """Gradio wrapper for benchmark mode."""
76
+ ep_count = min(int(episodes), _benchmark_episode_cap())
 
77
  mode = forge_provider_label if forge_provider_label in (
78
  "auto", "custom_hf", "nim", "openrouter", "offline", "mock"
79
  ) else "offline"
 
104
 
105
  def run_compare_ui(episodes, forge_provider_label: str):
106
  """Gradio wrapper for compare mode."""
107
+ ep_count = min(int(episodes), 10 if _cuda_ready() else 3)
108
  mode = forge_provider_label if forge_provider_label in (
109
  "auto", "custom_hf", "nim", "openrouter", "offline", "mock"
110
  ) else "offline"
 
160
  episodes_input = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="Episodes (Limited for Demo)")
161
  provider_input = gr.Dropdown(
162
  choices=FORGE_PROVIDER_OPTIONS,
163
+ value=default_forge_ui_provider(),
164
  label="Inference provider",
165
+ info=(
166
+ "**custom_hf** = local PyTorch + Hub weights on this machine (default on **GPU**). "
167
+ "**auto** = NIM β†’ OpenRouter β†’ optional local HF if **HF_TOKEN** is set β†’ else offline. "
168
+ "**offline** = no external APIs (CPU-friendly fallback)."
169
+ ),
170
  )
171
 
172
  with gr.Row():
 
197
  FORGE-v4 serves **Gradio at `/`** and the OpenEnv JSON routes at the **same origin** (`/health`, `/reset`, `/step`, `/state`). Locally, `python api_server.py` serves **API-only** on **`:8000`**; `python app.py` serves UI **+** API on **`:7860`**. On this Space, use your **`*.hf.space`** base URL (no `/start` β€” use **`POST /reset`** then **`POST /step`**).
198
 
199
  - **`GET /health`**: Liveness / version check.
200
+ - **`POST /reset`**: Starts a new episode and returns the initial state (new random task each time unless Space secret **`FORGE_DETERMINISTIC_RESET=1`**).
201
  - **`POST /step`**: JSON body: `coder_code`, `coder_version`, optional `candidate_solutions` (array of strings). Returns rewards and updated state.
202
  - **`GET /state`**: Current environment snapshot.
203
 
config.py CHANGED
@@ -108,9 +108,25 @@ OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL", "qwen/qwen2.5-coder-7b-instruct
108
 
109
  HF_TOKEN = os.getenv("HF_TOKEN", os.getenv("HUGGING_FACE_HUB_TOKEN", ""))
110
 
111
- # Policy "model" routing: offline | auto | custom_hf | nim | openrouter (legacy env value "mock" == offline)
112
- _CODE_PROVIDER_RAW = os.getenv("CODE_PROVIDER_MODE", "offline").strip().lower()
113
- CODE_PROVIDER_MODE = "offline" if _CODE_PROVIDER_RAW in ("", "mock") else _CODE_PROVIDER_RAW
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  # Per-provider HTTP / wrapped inference timeouts (seconds)
116
  # Local HF load+infer can exceed 60s on cold CPU; default cap keeps Gradio responsive (raise via env on GPU).
 
108
 
109
  HF_TOKEN = os.getenv("HF_TOKEN", os.getenv("HUGGING_FACE_HUB_TOKEN", ""))
110
 
111
+ # Policy "model" routing: offline | auto | custom_hf | nim | openrouter (legacy "mock" == offline).
112
+ # If CODE_PROVIDER_MODE is unset: use custom_hf when CUDA is available (GPU Space), else offline.
113
+
114
+
115
+ def _default_code_provider_mode() -> str:
116
+ try:
117
+ import torch # noqa: PLC0415 β€” optional; absent in slim Docker images
118
+ except ImportError:
119
+ return "offline"
120
+ return "custom_hf" if torch.cuda.is_available() else "offline"
121
+
122
+
123
+ _code_raw = os.getenv("CODE_PROVIDER_MODE", "").strip().lower()
124
+ if _code_raw == "mock":
125
+ CODE_PROVIDER_MODE = "offline"
126
+ elif _code_raw:
127
+ CODE_PROVIDER_MODE = _code_raw
128
+ else:
129
+ CODE_PROVIDER_MODE = _default_code_provider_mode()
130
 
131
  # Per-provider HTTP / wrapped inference timeouts (seconds)
132
  # Local HF load+infer can exceed 60s on cold CPU; default cap keeps Gradio responsive (raise via env on GPU).
requirements-core.txt ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FORGE-v4 β€” slim stack (Docker Hub image, CPU-only local runs, CI).
2
+ # Hugging Face Spaces use root requirements.txt which includes this file plus PyTorch / HF inference.
3
+
4
+ # OpenEnv (official framework β€” Meta / HF ecosystem)
5
+ # Needs websockets>=15.1; use Gradio >=5.18 (see README Space sdk_version).
6
+ openenv-core>=0.2.3
7
+
8
+ # Core
9
+ tqdm>=4.66.0
10
+ numpy>=1.26.0
11
+ pandas>=2.2.0
12
+ matplotlib>=3.8.0
13
+ PyYAML>=6.0.1
14
+ requests>=2.32.0
15
+ python-dotenv>=1.0.1
16
+
17
+ # HF Spaces installs gradio[oauth]==sdk_version from README YAML β€” keep sdk_version in sync.
18
+ gradio>=5.18.0,<6
19
+
20
+ # API β€” Gradio 5.x needs fastapi>=0.115.2
21
+ fastapi>=0.115.2,<1.0
22
+ uvicorn>=0.30.0
23
+ pydantic>=2.7.0
requirements-train.txt CHANGED
@@ -1,5 +1,5 @@
1
- # GPU / Colab / full Docker image β€” install on top of requirements.txt
2
- # Not used on Hugging Face CPU Spaces (use CODE_PROVIDER_MODE=offline there).
3
 
4
  torch>=2.3.0
5
  transformers>=4.41.0
 
1
+ # Extra training stack β€” install with root requirements.txt (Spaces / Dockerfile.train).
2
+ # Root requirements.txt already includes torch/transformers/PEFT; this file adds overlap for Colab-only flows.
3
 
4
  torch>=2.3.0
5
  transformers>=4.41.0
requirements.txt CHANGED
@@ -1,23 +1,13 @@
1
- # FORGE-v4 β€” default install (Hugging Face CPU Spaces, Gradio demo, API).
2
- # For training / local_model / HF custom weights, also install: pip install -r requirements-train.txt
3
-
4
- # OpenEnv (official framework β€” Meta / HF ecosystem)
5
- # Needs websockets>=15.1; use Gradio >=5.18 (see README Space sdk_version).
6
- openenv-core>=0.2.3
7
-
8
- # Core
9
- tqdm>=4.66.0
10
- numpy>=1.26.0
11
- pandas>=2.2.0
12
- matplotlib>=3.8.0
13
- PyYAML>=6.0.1
14
- requests>=2.32.0
15
- python-dotenv>=1.0.1
16
-
17
- # HF Spaces installs gradio[oauth]==sdk_version from README YAML β€” keep sdk_version in sync.
18
- gradio>=5.18.0,<6
19
-
20
- # API β€” Gradio 5.x needs fastapi>=0.115.2
21
- fastapi>=0.115.2,<1.0
22
- uvicorn>=0.30.0
23
- pydantic>=2.7.0
 
1
+ # FORGE-v4 β€” default install for Hugging Face Spaces (T4 GPU: local HF inference + Gradio + API).
2
+ # Slim installs: use requirements-core.txt only (see Dockerfile).
3
+
4
+ -r requirements-core.txt
5
+
6
+ # Local Hugging Face inference (custom_hf on GPU Spaces)
7
+ torch>=2.3.0
8
+ transformers>=4.41.0
9
+ trl>=0.9.4
10
+ peft>=0.11.1
11
+ datasets>=2.19.0
12
+ accelerate>=0.30.0
13
+ bitsandbytes>=0.43.1
 
 
 
 
 
 
 
 
 
 
trainer.py CHANGED
@@ -275,7 +275,7 @@ def run_benchmark_mode(
275
  forge_provider: str | None = None,
276
  ) -> dict[str, Any]:
277
  """Run evidence benchmark and export judge assets."""
278
- episodes = max(20, episodes)
279
  summary = train_with_policy_name(
280
  policy_name=policy_name,
281
  num_episodes=episodes,
 
275
  forge_provider: str | None = None,
276
  ) -> dict[str, Any]:
277
  """Run evidence benchmark and export judge assets."""
278
+ episodes = max(1, int(episodes))
279
  summary = train_with_policy_name(
280
  policy_name=policy_name,
281
  num_episodes=episodes,