# Architecture

`halo-offline-grpo-kit` is a clean-room starter. It loads 8-completion JSONL groups, turns caller-supplied rewards into group-mean advantages, and can build a White Circle `POST /api/events` body. It does not vendor Halo, does not launch a trainer, and does not record a training loss or a benchmark.

The dry-run path keeps those two jobs apart. Fixture `rewards` feed the advantage math. A local hash stub can score the first completion of a group. That stub is not written back into `rewards`.

## Data flow

Single-GPU offline GRPO here means: one JSONL row is one prompt plus eight completions, and the shipped NVIDIA file asks for one GPU (`per_device_train_batch_size: 1`, `gradient_accumulation_steps: 8`, `num_generations: 8`). Those fields describe a run shape. This repository never starts that run. `save_strategy` stays `"no"`.

```
JSONL row  schema=halo-offline-grpo-v1
  prompt + 8 completions
  rewards[8]            caller-supplied, not measured here
  kl[8]                 optional, each value >= 0
        |                                    |
        |                                    v
        |                     group_relative_advantages
        |                       adjusted_i = reward_i - kl_coef * kl_i
        |                       if the group is flat within 1e-12:
        |                           advantage_i = 0
        |                       else:
        |                           advantage_i = adjusted_i - mean
        |
        v
build_events(prompt, completion, view)
  final: prompt + last assistant message
  full:  prompt + every completion turn
  digest: refused
  Policy events are assistant text and tool-call arguments
  at or after the prompt. Prompt text does not score.
  Tool outputs are sent and are not policy events.
  No assistant text and no tool call: score 0
  ("empty completion"; silence is not a pass).
        |
        v
Live fetch, only when mock is false
  session = uuid4().hex          one id for the whole completion
  for each slice of at most 50 events:          MAX_EVENTS_PER_REQUEST
        POST https://<region>.whitecircle.com/api/events
        whitecircle-version: 2026-06-01         API_VERSION
        Authorization: Bearer <constructor argument>
        body: environment_id, external_session_id=session, events=chunk
  Verdict objects are merged on event_id.
        |
        +-- mock=true: sha256 stub on this machine.
                       request_count stays 0.
                       No environment read. No socket.
        |
        v
parse_verdicts -> score in [0, 1]
optional term value: weight * score ** exponent, exponent > 0
```

Region `us` posts to `https://us.whitecircle.com/api/events`. Region `eu` posts to `https://eu.whitecircle.com/api/events`. No other host is built.

Retries cover timeout, connection failure, HTTP 408, 429, and 5xx. A numeric `Retry-After` is used and capped at 60 seconds. Otherwise the wait is `retry_wait * 2 ** attempt`. HTTP 400, 401, and 403 fail on the first response. Defaults are a 30 second timeout and 4 retries. `max_concurrency` is checked (`>= 1`) and is not used by the fetch loop. Posts for one completion run one after another.

`on_error: invalid` raises. `on_error: neutral` returns an unscored 0 so other terms can continue. A listed policy or checklist id with no verdict is an error, not a quiet zero. `repr` on the client omits the bearer token. Mock mode refuses to require a key. Live mode requires one, passed in, never read from the environment.

Score in `[0, 1]`, from `parse_verdicts`:

| What you list | Score |
| --- | --- |
| No policy list and no checklist | 1 when no policy-event verdict is flagged, else 0 |
| `policies` | Share of those ids with no flagged verdict |
| `checklist` | 1 minus the share of items flagged. `flagged` flips when `1 - score >= 0.5` |

`view: full` is what both starter reward terms use, except the ROCm quality term, which sets `view: final` and a checklist. `weighted_term` is optional. The JSONL loader does not call it.

`scripts/dry_run_pipeline.py` loads `configs/qwen3_4b_single_gpu_grpo.yaml` and `examples/synthetic_trajectories.jsonl` with `require_dry_run=True`. Every fixture row must have `synthetic: true` and `dry_run_only: true`. The script scores `completions[0]` of each group through `GraderClient(mock=True)` and prints advantages from the fixture rewards. Those printed lines are a schema check.

## Advantage math

`group_relative_advantages` in `src/halo_grpo/offline_grpo.py` is the whole normalizer. Upstream Halo's offline trainer defaults to quantile normalization. This file does not reimplement that, and it does not shell out to Halo.

`N` is `group_size`, default `COMPLETIONS_PER_GROUP = 8`, and it must be at least 2. `rewards` and, when present, `kl` must both have length `N`. Values must be finite. Booleans are rejected. `kl_coef >= 0`. Each `kl_i >= 0`. If `kl` is omitted, every `kl_i` is `0`. The shipped YAML sets `kl_coef: 0.04`. That is a starter constant, not a measured KL.

