Compare commits

...
Author SHA1 Message Date
Mika SenghaasandGitHub a36151c951 fix(logger): preserve traceback in JSON sink (#2594)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix(logger): preserve traceback in JSON sink with enqueue=True

loguru's RecordException.__reduce__ unconditionally drops the
traceback object before pickling, so records dequeued by the
enqueue=True worker have exc.traceback=None and the JSON sink
emits only the exception type + message - no frames.

Pre-format the traceback into extra["_traceback"] via a loguru
patcher that runs at log time, while the live traceback is still
attached. The string survives pickling, and build_log_entry reads
it back into the "exception" field.

enqueue=True is kept because the trainer's torchrun workers all
write JSON lines to a shared inherited stdout, and loguru's docs
flag this as the case where the multiprocessing-safe queue is
required to avoid interleaved/corrupt output.

* refactor(logger): drop underscore prefix from traceback patcher/key

* chore(logger): tighten traceback patcher comments
2026-05-25 13:41:01 -07:00
c5559033bd Add indexCache training support (#2541)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* Add indexCache training support

* fix glm moe dsa index cache threading

Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>

* Delete tests/unit/train/models/test_glm_moe_dsa_index_cache.py

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>

* fix

* refactor: group IndexCache knobs into IndexCacheConfig sub-config

Replaces the three flat ModelConfig fields (use_index_cache,
index_topk_freq, index_topk_pattern) with a single
index_cache: IndexCacheConfig | None = None sub-config.

None signals "disabled" explicitly, so the brittle model_fields_set
check in get_model goes away. HF/vLLM-side flat fields stay flat —
they're written from the sub-config only when it's set.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Signed-off-by: faresobeid <111092724+faresobeid@users.noreply.github.com>
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: faresobeid <faresobeid@users.noreply.github.com>
Co-authored-by: samsja <sami@primeintellect.ai>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 11:55:07 -07:00
25d4b1dcc8 fix(orchestrator): trigger evals on orchestrator step (#2626)
Docker Push / Push CUDA image to Docker (push) Canceled after 0s
* fix: trigger evals from orchestrator step

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: simplify eval scheduling

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: inline resume eval skip

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor: clarify resume eval skip

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 11:12:33 -07:00
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
19 changed files with 465 additions and 329 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."""
@@ -68,6 +68,14 @@ class BenchConfig(BaseConfig):
"""Path to write benchmark results as JSON. If unset, results are only printed to the console."""
class IndexCacheConfig(BaseConfig):
topk_freq: int = Field(1, ge=1)
"""Recompute DSA top-k indices every N layers; intervening layers reuse the cached indices. ``1`` recomputes every layer (effectively no reuse). Mirrors vLLM's ``index_topk_freq`` HF override."""
topk_pattern: str | None = None
"""Optional per-layer schedule that overrides ``topk_freq``. ``'F'`` computes fresh indices for that layer; ``'S'`` reuses the previously cached indices. Length should match the number of decoder layers."""
class LoRAConfig(BaseConfig):
rank: int = Field(16, ge=1)
"""Rank of the low-rank decomposition matrices."""
@@ -168,6 +176,9 @@ class ModelConfig(BaseModelConfig):
fp8: bool = False
"""FP8 training via DeepGEMM. Replaces ``nn.Linear`` with FP8 blockwise linear and uses FP8 grouped GEMM for MoE experts. Requires SM90 (Hopper) GPUs and ``model.impl='custom'``."""
index_cache: IndexCacheConfig | None = None
"""DSA IndexCache sub-configuration. If set, sparse-attention top-k indices are reused across decoder layers per the configured schedule (mirrors vLLM's IndexCache HF overrides). If None, every layer recomputes its own indices."""
freeze_moe_router: bool = False
"""Freeze MoE router parameters during training."""
+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,
+1 -3
View File
@@ -186,7 +186,6 @@ class EvalEnv(Env):
self,
model_name: str,
get_client: Callable[[], Awaitable[vf.ClientConfig]],
ckpt_step: int,
step: int,
cache_salt: str,
) -> list[vf.RolloutOutput]:
@@ -256,7 +255,6 @@ class EvalEnv(Env):
get_monitor().log(
{
f"eval/{self.name}/failed_rollouts": failed_count / total_rollouts,
"progress/ckpt_step": ckpt_step,
"step": step,
},
step=step,
@@ -319,7 +317,7 @@ class EvalEnv(Env):
assert pass_at_k is not None
eval_metrics.update(pd.Series(pass_at_k.mean()).to_dict())
eval_metrics = {f"eval/{self.name}/{key}": v for key, v in eval_metrics.items()}
eval_metrics.update({"progress/ckpt_step": ckpt_step, "step": step})
eval_metrics["step"] = step
monitor.log(eval_metrics, step=step)
monitor.log_eval_samples(successful_outputs, env_name=self.name, step=step)
-26
View File
@@ -1,32 +1,6 @@
import numpy as np
def compute_eval_ckpt_step(
ckpt_step: int,
prev_ckpt_step: int,
last_eval_step: int,
interval: int,
eval_base_model: bool = True,
) -> int | None:
"""Determine which checkpoint step (if any) should trigger an eval.
Handles the case where ckpt_step jumps over interval boundaries by finding
the highest interval-aligned step in (prev_ckpt_step, ckpt_step].
Returns the interval step to eval at, or None if no eval should run.
"""
if ckpt_step <= prev_ckpt_step:
return None
highest_interval_step = (ckpt_step // interval) * interval
if highest_interval_step > prev_ckpt_step and highest_interval_step > last_eval_step:
if highest_interval_step == 0:
if ckpt_step == 0 and eval_base_model:
return 0
else:
return highest_interval_step
return None
def _pass_at_k(n: int, c: int, k: int) -> float:
"""Unbiased estimator of pass@k (Chen et al., 2021).
+9 -31
View File
@@ -8,7 +8,6 @@ import tomli_w
import prime_rl._compat # noqa: F401 — patch ring_flash_attn compat before transitive import
from prime_rl.orchestrator.advantage import compute_advantages
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step
from prime_rl.orchestrator.event_loop_lag import EventLoopLagMonitor
from prime_rl.orchestrator.inference_metrics import InferenceMetricsCollector
from prime_rl.orchestrator.patches import monkey_patch_chat_completion_logprobs, monkey_patch_oai_iterable_types
@@ -285,11 +284,6 @@ async def orchestrate(config: OrchestratorConfig):
logger.info(f"Initializing training batch sender ({config.rollout_transport})")
training_batch_sender = setup_training_batch_sender(config.output_dir, config.rollout_transport)
# Track last online eval checkpoint step per eval env
last_eval_steps: dict[str, int] = {env.name: -1 for env in eval_envs} if eval_envs else {}
# Track previous ckpt_step to detect when ckpt_step jumps over eval interval boundaries
prev_ckpt_step = -1
# Reset weights to base model if starting from scratch
progress = Progress()
@@ -297,13 +291,6 @@ async def orchestrate(config: OrchestratorConfig):
ckpt_manager.load(progress, buffer, step=checkpoint_step)
logger.info(f"Resuming training from checkpoint step {checkpoint_step}")
scheduler.ckpt_step = progress.step # Always resume from the latest checkpoint
if config.eval and config.eval.skip_eval_on_resume:
prev_ckpt_step = scheduler.ckpt_step
last_eval_steps = {name: scheduler.ckpt_step for name in last_eval_steps}
logger.info(f"Skipping online eval on resume (ckpt_step={scheduler.ckpt_step})")
else:
# Allow eval at resumed step by setting prev_ckpt_step one behind
prev_ckpt_step = scheduler.ckpt_step - 1
# In NCCL mode, skip existence check - weights are broadcasted, not stored on disk
check_exists = config.weight_broadcast.type != "nccl"
@@ -362,21 +349,18 @@ async def orchestrate(config: OrchestratorConfig):
envs_to_eval: list[EvalEnv] = []
if config.eval:
assert eval_envs is not None
for eval_env in eval_envs:
eval_ckpt_step = compute_eval_ckpt_step(
ckpt_step=ckpt_step,
prev_ckpt_step=prev_ckpt_step,
last_eval_step=last_eval_steps[eval_env.name],
interval=eval_env.config.interval,
eval_base_model=config.eval.eval_base_model,
)
if eval_ckpt_step is not None:
last_eval_steps[eval_env.name] = ckpt_step
envs_to_eval.append(eval_env)
if is_first_step and checkpoint_step is not None and config.eval.skip_eval_on_resume:
logger.info(f"Skipping online eval on resume (step={progress.step})")
else:
for eval_env in eval_envs:
if progress.step % eval_env.config.interval == 0 and (
progress.step > 0 or config.eval.eval_base_model
):
envs_to_eval.append(eval_env)
if envs_to_eval:
env_names = ", ".join(e.name for e in envs_to_eval)
logger.info(f"Running evals at {ckpt_step=} for {env_names}")
logger.info(f"Running evals at step={progress.step} for {env_names}")
# Pause weight updates and re-scheduling of training rollouts during eval
# to avoid evaluating across different checkpoints and avoid congestion
@@ -392,7 +376,6 @@ async def orchestrate(config: OrchestratorConfig):
eval_env.evaluate(
model_name=student_inference.model_name,
get_client=student_inference.get_eval_client,
ckpt_step=ckpt_step,
step=progress.step,
cache_salt=str(ckpt_step),
)
@@ -411,9 +394,6 @@ async def orchestrate(config: OrchestratorConfig):
# Resume weight updates
scheduler.checkpoint_ready.set()
# Update prev_ckpt_step for next iteration
prev_ckpt_step = ckpt_step
# Schedule generating the training batch. Retry on empty-after-filter
# batches so the trainer never receives an empty batch.
generate_completions_time = 0.0
@@ -637,7 +617,6 @@ async def orchestrate(config: OrchestratorConfig):
"progress/total_tokens": progress.total_tokens,
"progress/total_samples": progress.total_samples,
"progress/total_problems": progress.total_problems,
"progress/ckpt_step": ckpt_step, # Shared W&B axis
# Sequence length metrics
"seq_len/all/mean": by_example.seq_len.mean().mean(),
"seq_len/all/max": by_example.seq_len.mean().max(),
@@ -797,7 +776,6 @@ async def orchestrate(config: OrchestratorConfig):
eval_env.evaluate(
model_name=student_inference.model_name,
get_client=student_inference.get_eval_client,
ckpt_step=ckpt_step,
step=progress.step,
cache_salt=str(ckpt_step),
)
+18 -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(
@@ -472,6 +482,11 @@ def get_model(
model_config.use_grouped_mm = config.moe_use_grouped_mm
model_config.fp8 = config.fp8
if config.index_cache is not None:
model_config.use_index_cache = True
model_config.index_topk_freq = config.index_cache.topk_freq
model_config.index_topk_pattern = config.index_cache.topk_pattern
# Ensure pad_token_id is set (some models like Qwen3MoE don't have it).
# In transformers v5, token IDs moved from PretrainedConfig to GenerationConfig.
if not hasattr(model_config, "pad_token_id") or model_config.pad_token_id is None:
@@ -3,6 +3,17 @@ import warnings
from transformers.configuration_utils import PretrainedConfig
def _index_cache_skip_topk(config, layer_idx: int) -> bool:
if not getattr(config, "use_index_cache", False):
return False
index_topk_pattern = getattr(config, "index_topk_pattern", None)
if index_topk_pattern is not None:
return layer_idx < len(index_topk_pattern) and index_topk_pattern[layer_idx] == "S"
return layer_idx % getattr(config, "index_topk_freq", 1) != 0
class GlmMoeDsaConfig(PretrainedConfig):
r"""
Configuration class for the GLM-5 (GlmMoeDsa) model.
@@ -73,6 +84,13 @@ class GlmMoeDsaConfig(PretrainedConfig):
Whether to use interleaved RoPE style in the sparse indexer.
index_topk (`int`, defaults to 2048):
Number of top tokens selected by the sparse indexer.
use_index_cache (`bool`, defaults to `False`):
Whether to reuse sparse attention top-k indices across DSA layers.
index_topk_freq (`int`, defaults to 1):
Frequency for recomputing top-k indices when IndexCache is enabled.
index_topk_pattern (`str`, *optional*):
Optional per-layer pattern where ``"F"`` computes fresh indices and
``"S"`` reuses the cached indices from the previous full layer.
scoring_func (`str`, defaults to `"sigmoid"`):
Scoring function for MoE router. Must match the vLLM inference
server's expectation (vLLM defaults to ``"softmax"`` when this
@@ -141,6 +159,9 @@ class GlmMoeDsaConfig(PretrainedConfig):
indexer_rope_interleave=True,
pad_token_id=154820,
index_topk=2048,
use_index_cache=False,
index_topk_freq=1,
index_topk_pattern=None,
scoring_func="sigmoid",
topk_method="noaux_tc",
use_grouped_mm=True,
@@ -194,6 +215,9 @@ class GlmMoeDsaConfig(PretrainedConfig):
self.index_head_dim = index_head_dim
self.indexer_rope_interleave = indexer_rope_interleave
self.index_topk = index_topk
self.use_index_cache = use_index_cache
self.index_topk_freq = index_topk_freq
self.index_topk_pattern = index_topk_pattern
self.scoring_func = scoring_func
self.topk_method = topk_method
self.use_grouped_mm = use_grouped_mm
@@ -13,7 +13,7 @@ from transformers.utils import TransformersKwargs, auto_docstring
from transformers.utils.deprecation import deprecate_kwarg
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig
from prime_rl.trainer.models.glm_moe_dsa.configuration_glm_moe_dsa import GlmMoeDsaConfig, _index_cache_skip_topk
from prime_rl.trainer.models.glm_moe_dsa.converting_glm_moe_dsa import (
convert_hf_layer_to_tt,
convert_hf_to_tt_moe,
@@ -29,7 +29,7 @@ from prime_rl.trainer.models.layers.norms import RMSNorm, RMSNormConfig
from prime_rl.trainer.models.layers.rotary_emb import RotaryEmbedding, RotaryEmbeddingConfig
def _sparse_mla_attention_args(config: GlmMoeDsaConfig) -> SparseMlaAttentionArgs:
def _sparse_mla_attention_args(config: GlmMoeDsaConfig, layer_idx: int) -> SparseMlaAttentionArgs:
if config.q_lora_rank is None:
raise ValueError("Sparse MLA attention requires q_lora_rank to be set")
return SparseMlaAttentionArgs(
@@ -46,6 +46,8 @@ def _sparse_mla_attention_args(config: GlmMoeDsaConfig) -> SparseMlaAttentionArg
index_n_heads=config.index_n_heads,
index_head_dim=config.index_head_dim,
index_topk=config.index_topk,
use_index_cache=getattr(config, "use_index_cache", False),
skip_topk=_index_cache_skip_topk(config, layer_idx),
)
@@ -53,7 +55,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config: GlmMoeDsaConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = GlmMoeDsaAttention(_sparse_mla_attention_args(config))
self.self_attn = GlmMoeDsaAttention(_sparse_mla_attention_args(config, layer_idx))
moe_args = MoEArgs(
num_experts=config.n_routed_experts,
@@ -95,15 +97,17 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
ks: Optional[torch.Tensor] = None,
ke: Optional[torch.Tensor] = None,
cached_indices: Optional[torch.Tensor] = None,
routed_experts: Optional[torch.LongTensor] = None,
) -> torch.Tensor:
) -> tuple[torch.Tensor, torch.Tensor | None]:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states, _ = self.self_attn(
hidden_states, cached_indices = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
ks=ks,
ke=ke,
cached_indices=cached_indices,
)
hidden_states = residual + hidden_states
@@ -111,7 +115,7 @@ class GlmMoeDsaDecoderLayer(GradientCheckpointingLayer):
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states, routed_experts=routed_experts)
hidden_states = residual + hidden_states
return hidden_states
return hidden_states, cached_indices
@auto_docstring
@@ -256,15 +260,19 @@ class GlmMoeDsaModel(GlmMoeDsaPreTrainedModel):
else:
ks, ke = ks_full, ke_full
cached_indices = None
use_index_cache = getattr(self.config, "use_index_cache", False)
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
routed_experts_layer = routed_experts[:, :, layer_idx, :] if routed_experts is not None else None
hidden_states = decoder_layer(
hidden_states, next_cached_indices = decoder_layer(
hidden_states,
position_embeddings=position_embeddings,
ks=ks,
ke=ke,
cached_indices=cached_indices,
routed_experts=routed_experts_layer,
)
cached_indices = next_cached_indices if use_index_cache else None
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(last_hidden_state=hidden_states)
@@ -32,6 +32,8 @@ class SparseMlaAttentionArgs:
index_n_heads: int
index_head_dim: int
index_topk: int
use_index_cache: bool = False
skip_topk: bool = False
class _SparseMLA(torch.autograd.Function):
@@ -157,6 +159,8 @@ class GlmMoeDsaAttention(nn.Module):
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, args.hidden_size, bias=args.attention_bias)
self.indexer = Indexer(args)
self.use_index_cache = args.use_index_cache
self.skip_topk = args.skip_topk
self.scaling = self.qk_head_dim ** (-0.5)
self._cp_group: dist.ProcessGroup | None = None
@@ -234,6 +238,7 @@ class GlmMoeDsaAttention(nn.Module):
position_embeddings: tuple[torch.Tensor, torch.Tensor],
ks: torch.Tensor | None = None,
ke: torch.Tensor | None = None,
cached_indices: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor | None]:
q_latent, k_compressed_normed, k_rope = self.attn_projections(hidden_states)
@@ -241,17 +246,19 @@ class GlmMoeDsaAttention(nn.Module):
k_compressed_normed = gather_for_cp(k_compressed_normed, self._cp_group)
k_rope = gather_for_cp(k_rope, self._cp_group)
indices = self.indexer.compute_sparse_indices(
hidden_states_local=hidden_states,
q_latent_local=q_latent,
ks=ks,
ke=ke,
index_topk=self.args.index_topk,
position_embeddings_full=position_embeddings,
cp_group=self._cp_group,
cp_world_size=self._cp_world_size,
cp_rank=self._cp_rank,
)
indices = cached_indices
if not self.skip_topk:
indices = self.indexer.compute_sparse_indices(
hidden_states_local=hidden_states,
q_latent_local=q_latent,
ks=ks,
ke=ke,
index_topk=self.args.index_topk,
position_embeddings_full=position_embeddings,
cp_group=self._cp_group,
cp_world_size=self._cp_world_size,
cp_rank=self._cp_rank,
)
sparse_q, sparse_kv, w_v = self.mla_up_proj(
q_latent_local=q_latent,
@@ -261,4 +268,5 @@ class GlmMoeDsaAttention(nn.Module):
)
out = _SparseMLA.apply(sparse_q, sparse_kv, indices, self.scaling)
return self.output_proj(out, w_v), None
cached_indices = indices if self.use_index_cache else None
return self.output_proj(out, w_v), cached_indices
+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
+16 -2
View File
@@ -39,7 +39,11 @@ def build_log_entry(record) -> dict:
"function": record["function"],
"line": record["line"],
}
if record["exception"] is not None:
# extra["traceback"] is set by traceback_patcher when enqueue=True (loguru
# drops the traceback object during pickling, so it must be pre-formatted).
if extra.get("traceback"):
log_entry["exception"] = extra.pop("traceback")
elif record["exception"] is not None:
exc = record["exception"]
log_entry["exception"] = "".join(traceback.format_exception(exc.type, exc.value, exc.traceback))
# Extract tag from extra if present (used by workers to identify themselves)
@@ -52,6 +56,12 @@ def build_log_entry(record) -> dict:
return log_entry
def traceback_patcher(record) -> None:
exc = record["exception"]
if exc is not None and exc.traceback is not None:
record["extra"]["traceback"] = "".join(traceback.format_exception(exc.type, exc.value, exc.traceback))
def json_sink(message) -> None:
"""Sink that outputs flat JSON to stdout for log aggregation (Loki, Grafana, etc.)."""
log_entry = build_log_entry(message.record)
@@ -118,6 +128,10 @@ def setup_logger(
from loguru._logger import Core as _Core
from loguru._logger import Logger as _Logger
# enqueue=True drops the traceback during pickling, so pre-format it here
# while the live traceback is still attached.
patchers = [traceback_patcher] if json_logging else []
logger = _Logger(
core=_Core(),
exception=None,
@@ -127,7 +141,7 @@ def setup_logger(
colors=False,
raw=False,
capture=True,
patchers=[],
patchers=patchers,
extra={},
)
@@ -1,86 +0,0 @@
"""Unit tests for eval scheduling logic - specifically the range check
that detects when ckpt_step jumps over eval interval boundaries."""
from prime_rl.orchestrator.eval_utils import compute_eval_ckpt_step
def test_exact_hit():
result = compute_eval_ckpt_step(ckpt_step=25, prev_ckpt_step=24, last_eval_step=0, interval=25)
assert result == 25
def test_jump_over_interval():
result = compute_eval_ckpt_step(ckpt_step=26, prev_ckpt_step=24, last_eval_step=0, interval=25)
assert result == 25
def test_no_interval_crossed():
result = compute_eval_ckpt_step(ckpt_step=23, prev_ckpt_step=22, last_eval_step=0, interval=25)
assert result is None
def test_base_model_eval_at_step_0():
result = compute_eval_ckpt_step(
ckpt_step=0, prev_ckpt_step=-1, last_eval_step=-1, interval=25, eval_base_model=True
)
assert result == 0
def test_base_model_eval_disabled():
result = compute_eval_ckpt_step(
ckpt_step=0, prev_ckpt_step=-1, last_eval_step=-1, interval=25, eval_base_model=False
)
assert result is None
def test_no_double_eval():
result = compute_eval_ckpt_step(ckpt_step=25, prev_ckpt_step=24, last_eval_step=25, interval=25)
assert result is None
def test_no_change_in_ckpt_step():
result = compute_eval_ckpt_step(ckpt_step=25, prev_ckpt_step=25, last_eval_step=0, interval=25)
assert result is None
def test_multiple_intervals_crossed():
result = compute_eval_ckpt_step(ckpt_step=76, prev_ckpt_step=24, last_eval_step=0, interval=25)
assert result == 75
def test_second_interval():
result = compute_eval_ckpt_step(ckpt_step=50, prev_ckpt_step=49, last_eval_step=25, interval=25)
assert result == 50
def test_jump_across_second_interval():
result = compute_eval_ckpt_step(ckpt_step=51, prev_ckpt_step=48, last_eval_step=25, interval=25)
assert result == 50
def test_production_scenario_step25_skipped():
"""Reproduces the bug from run c14miuyha2yhxkw1z3eqgyub."""
result = compute_eval_ckpt_step(ckpt_step=26, prev_ckpt_step=24, last_eval_step=0, interval=25)
assert result == 25
def test_production_scenario_step50_exact():
result = compute_eval_ckpt_step(ckpt_step=50, prev_ckpt_step=49, last_eval_step=26, interval=25)
assert result == 50
def test_simulate_full_run():
ckpt_steps = [0, 0, 3, 5, 10, 15, 20, 24, 26, 30, 35, 40, 48, 51, 60, 70, 74, 76]
interval = 25
last_eval_step = -1
prev_ckpt_step = -1
eval_triggered_at = []
for ckpt_step in ckpt_steps:
result = compute_eval_ckpt_step(ckpt_step, prev_ckpt_step, last_eval_step, interval)
if result is not None:
eval_triggered_at.append(result)
last_eval_step = ckpt_step
prev_ckpt_step = ckpt_step
assert eval_triggered_at == [0, 25, 50, 75]