Compare commits

...
Author SHA1 Message Date
3b386a4489 chore: drop teacher_inference from rl entrypoint (#2629)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
The `rl` entrypoint now only manages student-policy inference. External
teachers (OPD, local-vLLM SFT) must be started manually and pointed at
via `[orchestrator.teacher.client]`.

Removed:
- `[teacher_inference]` block from `RLConfig`
- `deployment.num_teacher_gpus` (`SingleNodeDeploymentConfig`)
- `deployment.num_teacher_nodes` (`MultiNodeDeploymentConfig`)
- launcher code that spawned/monitored the teacher inference subprocess
- related validators (`auto_setup_teacher_inference`,
  `_stub_orchestrator_teacher_for_auto_setup`,
  `validate_no_teacher_in_multinode`,
  `teacher_inference_not_supported`)

Fixes #2627

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:56:19 -07:00
faresobeidandGitHub 38303f82d4 add routing confidence metric (#2545)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
2026-05-25 10:21:32 -07:00
JannikStandGitHub f5e8113420 chore: drop environment gate on manifest job (#2624)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Each job referencing environment: ghcr-publish requires its own admin approval. manifest only combines arch-suffixed tags that build already pushed (and build was already approved), so a second approval doesn't add meaningful security but adds friction. Keep the gate on build.
2026-05-25 04:47:38 +02:00
ef773f1cee chore: add manual ghcr image build workflow (#2385)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* chore: also publish image to ghcr + add manual trigger

* chore: drop push/tag triggers, keep manual dispatch only

* chore: revert release.yaml, add manual ghcr build workflow

* fix: avoid script injection by passing inputs via env

* fix: trim trailing dash after tag truncation

* chore: dispatch build_image after creating dev tag

* multi platform builds (am64 and arm64)

* OCI metadata

* remove temporary push trigger

* trigger image builds when gh releases are published

* add step to init public submodules

* add pydantic-config to submodules

* should fail on failed image builds

* chore: gate ghcr publish on environment + ref/tag allowlist

- Require ghcr-publish environment for build and manifest jobs (admin approval)
- Reject refs other than main, v*, or *.dev*
- Disallow custom tag input unless ref=main, so a feature branch can't overwrite v1.2.3

* chore: allow tag input when it matches ref

Release events and the dev-tag auto-dispatch always pass ref==tag (e.g. v1.2.3/v1.2.3); the previous guard rejected those because tag was set and ref was not main. Only block when tag and ref diverge.

* chore: serialize same-tag builds and skip manifest job when single-arch

- Add concurrency group keyed on resolved tag so two runs for the same image queue rather than interleave (would otherwise mix arch digests in the unsuffixed manifest).
- Skip the manifest job when platforms != 'both' so a single-arch dispatch can't replace an existing multi-arch :tag with a single-arch index. The suffixed :tag-amd64 / :tag-arm64 are still pushed by build.

---------

Co-authored-by: eexwhyzee <13672394+eexwhyzee@users.noreply.github.com>
2026-05-25 03:15:55 +02:00
84f072bc99 chore(deps): bump pydantic-config for dict[str, str] coercion fix (#2618)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
Pulls in PrimeIntellect-ai/pydantic-config#14, which stops
`BaseConfig._coerce_dict_str_values` from rewriting string values in
`dict[str, str]` fields. Configs like
`configs/private/rlm5/glm5-swe.toml` that set
`prefill_env_overrides = {"VLLM_ENABLE_MOE_DP_CHUNK"="0"}` previously
failed validation because "0" was coerced to int(0); they now load.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 19:58:54 -07:00
11 changed files with 365 additions and 163 deletions
+262
View File
@@ -0,0 +1,262 @@
name: Build Image (ghcr)
on:
release:
types: [published]
workflow_dispatch:
inputs:
ref:
description: "Branch, tag, or commit to build"
required: false
default: "main"
type: string
tag:
description: "Image tag (defaults to sanitized ref)"
required: false
type: string
platforms:
description: "Target platforms to build"
required: false
default: "both"
type: choice
options:
- amd64-only
- arm64-only
- both
env:
REGISTRY: ghcr.io
IMAGE_NAME: primeintellect-ai/prime-rl
BUILD_REF: ${{ github.event.release.tag_name || inputs.ref || github.ref_name }}
BUILD_TAG: ${{ github.event.release.tag_name || inputs.tag || '' }}
BUILD_PLATFORMS: ${{ inputs.platforms || 'both' }}
concurrency:
group: build-image-${{ github.event.release.tag_name || inputs.tag || inputs.ref || github.ref_name }}
cancel-in-progress: false
jobs:
prepare:
name: Prepare build
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
matrix: ${{ steps.matrix.outputs.matrix }}
ref: ${{ steps.vars.outputs.ref }}
tag: ${{ steps.vars.outputs.tag }}
sha: ${{ steps.vars.outputs.sha }}
full_sha: ${{ steps.vars.outputs.full_sha }}
platforms: ${{ steps.vars.outputs.platforms }}
steps:
- name: Set build matrix
id: matrix
env:
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
run: |
case "$PLATFORMS" in
arm64-only)
echo 'matrix={"include":[{"runner":"image-builder-arm-2204","platform":"linux/arm64","suffix":"arm64"}]}' >> "$GITHUB_OUTPUT"
;;
both)
echo 'matrix={"include":[{"runner":"image-builder","platform":"linux/amd64","suffix":"amd64"},{"runner":"image-builder-arm-2204","platform":"linux/arm64","suffix":"arm64"}]}' >> "$GITHUB_OUTPUT"
;;
amd64-only)
echo 'matrix={"include":[{"runner":"image-builder","platform":"linux/amd64","suffix":"amd64"}]}' >> "$GITHUB_OUTPUT"
;;
*)
echo "Unsupported platforms value: ${PLATFORMS}" >&2
exit 1
;;
esac
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ env.BUILD_REF }}
fetch-depth: 0
- name: Resolve image vars
id: vars
env:
INPUT_REF: ${{ env.BUILD_REF }}
INPUT_TAG: ${{ env.BUILD_TAG }}
PLATFORMS: ${{ env.BUILD_PLATFORMS }}
run: |
case "$INPUT_REF" in
main|v[0-9]*|*.dev[0-9]*) ;;
*)
echo "ref '${INPUT_REF}' not allowed for ghcr publish (must be main, v*, or *.dev*)" >&2
exit 1
;;
esac
if [ -n "$INPUT_TAG" ] && [ "$INPUT_TAG" != "$INPUT_REF" ] && [ "$INPUT_REF" != "main" ]; then
echo "custom 'tag' that differs from 'ref' is only allowed when ref=main; got ref='${INPUT_REF}' tag='${INPUT_TAG}'" >&2
exit 1
fi
raw_tag="$INPUT_TAG"
if [ -z "$raw_tag" ]; then
raw_tag="$INPUT_REF"
fi
tag=$(echo "$raw_tag" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]/-/g' | sed 's/--*/-/g' | cut -c1-50 | sed 's/^-//;s/-$//')
if [ -z "$tag" ]; then
echo "Could not derive a valid image tag from '${raw_tag}'." >&2
exit 1
fi
echo "ref=${INPUT_REF}" >> "$GITHUB_OUTPUT"
echo "tag=${tag}" >> "$GITHUB_OUTPUT"
echo "sha=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
echo "full_sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
echo "platforms=${PLATFORMS}" >> "$GITHUB_OUTPUT"
build:
name: Build and push (${{ matrix.suffix }})
needs: prepare
environment: ghcr-publish
strategy:
fail-fast: true
matrix: ${{ fromJson(needs.prepare.outputs.matrix) }}
runs-on: ${{ matrix.runner }}
permissions:
contents: read
packages: write
steps:
- name: Remove unnecessary packages
run: |
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ needs.prepare.outputs.ref }}
fetch-depth: 0
submodules: false
- name: Init public submodules
run: |
if [ -f .gitmodules ]; then
git config --global url."https://github.com/".insteadOf "git@github.com:"
git submodule update --init --recursive -- deps/pydantic-config deps/verifiers deps/renderers deps/research-environments
fi
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build and push
id: build
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile.cuda
push: true
platforms: ${{ matrix.platform }}
tags: |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.prepare.outputs.tag }}-${{ matrix.suffix }}
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:commit-${{ needs.prepare.outputs.sha }}-${{ matrix.suffix }}
labels: |
org.opencontainers.image.revision=${{ needs.prepare.outputs.full_sha }}
org.opencontainers.image.version=${{ needs.prepare.outputs.tag }}
org.opencontainers.image.source=https://github.com/${{ github.repository }}
- name: Summary
env:
INPUT_REF: ${{ needs.prepare.outputs.ref }}
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
PLATFORM: ${{ matrix.platform }}
SUFFIX: ${{ matrix.suffix }}
run: |
{
echo "## Build Summary (${SUFFIX})"
echo ""
echo "| Property | Value |"
echo "|----------|-------|"
echo "| **Ref** | \`${INPUT_REF}\` |"
echo "| **Platform** | \`${PLATFORM}\` |"
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}-${SUFFIX}\` |"
echo "| **Commit** | \`${IMAGE_SHA}\` |"
echo "| **Digest** | \`${IMAGE_DIGEST}\` |"
} >> "$GITHUB_STEP_SUMMARY"
manifest:
name: Create multi-arch manifest
needs: [prepare, build]
if: needs.prepare.outputs.platforms == 'both'
runs-on: ubuntu-latest
permissions:
packages: write
steps:
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Create and push manifests
env:
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
IMAGE_FULL_SHA: ${{ needs.prepare.outputs.full_sha }}
PLATFORMS: ${{ needs.prepare.outputs.platforms }}
SOURCE_URL: https://github.com/${{ github.repository }}
run: |
set -euo pipefail
image="${REGISTRY}/${IMAGE_NAME}"
tag_sources=()
sha_sources=()
if [ "$PLATFORMS" != "arm64-only" ]; then
tag_sources+=("${image}:${IMAGE_TAG}-amd64")
sha_sources+=("${image}:commit-${IMAGE_SHA}-amd64")
fi
if [ "$PLATFORMS" != "amd64-only" ]; then
tag_sources+=("${image}:${IMAGE_TAG}-arm64")
sha_sources+=("${image}:commit-${IMAGE_SHA}-arm64")
fi
docker buildx imagetools create \
--annotation "index:org.opencontainers.image.revision=${IMAGE_FULL_SHA}" \
--annotation "index:org.opencontainers.image.version=${IMAGE_TAG}" \
--annotation "index:org.opencontainers.image.source=${SOURCE_URL}" \
-t "${image}:${IMAGE_TAG}" \
"${tag_sources[@]}"
docker buildx imagetools create \
--annotation "index:org.opencontainers.image.revision=${IMAGE_FULL_SHA}" \
--annotation "index:org.opencontainers.image.version=${IMAGE_TAG}" \
--annotation "index:org.opencontainers.image.source=${SOURCE_URL}" \
-t "${image}:commit-${IMAGE_SHA}" \
"${sha_sources[@]}"
- name: Summary
env:
INPUT_REF: ${{ needs.prepare.outputs.ref }}
IMAGE_TAG: ${{ needs.prepare.outputs.tag }}
IMAGE_SHA: ${{ needs.prepare.outputs.sha }}
PLATFORMS: ${{ needs.prepare.outputs.platforms }}
run: |
{
echo "## Manifest Summary"
echo ""
echo "| Property | Value |"
echo "|----------|-------|"
echo "| **Ref** | \`${INPUT_REF}\` |"
echo "| **Platforms** | \`${PLATFORMS}\` |"
echo "| **Image** | \`${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}\` |"
echo "| **Commit Image** | \`${REGISTRY}/${IMAGE_NAME}:commit-${IMAGE_SHA}\` |"
} >> "$GITHUB_STEP_SUMMARY"
+15 -1
View File
@@ -7,6 +7,7 @@ on:
permissions:
contents: write
actions: write
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -81,7 +82,6 @@ jobs:
sha,
});
core.notice(`Created tag ${tag} at ${sha}`);
return;
} catch (error) {
if (error.status === 422) {
core.warning(`Tag ${tag} already exists, retrying...`);
@@ -89,6 +89,20 @@ jobs:
}
throw error;
}
try {
await github.rest.actions.createWorkflowDispatch({
owner,
repo,
workflow_id: "build_image.yaml",
ref: "main",
inputs: { ref: tag, tag, platforms: "both" },
});
core.notice(`Dispatched build_image.yaml for ${tag}`);
} catch (error) {
core.setFailed(`Failed to dispatch build_image.yaml: ${error.message}`);
}
return;
}
core.setFailed("Could not create a unique .dev tag after retries.");
+1
View File
@@ -2,6 +2,7 @@
Documenting **breaking** configuration changes — renamed, removed, or moved fields that require users to update existing configs.
- **`teacher_inference` removed from RL entrypoint**: The `[teacher_inference]` config block and the `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` fields have been removed. The `rl` entrypoint now only manages the student-policy inference server. External teachers (used by OPD and local-vLLM SFT) must be started manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001 ...`) and pointed at via `[orchestrator.teacher.client]`. Existing configs using `[teacher_inference]` or `deployment.num_teacher_gpus` / `deployment.num_teacher_nodes` must drop those fields and bring up the teacher out-of-band. (2026-05-25)
- **`rollouts_per_example` → `group_size`**: The orchestrator-level field, the group-level `[orchestrator.eval]` field, and the per-env `[[orchestrator.eval.env]]` field have all been renamed. The old name still parses as a validation alias (in both TOML and CLI), so existing configs keep working without changes; new configs should prefer `group_size`. (2026-05-22)
- **`AdvantageInputs` / `AdvantageOutputs` are now per-group, and `AdvantageOutputs.advantages` is a plain `list[float]`** (second breaking change to this API in three weeks). `AdvantageInputs.rollouts` is now `list[vf.RolloutOutput]` (a single group) instead of `list[list[vf.RolloutOutput]]`, and `AdvantageOutputs.advantages` is now `list[float]` instead of a 2D `Float[Tensor, "num_examples rollouts_per_example"]`. `compute_advantages` calls `advantage_fn` once per group, which lets partial-group training (groups smaller than `rollouts_per_example` after rollout errors) round-trip without the previous bucket-by-size workaround. Custom advantage functions must drop the outer list dimension and return a list of floats — e.g. `AdvantageOutputs(advantages=(rewards - rewards.mean(dim=1, keepdim=True)).tolist())` becomes `AdvantageOutputs(advantages=[r - mean for r in rewards])` (or `.tolist()` if you keep torch internally). (2026-05-22)
- **`[model.vlm]` requires `orchestrator.use_renderer = true`**: VLMs must go through the renderer path; the `vlm_requires_renderer` validator rejects `use_renderer = false` when `[model.vlm]` is set. The renderer owns the HF processor per-slot and ships generic `mm_kwargs` keyed by the model's forward signature. Since `use_renderer` already defaults to `true`, most VLM configs need no change. (2026-05-19)
+2 -1
View File
@@ -33,7 +33,8 @@ See [`configs/debug/training_modes/README.md`](../configs/debug/training_modes/R
| Parameter | Default | Description |
|-----------|---------|-------------|
| `training_mode` | `"rl"` | One of `rl`, `opd`, `sft`. Propagates to `orchestrator.training_mode` and (for sft) `trainer.loss.type`. |
| `deployment.num_teacher_gpus` | `None` | Number of GPUs for the teacher vLLM server. Auto-starts when set. OPD only. |
| `trainer.loss.teacher_tau` | `0.0` | Distillation strength. Must be `> 0` in OPD. |
| `trainer.loss.adv_tau` | `1.0` | Weight for the RL advantage signal. Set `0` for pure distillation. |
| `orchestrator.verification.enabled` | `true` | Enable/disable verification. Set to `false` for pure distillation with `adv_tau = 0`. |
> Note: the `rl` entrypoint only manages student-policy inference. For OPD and (local) SFT, start the teacher inference server manually (e.g. `CUDA_VISIBLE_DEVICES=1 uv run inference --model.name <teacher> --server.port 8001`) and point `[orchestrator.teacher.client]` at it. See [`configs/debug/training_modes/README.md`](../configs/debug/training_modes/README.md) for a full example.
@@ -140,16 +140,13 @@ class SingleNodeDeploymentConfig(BaseDeploymentConfig):
num_infer_gpus: int = 1
"""GPUs allocated to inference."""
num_teacher_gpus: int | None = None
"""GPUs allocated to teacher inference (None disables the teacher server)."""
@model_validator(mode="after")
def validate_gpu_count(self):
total = self.num_train_gpus + self.num_infer_gpus + (self.num_teacher_gpus or 0)
total = self.num_train_gpus + self.num_infer_gpus
if total > self.gpus_per_node:
raise ValueError(
f"Total GPU count ({total} = {self.num_train_gpus} train + {self.num_infer_gpus} infer"
f" + {self.num_teacher_gpus or 0} teacher) exceeds gpus_per_node ({self.gpus_per_node})."
f"Total GPU count ({total} = {self.num_train_gpus} train + {self.num_infer_gpus} infer)"
f" exceeds gpus_per_node ({self.gpus_per_node})."
)
return self
@@ -166,9 +163,6 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
num_infer_replicas: int = Field(1, ge=1)
"""Independent inference replicas. Total inference nodes = ``num_infer_nodes * num_infer_replicas``."""
num_teacher_nodes: int | None = None
"""Teacher inference nodes."""
nodes_per_fsdp_group: int | None = None
"""Training nodes per FSDP island. Auto-sets ``trainer.dp_replicate = num_train_nodes / nodes_per_fsdp_group``."""
@@ -176,12 +170,6 @@ class MultiNodeDeploymentConfig(BaseDeploymentConfig):
def total_infer_nodes(self) -> int:
return self.num_infer_nodes * self.num_infer_replicas
@model_validator(mode="after")
def teacher_inference_not_supported(self):
if self.num_teacher_nodes is not None:
raise ValueError("Teacher inference is not yet supported in multi node deployment.")
return self
DeploymentConfig: TypeAlias = Annotated[
SingleNodeDeploymentConfig | MultiNodeDeploymentConfig, Field(discriminator="type")
@@ -196,9 +184,6 @@ class RLConfig(BaseConfig):
inference: InferenceConfig | None = None
"""Inference server configuration. If None, the rl entrypoint will not start an inference server (useful for elastic inference pools or manually started servers)."""
teacher_inference: InferenceConfig | None = None
"""Teacher inference server configuration. If None, falls back to the same config as ``inference`` (or a default). Only used when teacher GPUs/nodes are set."""
output_dir: Path = Path("outputs")
"""Output directory. Should be unique per experiment."""
@@ -248,27 +233,6 @@ class RLConfig(BaseConfig):
### Validate configs (e.g. raise for unsupported (combinations of) configs)
@model_validator(mode="before")
@classmethod
def _stub_orchestrator_teacher_for_auto_setup(cls, data):
"""When `deployment.num_teacher_gpus > 0` and the user didn't write an
`[orchestrator.teacher]` block, inject an empty one so
`OrchestratorConfig.validate_training_mode` (which fires during nested
validation) doesn't reject `training_mode = "opd"` for "missing teacher".
`auto_setup_teacher_inference` (after) then fills in client.base_url and
model.name from the auto-launched teacher_inference server."""
if not isinstance(data, dict):
return data
deployment = data.get("deployment")
if not isinstance(deployment, dict):
return data
if not deployment.get("num_teacher_gpus"):
return data
orch = data.setdefault("orchestrator", {})
if isinstance(orch, dict) and "teacher" not in orch and "teacher_model" not in orch:
orch["teacher"] = {}
return data
@model_validator(mode="after")
def validate_deployment(self):
if self.deployment.type == "multi_node":
@@ -288,16 +252,6 @@ class RLConfig(BaseConfig):
)
return self
# TODO: fix this
@model_validator(mode="after")
def validate_no_teacher_in_multinode(self):
if self.deployment.type == "multi_node" and self.teacher_inference is not None:
raise ValueError(
"Teacher inference is not supported in multi-node deployment. "
"The SLURM template only handles inference and training nodes."
)
return self
@model_validator(mode="after")
def validate_enough_devices_for_nccl(self):
if self.deployment.type == "single_node":
@@ -642,47 +596,6 @@ class RLConfig(BaseConfig):
client.base_url = [f"http://{host}:{port}/v1"]
return self
@model_validator(mode="after")
def auto_setup_teacher_inference(self):
"""Auto-configure teacher inference server and orchestrator teacher_model client."""
if self.deployment.type != "single_node":
return self
if self.deployment.num_teacher_gpus is None or self.deployment.num_teacher_gpus == 0:
return self
import copy
from prime_rl.configs.orchestrator import RolloutModelConfig
if self.teacher_inference is None:
if self.inference is None:
self.teacher_inference = InferenceConfig()
else:
self.teacher_inference = copy.deepcopy(self.inference)
self.teacher_inference.server.port = (self.inference.server.port if self.inference else 8000) + 1
elif self.inference is not None and self.teacher_inference.server.port == self.inference.server.port:
raise ValueError(
f"teacher_inference.server.port ({self.teacher_inference.server.port}) conflicts with "
f"inference.server.port ({self.inference.server.port}). "
"Either use different ports or let teacher_inference be auto-configured."
)
tp = self.teacher_inference.parallel.tp
num_teacher_gpus = self.deployment.num_teacher_gpus
if num_teacher_gpus != self.teacher_inference.parallel.dp * tp:
assert num_teacher_gpus % tp == 0, "Number of teacher GPUs must be divisible by tensor parallel size"
assert num_teacher_gpus > 0, "num_teacher_gpus cannot be zero"
self.teacher_inference.parallel.dp = num_teacher_gpus // tp
if self.orchestrator.teacher is None:
self.orchestrator.teacher = RolloutModelConfig()
host = self.teacher_inference.server.host or "localhost"
port = self.teacher_inference.server.port
self.orchestrator.teacher.client.base_url = [f"http://{host}:{port}/v1"]
self.orchestrator.teacher.model.name = self.teacher_inference.model.name
return self
@model_validator(mode="after")
def auto_setup_slurm_template(self):
"""Auto-setup the default single-node/multi-node SLURM template if no custom template is provided."""
+7 -50
View File
@@ -31,7 +31,6 @@ RL_SBATCH = "rl.sbatch"
TRAINER_TOML = "trainer.toml"
ORCHESTRATOR_TOML = "orchestrator.toml"
INFERENCE_TOML = "inference.toml"
TEACHER_INFERENCE_TOML = "teacher_inference.toml"
def get_physical_gpu_ids() -> list[int]:
@@ -67,11 +66,6 @@ def write_subconfigs(config: RLConfig, output_dir: Path) -> None:
with open(output_dir / INFERENCE_TOML, "wb") as f:
tomli_w.dump(config.inference.model_dump(exclude=exclude_inference, exclude_none=True, mode="json"), f)
teacher_inference = getattr(config, "teacher_inference", None)
if teacher_inference is not None:
with open(output_dir / TEACHER_INFERENCE_TOML, "wb") as f:
tomli_w.dump(teacher_inference.model_dump(exclude_none=True, mode="json"), f)
def rl_local(config: RLConfig):
assert config.deployment.type == "single_node"
@@ -95,11 +89,8 @@ def rl_local(config: RLConfig):
infer_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_infer_gpus))
gpu_offset += num_infer_gpus
trainer_local_gpu_ids = list(range(gpu_offset, gpu_offset + config.deployment.num_train_gpus))
gpu_offset += config.deployment.num_train_gpus
num_teacher_gpus = config.deployment.num_teacher_gpus or 0
teacher_local_gpu_ids = list(range(gpu_offset, gpu_offset + num_teacher_gpus)) if num_teacher_gpus > 0 else []
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus + num_teacher_gpus
total_requested_gpus = num_infer_gpus + config.deployment.num_train_gpus
physical_gpu_ids = get_physical_gpu_ids()
if total_requested_gpus > len(physical_gpu_ids):
raise ValueError(
@@ -111,7 +102,6 @@ def rl_local(config: RLConfig):
infer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in infer_local_gpu_ids]
trainer_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in trainer_local_gpu_ids]
teacher_gpu_ids = [physical_gpu_mapping[local_gpu_id] for local_gpu_id in teacher_local_gpu_ids]
start_command = sys.argv
logger.info("Starting RL run")
@@ -194,44 +184,12 @@ def rl_local(config: RLConfig):
"will hang waiting for it."
)
# Optionally, start teacher inference process
if config.teacher_inference:
if not teacher_gpu_ids:
raise ValueError(
"teacher_inference is configured but deployment.num_teacher_gpus is not set. "
"Either set deployment.num_teacher_gpus to start a teacher inference server, "
"or omit teacher_inference and configure orchestrator.teacher to use an existing server."
)
teacher_inference_cmd = ["inference", "@", (config_dir / TEACHER_INFERENCE_TOML).as_posix()]
logger.info(f"Starting teacher inference process on GPU(s) {' '.join(map(str, teacher_gpu_ids))}")
logger.debug(f"Teacher inference start command: {' '.join(teacher_inference_cmd)}")
with open(log_dir / "teacher_inference.log", "w") as log_file:
teacher_inference_process = Popen(
teacher_inference_cmd,
env={
**os.environ,
"CUDA_VISIBLE_DEVICES": ",".join(map(str, teacher_gpu_ids)),
},
stdout=log_file,
stderr=log_file,
)
processes.append(teacher_inference_process)
# Start monitoring thread
stop_event = Event()
stop_events["teacher_inference"] = stop_event
monitor_thread = Thread(
target=monitor_process,
args=(teacher_inference_process, stop_event, error_queue, "teacher_inference"),
daemon=True,
)
monitor_thread.start()
monitor_threads.append(monitor_thread)
elif config.orchestrator.teacher:
logger.warning(
"No teacher_inference config specified, skipping starting teacher inference server. "
"Is your teacher inference server running? Make sure orchestrator.teacher is configured."
if config.orchestrator.teacher:
logger.info(
"orchestrator.teacher is configured - the rl entrypoint does not start teacher inference "
"servers. Make sure your teacher endpoint at "
f"{', '.join(config.orchestrator.teacher.client.base_url)} is running before the "
"orchestrator starts, otherwise rollouts will hang."
)
# Start orchestrator process
@@ -434,7 +392,6 @@ def write_slurm_script(config: RLConfig, config_dir: Path, script_path: Path) ->
num_infer_nodes=config.deployment.total_infer_nodes,
nodes_per_infer_replica=config.deployment.num_infer_nodes,
num_infer_replicas=config.deployment.num_infer_replicas,
num_teacher_nodes=config.deployment.num_teacher_nodes,
gpus_per_node=config.deployment.gpus_per_node,
router_port=getattr(config.inference.deployment, "router_port", 8000) if config.inference else 8000,
backend_port=getattr(config.inference.deployment, "backend_port", 8100) if config.inference else 8100,
+13 -3
View File
@@ -393,6 +393,7 @@ def get_load_balance_stats(
model: nn.Module, reset_stats: bool = True, try_to_avoid_padding_experts: bool = True
) -> dict[str, Tensor | None]:
per_layer_max_vio = []
per_layer_routing_confidence = []
language_model = get_language_model(model)
for transformer_block in language_model.layers:
# This is necessary for models that have mixed dense layers
@@ -400,16 +401,25 @@ def get_load_balance_stats(
if block_mlp is None or not hasattr(block_mlp, "tokens_per_expert"):
continue
tokens_per_expert: torch.Tensor = block_mlp.tokens_per_expert
num_routed_tokens = tokens_per_expert.sum() / block_mlp.router.top_k
if try_to_avoid_padding_experts:
tokens_per_expert = tokens_per_expert.sort(dim=0, descending=True).values[block_mlp.router.top_k :]
balanced_load = tokens_per_expert.mean()
max_vio = (tokens_per_expert.max() - balanced_load) / balanced_load
per_layer_max_vio.append(max_vio.item())
per_layer_max_vio.append(max_vio.detach())
routing_confidence = block_mlp.routing_confidence_sum / num_routed_tokens
per_layer_routing_confidence.append(routing_confidence.detach())
if reset_stats:
block_mlp.tokens_per_expert.zero_()
block_mlp.routing_confidence_sum.zero_()
if len(per_layer_max_vio) == 0:
return {"max_vio": None}
return {"max_vio": torch.tensor(per_layer_max_vio, device=torch.device("cuda"))}
return {"max_vio": None, "routing_confidence": None}
return {
"max_vio": torch.stack(per_layer_max_vio),
"routing_confidence": torch.stack(per_layer_routing_confidence),
}
def get_model(
+30 -6
View File
@@ -387,6 +387,16 @@ class GptOssGroupedExperts(nn.Module):
nn.init.zeros_(self.down_proj_bias)
def _selected_probability_mass_sum(
scores: torch.Tensor, top_scores: torch.Tensor, score_func: Literal["softmax", "sigmoid"]
) -> torch.Tensor:
with torch.no_grad():
if score_func == "softmax":
return top_scores.sum()
selected_prob_mass = top_scores / (scores.sum(dim=-1, keepdim=True) + 1e-20)
return selected_prob_mass.sum(dim=-1).sum()
class TokenChoiceTopKRouter(nn.Module):
"""This class implements token-choice routing. In token-choice top-K routing, each token is
routed to top K experts based on the router scores.
@@ -420,7 +430,7 @@ class TokenChoiceTopKRouter(nn.Module):
def forward(
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None, routed_experts: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Args:
x (torch.Tensor): Input tensor with shape ``(bs*slen, dim)``.
@@ -429,13 +439,15 @@ class TokenChoiceTopKRouter(nn.Module):
routed_experts (torch.Tensor | None, optional): Optional tensor with shape ``(bs * slen, top_k)``.
Returns:
tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
- top_scores (torch.Tensor):
Routing scores for selected experts with shape ``(bs*slen, top_k)``.
- selected_experts_indices (torch.Tensor):
Expert indices selected for each token with shape ``(bs*slen, top_k)``.
- num_tokens_per_expert (torch.Tensor):
Number of tokens assigned to each expert with shape ``(num_experts,)``.
- routing_confidence_sum (torch.Tensor):
Sum over tokens of the selected-expert probability mass before route normalization/scaling.
"""
# scores shape (bs*slen, num_experts)
assert routed_experts is None or routed_experts.shape[-1] == self.top_k, (
@@ -469,6 +481,8 @@ class TokenChoiceTopKRouter(nn.Module):
else:
top_scores, selected_experts_indices = torch.topk(scores, k=self.top_k, dim=1)
routing_confidence_sum = _selected_probability_mass_sum(scores, top_scores, self.score_func)
if self.route_norm:
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
top_scores = top_scores / denominator
@@ -482,7 +496,7 @@ class TokenChoiceTopKRouter(nn.Module):
max=self.num_experts,
)
return top_scores, selected_experts_indices, num_tokens_per_expert
return top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum
def init_weights(self, init_std: float):
nn.init.trunc_normal_(self.gate.weight, mean=0.0, std=init_std)
@@ -600,6 +614,7 @@ class MoE(nn.Module):
torch.zeros(num_experts, dtype=torch.float32),
persistent=False,
)
self.register_buffer("routing_confidence_sum", torch.tensor(0.0, dtype=torch.float32), persistent=False)
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
self.ep_comm_backend = backend
@@ -718,6 +733,7 @@ class MoE(nn.Module):
top_scores,
selected_experts_indices,
num_tokens_per_expert,
routing_confidence_sum,
) = self.router(x, self.expert_bias, routed_experts=routed_experts)
# tokens_per_expert will be used to update the expert bias for load balancing.
@@ -727,6 +743,7 @@ class MoE(nn.Module):
# routed expert compute below.
with torch.no_grad():
self.tokens_per_expert.add_(num_tokens_per_expert)
self.routing_confidence_sum.add_(routing_confidence_sum)
if self.ep_comm_backend == "deepep":
routed_output = self._run_deepep_routed_experts(x, selected_experts_indices, top_scores)
@@ -774,6 +791,7 @@ class MoE(nn.Module):
with torch.device(buffer_device):
self.tokens_per_expert = torch.zeros(self.experts.num_experts, dtype=torch.float32)
self.routing_confidence_sum = torch.tensor(0.0, dtype=torch.float32)
if self.load_balance_coeff is not None:
self.expert_bias = torch.zeros(self.experts.num_experts, dtype=torch.float32)
@@ -938,7 +956,7 @@ class NemotronHRouter(nn.Module):
def forward(
self, x: torch.Tensor, expert_bias: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
scores = F.linear(x.float(), self.gate.float()).sigmoid()
scores_for_choice = scores + self.e_score_correction_bias
@@ -964,6 +982,7 @@ class NemotronHRouter(nn.Module):
selected_experts_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
top_scores = scores.gather(1, selected_experts_indices)
routing_confidence_sum = _selected_probability_mass_sum(scores, top_scores, "sigmoid")
if self.norm_topk_prob:
denominator = top_scores.sum(dim=-1, keepdim=True) + 1e-20
@@ -976,7 +995,7 @@ class NemotronHRouter(nn.Module):
max=self.num_experts,
)
return top_scores, selected_experts_indices, num_tokens_per_expert
return top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum
def init_weights(self, init_std: float):
nn.init.trunc_normal_(self.gate, mean=0.0, std=init_std)
@@ -1067,6 +1086,7 @@ class LatentMoE(nn.Module):
torch.zeros(num_experts, dtype=torch.float32),
persistent=False,
)
self.register_buffer("routing_confidence_sum", torch.tensor(0.0, dtype=torch.float32), persistent=False)
def set_ep_comm_backend(self, backend: EPCommBackend) -> None:
self.ep_comm_backend = backend
@@ -1161,10 +1181,13 @@ class LatentMoE(nn.Module):
bs, slen, dim = x.shape
x_flat = x.view(-1, dim)
top_scores, selected_experts_indices, num_tokens_per_expert = self.router(x_flat, self.expert_bias)
top_scores, selected_experts_indices, num_tokens_per_expert, routing_confidence_sum = self.router(
x_flat, self.expert_bias
)
with torch.no_grad():
self.tokens_per_expert.add_(num_tokens_per_expert)
self.routing_confidence_sum.add_(routing_confidence_sum)
if self.ep_comm_backend == "deepep":
routed_output = self._run_deepep_routed_experts(x_flat, selected_experts_indices, top_scores)
@@ -1196,5 +1219,6 @@ class LatentMoE(nn.Module):
with torch.device(buffer_device):
self.tokens_per_expert = torch.zeros(self.experts.num_experts, dtype=torch.float32)
self.routing_confidence_sum = torch.tensor(0.0, dtype=torch.float32)
if self.load_balance_coeff is not None:
self.expert_bias = torch.zeros(self.experts.num_experts, dtype=torch.float32)
+4
View File
@@ -521,6 +521,8 @@ def train(config: TrainerConfig):
micro_step_message += f" | Mismatch KL: {tensors['mismatch_kl/all'][-1].mean().item():.4f}"
if "max_vio" in tensors:
micro_step_message += f" | Max Vio: {tensors['max_vio'][-1].mean().item():.4f}"
if "routing_confidence" in tensors:
micro_step_message += f" | Routing Conf.: {tensors['routing_confidence'][-1].mean().item():.4f}"
logger.debug(micro_step_message)
# compute_loss already divided by the global token count. Undo FSDP's per-rank averaging
@@ -580,6 +582,8 @@ def train(config: TrainerConfig):
step_message += f" | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f} GiB"
if "max_vio/mean" in tensor_stats:
step_message += f" | Max Vio: {tensor_stats['max_vio/mean']:.4f}"
if "routing_confidence/mean" in tensor_stats:
step_message += f" | Routing Conf.: {tensor_stats['routing_confidence/mean']:.4f}"
logger.success(step_message)
# Log performance metrics
+27 -11
View File
@@ -381,7 +381,15 @@ def train(config: SFTConfig):
step_loss_sum = torch.tensor(0.0, device="cuda")
step_local_token_count = torch.tensor(0, dtype=torch.int64, device="cuda")
nan_loss_count = torch.tensor(0, device="cuda")
batch_max_vio = torch.tensor(0.0, device="cuda")
is_moe_model = is_tt_moe_model(model)
moe_stats = (
{
"max_vio": torch.tensor(0.0, device="cuda"),
"routing_confidence": torch.tensor(0.0, device="cuda"),
}
if is_moe_model
else {}
)
for micro_step in range(grad_accum_steps):
micro_batch = next(dataiter)
@@ -406,12 +414,16 @@ def train(config: SFTConfig):
with maybe_record_function("backward"):
scaled_loss.backward()
if is_tt_moe_model(model):
max_vio = get_load_balance_stats(model)["max_vio"]
if max_vio is not None:
max_vio = max_vio.mean()
dist.all_reduce(max_vio, op=dist.ReduceOp.MAX)
batch_max_vio += max_vio / grad_accum_steps
if is_moe_model:
for name, values in get_load_balance_stats(model).items():
if values is None:
continue
value = values.mean()
reduce_op = dist.ReduceOp.MAX if name == "max_vio" else dist.ReduceOp.SUM
dist.all_reduce(value, op=reduce_op)
if reduce_op == dist.ReduceOp.SUM:
value /= dist.get_world_size()
moe_stats[name] += value / grad_accum_steps
forward_backward_time = time.perf_counter() - forward_backward_start_time
@@ -489,8 +501,11 @@ def train(config: SFTConfig):
if grad_norm is not None:
step_message += f" | Grad. Norm: {grad_norm:.4f}"
step_message += f" | LR: {current_lr:.2e} | Throughput: {throughput:.0f} tokens/s | MFU: {mfu:.1f}% | Peak Mem.: {peak_memory:.1f}/{max_memory:.1f} GiB ({peak_memory / max_memory * 100:.1f}%)"
if is_tt_moe_model(model) and batch_max_vio.item() > 0:
step_message += f" | Max Vio: {batch_max_vio.item():.4f}"
if is_moe_model:
for name, label in (("max_vio", "Max Vio"), ("routing_confidence", "Routing Conf.")):
value = moe_stats[name].item()
if value > 0:
step_message += f" | {label}: {value:.4f}"
logger.success(step_message)
# Log progress metrics
@@ -558,8 +573,9 @@ def train(config: SFTConfig):
disk_metrics["step"] = progress.step
monitor.log(disk_metrics, step=progress.step)
if is_tt_moe_model(model) and batch_max_vio.item() > 0:
monitor.log({"max_vio/mean": batch_max_vio.item(), "step": progress.step}, step=progress.step)
moe_log_metrics = {f"{name}/mean": value.item() for name, value in moe_stats.items() if value.item() > 0}
if moe_log_metrics:
monitor.log({**moe_log_metrics, "step": progress.step}, step=progress.step)
is_first_step = False
progress.step += 1