```
adjusted_i = reward_i - kl_coef * kl_i
mean       = sum(adjusted) / N
flat       = all(abs(adjusted_i - mean) <= 1e-12)
advantage_i = 0                      if flat
advantage_i = adjusted_i - mean      otherwise
```

`1e-12` is `_ADVANTAGE_TOLERANCE`. The flat branch exists so a tied group does not look like a spread and does not divide by a zero standard deviation. This function never divides by a standard deviation. A tied group is a real outcome: there is nothing to learn from, so every advantage is `0` and `zero_variance` is true. When the group is not flat, advantages are mean-centered, so they sum to `0`.

The loader (`load_offline_jsonl` / `parse_group`) checks the row before any of that math. Schema must be `halo-offline-grpo-v1`. `label` is a non-empty string. The prompt must contain a user message. Each completion must contain assistant text or a non-empty `tool_calls` list. Blank JSONL lines are skipped. Rewards in the file stay caller-supplied. This module does not measure them.

## Hardware

VRAM figures below are the board class this note is naming. No config field stores a memory size, and this repo has not measured whether a weight fits.

| Board class | What this repo accepts | Attention | Shipped file |
| --- | --- | --- | --- |
| RTX PRO 6000, Blackwell compute capability 12.x, 96 GB class | `device_class: rtx_pro_6000`. `blackwell_cc_12` and `rtx_50` are the other cc 12.x names. | `attention_for_device` returns `flash_attention_2`. The schema still accepts `sdpa` on those names if the FA2 wheel will not load. FA4 is not selected. The source comment says the FA4 kernel the Blackwell server image auto-selects does not run on cc 12.x. | `configs/qwen3_4b_single_gpu_grpo.yaml`. Model `Qwen/Qwen3-4B-Instruct-2507`. LoRA rank 16, alpha 32, dropout 0.05, targets `q_proj`, `k_proj`, `v_proj`, `o_proj`, `gate_proj`, `up_proj`, `down_proj`. Prompt cap 2560, completion cap 4096, `max_steps: 10`, `lr_scheduler_type: constant`, learning rate `5.0e-6`. |
| AMD MI300X class, ROCm, 192 GB class | The string `MI300X` is not in the tree. The accepted names are `rocm` and `amd`. | Must be `sdpa`. `flash_attention_2` fails validation on those names. | `configs/qwen3_8b_rocm_sdpa.yaml`. Model `Qwen/Qwen3-8B`. Same LoRA shape and the same batch, generation count, `kl_coef`, and `max_steps`. Prompt and completion caps are 2048. The file says it is not a CUDA Halo image launch. Published Halo images are NVIDIA CUDA builds. Use the file as a LoRA and attention shape for a ROCm stack that can already load the Hub weights. |
| B200 / B300 | No `device_class` value. `validate_config` rejects anything outside `rtx_pro_6000`, `blackwell_cc_12`, `rtx_50`, `rocm`, and `amd`. `attention_for_device` raises. | No default in this kit. Those parts stay on the Halo image, which auto-selects FA4. This repository does not set FA4 and does not ship a B200 or B300 YAML. | None. |

Both YAMLs set `dry_run_banner: true`, `method: offline_grpo`, `schema_version: 1`, `use_peft: true`, and `environment_id: your_environment_id`. Policy ids in the files are placeholders. Secret-shaped keys are rejected. `dataset` points at `examples/synthetic_trajectories.jsonl`.

## Reproducibility

Checked in this working tree on Python 3.12.14 (the repo `.venv`):

```bash
python3 -m pip install -e ".[dev]"
python3 -m pytest
python3 scripts/dry_run_pipeline.py
```

`pytest` reported 18 passed, exit 0. The four modules are `tests/test_config_schema.py`, `tests/test_dry_run_pipeline.py`, `tests/test_grader_client.py`, and `tests/test_offline_grpo.py`. The cited 18/18 is that 3.12 run. `offline_grpo.py` calls `zip(..., strict=True)`, which needs Python 3.10 or newer. Do not cite a 3.9 interpreter for this count.

The dry-run's first lines were:

```
offline dry-run only
Synthetic fixture pass. Not a training score. Not a benchmark result.
groups: 5
model: Qwen/Qwen3-4B-Instruct-2507
attention: flash_attention_2
kl_coef: 0.04
```

Later lines print per-group advantages and a `mock_score`. Advantages are group-mean arithmetic on the fixture rewards. `mock_score` is the hash stub. Neither number is a training score or a benchmark result. The script does not open a socket. There is no logged loss, no reward curve, and no claim that `max_steps: 10` was executed on a GPU.
