Compare commits
20
Commits
v0.7.1.dev45
...
trinity
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6087c3addb | ||
|
|
99957ccd93 | ||
|
|
31ff561df6 | ||
|
|
dea7707526 | ||
|
|
fca9fb0975 | ||
|
|
1dcec737d9 | ||
|
|
43c2905243 | ||
|
|
54307fc301 | ||
|
|
069e580c78 | ||
|
|
45488ca048 | ||
|
|
3b5d031028 | ||
|
|
783cff546d | ||
|
|
acbabc6f0f | ||
|
|
055f62ca32 | ||
|
|
1b8c5ef01a | ||
|
|
55fc08db46 | ||
|
|
440b3afaa8 | ||
|
|
f5946b098e | ||
|
|
cd00986f71 | ||
|
|
208ea64308 |
@@ -1,8 +1,6 @@
|
||||
name: Build Image (ghcr)
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
ref:
|
||||
@@ -27,12 +25,12 @@ on:
|
||||
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_REF: ${{ inputs.ref || github.ref_name }}
|
||||
BUILD_TAG: ${{ inputs.tag || '' }}
|
||||
BUILD_PLATFORMS: ${{ inputs.platforms || 'both' }}
|
||||
|
||||
concurrency:
|
||||
group: build-image-${{ github.event.release.tag_name || inputs.tag || inputs.ref || github.ref_name }}
|
||||
group: build-image-${{ inputs.tag || inputs.ref || github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
|
||||
@@ -121,3 +121,11 @@ jobs:
|
||||
PYTEST_OUTPUT_DIR: /tmp/outputs
|
||||
VLLM_WORKER_MULTIPROC_METHOD: spawn
|
||||
run: uv run pytest -vvs ${{ matrix.pytest_args }}
|
||||
- name: Upload run logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ matrix.test }}-logs
|
||||
path: /tmp/outputs/**/*.log
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
name: Nightly FFT
|
||||
|
||||
on:
|
||||
# Allow to manually trigger the workflow
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
config_file:
|
||||
description: "Full-FT config to dispatch (e.g. configs/ci/nightly-fft/wordle.toml). Leave empty to run all."
|
||||
required: false
|
||||
default: ""
|
||||
image_tag:
|
||||
description: "prime-rl image tag to pin (e.g. v0.7.1.dev58). Leave empty to auto-resolve the newest v*.dev* with a published manifest."
|
||||
required: false
|
||||
default: ""
|
||||
|
||||
# Scheduled run at 3AM PST (11AM UTC) — disabled for now, enable once dry-run passes
|
||||
# schedule:
|
||||
# - cron: "0 11 * * *"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: read
|
||||
|
||||
jobs:
|
||||
discover-configs:
|
||||
name: Discover configs
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
outputs:
|
||||
matrix: ${{ steps.build-matrix.outputs.matrix }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
- name: Build matrix from nightly FFT configs
|
||||
id: build-matrix
|
||||
run: |
|
||||
# Find all nightly full-finetune configs
|
||||
files=$(ls configs/ci/nightly-fft/*.toml)
|
||||
|
||||
# Filter to specific config if provided in workflow_dispatch
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ github.event.inputs.config_file }}" ]; then
|
||||
filtered=$(echo "$files" | grep -F "${{ github.event.inputs.config_file }}" || true)
|
||||
if [ -z "$filtered" ]; then
|
||||
echo "Error: Config file '${{ github.event.inputs.config_file }}' not found"
|
||||
exit 1
|
||||
fi
|
||||
files="$filtered"
|
||||
fi
|
||||
|
||||
echo "Discovered nightly FFT configs:"
|
||||
echo "$files"
|
||||
|
||||
# Build JSON of the form: { "config_file": ["configs/ci/nightly-fft/foo.toml", ...] }
|
||||
json=$(printf '%s\n' "$files" | jq -R . | jq -sc '{config_file: .}')
|
||||
|
||||
echo "matrix=$json" >> "$GITHUB_OUTPUT"
|
||||
|
||||
dispatch-run:
|
||||
name: Dispatch hosted FFT run
|
||||
needs: discover-configs
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: ${{ fromJSON(needs.discover-configs.outputs.matrix) }}
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
submodules: false
|
||||
|
||||
- name: Resolve prime-rl image tag
|
||||
id: image
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# Pass the dispatch input through env so a malicious value
|
||||
# cannot break out of shell context via $(...) or embedded
|
||||
# quotes — the GitHub expression is substituted before Bash
|
||||
# parses the script.
|
||||
REQUESTED_IMAGE_TAG: ${{ github.event.inputs.image_tag }}
|
||||
run: |
|
||||
# If workflow_dispatch passed an explicit image_tag, validate
|
||||
# it as a Docker/OCI tag, verify its manifest is pullable,
|
||||
# and use it as-is (skip resolution).
|
||||
requested="$REQUESTED_IMAGE_TAG"
|
||||
if [ -n "$requested" ]; then
|
||||
# OCI/Docker tag charset: [A-Za-z0-9._-], max 128, no
|
||||
# leading '.' or '-'. Reject anything else before it
|
||||
# reaches curl or GITHUB_OUTPUT.
|
||||
if ! printf '%s' "$requested" | grep -Eq '^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$'; then
|
||||
echo "Invalid image_tag: only [A-Za-z0-9._-] allowed, max 128 chars, no leading '.' or '-'." >&2
|
||||
exit 1
|
||||
fi
|
||||
registry_token=$(curl -fsSL \
|
||||
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
|
||||
| jq -r .token)
|
||||
code=$(curl -sS -o /dev/null -w '%{http_code}' \
|
||||
-H "Authorization: Bearer $registry_token" \
|
||||
-H 'Accept: application/vnd.oci.image.index.v1+json' \
|
||||
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
|
||||
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$requested")
|
||||
if [ "$code" != "200" ]; then
|
||||
echo "Requested image_tag '$requested' has no published manifest (HTTP $code)." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Using pinned prime-rl image tag: $requested"
|
||||
echo "tag=$requested" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# The GHCR versions API can list a tag before its manifest is
|
||||
# actually pullable (build in-flight, or manifest step didn't
|
||||
# finish). So: pull the top N candidate tags, then verify each
|
||||
# with a manifest HEAD via the anonymous registry token flow;
|
||||
# take the newest one that resolves.
|
||||
candidates=$(gh api --paginate \
|
||||
"/orgs/primeintellect-ai/packages/container/prime-rl/versions" \
|
||||
--jq '.[].metadata.container.tags[]' \
|
||||
| grep -E '^v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+$' \
|
||||
| sort -Vru | head -n 10)
|
||||
if [ -z "$candidates" ]; then
|
||||
echo "No v*.dev* tag listed on GHCR." >&2
|
||||
exit 1
|
||||
fi
|
||||
registry_token=$(curl -fsSL \
|
||||
"https://ghcr.io/token?scope=repository:primeintellect-ai/prime-rl:pull" \
|
||||
| jq -r .token)
|
||||
tag=""
|
||||
for cand in $candidates; do
|
||||
code=$(curl -sS -o /dev/null -w '%{http_code}' \
|
||||
-H "Authorization: Bearer $registry_token" \
|
||||
-H 'Accept: application/vnd.oci.image.index.v1+json' \
|
||||
-H 'Accept: application/vnd.docker.distribution.manifest.list.v2+json' \
|
||||
"https://ghcr.io/v2/primeintellect-ai/prime-rl/manifests/$cand")
|
||||
if [ "$code" = "200" ]; then
|
||||
tag="$cand"
|
||||
break
|
||||
fi
|
||||
echo "Skip $cand — manifest HEAD returned $code"
|
||||
done
|
||||
if [ -z "$tag" ]; then
|
||||
echo "None of the top v*.dev* tags have a published manifest." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Latest published prime-rl image tag on GHCR: $tag"
|
||||
echo "tag=$tag" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
|
||||
- name: Install prime CLI (latest)
|
||||
run: uv tool install prime
|
||||
|
||||
- name: Dispatch run
|
||||
env:
|
||||
PRIME_API_KEY: ${{ secrets.PRIME_FFT_API_KEY }}
|
||||
PRIME_TEAM_ID: ${{ secrets.PRIME_FFT_TEAM_ID }}
|
||||
PRIME_BASE_URL: ${{ secrets.PRIME_BASE_URL }}
|
||||
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
|
||||
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
||||
run: |
|
||||
echo "Dispatching config: ${{ matrix.config_file }}"
|
||||
echo "Image tag: ${{ steps.image.outputs.tag }}"
|
||||
# Tag the RFTRun so it's identifiable on the platform as
|
||||
# coming from this workflow. Injected here rather than in
|
||||
# the checked-in toml because a top-level `name` field
|
||||
# breaks tests/unit/test_configs.py::test_load_configs
|
||||
# (RLConfig has no top-level name).
|
||||
config_base=$(basename "${{ matrix.config_file }}" .toml)
|
||||
run_name="nightly-${config_base}-$(date -u +%Y-%m-%d)-${{ github.run_id }}"
|
||||
dispatch_cfg=$(mktemp --suffix=.toml)
|
||||
printf 'name = "%s"\n\n' "$run_name" > "$dispatch_cfg"
|
||||
cat "${{ matrix.config_file }}" >> "$dispatch_cfg"
|
||||
echo "Dispatched run name: $run_name"
|
||||
# Forward WANDB_API_KEY / HF_TOKEN into the hosted payload:
|
||||
# the full-FT dispatch path (`prime train`) only picks up
|
||||
# secrets that were explicitly collected via `-e` / `--env-file`,
|
||||
# not ambient env, so the workflow env: block alone is not
|
||||
# enough to reach the hosted trainer/orchestrator pods.
|
||||
prime train "$dispatch_cfg" \
|
||||
--image-tag "${{ steps.image.outputs.tag }}" \
|
||||
-e WANDB_API_KEY \
|
||||
-e HF_TOKEN \
|
||||
--yes --output json
|
||||
@@ -1,11 +1,9 @@
|
||||
name: Sync Docs to Public Docs
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- 'docs/**'
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
|
||||
@@ -119,6 +119,8 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
# Needed to dispatch build_image.yaml below (POST .../dispatches).
|
||||
actions: write
|
||||
steps:
|
||||
- name: Publish draft release
|
||||
env:
|
||||
@@ -127,11 +129,22 @@ jobs:
|
||||
run: |
|
||||
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
|
||||
|
||||
# Publishing runs as GITHUB_TOKEN, whose events don't retrigger
|
||||
# workflows, so dispatch the image build explicitly.
|
||||
- name: Trigger image build for the release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ needs.auto-tag-on-main.outputs.tag }}
|
||||
run: |
|
||||
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
|
||||
|
||||
tag-and-release:
|
||||
if: github.event_name == 'workflow_dispatch' || startsWith(github.ref, 'refs/tags/v')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
# Needed to dispatch build_image.yaml below (POST .../dispatches).
|
||||
actions: write
|
||||
steps:
|
||||
- name: Checkout tagged release (dispatch)
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
@@ -195,6 +208,7 @@ jobs:
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Publish draft release
|
||||
id: publish
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ steps.release.outputs.tag }}
|
||||
@@ -207,6 +221,17 @@ jobs:
|
||||
fi
|
||||
if [ "$STATE" = "false" ]; then
|
||||
echo "Release $TAG is already published; nothing to do."
|
||||
echo "published=false" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false --latest
|
||||
echo "published=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Skipped when the release was already published (no rebuild needed).
|
||||
- name: Trigger image build for the release
|
||||
if: steps.publish.outputs.published == 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ steps.release.outputs.tag }}
|
||||
run: |
|
||||
gh workflow run build_image.yaml --repo "$GITHUB_REPOSITORY" -f ref="$TAG"
|
||||
|
||||
+2
-1
@@ -3,7 +3,8 @@
|
||||
url = git@github.com:PrimeIntellect-ai/verifiers.git
|
||||
[submodule "renderers"]
|
||||
path = deps/renderers
|
||||
url = git@github.com:PrimeIntellect-ai/renderers.git
|
||||
url = ../renderers.git
|
||||
branch = trinity
|
||||
[submodule "research-environments"]
|
||||
path = deps/research-environments
|
||||
url = git@github.com:PrimeIntellect-ai/research-environments.git
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
max_steps = 200
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
project = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "alphabet-sort"
|
||||
env.taskset = { id = "alphabet-sort-v1", min_turns = 3, max_turns = 5, task = { power_per_turn = false } }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 768
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
@@ -0,0 +1,49 @@
|
||||
max_steps = 5000
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
project = "hendrycks-sanity"
|
||||
name = "hendrycks-sanity"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 8
|
||||
seq_len = 8192
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "hendrycks-math"
|
||||
env.taskset = { id = "math-env-v1", dataset_name = "mikasenghaas/Sanity-Test-R1D-1.5B", dataset_subset = "default" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
name = "aime2024"
|
||||
env.taskset = { id = "aime24-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
group_size = 32
|
||||
|
||||
[trainer]
|
||||
|
||||
[trainer.model]
|
||||
seq_len = 16384
|
||||
attn = "flash_attention_2"
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
|
||||
[inference.model]
|
||||
max_model_len = 8192
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "default"
|
||||
reasoning_parser = "think"
|
||||
@@ -0,0 +1,34 @@
|
||||
max_steps = 20
|
||||
seq_len = 2048
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 1
|
||||
num_infer_gpus = 1
|
||||
|
||||
[wandb]
|
||||
project = "reverse-text"
|
||||
name = "reverse-text"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 128
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "reverse-text"
|
||||
env.taskset = { id = "reverse-text-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
@@ -0,0 +1,40 @@
|
||||
max_steps = 200
|
||||
seq_len = 4096
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 4
|
||||
num_infer_gpus = 4
|
||||
|
||||
[wandb]
|
||||
project = "wiki-search"
|
||||
name = "wiki-search"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "Qwen/Qwen3-4B-Instruct-2507"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
oversampling_factor = 2.0
|
||||
|
||||
[[orchestrator.pre_batch_filters]]
|
||||
type = "zero_advantage"
|
||||
enforce = true
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "wiki-search"
|
||||
env.taskset = { id = "wiki-search-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 512
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 4
|
||||
|
||||
[inference.model]
|
||||
tool_call_parser = "hermes"
|
||||
@@ -0,0 +1,35 @@
|
||||
max_steps = 200
|
||||
seq_len = 8192
|
||||
|
||||
[deployment]
|
||||
num_train_gpus = 2
|
||||
num_infer_gpus = 6
|
||||
|
||||
[wandb]
|
||||
project = "wordle"
|
||||
name = "wordle"
|
||||
|
||||
[ckpt]
|
||||
|
||||
[model]
|
||||
name = "PrimeIntellect/Qwen3-1.7B-Wordle-SFT"
|
||||
|
||||
[orchestrator]
|
||||
batch_size = 512
|
||||
group_size = 16
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
name = "wordle"
|
||||
env.taskset = { id = "wordle-v1" }
|
||||
env.agent.harness = { id = "null", runtime = { type = "subprocess" } }
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 1024
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference.parallel]
|
||||
dp = 6
|
||||
|
||||
[orchestrator.renderer]
|
||||
name = "prime-qwen3"
|
||||
Vendored
+1
-1
Submodule deps/renderers updated: bdb96b0c84...e9619bf8f0
Vendored
+1
-1
Submodule deps/research-environments updated: e40d32690f...f5d423c321
Vendored
+1
-1
Submodule deps/verifiers updated: 192fd8ef0d...b13ba60da6
@@ -14,6 +14,7 @@ This page covers workflows for developing on `prime-rl` itself — running the t
|
||||
- [Implement the Modeling Code](#implement-the-modeling-code)
|
||||
- [Register a Mini Preset](#register-a-mini-preset)
|
||||
- [Run the Smoke Test](#run-the-smoke-test)
|
||||
- [Adding a Custom VLM Implementation](#adding-a-custom-vlm-implementation)
|
||||
|
||||
## Test Suite
|
||||
|
||||
@@ -137,3 +138,15 @@ Before merging a new model, you need to ensure the following:
|
||||
- The small smoke test passes.
|
||||
|
||||
In the PR that adds the new model, you also need to provide a table covering the KL mismatch across 20 steps on `math` environment with `batch_size=64`. All the entries in the table must lower than 0.015. If this is not met, the PR will not be merged (unless reasonable justification is provided). This is to ensure all our models are consistent and their implementations match the implementations in the inference framework.
|
||||
|
||||
## Adding a Custom VLM Implementation
|
||||
|
||||
VLM training (any run with `[model.vlm]` set, SFT or RL) is custom-implementation-only: `get_model` rejects models without a custom PrimeRL VLM class at load time. To make a new VLM family trainable, extend a custom text model with a composite VLM body — the Qwen3.5 dense (`models/qwen3_5/`) and MoE (`models/qwen3_5_moe/`) implementations are the reference. The pieces, in dependency order:
|
||||
|
||||
1. **Custom text model first.** The VLM body wraps a custom `*ForCausalLM` (see [Adding a New Model](#adding-a-new-model)), so the text side — including its state-dict conversion and KL-mismatch table — comes first.
|
||||
2. **Composite VLM body.** A `*VLMModel` that holds the HF vision encoder and the custom text model, with a `prepare_inputs_embeds_and_position_ids` step: embed tokens, run the vision encoder, scatter image embeddings over placeholder tokens, and build MRoPE 3D positions from `mm_token_type_ids` (the renderer owns the token→modality mapping). The unified `*ForCausalLM` dispatches on the config: composite config → VLM path, text config → text path.
|
||||
3. **Always run the vision encoder.** Text-only micro-batches must feed the encoder dummy pixels and graft the result into the graph with zero contribution (`inputs_embeds + image_embeds.sum() * 0.0`) so FSDP/EP collectives stay symmetric across ranks when the encoder is trainable.
|
||||
4. **Packed-boundary consumption.** Samples pack into shared rows with per-document boundaries in `seq_lens`; every custom model's `forward()` declares the typed `seq_lens`/`seq_lens_are_pre_shard` parameters (the trainer passes them unconditionally) and must honor the boundaries — varlen flash `cu_seqlens`, linear-attention state resets per document, and a loud rejection on attention paths that can't (see the packed-batch guard in any modeling file). Set `supports_packed_multimodal_training` on the VLM model once packed rows are handled — RL fails loudly at startup for VLM models without it.
|
||||
5. **Registration.** Register the composite `model_type` in `_CUSTOM_VLM_MAPPING` (`models/__init__.py`) so `get_model` dispatches to the custom class, and describe the family in `VLM_REGISTRY` (`utils/vlm.py`).
|
||||
6. **Context parallelism (optional).** CP-capable VLMs implement `set_context_parallel_attributes` and shard embeds/positions inside the model after the vision merge; the trainers defer sharding to the model for MRoPE batches under ulysses.
|
||||
7. **Validation.** Same bar as text models: the KL-mismatch table for the text path, plus an SFT run and an RL run on a real multimodal dataset (the `color-codeword` environment is the reference task).
|
||||
|
||||
@@ -46,7 +46,7 @@ enable_router_replay = true
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
# term is pass_rate-scaled and normalized by the group's own max before the GRPO baseline
|
||||
# subtraction.
|
||||
#
|
||||
# 2 train + 4 infer nodes. Trainer uses cp=8 (ulysses) plus
|
||||
# 2 train + 4 infer nodes. Trainer uses cp=4 (ulysses) plus
|
||||
# the memory improvements from the GLM-5.1 prod run (research-prod rlm5/prod.toml): LM-head token
|
||||
# chunking, activation checkpointing (freq=1) + activation offloading (max_inflight=1), optimizer
|
||||
# CPU offload, and skip-gather / skip-optimizer checkpointing.
|
||||
@@ -57,7 +57,7 @@ enable_router_replay = true
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
@@ -47,7 +47,7 @@ enable_router_replay = true
|
||||
[trainer.model]
|
||||
impl = "custom"
|
||||
attn = "flash_attention_3"
|
||||
cp = 8
|
||||
cp = 4
|
||||
cp_style = "ulysses"
|
||||
fused_lm_head_token_chunk_size = 1024
|
||||
optim_cpu_offload = true
|
||||
|
||||
@@ -14,6 +14,7 @@ from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
ClientConfig,
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
LogConfig,
|
||||
@@ -31,6 +32,9 @@ class OptimizerConfig(BaseConfig):
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
init_path: Path | None = None
|
||||
"""Initial adapter for a fresh optimizer run; full checkpoint resume takes precedence."""
|
||||
|
||||
name: str | None = None
|
||||
"""LoRA adapter name. If None, auto-generated from rank and alpha."""
|
||||
|
||||
@@ -493,6 +497,9 @@ class OrchestratorConfig(BaseConfig):
|
||||
|
||||
prime_monitor: PrimeMonitorConfig | None = None
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, orchestrator metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
|
||||
collect_inference_metrics: bool = True
|
||||
"""Collect inference-server metrics (requires wandb)."""
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ from prime_rl.configs.orchestrator import (
|
||||
)
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
SlurmConfig,
|
||||
VLMConfig,
|
||||
)
|
||||
@@ -242,6 +243,9 @@ class RLConfig(BaseConfig):
|
||||
wandb: SharedWandbConfig | None = None
|
||||
"""Shared W&B config. If None, falls back to the sub-config W&B settings."""
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Shared local JSONL metric sink. If set, enables ``<output_dir>/metrics.jsonl`` on both trainer and orchestrator. If None, falls back to the sub-config settings."""
|
||||
|
||||
model: SharedModelConfig | None = None
|
||||
"""Shared model config. If None, falls back to the sub-config model settings."""
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ from renderers.base import MODEL_RENDERER_MAP
|
||||
|
||||
from prime_rl.configs.shared import (
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
HeartbeatConfig,
|
||||
SlurmConfig,
|
||||
TrainerLogConfig,
|
||||
@@ -191,6 +192,9 @@ class SFTConfig(BaseConfig):
|
||||
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
|
||||
@@ -318,8 +322,6 @@ class SFTConfig(BaseConfig):
|
||||
raise ValueError(
|
||||
"VLM models must use optimization_dtype='bfloat16' and reduce_dtype='bfloat16' to match vLLM inference."
|
||||
)
|
||||
if self.model.cp > 1 and self.model.cp_style != "ulysses":
|
||||
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
|
||||
if self.data.micro_batch_size != 1:
|
||||
raise ValueError("VLM SFT requires data.micro_batch_size = 1.")
|
||||
if self.val is not None and self.val.data.micro_batch_size != 1:
|
||||
|
||||
@@ -221,6 +221,18 @@ class WandbWithExtrasConfig(WandbConfig):
|
||||
"""Extras logging configuration. If None, no extras are logged."""
|
||||
|
||||
|
||||
class FileMonitorConfig(BaseConfig):
|
||||
"""Enable the local JSONL metric sink (``<output_dir>/metrics.jsonl``).
|
||||
|
||||
Present (non-None) enables it, mirroring the ``prime_monitor`` pattern. Metrics
|
||||
are the same scalars sent to W&B; useful for self-hosted dashboards or when W&B
|
||||
is disabled.
|
||||
"""
|
||||
|
||||
filename: str = "metrics.jsonl"
|
||||
"""Name of the JSONL file written under the component's ``output_dir``."""
|
||||
|
||||
|
||||
class PrimeMonitorConfig(BaseConfig):
|
||||
base_url: str = "https://api.primeintellect.ai/api/v1/rft"
|
||||
"""Base URL for the Prime Intellect monitoring API."""
|
||||
|
||||
@@ -7,6 +7,7 @@ from pydantic import Field, model_validator
|
||||
from prime_rl.configs.shared import (
|
||||
BaseModelConfig,
|
||||
EnvVars,
|
||||
FileMonitorConfig,
|
||||
FileSystemTransportConfig,
|
||||
HeartbeatConfig,
|
||||
MetricsServerConfig,
|
||||
@@ -72,6 +73,9 @@ class IndexCacheConfig(BaseConfig):
|
||||
|
||||
|
||||
class LoRAConfig(BaseConfig):
|
||||
init_path: Path | None = None
|
||||
"""Initialize adapter weights from a PEFT directory when not resuming a full checkpoint."""
|
||||
|
||||
rank: int = Field(16, ge=1)
|
||||
"""Rank of the low-rank decomposition matrices."""
|
||||
|
||||
@@ -241,6 +245,12 @@ class ModelConfig(BaseModelConfig):
|
||||
raise ValueError("VLM training requires model.impl='custom'")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def vlm_cp_requires_ulysses(self):
|
||||
if self.vlm is not None and self.cp > 1 and self.cp_style != "ulysses":
|
||||
raise ValueError("VLM models require cp_style='ulysses' for context parallelism")
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_cp(self):
|
||||
if self.cp > 1 and self.attn not in ["flash_attention_2", "flash_attention_3", "flash_attention_4", "auto"]:
|
||||
@@ -582,6 +592,9 @@ class TrainerConfig(BaseConfig):
|
||||
|
||||
wandb: WandbConfig | None = None
|
||||
|
||||
file_monitor: FileMonitorConfig | None = None
|
||||
"""Local JSONL metric sink. If set, trainer metrics are appended to ``<output_dir>/metrics.jsonl``."""
|
||||
|
||||
output_dir: Path = Path("outputs")
|
||||
"""Directory to write outputs to — checkpoints, weights, rollouts, and logs are written as subdirectories. Should be a persistent directory with enough disk space and unique per experiment running on a single node."""
|
||||
|
||||
|
||||
@@ -106,6 +106,9 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
propagate("wandb.tags", "trainer.wandb.tags", "orchestrator.wandb.tags")
|
||||
propagate("wandb.offline", "trainer.wandb.offline", "orchestrator.wandb.offline")
|
||||
|
||||
# [file_monitor] leaf. (Bare empty ``[file_monitor]`` block enablement is at the end.)
|
||||
propagate("file_monitor.filename", "trainer.file_monitor.filename", "orchestrator.file_monitor.filename")
|
||||
|
||||
# [tokenizer]. ``chat_template`` also flows to ``inference.model`` (vLLM's
|
||||
# ``--chat-template``); ``name`` and ``trust_remote_code`` can legitimately
|
||||
# differ between sub-configs (auto-derived from model names, which may
|
||||
@@ -172,7 +175,7 @@ def propagate_shared_fields(data: Any) -> Any:
|
||||
# (not ``is not None``) is what makes CLI ``--no-wandb`` / ``--no-ckpt``
|
||||
# work — those land as the *string* ``"None"`` until ``BaseConfig``'s
|
||||
# parent-class validator converts it, which happens after this one.
|
||||
for key in ("ckpt", "wandb"):
|
||||
for key in ("ckpt", "wandb", "file_monitor"):
|
||||
if isinstance(get(key), dict):
|
||||
fill(f"trainer.{key}", {})
|
||||
fill(f"orchestrator.{key}", {})
|
||||
|
||||
@@ -387,6 +387,7 @@ class RolloutDispatcher:
|
||||
kind=kind,
|
||||
env_name=env_name,
|
||||
task_idx=example["task_idx"],
|
||||
task=example.get("task"),
|
||||
rollouts_to_schedule=group_size,
|
||||
target_rollouts=group_size,
|
||||
eval_step=eval_step,
|
||||
@@ -438,6 +439,7 @@ class RolloutDispatcher:
|
||||
cache_salt = None
|
||||
|
||||
if env.requires_group_scoring:
|
||||
# Legacy-only route (a v1 env never group-scores) — addressed by row.
|
||||
permits = group.rollouts_to_schedule
|
||||
group.rollouts_to_schedule = 0
|
||||
await self.acquire(permits)
|
||||
@@ -451,15 +453,20 @@ class RolloutDispatcher:
|
||||
)
|
||||
)
|
||||
else:
|
||||
# A v1 env takes the task itself; the legacy bridge its dataset row.
|
||||
if group.task is not None:
|
||||
addressing = {"task_data": group.task.data.model_dump(mode="json")}
|
||||
else:
|
||||
addressing = {"task_idx": group.task_idx}
|
||||
permits = 1
|
||||
group.rollouts_to_schedule -= 1
|
||||
await self.acquire(permits)
|
||||
task = asyncio.create_task(
|
||||
env.run(
|
||||
client=client,
|
||||
task_idx=group.task_idx,
|
||||
model_name=model_name,
|
||||
cache_salt=cache_salt,
|
||||
**addressing,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -2,15 +2,19 @@
|
||||
|
||||
Each ``Env`` owns a v1 ``EnvServer`` (spawned as a child process, or an
|
||||
external one given by ``config.address``) and an ``EnvClient`` to drive it. The
|
||||
orchestrator never *runs* an environment: it asks the server for ``info``
|
||||
(``num_tasks`` + whether group scoring is needed), then runs rollouts purely by
|
||||
**task index**. The server answers one ``Episode`` per env-rollout, whose traces
|
||||
we validate into ``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose
|
||||
dicts) whose task keeps the env's task-specific
|
||||
fields as extras (``WireTaskData`` allows them). The orchestrator never imports the
|
||||
env package: the env's *type* and *runtime* both live only in the server, and the orchestrator
|
||||
drives it purely by task index. (Nothing here reads typed env task fields — only ``task.idx``
|
||||
and a full ``task.model_dump``, both of which ``WireTaskData`` preserves.)
|
||||
orchestrator never *runs* an environment — the agents and their runtimes live only
|
||||
in the server — but it does own the *taskset*: a v1 env's tasks are loaded here,
|
||||
once, and each dispatched env-rollout ships its task's data on the request
|
||||
(``task_data``); the server pydantic-validates it into the taskset's declared
|
||||
``TaskData`` type and runs it. That keeps the server (and every worker in its
|
||||
pool) stateless about data — no per-worker dataset loads, no idx-addressed task
|
||||
cache — and gives the orchestrator real tasks to cycle, shuffle, and filter. Only
|
||||
the legacy (v0) bridge, whose dataset genuinely lives server-side, is still driven
|
||||
by ``task_idx`` (its count comes from ``info``).
|
||||
|
||||
The server answers one ``Episode`` per env-rollout, whose traces we validate into
|
||||
``Trace[WireTaskData]`` — real ``vf.Trace``\\ s (never loose dicts) whose task
|
||||
keeps the env's task-specific fields as extras (``WireTaskData`` allows them).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +26,7 @@ import os
|
||||
import queue
|
||||
import sys
|
||||
from collections.abc import Iterator, Sequence
|
||||
from itertools import islice
|
||||
from multiprocessing.process import BaseProcess
|
||||
from pathlib import Path
|
||||
from typing import Generic, TypeVar
|
||||
@@ -40,9 +45,8 @@ from prime_rl.utils.logger import get_logger
|
||||
# task.idx + task.model_dump).
|
||||
ROLLOUT_TYPE = Rollout[vf.WireTaskData]
|
||||
|
||||
# Max wait for a spawned env server to bind and report its address. The child
|
||||
# loads the taskset (possibly downloading a dataset) before reporting, so this
|
||||
# is generous.
|
||||
# Max wait for a spawned env server to bind and report its address. A legacy
|
||||
# child loads its dataset before reporting, so this is generous.
|
||||
ENV_SERVER_SPAWN_TIMEOUT = 600.0
|
||||
|
||||
|
||||
@@ -78,14 +82,20 @@ def _run_env_server(
|
||||
|
||||
|
||||
class Env:
|
||||
"""Wraps a v1 env server + client. The orchestrator never loads the env."""
|
||||
"""Wraps a v1 env server + client. The orchestrator owns the taskset (loaded once,
|
||||
client-side); the server owns agent/harness execution."""
|
||||
|
||||
def __init__(self, config: EnvConfig):
|
||||
self.config = config
|
||||
self.sampling_args: dict = {}
|
||||
self.num_tasks: int | None = 0
|
||||
"""Task count reported by the server; ``None`` means the taskset is infinite."""
|
||||
"""Task count; ``None`` means the taskset is infinite."""
|
||||
self.requires_group_scoring: bool = False
|
||||
self.tasks: Iterator[vf.Task] | None = None
|
||||
"""The env's tasks, client-side; ``None`` for legacy (its dataset lives on the
|
||||
server). A finite taskset is materialized at ``start()`` (``num_tasks`` is its
|
||||
count) and iterated from there; an infinite one streams off its generator.
|
||||
Consumed once — by ``TrainSource`` (train) or ``EvalEnv.start`` (eval)."""
|
||||
self._env_client: EnvClient | None = None
|
||||
self._env_server_process: BaseProcess | None = None
|
||||
|
||||
@@ -100,25 +110,36 @@ class Env:
|
||||
return self._env_client
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
"""Spawn the env server (if needed), connect, and cache its ``info``."""
|
||||
"""Spawn the env server (if needed), connect, and load the taskset client-side
|
||||
(legacy instead asks the server for ``info`` — its dataset is server-side)."""
|
||||
external = self.config.address is not None
|
||||
address = self.config.address or await self._spawn(log_dir, log_level or "INFO", json_logging)
|
||||
get_logger().debug(f"Connecting {self.name} to env server {address}")
|
||||
self._env_client = EnvClient(address=address)
|
||||
# A spawned server already reported its address *after* binding + loading,
|
||||
# so it's up — the untimed ``info`` below is enough. An external server has
|
||||
# no such handshake, so poll until it answers before we block on ``info``.
|
||||
# A spawned server already reported its address *after* binding, so it's up. An
|
||||
# external server has no such handshake, so poll until it answers.
|
||||
if external:
|
||||
await self.env_client.wait_for_server_startup()
|
||||
info = await self.env_client.info()
|
||||
self.num_tasks = info.num_tasks
|
||||
self.requires_group_scoring = info.requires_group_scoring
|
||||
if self.config.is_legacy:
|
||||
info = await self.env_client.info()
|
||||
self.num_tasks = info.num_tasks
|
||||
self.requires_group_scoring = info.requires_group_scoring
|
||||
else:
|
||||
taskset = vf.load_taskset(self.config.env.taskset)
|
||||
if type(taskset).INFINITE:
|
||||
self.tasks = iter(taskset.load())
|
||||
self.num_tasks = None
|
||||
else:
|
||||
# Materialize off the event loop — load() may pull a dataset.
|
||||
materialized = await asyncio.to_thread(lambda: list(taskset.load()))
|
||||
self.tasks = iter(materialized)
|
||||
self.num_tasks = len(materialized)
|
||||
num_tasks = self.num_tasks if self.num_tasks is not None else "infinite"
|
||||
get_logger().info(f"Env {self.name} ready: num_tasks={num_tasks} group_scoring={self.requires_group_scoring}")
|
||||
|
||||
async def _spawn(self, log_dir: Path, log_level: str, json_logging: bool) -> str:
|
||||
"""Spawn a v1 EnvServer child process (it loads the env; we never do).
|
||||
The server binds an OS-assigned port (``:0``) and reports the concrete
|
||||
"""Spawn a v1 EnvServer child process (it runs the agents; the tasks come from
|
||||
us). The server binds an OS-assigned port (``:0``) and reports the concrete
|
||||
address back over a queue — no free-port guess, no TOCTOU race. Its output
|
||||
goes to ``<log_dir>/<name>.log`` (``log_dir`` is already the train/eval-split
|
||||
``.../logs/envs/{train,eval}`` the orchestrator passes in)."""
|
||||
@@ -170,12 +191,20 @@ class Env:
|
||||
return vf.SamplingConfig(**sampling)
|
||||
|
||||
async def run(
|
||||
self, client: vf.ClientConfig, task_idx: int, model_name: str, cache_salt: str | None
|
||||
self,
|
||||
client: vf.ClientConfig,
|
||||
model_name: str,
|
||||
cache_salt: str | None,
|
||||
task_data: dict | None = None,
|
||||
task_idx: int | None = None,
|
||||
) -> list[Rollout]:
|
||||
"""Run one episode for ``task_idx``; return its typed Traces. A zero-trace
|
||||
episode raises (the dispatcher synthesizes the error marker); a not-``ok``
|
||||
episode marks its clean traces failed so partial episodes never train."""
|
||||
"""Run one episode; return its typed Traces. A v1 env takes the task itself
|
||||
(``task_data``); the legacy bridge is addressed by dataset row (``task_idx``).
|
||||
A zero-trace episode raises (the dispatcher synthesizes the error marker); a
|
||||
not-``ok`` episode marks its clean traces failed so partial episodes never
|
||||
train."""
|
||||
episode = await self.env_client.run(
|
||||
task_data=task_data,
|
||||
task_idx=task_idx,
|
||||
client=client,
|
||||
model=model_name,
|
||||
@@ -236,13 +265,16 @@ class EvalEnv(Env):
|
||||
|
||||
async def start(self, log_dir: Path, log_level: str | None = None, json_logging: bool = False) -> None:
|
||||
await super().start(log_dir=log_dir, log_level=log_level, json_logging=json_logging)
|
||||
if self.num_tasks is None:
|
||||
if self.config.num_examples < 0:
|
||||
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
|
||||
n = self.config.num_examples
|
||||
else:
|
||||
n = self.num_tasks if self.config.num_examples < 0 else min(self.config.num_examples, self.num_tasks)
|
||||
self.examples = [{"task_idx": i} for i in range(n)]
|
||||
n = self.config.num_examples
|
||||
if self.tasks is None: # legacy: the dataset lives on the server — address it by row
|
||||
count = self.num_tasks if n < 0 else min(n, self.num_tasks)
|
||||
self.examples = [{"task_idx": i} for i in range(count)]
|
||||
return
|
||||
if self.num_tasks is None and n < 0:
|
||||
raise ValueError(f"Eval env {self.name} has an infinite taskset — set num_examples to bound it")
|
||||
# A fixed eval set, pulled off the tasks once and reused every epoch.
|
||||
tasks = list(self.tasks) if n < 0 else list(islice(self.tasks, n))
|
||||
self.examples = [{"task_idx": task.data.idx, "task": task} for task in tasks]
|
||||
|
||||
|
||||
EnvT = TypeVar("EnvT", bound=Env)
|
||||
|
||||
@@ -176,6 +176,8 @@ class Orchestrator:
|
||||
self.eval_triggered_at = {}
|
||||
self.consecutive_empty_batches = 0
|
||||
self.gate_closed_at = None
|
||||
# Pulsed by the version hooks so a held ship can re-check ``policy.version``
|
||||
self.version_advanced = asyncio.Event()
|
||||
self.wait_for_policy_time = 0.0
|
||||
self.component_tasks = []
|
||||
|
||||
@@ -231,6 +233,7 @@ class Orchestrator:
|
||||
self.monitor = setup_monitor(
|
||||
wandb_config=config.wandb,
|
||||
prime_config=config.prime_monitor,
|
||||
file_config=config.file_monitor,
|
||||
output_dir=config.output_dir,
|
||||
tokenizer=self.tokenizer,
|
||||
run_config=config,
|
||||
@@ -377,6 +380,15 @@ class Orchestrator:
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = sync_version
|
||||
|
||||
elif config.model.lora is not None and config.model.lora.init_path is not None:
|
||||
await self.policy_inference.update_weights(
|
||||
config.model.lora.init_path, lora_name=self.lora_name, step=0
|
||||
)
|
||||
self.policy_inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
self.policy.version = 0
|
||||
get_logger().info(f"Initialized policy v0 from adapter {config.model.lora.init_path}")
|
||||
|
||||
self.train_source = TrainSource(self.train_envs, seed=42)
|
||||
self.eval_source: EvalSource | None = (
|
||||
EvalSource(
|
||||
@@ -601,6 +613,35 @@ class Orchestrator:
|
||||
f"({n_trainable / len(batch.rollouts):.1%}) — consider reviewing task difficulty / filter config"
|
||||
)
|
||||
|
||||
# Ship batch ``step`` only once the trainer has published v{step-1-TARGET_LAG}.
|
||||
# Without this, fast envs fill batches from buffered rollouts, the
|
||||
# orchestrator finishes early, and its teardown strands the trainer inside
|
||||
# an in-memory broadcast handshake that needs the live weight watcher.
|
||||
# Always satisfiable: the trainer skips only the final TARGET_LAG+1
|
||||
# in-memory broadcasts. Bench runs have no trainer, so they ship freely.
|
||||
required_version = step - 1 - TARGET_LAG
|
||||
if not config.bench and self.policy.version < required_version:
|
||||
get_logger().info(
|
||||
f"Holding batch {step} until the trainer publishes policy v{required_version} "
|
||||
f"(currently v{self.policy.version})"
|
||||
)
|
||||
hold_start = time.perf_counter()
|
||||
while True:
|
||||
self.version_advanced.clear()
|
||||
if self.policy.version >= required_version:
|
||||
break
|
||||
await self.version_advanced.wait()
|
||||
self.wait_for_policy_time += time.perf_counter() - hold_start
|
||||
|
||||
# Stamp each rollout's true staleness: batch ``step`` trains on policy
|
||||
# v{step-1}, so a rollout generated from v{k} is (step-1)-k versions
|
||||
# off-policy — queue time included, unlike the dispatcher's in-flight
|
||||
# counter, which only sees weight updates during generation. Frozen-
|
||||
# sourced rollouts stay 0 (their sampler doesn't follow the policy).
|
||||
for r in batch.rollouts:
|
||||
if self.train_envs.get(r.env_name).sampler.samples_from_live_policy:
|
||||
r.off_policy_steps = (step - 1) - r.policy_version
|
||||
|
||||
# The effective (clean, trained-on) subset lands in the per-step ``effective`` trace file
|
||||
# at ship time; the full arrival window already streamed into ``all`` on arrival.
|
||||
# to_record drops the per-node training tensors — they're for training, not the rollout
|
||||
@@ -904,11 +945,14 @@ class Orchestrator:
|
||||
gate.set()
|
||||
|
||||
async def on_version_pending(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook, fired at publish confirmation (pre-apply):
|
||||
``policy.version`` already carries the new version, so wake a held ship."""
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_READY)
|
||||
self.version_advanced.set()
|
||||
|
||||
async def on_new_version(self, step: int) -> None:
|
||||
"""``VersionObserver`` hook: the watcher just advanced ``policy.version``;
|
||||
"""``VersionObserver`` hook: the weight update completed;
|
||||
re-evaluate the dispatch gate (may resume if the trainer caught up)."""
|
||||
if self.model_express is not None:
|
||||
await asyncio.to_thread(self.model_express.set_status, p2p_pb2.SOURCE_STATUS_INITIALIZING)
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
"""TrainSource: weighted round-robin across train envs, infinite pull.
|
||||
|
||||
Weights are each env's configured ``ratio`` (default 1, i.e. equal weight
|
||||
per env). A finite env serves a shuffled task-index table, reshuffled on
|
||||
cursor exhaustion; an infinite env (``num_tasks is None``) streams a
|
||||
monotonic ``task_idx`` — the server generates tasks on demand, so every
|
||||
pull is a fresh task and there are no epochs to shuffle."""
|
||||
per env). A v1 env serves the tasks the orchestrator loaded client-side: a
|
||||
finite one as a shuffled table (reshuffled on cursor exhaustion), an
|
||||
infinite one (``num_tasks is None``) straight off its generator — every
|
||||
pull is a fresh task and there are no epochs to shuffle. A legacy env's
|
||||
dataset lives on its server, so it serves shuffled task *indices*."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from collections.abc import Iterator
|
||||
|
||||
import verifiers.v1 as vf
|
||||
|
||||
from prime_rl.orchestrator.envs import TrainEnvs
|
||||
|
||||
@@ -17,7 +21,8 @@ class TrainSource:
|
||||
"""``next_example(available_permits)`` picks a weighted-RR env and
|
||||
returns its next example (or ``None`` when the env's per-call permit
|
||||
cost doesn't fit — the dispatch loop retries when permits free up).
|
||||
Returned dicts carry ``env_name`` + ``task_idx``."""
|
||||
Returned dicts carry ``env_name`` + ``task_idx`` (+ ``task`` for v1 envs,
|
||||
whose data is shipped to the env server at dispatch)."""
|
||||
|
||||
def __init__(self, train_envs: TrainEnvs, *, seed: int | None) -> None:
|
||||
self.rng = random.Random(seed)
|
||||
@@ -25,22 +30,26 @@ class TrainSource:
|
||||
if not self.envs:
|
||||
raise ValueError("TrainSource needs at least one train env")
|
||||
|
||||
# A finite env's shuffled index table; ``None`` for an infinite env,
|
||||
# whose cursor alone is the (monotonic) task_idx stream.
|
||||
# A finite env's shuffled example table; ``None`` for an infinite env,
|
||||
# whose generator (``self.iters``) is pulled per example.
|
||||
self.examples: dict[str, list[dict] | None] = {}
|
||||
self.iters: dict[str, Iterator[vf.Task]] = {}
|
||||
self.cursors: dict[str, int] = {}
|
||||
# Group-scoring envs reserve ``group_size`` permits up front;
|
||||
# per-rollout envs need 1
|
||||
self.env_costs: dict[str, int] = {}
|
||||
for env in self.envs:
|
||||
# The orchestrator never loads the env: sample over the task-index
|
||||
# range the server reported via info() (num_tasks; None = infinite).
|
||||
if env.num_tasks is None:
|
||||
self.examples[env.name] = None
|
||||
else:
|
||||
if env.tasks is None: # legacy: sample over the index range from info()
|
||||
rows: list[dict] = [{"task_idx": i, "env_name": env.name} for i in range(env.num_tasks)]
|
||||
self.rng.shuffle(rows)
|
||||
self.examples[env.name] = rows
|
||||
elif env.num_tasks is None: # infinite: pull the generator per example
|
||||
self.examples[env.name] = None
|
||||
self.iters[env.name] = env.tasks
|
||||
else:
|
||||
rows = [{"task_idx": task.data.idx, "task": task, "env_name": env.name} for task in env.tasks]
|
||||
self.rng.shuffle(rows)
|
||||
self.examples[env.name] = rows
|
||||
self.cursors[env.name] = 0
|
||||
self.env_costs[env.name] = env.config.group_size if env.requires_group_scoring else 1
|
||||
|
||||
@@ -53,9 +62,9 @@ class TrainSource:
|
||||
return None
|
||||
rows = self.examples[env_name]
|
||||
cursor = self.cursors[env_name]
|
||||
if rows is None: # infinite env: the cursor is the task_idx
|
||||
self.cursors[env_name] = cursor + 1
|
||||
return {"task_idx": cursor, "env_name": env_name}
|
||||
if rows is None: # infinite env: pull the next generated task
|
||||
task = next(self.iters[env_name])
|
||||
return {"task_idx": task.data.idx, "task": task, "env_name": env_name}
|
||||
if cursor >= len(rows):
|
||||
self.rng.shuffle(rows)
|
||||
cursor = 0
|
||||
|
||||
@@ -63,6 +63,9 @@ class GroupState:
|
||||
task_idx: int
|
||||
rollouts_to_schedule: int
|
||||
target_rollouts: int
|
||||
task: vf.Task | None = None
|
||||
"""The group's task (v1 envs — its data is shipped on every dispatch). ``None`` for
|
||||
legacy envs, which are addressed by ``task_idx`` alone."""
|
||||
emitted: int = 0
|
||||
eval_step: int | None = None
|
||||
pinned_client: vf.ClientConfig | None = None
|
||||
|
||||
@@ -64,6 +64,12 @@ class WeightWatcher:
|
||||
|
||||
async def stop(self) -> None:
|
||||
self.stopped.set()
|
||||
# Let an in-flight apply finish before dying: the trainer blocks inside
|
||||
# its in-memory broadcast until the apply completes, so cancelling
|
||||
# mid-apply would strand it. The orchestrator's global teardown budget
|
||||
# bounds this wait.
|
||||
async with self.update_lock:
|
||||
pass
|
||||
if self.task is not None:
|
||||
await safe_cancel(self.task)
|
||||
self.task = None
|
||||
@@ -103,6 +109,13 @@ class WeightWatcher:
|
||||
await wait_for_path(stable_marker)
|
||||
self.last_wait_for_ckpt_time = time.perf_counter() - t0
|
||||
|
||||
# Publish confirmed: the policy version advances here, before the
|
||||
# apply — inference pauses during the update, so nothing can generate
|
||||
# under the new number from the old weights, and a ship held on this
|
||||
# version releases without waiting out the inference weight reload.
|
||||
self.ckpt_step = next_step
|
||||
self.policy.version = next_step
|
||||
|
||||
# Drain off-policy rollouts BEFORE pausing the inference engines.
|
||||
# Aborting a rollout triggers vLLM's KV-connector cleanup (NIXL's
|
||||
# ``_reqs_not_processed``), which is only propagated to the workers
|
||||
@@ -128,8 +141,6 @@ class WeightWatcher:
|
||||
self.update_count += 1
|
||||
get_logger().debug(f"Updated weights to step {next_step} in {format_time(self.last_update_weights_time)}")
|
||||
|
||||
self.ckpt_step = next_step
|
||||
self.policy.version = next_step
|
||||
if self.lora_name is not None:
|
||||
self.inference.update_model_name(self.lora_name)
|
||||
self.policy.model_name = self.lora_name
|
||||
|
||||
@@ -94,11 +94,25 @@ def _truncate_mm(
|
||||
return cut, sliced
|
||||
|
||||
|
||||
def multimodal_sample_error(sample: TrainingSample) -> str | None:
|
||||
mm_token_type_ids = sample.mm_token_type_ids
|
||||
if mm_token_type_ids is not None and len(mm_token_type_ids) != len(sample.token_ids):
|
||||
return (
|
||||
"mm_token_type_ids length must match token_ids length "
|
||||
f"({len(mm_token_type_ids)} != {len(sample.token_ids)})"
|
||||
)
|
||||
if sample.mm_kwargs is not None and "image_grid_thw" in sample.mm_kwargs and mm_token_type_ids is None:
|
||||
return "image_grid_thw multimodal samples require mm_token_type_ids"
|
||||
return None
|
||||
|
||||
|
||||
def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch:
|
||||
"""
|
||||
Prepare a problem for sequence packing training.
|
||||
Tokenize and prepare tensors.
|
||||
"""
|
||||
if error := multimodal_sample_error(training_example):
|
||||
raise ValueError(error)
|
||||
input_ids = training_example.token_ids
|
||||
loss_mask = training_example.mask
|
||||
inference_logprobs = training_example.logprobs
|
||||
@@ -186,10 +200,6 @@ def prepare_sample(training_example: TrainingSample, seq_len: int) -> MicroBatch
|
||||
)
|
||||
assert len(routed_experts.data) == len(input_ids) * _routed_experts_row_size(routed_experts)
|
||||
|
||||
if mm_token_type_ids is not None:
|
||||
assert len(mm_token_type_ids) == len(input_ids), (
|
||||
f"mm_token_type_ids: {len(mm_token_type_ids)}, input_ids: {len(input_ids)}"
|
||||
)
|
||||
assert len(env_names) == len(input_ids), f"env_names: {len(env_names)}, input_ids: {len(input_ids)}"
|
||||
|
||||
return MicroBatch(
|
||||
@@ -230,17 +240,45 @@ class _MicroBatchBin:
|
||||
def first_sample(self) -> MicroBatch:
|
||||
return self.samples[0][1]
|
||||
|
||||
def can_add(self, sample: MicroBatch, max_seq_len: int) -> bool:
|
||||
@property
|
||||
def first_lora_idx(self) -> int:
|
||||
return self.samples[0][0]
|
||||
|
||||
@property
|
||||
def first_multimodal_sample(self) -> MicroBatch | None:
|
||||
for _, sample in self.samples:
|
||||
if _is_multimodal_sample(sample):
|
||||
return sample
|
||||
return None
|
||||
|
||||
def can_add(self, sample: MicroBatch, max_seq_len: int, lora_idx: int) -> bool:
|
||||
# Loss routing is per token (component weight streams), so samples of
|
||||
# different loss types pack together freely — only modality, length and
|
||||
# routed-experts presence constrain packing.
|
||||
# different loss types pack together freely. Multimodal packing is still
|
||||
# constrained by modality sidecars, length, routed experts, and LoRA/run.
|
||||
first_sample = self.first_sample
|
||||
return (
|
||||
not _is_multimodal_sample(first_sample)
|
||||
and not _is_multimodal_sample(sample)
|
||||
and self.length + len(sample.input_ids) <= max_seq_len
|
||||
and (first_sample.routed_experts is None) == (sample.routed_experts is None)
|
||||
)
|
||||
if self.length + len(sample.input_ids) > max_seq_len:
|
||||
return False
|
||||
if (first_sample.routed_experts is None) != (sample.routed_experts is None):
|
||||
return False
|
||||
|
||||
sample_is_mm = _is_multimodal_sample(sample)
|
||||
existing_mm_sample = self.first_multimodal_sample
|
||||
if existing_mm_sample is None and not sample_is_mm:
|
||||
return True
|
||||
if self.first_lora_idx != lora_idx:
|
||||
return False
|
||||
if existing_mm_sample is not None and sample_is_mm:
|
||||
dst = existing_mm_sample.mm_kwargs
|
||||
src = sample.mm_kwargs
|
||||
assert dst is not None and src is not None, "multimodal samples must carry mm_kwargs"
|
||||
return set(dst) == set(src) and all(
|
||||
dst[key].dtype == src[key].dtype
|
||||
and len(dst[key].shape) > 0
|
||||
and len(dst[key].shape) == len(src[key].shape)
|
||||
and dst[key].shape[1:] == src[key].shape[1:]
|
||||
for key in dst
|
||||
)
|
||||
return True
|
||||
|
||||
def add(self, lora_idx: int, sample: MicroBatch) -> None:
|
||||
self.samples.append((lora_idx, sample))
|
||||
@@ -285,6 +323,7 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
||||
env_names: list[str] = []
|
||||
ref_logprobs: list[float] | None = [] if has_ref_logprobs else None
|
||||
mm_token_type_ids: list[int] | None = [] if has_mm_token_type_ids else None
|
||||
mm_kwargs: dict[str, EncodedTensor] | None = None
|
||||
streams: dict[str, list[float] | None] = {name: ([] if has_stream[name] else None) for name in STREAM_FILL}
|
||||
seq_lens: list[int] = []
|
||||
routed_experts: RoutedExperts | None = None
|
||||
@@ -318,13 +357,19 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
||||
assert routed_experts.shape[1:] == sample.routed_experts.shape[1:]
|
||||
routed_experts.data += sample.routed_experts.data
|
||||
routed_experts.shape[0] += sample.routed_experts.shape[0]
|
||||
if sample.mm_kwargs is not None:
|
||||
if mm_kwargs is None:
|
||||
mm_kwargs = copy.deepcopy(sample.mm_kwargs)
|
||||
else:
|
||||
for key in mm_kwargs:
|
||||
mm_kwargs[key].data += sample.mm_kwargs[key].data
|
||||
mm_kwargs[key].shape[0] += sample.mm_kwargs[key].shape[0]
|
||||
seq_lens.extend(sample.seq_lens)
|
||||
lora_num_tokens[lora_idx] += sample_len
|
||||
|
||||
sequence_lengths = [len(sample.input_ids) for _, sample in bin_content.samples]
|
||||
assert sum(sequence_lengths) == len(input_ids), (sequence_lengths, len(input_ids))
|
||||
assert sum(seq_lens) == len(input_ids), (seq_lens, len(input_ids))
|
||||
first_sample = bin_content.first_sample
|
||||
|
||||
return MicroBatch(
|
||||
input_ids=input_ids,
|
||||
@@ -339,7 +384,7 @@ def _materialize_bin(bin_content: _MicroBatchBin, num_loras: int) -> MicroBatch:
|
||||
routed_experts=routed_experts,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
env_names=env_names,
|
||||
mm_kwargs=first_sample.mm_kwargs if _is_multimodal_sample(first_sample) else None,
|
||||
mm_kwargs=mm_kwargs,
|
||||
rl_weights=streams["rl_weights"],
|
||||
ce_weights=streams["ce_weights"],
|
||||
ref_kl_weights=streams["ref_kl_weights"],
|
||||
@@ -354,7 +399,7 @@ def _expand_bins_by_splitting(
|
||||
candidates = [
|
||||
(bin_content.workload(bin_cost), idx)
|
||||
for idx, bin_content in enumerate(bins)
|
||||
if len(bin_content.samples) > 1
|
||||
if len(bin_content.samples) > 1 and bin_content.first_multimodal_sample is None
|
||||
]
|
||||
if not candidates:
|
||||
break
|
||||
@@ -376,8 +421,9 @@ def packed_samples_into_micro_bs(
|
||||
We follow the First Fit Decreasing algorithm to pack the samples into bins and minimize potential padding while never truncating.
|
||||
With per-token temperatures, samples can be packed together regardless of their temperature values.
|
||||
|
||||
NOTE: Multimodal samples (with mm_kwargs) are NOT packed together as they have variable-sized
|
||||
vision data that doesn't pack well. Each multimodal sample becomes its own micro batch.
|
||||
Multimodal samples pack with text spans from the same run/LoRA and with
|
||||
compatible eager ``mm_kwargs`` samples. Packed batches preserve sample
|
||||
boundaries in ``seq_lens``.
|
||||
"""
|
||||
# Sort by (lora_idx, -length) for packing efficiency
|
||||
samples.sort(key=lambda x: (x[0], -len(x[1].input_ids)))
|
||||
@@ -385,9 +431,10 @@ def packed_samples_into_micro_bs(
|
||||
bins: list[_MicroBatchBin] = []
|
||||
|
||||
for idx, sample in samples:
|
||||
# Try to find a bin that can fit this sequence (only pack text-only samples)
|
||||
# Try to find a bin that can fit this sequence. Multimodal samples only
|
||||
# pack when their sidecar tensors are compatible.
|
||||
for bin_content in bins:
|
||||
if bin_content.can_add(sample, max_seq_len):
|
||||
if bin_content.can_add(sample, max_seq_len, idx):
|
||||
bin_content.add(idx, sample)
|
||||
break
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Strict attention-only PEFT initialization without optimizer restoration."""
|
||||
|
||||
import json
|
||||
|
||||
import torch
|
||||
from safetensors.torch import load_file
|
||||
from torch.distributed.tensor import DTensor, distribute_tensor
|
||||
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
|
||||
def load_attention_adapter(model, config):
|
||||
adapter = config.lora
|
||||
path = adapter.init_path
|
||||
metadata = json.loads((path / "adapter_config.json").read_text())
|
||||
allowed = {"q_proj", "k_proj", "v_proj", "o_proj"}
|
||||
if set(adapter.target_modules) != allowed or adapter.modules_to_save:
|
||||
raise ValueError("Adapter warm start supports only attention q/k/v/o with no modules_to_save")
|
||||
if (metadata.get("r") != adapter.rank or metadata.get("lora_alpha") != adapter.alpha
|
||||
or metadata.get("lora_dropout", 0.0) != adapter.dropout
|
||||
or set(metadata.get("target_modules", [])) != allowed
|
||||
or metadata.get("modules_to_save") or metadata.get("bias", "none") != "none"
|
||||
or metadata.get("base_model_name_or_path") != config.name):
|
||||
raise ValueError("Warm-start adapter metadata does not match trainer configuration")
|
||||
saved = {k.removeprefix("base_model.model."): v for k, v in
|
||||
load_file(str(path / "adapter_model.safetensors"), device="cpu").items()}
|
||||
targets = {}
|
||||
for name, param in model.named_parameters():
|
||||
if ".lora_A." not in name and ".lora_B." not in name:
|
||||
continue
|
||||
name = name.replace("._orig_mod", "")
|
||||
if not name.endswith(".0"):
|
||||
raise ValueError("Adapter warm start supports one adapter slot only")
|
||||
key = name[:-2] + ".weight"
|
||||
if key in targets:
|
||||
raise ValueError(f"Duplicate adapter destination: {key}")
|
||||
targets[key] = param
|
||||
if set(saved) != set(targets):
|
||||
raise ValueError(f"Adapter key mismatch: missing={set(targets)-set(saved)}, extra={set(saved)-set(targets)}")
|
||||
for key, param in targets.items():
|
||||
if saved[key].shape != param.shape or not torch.isfinite(saved[key]).all():
|
||||
raise ValueError(f"Invalid adapter tensor: {key}")
|
||||
with torch.no_grad():
|
||||
for key, param in targets.items():
|
||||
value = saved[key].to(device=param.device, dtype=param.dtype)
|
||||
if isinstance(param, DTensor):
|
||||
value = distribute_tensor(value, param.device_mesh, param.placements)
|
||||
param.copy_(value)
|
||||
actual = param.to_local() if isinstance(param, DTensor) else param
|
||||
expected = value.to_local() if isinstance(value, DTensor) else value
|
||||
if not torch.equal(actual, expected):
|
||||
raise ValueError(f"Adapter copy verification failed: {key}")
|
||||
get_logger().success(f"Warm-started {len(targets)} adapter tensors from {path}; optimizer state is fresh")
|
||||
@@ -937,7 +937,10 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
snapshot_keys = dict.fromkeys(load_state_dict_keys(source_path))
|
||||
model_keys = dict.fromkeys(model.state_dict().keys())
|
||||
|
||||
if model.is_hf_state_dict(snapshot_keys) and model.is_prime_state_dict(model_keys):
|
||||
snapshot_is_hf = model.is_hf_state_dict(snapshot_keys)
|
||||
snapshot_is_prime = model.is_prime_state_dict(snapshot_keys)
|
||||
|
||||
if snapshot_is_hf and not snapshot_is_prime and model.is_prime_state_dict(model_keys):
|
||||
logger.warning(
|
||||
"Found HF weight format in snapshot state dict and PrimeRL weight format in model state dict. Trying to auto-convert..."
|
||||
)
|
||||
@@ -951,7 +954,7 @@ def load_dcp_from_hf(model: nn.Module, config: ModelConfig, parallel_dims: Paral
|
||||
save_state_dict(snapshot_state_dict, snapshot_path)
|
||||
del snapshot_state_dict
|
||||
|
||||
elif model.is_prime_state_dict(snapshot_keys) and model.is_hf_state_dict(model_keys):
|
||||
elif snapshot_is_prime and not snapshot_is_hf and model.is_hf_state_dict(model_keys):
|
||||
logger.warning(
|
||||
"Found PrimeRL weight format in snapshot state dict and HF weight format in model state dict. Trying to auto-convert..."
|
||||
)
|
||||
|
||||
@@ -15,6 +15,13 @@ def ceil_div(x: int, y: int) -> int:
|
||||
return (x + y - 1) // y
|
||||
|
||||
|
||||
def ue8m0_for_device(device: torch.device | None = None) -> bool:
|
||||
"""DeepGEMM requires UE8M0 (power-of-2) scales on SM100; SM90 supports exact float
|
||||
scales, and UE8M0 there is a pure precision loss (it measurably raises the
|
||||
trainer/inference mismatch KL)."""
|
||||
return torch.cuda.get_device_capability(device)[0] >= 10
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Layout building
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -16,6 +16,7 @@ from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
grouped_per_channel_cast_to_fp8_rowmajor_triton,
|
||||
grouped_per_channel_cast_to_fp8_sm90_kmajor_triton,
|
||||
grouped_per_token_cast_to_fp8_triton,
|
||||
ue8m0_for_device,
|
||||
unpack_rows_triton,
|
||||
)
|
||||
|
||||
@@ -66,7 +67,7 @@ def _compute_grad_weight(
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
True,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
dy_fp8 = grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
@@ -77,7 +78,7 @@ def _compute_grad_weight(
|
||||
actual_ms_tensor,
|
||||
ks_tensor,
|
||||
block_starts_tensor,
|
||||
True,
|
||||
False,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grouped_weight_grad = deep_gemm.k_grouped_fp8_gemm_nt_contiguous
|
||||
@@ -113,6 +114,7 @@ class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
block_starts_tensor,
|
||||
) = build_grouped_layout(offs, total_m=x.size(0))
|
||||
|
||||
use_ue8m0 = ue8m0_for_device(x.device)
|
||||
x_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
x,
|
||||
padded_total_m,
|
||||
@@ -120,12 +122,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
True,
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight.transpose(1, 2),
|
||||
True,
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
|
||||
@@ -197,6 +199,7 @@ class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
)
|
||||
|
||||
if ctx.needs_input_grad[0]:
|
||||
use_ue8m0 = ue8m0_for_device(grad_output.device)
|
||||
dy_fp8 = grouped_per_token_cast_to_fp8_triton(
|
||||
grad_output,
|
||||
padded_total_m,
|
||||
@@ -204,12 +207,12 @@ class _GroupedFP8Gemm(torch.autograd.Function):
|
||||
starts_tensor,
|
||||
actual_ms_tensor,
|
||||
block_starts_tensor,
|
||||
True,
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
weight_dx_fp8 = grouped_per_block_cast_to_fp8_triton(
|
||||
weight,
|
||||
True,
|
||||
use_ue8m0,
|
||||
GROUP_ALIGNMENT,
|
||||
)
|
||||
grad_x_padded = torch.empty(
|
||||
|
||||
@@ -17,6 +17,7 @@ from prime_rl.trainer.models.kernels.fp8_utils import (
|
||||
per_block_cast_to_fp8_triton,
|
||||
per_token_cast_to_fp8_tp_triton,
|
||||
per_token_cast_to_fp8_triton,
|
||||
ue8m0_for_device,
|
||||
)
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
@@ -26,8 +27,9 @@ class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
def forward(ctx, x, weight, block_size, out_dtype=torch.bfloat16):
|
||||
x_shape = x.shape
|
||||
x_2d = x.reshape(-1, x_shape[-1]).contiguous()
|
||||
x_fp8 = per_token_cast_to_fp8_triton(x_2d, True, block_size)
|
||||
weight_fp8 = per_block_cast_to_fp8_triton(weight, True, block_size)
|
||||
use_ue8m0 = ue8m0_for_device(x.device)
|
||||
x_fp8 = per_token_cast_to_fp8_triton(x_2d, use_ue8m0, block_size)
|
||||
weight_fp8 = per_block_cast_to_fp8_triton(weight, use_ue8m0, block_size)
|
||||
|
||||
out = torch.empty((x_2d.size(0), weight.size(0)), device=x.device, dtype=out_dtype)
|
||||
deep_gemm.fp8_gemm_nt(x_fp8, weight_fp8, out)
|
||||
@@ -42,11 +44,12 @@ class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
x_2d, weight = ctx.saved_tensors
|
||||
block_size = ctx.block_size
|
||||
grad_output_2d = grad_output.reshape(-1, grad_output.shape[-1]).contiguous()
|
||||
use_ue8m0 = ue8m0_for_device(grad_output.device)
|
||||
|
||||
grad_x = grad_weight = None
|
||||
if ctx.needs_input_grad[0]:
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, True, block_size)
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, True, block_size)
|
||||
grad_output_fp8 = per_token_cast_to_fp8_triton(grad_output_2d, use_ue8m0, block_size)
|
||||
weight_dx_fp8 = per_block_cast_to_fp8_tp_triton(weight, use_ue8m0, block_size)
|
||||
grad_x_2d = torch.empty_like(x_2d)
|
||||
deep_gemm.fp8_gemm_nt(grad_output_fp8, weight_dx_fp8, grad_x_2d)
|
||||
grad_x = grad_x_2d.reshape(ctx.x_shape)
|
||||
@@ -64,8 +67,8 @@ class _FP8BlockwiseMM(torch.autograd.Function):
|
||||
else:
|
||||
grad_output_2d_padded = grad_output_2d
|
||||
x_2d_padded = x_2d
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, True, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, True, block_size)
|
||||
grad_output_t_fp8 = per_token_cast_to_fp8_tp_triton(grad_output_2d_padded, use_ue8m0, block_size)
|
||||
x_t_fp8 = per_token_cast_to_fp8_tp_triton(x_2d_padded, use_ue8m0, block_size)
|
||||
grad_weight_fp32 = torch.zeros_like(weight, dtype=torch.float32)
|
||||
deep_gemm.fp8_gemm_nt(
|
||||
grad_output_t_fp8,
|
||||
|
||||
@@ -124,8 +124,10 @@ class LlamaPreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
"""Check if the state dict is in PrimeRL training format."""
|
||||
return True
|
||||
# Dense models use identical key names in HF and PrimeRL format, so we
|
||||
# never claim to be in a separate PrimeRL format. This disables the
|
||||
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
|
||||
@@ -107,7 +107,10 @@ class Qwen3PreTrainedModel(PreTrainedModelPrimeRL):
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return True
|
||||
# Dense models use identical key names in HF and PrimeRL format, so we
|
||||
# never claim to be in a separate PrimeRL format. This disables the
|
||||
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
|
||||
@@ -160,7 +160,10 @@ class Qwen3_5PreTrainedModel(PreTrainedModelPrimeRL, HFQwen3_5PreTrainedModel):
|
||||
|
||||
@classmethod
|
||||
def is_prime_state_dict(cls, state_dict: dict[str, Tensor]) -> bool:
|
||||
return True
|
||||
# Dense models use identical key names in HF and PrimeRL format, so we
|
||||
# never claim to be in a separate PrimeRL format. This disables the
|
||||
# auto-conversion path in load_dcp_from_hf and lets DCP load directly.
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def convert_to_hf(cls, state_dict: dict[str, Tensor]) -> dict[str, Tensor]:
|
||||
@@ -371,6 +374,7 @@ class Qwen3_5ForCausalLM(Qwen3_5PreTrainedModel, GenerationMixin):
|
||||
def __init__(self, config, **kwargs):
|
||||
super().__init__(config, **kwargs)
|
||||
self._is_vlm = hasattr(config, "vision_config")
|
||||
self.supports_packed_multimodal_training = self._is_vlm
|
||||
|
||||
if self._is_vlm:
|
||||
self.model = Qwen3_5VLMModel(config)
|
||||
|
||||
@@ -892,6 +892,7 @@ class Qwen3_5MoeForCausalLM(Qwen3_5MoePreTrainedModel, GenerationMixin):
|
||||
def __init__(self, config, **kwargs):
|
||||
super().__init__(config, **kwargs)
|
||||
self._is_vlm = hasattr(config, "vision_config")
|
||||
self.supports_packed_multimodal_training = self._is_vlm
|
||||
|
||||
if self._is_vlm:
|
||||
self.model = Qwen3_5MoeVLMModel(config)
|
||||
|
||||
@@ -92,9 +92,10 @@ def is_view_of(value: torch.Tensor, root: torch.Tensor) -> bool:
|
||||
def plan_tensor_replay(shape: tuple[int, ...], dtype: torch.dtype, ops: OperationChain) -> TensorReplayPlan:
|
||||
"""Resolve a directly transferable source view and local replay suffix.
|
||||
|
||||
The prefix must remain a same-dtype view of the trainer root and can
|
||||
therefore be addressed by RDMA. The first materializing or dtype-changing
|
||||
operation and everything after it is replayed on the receive arena.
|
||||
The prefix must remain a contiguous, same-dtype view of the trainer root
|
||||
and can therefore be transferred in large RDMA runs. The first strided,
|
||||
materializing, or dtype-changing operation and everything after it is
|
||||
replayed on the receive arena.
|
||||
"""
|
||||
root = torch.empty(shape, dtype=dtype, device="meta")
|
||||
prefix_len = 0
|
||||
@@ -105,7 +106,7 @@ def plan_tensor_replay(shape: tuple[int, ...], dtype: torch.dtype, ops: Operatio
|
||||
if candidate_len < len(ops) and ops[candidate_len].name == "tuple_getitem":
|
||||
continue
|
||||
candidate = apply_chain(root, ops[:candidate_len])
|
||||
if candidate.dtype != dtype or not is_view_of(candidate, root):
|
||||
if candidate.dtype != dtype or not is_view_of(candidate, root) or not candidate.is_contiguous():
|
||||
break
|
||||
prefix_len = candidate_len
|
||||
source_view = candidate
|
||||
|
||||
@@ -6,7 +6,7 @@ from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from collections.abc import Callable, Sequence
|
||||
|
||||
from prime_rl.trainer.batch import prepare_batch
|
||||
from prime_rl.trainer.batch import multimodal_sample_error, prepare_batch
|
||||
from prime_rl.trainer.runs import get_multi_run_manager
|
||||
from prime_rl.transport import (
|
||||
MicroBatch,
|
||||
@@ -177,6 +177,8 @@ class MultiPacker(BasePacker):
|
||||
False,
|
||||
f"Run wrote a sample with ref logprobs length != sample length ({len(sample.ref_logprobs)} != {sample_length})",
|
||||
)
|
||||
if error := multimodal_sample_error(sample):
|
||||
return False, error
|
||||
return True, None
|
||||
|
||||
def _get_batch(self) -> None:
|
||||
|
||||
@@ -10,6 +10,7 @@ from torch import Tensor
|
||||
|
||||
from prime_rl.configs.trainer import DefaultLossConfig, TrainerConfig
|
||||
from prime_rl.trainer.rl.loss import compute_importance_ratio_and_mismatch_kl
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
@@ -93,7 +94,12 @@ class TokenExporter:
|
||||
ready_run_ids = ready_run_ids or set()
|
||||
for run_id in [rid for rid in self._pending_stable_dirs if rid is None or rid in ready_run_ids]:
|
||||
for stable_dir in self._pending_stable_dirs.pop(run_id):
|
||||
(stable_dir / "STABLE").touch()
|
||||
try:
|
||||
(stable_dir / "STABLE").touch()
|
||||
except FileNotFoundError:
|
||||
# A multi-run run dir can be deleted while its tail steps are
|
||||
# still flushing (mirrors the broadcast paths' guard)
|
||||
get_logger().warning(f"Run dir for {run_id} is deleted, skipping token-export STABLE marker")
|
||||
|
||||
def _export_dir(self, export_step: int, run_id: str | None) -> Path:
|
||||
if run_id is not None:
|
||||
|
||||
@@ -86,7 +86,9 @@ def train(config: TrainerConfig):
|
||||
|
||||
# Setup the monitor
|
||||
logger.info(f"Initializing monitor ({config.wandb})")
|
||||
monitor = setup_monitor(config.wandb, output_dir=config.output_dir, run_config=config)
|
||||
monitor = setup_monitor(
|
||||
config.wandb, file_config=config.file_monitor, output_dir=config.output_dir, run_config=config
|
||||
)
|
||||
|
||||
# Setup heartbeat (only on rank 0)
|
||||
heart = None
|
||||
@@ -152,6 +154,9 @@ def train(config: TrainerConfig):
|
||||
logger.info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
if config.model.vlm is not None and not getattr(model, "supports_packed_multimodal_training", False):
|
||||
raise ValueError("Packed multimodal training requires model support")
|
||||
|
||||
# Set up the loss function for the RL loss type (ce / ref_kl are fixed)
|
||||
logger.info(f"Setting up loss function ({config.loss})")
|
||||
rl_loss_fn = setup_rl_loss_fn(config.loss)
|
||||
@@ -168,7 +173,14 @@ def train(config: TrainerConfig):
|
||||
cpu_offload=config.model.optim_cpu_offload,
|
||||
)
|
||||
scheduler = setup_scheduler(optimizer, config.scheduler, config.max_steps, config.optim.lr)
|
||||
# Run creation resets adapters; initialize only after that reset has finished.
|
||||
if checkpoint_step is None and config.model.lora is not None and config.model.lora.init_path is not None:
|
||||
from prime_rl.trainer.lora_init import load_attention_adapter
|
||||
|
||||
load_attention_adapter(model, config.model)
|
||||
else:
|
||||
if config.model.lora is not None and config.model.lora.init_path is not None:
|
||||
raise ValueError("Adapter warm start requires max_concurrent_runs=1")
|
||||
optimizer = setup_multi_optimizer(config.optim, parallel_dims)
|
||||
scheduler = setup_multi_scheduler(optimizer, config.scheduler, config.max_steps)
|
||||
|
||||
@@ -366,6 +378,11 @@ def train(config: TrainerConfig):
|
||||
# tensor to CUDA and let the model's forward sort them.
|
||||
mm_kwargs_raw = micro_batch.get("mm_kwargs")
|
||||
mm_kwargs = {k: v.to("cuda") for k, v in mm_kwargs_raw.items()} if mm_kwargs_raw else None
|
||||
if mm_kwargs is not None and config.model.vlm is None:
|
||||
raise ValueError(
|
||||
"Received multimodal samples but [model.vlm] is not set. "
|
||||
"Set [model.vlm] to train on multimodal samples."
|
||||
)
|
||||
mm_token_type_ids = (
|
||||
micro_batch["mm_token_type_ids"].to("cuda")
|
||||
if micro_batch.get("mm_token_type_ids") is not None
|
||||
@@ -376,30 +393,30 @@ def train(config: TrainerConfig):
|
||||
|
||||
labels = shift_tensor_left(input_ids)
|
||||
|
||||
# VLM + CP is not supported: MRoPE requires global positions but CP shards the sequence
|
||||
if cp_enabled and mm_kwargs is not None:
|
||||
raise NotImplementedError("Context parallelism is not supported with VLM/multimodal training")
|
||||
seq_lens_are_pre_shard = False
|
||||
|
||||
if cp_enabled:
|
||||
input_ids, forward_position_ids = setup_cp_params(
|
||||
input_ids,
|
||||
position_ids,
|
||||
cp_rank,
|
||||
cp_size,
|
||||
cp_group,
|
||||
seq_lens=seq_lens,
|
||||
cp_style=config.model.cp_style,
|
||||
)
|
||||
# MRoPE batches must merge image embeddings before sharding.
|
||||
defer_vlm_cp_to_model = mm_kwargs is not None and "image_grid_thw" in mm_kwargs
|
||||
if not defer_vlm_cp_to_model:
|
||||
input_ids, position_ids = setup_cp_params(
|
||||
input_ids,
|
||||
position_ids,
|
||||
cp_rank,
|
||||
cp_size,
|
||||
cp_group,
|
||||
seq_lens=seq_lens,
|
||||
cp_style=config.model.cp_style,
|
||||
)
|
||||
seq_lens_are_pre_shard = True
|
||||
labels = shard_for_cp(labels, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
if routed_experts is not None:
|
||||
if routed_experts is not None and not defer_vlm_cp_to_model:
|
||||
routed_experts = shard_for_cp(routed_experts, cp_rank=cp_rank, cp_world_size=cp_size)
|
||||
else:
|
||||
forward_position_ids = position_ids
|
||||
|
||||
if config.model.lora:
|
||||
lora_num_tokens = micro_batch["lora_num_tokens"].to("cuda")
|
||||
if cp_enabled:
|
||||
chunk_size = input_ids.shape[1]
|
||||
chunk_size = labels.shape[1]
|
||||
# Convert to cumsum, adjust for CP chunk, convert back to num_tokens
|
||||
cu_offsets = lora_num_tokens.cumsum(dim=0, dtype=torch.int32)
|
||||
adjusted_cu = torch.clip(cu_offsets - chunk_size * cp_rank, min=0, max=chunk_size)
|
||||
@@ -419,13 +436,13 @@ def train(config: TrainerConfig):
|
||||
out = forward(
|
||||
model,
|
||||
input_ids,
|
||||
forward_position_ids,
|
||||
position_ids,
|
||||
labels=labels,
|
||||
temperature=temperatures,
|
||||
mm_kwargs=mm_kwargs,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
seq_lens=seq_lens,
|
||||
seq_lens_are_pre_shard=cp_enabled,
|
||||
seq_lens_are_pre_shard=seq_lens_are_pre_shard,
|
||||
routed_experts=routed_experts,
|
||||
)
|
||||
|
||||
|
||||
@@ -73,7 +73,9 @@ def train(config: SFTConfig):
|
||||
|
||||
# Setup the monitor
|
||||
logger.info(f"Initializing monitor ({config.wandb})")
|
||||
monitor = setup_monitor(config.wandb, output_dir=config.output_dir, run_config=config)
|
||||
monitor = setup_monitor(
|
||||
config.wandb, file_config=config.file_monitor, output_dir=config.output_dir, run_config=config
|
||||
)
|
||||
|
||||
# Setup heartbeat (only on rank 0)
|
||||
heart = None
|
||||
|
||||
@@ -457,15 +457,11 @@ def _is_retryable_lora_error(exception: BaseException) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
# Per-attempt and total bounds for `/load_lora_adapter`. A LoRA load is fast
|
||||
# (small adapter file + KV cache reset, single-digit seconds in practice) but
|
||||
# the global admin AsyncClient uses `timeout=None`, so a stuck server hangs
|
||||
# the orchestrator forever inside `ElasticInferencePool._sync_server_adapter`.
|
||||
# `_PER_ATTEMPT` converts a hang into a TimeoutException so tenacity retries;
|
||||
# `_TOTAL` is the wall-clock budget across all retries — pick whichever
|
||||
# stop condition fires first.
|
||||
LORA_LOAD_READ_TIMEOUT_S = 30.0
|
||||
LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
|
||||
# Loaded multi-DP servers can take minutes to finish an adapter update. Keep
|
||||
# finite timeouts without retrying a healthy update after only a few seconds.
|
||||
# The retry budget is checked between attempts, not as a hard outer deadline.
|
||||
LORA_LOAD_READ_TIMEOUT_S = 300.0
|
||||
LORA_LOAD_TOTAL_TIMEOUT_S = 600.0
|
||||
|
||||
|
||||
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
|
||||
|
||||
@@ -2,9 +2,10 @@ from pathlib import Path
|
||||
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig, WandbWithExtrasConfig
|
||||
from prime_rl.configs.shared import FileMonitorConfig, PrimeMonitorConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.monitor.base import Monitor, NoOpMonitor
|
||||
from prime_rl.utils.monitor.file import FileMonitor
|
||||
from prime_rl.utils.monitor.multi import MultiMonitor
|
||||
from prime_rl.utils.monitor.prime import PrimeMonitor
|
||||
from prime_rl.utils.monitor.wandb import WandbMonitor
|
||||
@@ -13,6 +14,7 @@ __all__ = [
|
||||
"Monitor",
|
||||
"WandbMonitor",
|
||||
"PrimeMonitor",
|
||||
"FileMonitor",
|
||||
"MultiMonitor",
|
||||
"NoOpMonitor",
|
||||
"setup_monitor",
|
||||
@@ -37,6 +39,7 @@ def setup_monitor(
|
||||
run_config: BaseConfig | None = None,
|
||||
*,
|
||||
prime_config: PrimeMonitorConfig | None = None,
|
||||
file_config: FileMonitorConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
train_env_names: list[str] = [],
|
||||
eval_env_names: list[str] = [],
|
||||
@@ -83,6 +86,16 @@ def setup_monitor(
|
||||
)
|
||||
)
|
||||
|
||||
if file_config is not None:
|
||||
monitors.append(
|
||||
FileMonitor(
|
||||
config=file_config,
|
||||
output_dir=output_dir,
|
||||
run_config=run_config,
|
||||
keep_full_history=keep_full_history,
|
||||
)
|
||||
)
|
||||
|
||||
if len(monitors) == 0:
|
||||
_MONITOR = NoOpMonitor(keep_full_history=keep_full_history)
|
||||
elif len(monitors) == 1:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import random
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@@ -8,6 +9,45 @@ if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
_DROPPED_JSON_VALUE = object()
|
||||
|
||||
|
||||
def drop_non_finite_json_values(value: Any, dropped_paths: list[str], path: str = "") -> Any:
|
||||
"""Recursively drop non-finite floats (NaN/inf) from a JSON-serializable value.
|
||||
|
||||
Appends the dotted path of each dropped value to `dropped_paths`. Used before
|
||||
serializing metric payloads that must be strict JSON (the public Prime API and
|
||||
the local `metrics.jsonl` sink), since NaN/Infinity are not valid JSON.
|
||||
"""
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
dropped_paths.append(path)
|
||||
return _DROPPED_JSON_VALUE
|
||||
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
key: sanitized_item
|
||||
for key, item in value.items()
|
||||
if (
|
||||
sanitized_item := drop_non_finite_json_values(
|
||||
item,
|
||||
dropped_paths,
|
||||
f"{path}.{key}" if path else str(key),
|
||||
)
|
||||
)
|
||||
is not _DROPPED_JSON_VALUE
|
||||
}
|
||||
|
||||
if isinstance(value, list):
|
||||
return [
|
||||
sanitized_item
|
||||
for idx, item in enumerate(value)
|
||||
if (sanitized_item := drop_non_finite_json_values(item, dropped_paths, f"{path}[{idx}]"))
|
||||
is not _DROPPED_JSON_VALUE
|
||||
]
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def sample_items_for_logging(items: list[Any], sample_ratio: float | None) -> list[Any]:
|
||||
"""Apply monitor sample_ratio semantics to a batch of items.
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from prime_rl.configs.shared import FileMonitorConfig
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, drop_non_finite_json_values
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
|
||||
|
||||
class FileMonitor(Monitor):
|
||||
"""Appends logged metrics to a local ``metrics.jsonl`` file.
|
||||
|
||||
A self-hosted, dependency-free mirror of what ``WandbMonitor.log`` sees: one
|
||||
JSON object per line, ``{"step": step, "time": <wall>, **metrics}``. The file is
|
||||
flushed after every write so an in-progress run can be read (e.g. to build a
|
||||
static dashboard snapshot mid-run). Only rank 0 writes. Samples and
|
||||
distributions are not persisted here (scalars only).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: FileMonitorConfig | None,
|
||||
output_dir: Path | None = None,
|
||||
run_config: BaseConfig | None = None,
|
||||
keep_full_history: bool = True,
|
||||
):
|
||||
self.config = config
|
||||
self.logger = get_logger()
|
||||
self.history: list[dict[str, Any]] = []
|
||||
self._keep_full_history = keep_full_history
|
||||
self.output_dir = output_dir
|
||||
self._file = None
|
||||
|
||||
rank = int(os.environ.get("RANK", os.environ.get("DP_RANK", "0")))
|
||||
self.enabled = self.config is not None
|
||||
self.is_master = rank == 0
|
||||
if not self.enabled or not self.is_master:
|
||||
if not self.is_master:
|
||||
self.logger.warning(f"Skipping {self.__class__.__name__} initialization from non-master rank ({rank})")
|
||||
return
|
||||
|
||||
if output_dir is None:
|
||||
self.logger.warning("FileMonitor requires an output_dir; disabling.")
|
||||
self.enabled = False
|
||||
return
|
||||
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._path = output_dir / config.filename
|
||||
# Line-buffered append so a concurrently-running dashboard can tail the file.
|
||||
self._file = open(self._path, "a", buffering=1) # noqa: SIM115
|
||||
self.logger.info(f"Logging metrics to {self._path}")
|
||||
|
||||
def log(self, metrics: dict[str, Any], step: int) -> None:
|
||||
if self._keep_full_history:
|
||||
self.history.append(metrics)
|
||||
else:
|
||||
self.history = [metrics]
|
||||
if not self.is_master or not self.enabled or self._file is None:
|
||||
return
|
||||
|
||||
dropped_paths: list[str] = []
|
||||
sanitized = drop_non_finite_json_values(metrics, dropped_paths)
|
||||
if dropped_paths:
|
||||
preview = ", ".join(dropped_paths[:5])
|
||||
suffix = " ..." if len(dropped_paths) > 5 else ""
|
||||
self.logger.debug(
|
||||
f"Dropping {len(dropped_paths)} non-finite value(s) from metrics.jsonl: {preview}{suffix}"
|
||||
)
|
||||
|
||||
row = {"step": step, "time": time.time(), **sanitized}
|
||||
self._file.write(json.dumps(row))
|
||||
self._file.write("\n")
|
||||
|
||||
def log_samples(self, rollouts: list[Rollout], step: int) -> None:
|
||||
pass
|
||||
|
||||
def log_eval_samples(self, rollouts: list[Rollout], env_name: str, step: int) -> None:
|
||||
pass
|
||||
|
||||
def log_distributions(self, distributions: dict[str, list[float]], step: int) -> None:
|
||||
pass
|
||||
|
||||
def save_final_summary(self, filename: str = "final_summary.json") -> None:
|
||||
if not self.is_master or not self.enabled or self.output_dir is None:
|
||||
return
|
||||
summary = self.history[-1] if self.history else {}
|
||||
dropped_paths: list[str] = []
|
||||
sanitized = drop_non_finite_json_values(summary, dropped_paths)
|
||||
with open(self.output_dir / filename, "w") as f:
|
||||
json.dump(sanitized, f)
|
||||
|
||||
def close(self) -> None:
|
||||
if self._file is not None:
|
||||
self._file.close()
|
||||
self._file = None
|
||||
@@ -3,7 +3,6 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
@@ -21,7 +20,7 @@ from verifiers.v1.push import trace_to_sample
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.configs.shared import PrimeMonitorConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
|
||||
from prime_rl.utils.monitor.base import Monitor, drop_non_finite_json_values, sample_items_for_logging
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from prime_rl.orchestrator.types import Rollout
|
||||
@@ -52,46 +51,13 @@ _SAMPLE_SCHEMA = pa.schema(
|
||||
)
|
||||
|
||||
|
||||
_DROPPED_JSON_VALUE = object()
|
||||
|
||||
|
||||
def _drop_non_finite_json_values(value: Any, dropped_paths: list[str], path: str = "") -> Any:
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
dropped_paths.append(path)
|
||||
return _DROPPED_JSON_VALUE
|
||||
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
key: sanitized_item
|
||||
for key, item in value.items()
|
||||
if (
|
||||
sanitized_item := _drop_non_finite_json_values(
|
||||
item,
|
||||
dropped_paths,
|
||||
f"{path}.{key}" if path else str(key),
|
||||
)
|
||||
)
|
||||
is not _DROPPED_JSON_VALUE
|
||||
}
|
||||
|
||||
if isinstance(value, list):
|
||||
return [
|
||||
sanitized_item
|
||||
for idx, item in enumerate(value)
|
||||
if (sanitized_item := _drop_non_finite_json_values(item, dropped_paths, f"{path}[{idx}]"))
|
||||
is not _DROPPED_JSON_VALUE
|
||||
]
|
||||
|
||||
return value
|
||||
|
||||
|
||||
class PrimeMonitor(Monitor):
|
||||
"""Logs to Prime Intellect API."""
|
||||
|
||||
def _sanitize_json_payload(self, endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Drop non-finite floats before sending JSON payloads to the public API."""
|
||||
dropped_paths: list[str] = []
|
||||
sanitized_payload = _drop_non_finite_json_values(payload, dropped_paths)
|
||||
sanitized_payload = drop_non_finite_json_values(payload, dropped_paths)
|
||||
if not dropped_paths:
|
||||
return payload
|
||||
|
||||
|
||||
+2
-3
@@ -1,5 +1,4 @@
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
@@ -74,11 +73,11 @@ def branch_name() -> str:
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def output_dir(tmp_path_factory: pytest.TempPathFactory) -> Generator[Path, None, None]:
|
||||
"""Fixture for temporary output directory for tests with automatic cleanup"""
|
||||
"""Fixture for the tests' output directory. Never deleted — CI uploads run logs
|
||||
from it on failure; runs start with ``--clean-output-dir`` for a fresh workspace."""
|
||||
output_dir = Path(os.environ.get("PYTEST_OUTPUT_DIR", tmp_path_factory.mktemp("outputs")))
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
yield output_dir
|
||||
shutil.rmtree(output_dir, ignore_errors=True)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
|
||||
@@ -38,6 +38,7 @@ def rl_process(
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/alphabet_sort.toml",
|
||||
"--clean-output-dir",
|
||||
"--wandb.project",
|
||||
wandb_project,
|
||||
"--wandb.name",
|
||||
|
||||
@@ -29,6 +29,7 @@ def rl_process(
|
||||
"rl",
|
||||
"@",
|
||||
"configs/ci/integration/reverse-text-moe/start.toml",
|
||||
"--clean-output-dir",
|
||||
"--trainer.model.impl",
|
||||
"custom",
|
||||
"--wandb.project",
|
||||
|
||||
@@ -20,6 +20,17 @@ TIMEOUT = 600 # 10 minutes (was 300s — too tight when 3 concurrent orchestrat
|
||||
ORCHESTRATOR_NAMES = ["alpha", "beta", "gamma"]
|
||||
|
||||
|
||||
def remove_run_dir(run_dir: Path) -> None:
|
||||
"""Delete a run dir, tolerating the shared trainer still flushing its tail
|
||||
(token exports recreate directories mid-rmtree -> 'Directory not empty')."""
|
||||
for _ in range(10):
|
||||
shutil.rmtree(run_dir, ignore_errors=True)
|
||||
if not run_dir.exists():
|
||||
return
|
||||
time.sleep(1)
|
||||
shutil.rmtree(run_dir)
|
||||
|
||||
|
||||
def wait_for_file(
|
||||
file_path: Path,
|
||||
timeout: int = 600,
|
||||
@@ -274,7 +285,7 @@ def multi_run_result(
|
||||
print(f"Copied alpha checkpoint to {tmp_path / 'alpha_ckpt_step_10'}")
|
||||
|
||||
# Remove alpha run directory
|
||||
shutil.rmtree(output_dir / "run_alpha")
|
||||
remove_run_dir(output_dir / "run_alpha")
|
||||
|
||||
# ===========================
|
||||
# Queue alpha's resume proc
|
||||
@@ -305,7 +316,7 @@ def multi_run_result(
|
||||
shutil.copy(run_dir / "logs" / "orchestrator.log", log_dir / "beta_orchestrator.log")
|
||||
shutil.copytree(beta_ckpt_dir, tmp_path / "beta_ckpt_step_20")
|
||||
print(f"Copied {beta_ckpt_dir} to {tmp_path / 'beta_ckpt_step_20'}")
|
||||
shutil.rmtree(run_dir)
|
||||
remove_run_dir(run_dir)
|
||||
|
||||
# =====================
|
||||
# Queue beta's resume
|
||||
@@ -329,7 +340,7 @@ def multi_run_result(
|
||||
timeout=TIMEOUT,
|
||||
)
|
||||
shutil.copy(output_dir / "run_gamma" / "logs" / "orchestrator.log", log_dir / "gamma_orchestrator.log")
|
||||
shutil.rmtree(output_dir / "run_gamma")
|
||||
remove_run_dir(output_dir / "run_gamma")
|
||||
|
||||
# ================================================
|
||||
# Wait for alpha_resume and beta_resume to finish
|
||||
|
||||
@@ -448,6 +448,51 @@ def test_prepare_sample_truncates_mm_at_image_boundary():
|
||||
assert n_placeholders == mb.mm_kwargs["pixel_values"].shape[0] # ppt == 1 here
|
||||
|
||||
|
||||
def test_prepare_batch_packs_multimodal_with_text():
|
||||
mm_sample = TrainingSample(
|
||||
token_ids=[10, 11, 12],
|
||||
mask=[False, True, True],
|
||||
logprobs=[0.0, -0.1, -0.2],
|
||||
temperatures=[1.0, 1.0, 1.0],
|
||||
advantages=[0.0, 1.0, 1.0],
|
||||
env_name="mm-env",
|
||||
mm_token_type_ids=[0, 1, 0],
|
||||
mm_kwargs={
|
||||
"pixel_values": _encoded(np.array([[1.0, 2.0]], dtype=np.float32)),
|
||||
"image_grid_thw": _encoded(np.array([[1, 2, 2]], dtype=np.int64)),
|
||||
},
|
||||
)
|
||||
text_sample = TrainingSample(
|
||||
token_ids=[20, 21],
|
||||
mask=[False, True],
|
||||
logprobs=[0.0, -0.3],
|
||||
temperatures=[0.7, 0.7],
|
||||
advantages=[0.0, 1.0],
|
||||
env_name="text-env",
|
||||
)
|
||||
|
||||
batches_per_gpu = prepare_batch(
|
||||
rollouts=[mm_sample, text_sample],
|
||||
seq_len=8,
|
||||
num_train_workers=2,
|
||||
idxs=[0, 0],
|
||||
num_loras=1,
|
||||
bin_cost=build_bin_cost(None),
|
||||
)
|
||||
|
||||
real_batches = [batch for batch in _flatten_batches(batches_per_gpu) if _has_loss_tokens(batch)]
|
||||
assert len(real_batches) == 1
|
||||
batch = real_batches[0]
|
||||
assert batch.seq_lens == [3, 2]
|
||||
assert batch.sequence_lengths == [3, 2]
|
||||
assert batch.position_ids == [0, 1, 2, 0, 1]
|
||||
assert batch.mm_token_type_ids == [0, 1, 0, 0, 0]
|
||||
assert batch.mm_kwargs is not None
|
||||
assert batch.mm_kwargs["pixel_values"].shape == [1, 2]
|
||||
assert batch.mm_kwargs["image_grid_thw"].shape == [1, 3]
|
||||
assert batch.env_names == ["mm-env"] * 3 + ["text-env"] * 2
|
||||
|
||||
|
||||
def test_prepare_sample_none_routed_experts():
|
||||
"""When routed_experts is None, micro_batch.routed_experts is None."""
|
||||
sample = TrainingSample(
|
||||
|
||||
@@ -268,6 +268,24 @@ def test_orchestrator_vlm_requires_renderer():
|
||||
assert config.renderer is not None
|
||||
|
||||
|
||||
def test_trainer_rejects_vlm_cp_with_ring():
|
||||
config = {
|
||||
"model": {
|
||||
"cp": 2,
|
||||
"impl": "custom",
|
||||
"optimization_dtype": "bfloat16",
|
||||
"reduce_dtype": "bfloat16",
|
||||
"vlm": {
|
||||
"vision_encoder_attr": "model.visual",
|
||||
"language_model_attr": "model.language_model",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
with pytest.raises(ValidationError, match="cp_style='ulysses'"):
|
||||
TrainerConfig.model_validate(config)
|
||||
|
||||
|
||||
def test_selective_activation_checkpointing_requires_custom_impl():
|
||||
with pytest.raises(ValidationError, match="Selective activation checkpointing requires model.impl='custom'"):
|
||||
TrainerModelConfig.model_validate({"impl": "hf", "ac": {"mode": "selective"}})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from pathlib import Path
|
||||
from typing import Generator
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import tomli_w
|
||||
import torch
|
||||
@@ -12,7 +13,7 @@ from prime_rl.trainer.rl.packer import MultiPacker
|
||||
from prime_rl.trainer.runs import setup_multi_run_manager
|
||||
from prime_rl.trainer.utils import build_bin_cost
|
||||
from prime_rl.trainer.world import reset_world
|
||||
from prime_rl.transport.types import TrainingSample
|
||||
from prime_rl.transport.types import EncodedTensor, TrainingSample
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True, scope="module")
|
||||
@@ -52,6 +53,66 @@ def make_training_sample() -> TrainingSample:
|
||||
)
|
||||
|
||||
|
||||
def _encoded_tensor(data, dtype) -> EncodedTensor:
|
||||
arr = np.asarray(data, dtype=dtype)
|
||||
return EncodedTensor(dtype=str(arr.dtype), shape=list(arr.shape), data=arr.tobytes())
|
||||
|
||||
|
||||
def _decode_encoded_tensor(encoded: EncodedTensor):
|
||||
return np.frombuffer(encoded.data, dtype=np.dtype(encoded.dtype)).reshape(encoded.shape).tolist()
|
||||
|
||||
|
||||
def _mm_sample(value: float, env_name: str = "test-env") -> TrainingSample:
|
||||
return TrainingSample(
|
||||
token_ids=[1, 250, 2],
|
||||
mask=[False, True, True],
|
||||
logprobs=[0.0, -0.1, -0.2],
|
||||
temperatures=[1.0, 1.0, 1.0],
|
||||
env_name=env_name,
|
||||
advantages=[0.0, 1.0, 1.0],
|
||||
mm_token_type_ids=[0, 1, 0],
|
||||
mm_kwargs={
|
||||
"pixel_values": _encoded_tensor([[value, value + 1]], np.float32),
|
||||
"image_grid_thw": _encoded_tensor([[1, 2, 2]], np.int64),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _packer_with_two_runs(tmp_path, monkeypatch, dp_world_size, seq_len):
|
||||
"""Set up a MultiPacker over two discovered runs; capture sent grids."""
|
||||
reset_world()
|
||||
runs._MULTI_RUN_MANAGER = None
|
||||
manager = setup_multi_run_manager(output_dir=tmp_path, max_runs=2, device=torch.device("cpu"))
|
||||
create_run_with_config(tmp_path, "run_a")
|
||||
create_run_with_config(tmp_path, "run_b")
|
||||
manager.discover_runs()
|
||||
|
||||
sent: list = []
|
||||
|
||||
class DummyReceiver:
|
||||
def receive(self):
|
||||
return []
|
||||
|
||||
def reset_run(self, idx):
|
||||
pass
|
||||
|
||||
class DummySender:
|
||||
def send(self, micro_batch_grid):
|
||||
sent.append(micro_batch_grid)
|
||||
|
||||
monkeypatch.setattr("prime_rl.trainer.rl.packer.setup_training_batch_receiver", lambda _c: DummyReceiver())
|
||||
monkeypatch.setattr("prime_rl.trainer.rl.packer.setup_micro_batch_sender", lambda *a, **k: DummySender())
|
||||
packer = MultiPacker(
|
||||
dp_world_size=dp_world_size,
|
||||
seq_len=seq_len,
|
||||
pad_to_multiple_of=1,
|
||||
config=FileSystemTransportConfig(),
|
||||
bin_cost=build_bin_cost(None),
|
||||
start_step=0,
|
||||
)
|
||||
return manager, packer, sent
|
||||
|
||||
|
||||
def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
reset_world()
|
||||
runs._MULTI_RUN_MANAGER = None
|
||||
@@ -114,3 +175,67 @@ def test_packer_progress_updates_once_per_run(tmp_path: Path, monkeypatch: pytes
|
||||
micro_batch = sender.sent[0][0][0]
|
||||
assert micro_batch.run_id == "run_test123"
|
||||
assert micro_batch.run_step == 1
|
||||
|
||||
|
||||
def test_multipacker_pack_preserves_mm_kwargs_modality_and_run_tagging(tmp_path, monkeypatch):
|
||||
"""MultiPacker keeps multimodal and text microbatches aligned across ranks."""
|
||||
from prime_rl.trainer.batch import _is_multimodal_sample
|
||||
|
||||
manager, packer, sent = _packer_with_two_runs(tmp_path, monkeypatch, dp_world_size=2, seq_len=5)
|
||||
malformed = _mm_sample(0.0)
|
||||
malformed.mm_token_type_ids = None
|
||||
valid, reason = packer._validate_sample(malformed)
|
||||
assert not valid
|
||||
assert reason is not None and "require mm_token_type_ids" in reason
|
||||
|
||||
a, b = manager.id_2_idx["run_a"], manager.id_2_idx["run_b"]
|
||||
for idx, value in ((a, 1.0), (b, 10.0)):
|
||||
packer.buffers[idx].append((_mm_sample(value), 0))
|
||||
packer.buffers[idx].append((make_training_sample(), 0))
|
||||
|
||||
packer.pack()
|
||||
assert sent, "pack() sent nothing"
|
||||
grid = sent[-1]
|
||||
assert len(grid) == 2
|
||||
|
||||
for step_mbs in zip(*grid):
|
||||
assert len({_is_multimodal_sample(mb) for mb in step_mbs}) == 1
|
||||
|
||||
mm_mbs = [mb for rank in grid for mb in rank if _is_multimodal_sample(mb)]
|
||||
assert mm_mbs, "no MM microbatches produced"
|
||||
real_run_idxs = set()
|
||||
for mb in mm_mbs:
|
||||
assert mb.mm_kwargs is not None
|
||||
if any(mb.loss_mask):
|
||||
tagged = [i for i, n in enumerate(mb.lora_num_tokens) if n > 0]
|
||||
assert len(tagged) == 1 and mb.lora_num_tokens[tagged[0]] == len(mb.input_ids)
|
||||
real_run_idxs.add(tagged[0])
|
||||
assert real_run_idxs == {a, b}, f"both runs' MM should be tagged; got {real_run_idxs}"
|
||||
|
||||
|
||||
def test_multipacker_packs_mm_kwargs_within_each_run(tmp_path, monkeypatch):
|
||||
"""Compatible eager multimodal samples pack within a run but never across runs."""
|
||||
from prime_rl.trainer.batch import _is_multimodal_sample
|
||||
|
||||
manager, packer, sent = _packer_with_two_runs(tmp_path, monkeypatch, dp_world_size=1, seq_len=12)
|
||||
a, b = manager.id_2_idx["run_a"], manager.id_2_idx["run_b"]
|
||||
for idx, base in ((a, 1.0), (b, 10.0)):
|
||||
packer.buffers[idx].append((_mm_sample(base), 0))
|
||||
packer.buffers[idx].append((_mm_sample(base + 2), 0))
|
||||
|
||||
packer.pack()
|
||||
assert sent
|
||||
grid = sent[-1]
|
||||
real_mm_mbs = [mb for rank in grid for mb in rank if _is_multimodal_sample(mb) and any(mb.loss_mask)]
|
||||
|
||||
assert len(real_mm_mbs) == 2
|
||||
for mb in real_mm_mbs:
|
||||
assert len(mb.input_ids) == 6
|
||||
assert mb.position_ids == [0, 1, 2, 0, 1, 2]
|
||||
assert mb.seq_lens == [3, 3]
|
||||
assert mb.mm_kwargs is not None
|
||||
assert mb.mm_kwargs["pixel_values"].shape == [2, 2]
|
||||
assert mb.mm_kwargs["image_grid_thw"].shape == [2, 3]
|
||||
assert len(_decode_encoded_tensor(mb.mm_kwargs["pixel_values"])) == 2
|
||||
tagged = [i for i, n in enumerate(mb.lora_num_tokens) if n > 0]
|
||||
assert len(tagged) == 1
|
||||
|
||||
@@ -4632,7 +4632,7 @@ requires-dist = [
|
||||
|
||||
[[package]]
|
||||
name = "openswe-v1"
|
||||
version = "0.1.2"
|
||||
version = "0.1.3"
|
||||
source = { editable = "deps/research-environments/environments/swe/openswe_v1" }
|
||||
dependencies = [
|
||||
{ name = "datasets" },
|
||||
@@ -4774,7 +4774,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "openthoughts-tblite-v1"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/research-environments/environments/terminal/openthoughts_tblite_v1" }
|
||||
dependencies = [
|
||||
{ name = "verifiers" },
|
||||
@@ -6446,7 +6446,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "senior-swe-bench-v1"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/research-environments/environments/swe/senior_swe_bench_v1" }
|
||||
dependencies = [
|
||||
{ name = "verifiers", extra = ["harbor"] },
|
||||
@@ -7091,7 +7091,7 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.2.1" }]
|
||||
|
||||
[[package]]
|
||||
name = "terminal-lego-v1"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
source = { editable = "deps/research-environments/environments/terminal/terminal_lego_v1" }
|
||||
dependencies = [
|
||||
{ name = "huggingface-hub" },
|
||||
|
||||
Reference in New Issue
Block a user