Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3dd67633d | ||
|
|
0a437ae340 | ||
|
|
9a55a0899c | ||
|
|
666297d09c | ||
|
|
202f108f33 |
+13
-10
@@ -153,22 +153,25 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& rm /tmp/prime-cli-overrides.txt \
|
||||
&& /app/.venv/bin/python -c 'import pathlib, verifiers; assert pathlib.Path(verifiers.__file__).is_relative_to("/app/deps/verifiers"), verifiers.__file__'
|
||||
|
||||
# Optional: build NIXL from source against the UCX 1.19 baked above. The PyPI
|
||||
# nixl wheel ships its own UCX which segfaults on prefill→decode KV transfer
|
||||
# (#2883); rebuilding against our UCX is the documented fix. Only needed for
|
||||
# the disaggregated P/D path — default off so training-only / single-node
|
||||
# inference builds are unaffected. Enable via `--build-arg INCLUDE_NIXL_FROM_SOURCE=1`.
|
||||
ARG INCLUDE_NIXL_FROM_SOURCE=0
|
||||
# Build NIXL from source against the UCX 1.19 baked above. The PyPI nixl wheel
|
||||
# ships its own UCX which segfaults on prefill→decode KV transfer (#2883);
|
||||
# rebuilding against our UCX is the documented fix. The rename is required: an
|
||||
# unrenamed source build is `nixl_cu12`, and the `nixl` shim imports nixl_cu13
|
||||
# (the PyPI wheel) first, so the fix would silently not apply. Libraries carry
|
||||
# RUNPATH=/opt/ucx/lib, so no LD_LIBRARY_PATH is needed at runtime.
|
||||
# Opt out via `--build-arg INCLUDE_NIXL_FROM_SOURCE=0`.
|
||||
ARG INCLUDE_NIXL_FROM_SOURCE=1
|
||||
ARG NIXL_VERSION=0.10.1
|
||||
RUN if [ "$INCLUDE_NIXL_FROM_SOURCE" = "1" ]; then \
|
||||
VIRTUAL_ENV=/app/.venv uv pip install pip \
|
||||
&& git clone --depth 1 --branch ${NIXL_VERSION} https://github.com/ai-dynamo/nixl.git /tmp/nixl \
|
||||
&& cd /tmp/nixl \
|
||||
&& uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml \
|
||||
&& PKG_CONFIG_PATH=/opt/ucx/lib/pkgconfig \
|
||||
LD_LIBRARY_PATH=/opt/ucx/lib:/opt/ucx/lib/ucx \
|
||||
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/app/deps \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /app/deps/nixl_cu13-*.whl \
|
||||
&& rm -rf /tmp/nixl /app/deps/nixl_cu13-*.whl; \
|
||||
/app/.venv/bin/python -m pip wheel . --no-deps --wheel-dir=/tmp/nixl-whl \
|
||||
&& VIRTUAL_ENV=/app/.venv uv pip install --reinstall --no-deps /tmp/nixl-whl/nixl_cu13-*.whl \
|
||||
&& ldd /app/.venv/lib/python3.12/site-packages/.nixl_cu13.mesonpy.libs/plugins/libplugin_UCX.so | grep -q /opt/ucx/lib/libucp.so \
|
||||
&& rm -rf /tmp/nixl /tmp/nixl-whl; \
|
||||
fi
|
||||
|
||||
# Trim the CUDA toolkit to the nvcc-JIT essentials in a separate stage, so the runtime
|
||||
|
||||
Vendored
+1
-1
Submodule deps/prime-envs updated: 647ff7ade5...565e8a74c0
Vendored
+1
-1
Submodule deps/verifiers updated: 509983f90e...c35ebd3201
@@ -574,6 +574,9 @@ class IPOLossConfig(BaseConfig):
|
||||
eps: float = Field(0.3, ge=0)
|
||||
"""Maximum absolute probability change before a token is masked."""
|
||||
|
||||
max_importance_ratio: float = Field(1e4, ge=1, allow_inf_nan=False)
|
||||
"""Cap the importance weight of accepted tokens while preserving its policy gradient."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
"""Temperature for the advantage term."""
|
||||
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ dependencies = [
|
||||
"transformers==5.6.2",
|
||||
"wandb>=0.26.1",
|
||||
"wandb-workspaces>=0.4.3",
|
||||
"prime-sandboxes>=0.3.0",
|
||||
"prime-sandboxes>=0.3.2",
|
||||
"prime-runs[train]>=0.1.3",
|
||||
"pyzmq>=27.1.0",
|
||||
"aiolimiter>=1.2.1",
|
||||
|
||||
+119
-45
@@ -5,67 +5,141 @@ set -e
|
||||
ulimit -n 32000 2>/dev/null || echo "Warning: Could not set ulimit (may need --ulimit flag in docker run)"
|
||||
|
||||
# Allow runtime override of the prime-rl source itself.
|
||||
# PRIME_RL_REF can be a git tag, branch, or commit hash. PRIME_RL_REPO
|
||||
# PRIME_RL_REF can be a git tag, branch, or full commit hash. PRIME_RL_REPO
|
||||
# optionally points at a fork; defaults to the upstream repo.
|
||||
#
|
||||
# We clone into a per-ref dir under /tmp, seed the venv from the baked
|
||||
# /app/.venv so heavy wheels (flash-attn, mamba-ssm, …) survive, then
|
||||
# `uv sync --inexact` re-installs prime_rl from the override source.
|
||||
# Workdir + PATH swap so the chart's `uv run trainer/inference/orchestrator`
|
||||
# resolves the entrypoints from the override venv.
|
||||
# The ref is fetched shallowly under /tmp and synced INTO the baked
|
||||
# /app/.venv: uv re-points the first-party editables (prime_rl, verifiers,
|
||||
# renderers, ...) at the checkout and reinstalls only third-party pins
|
||||
# that differ from the image's lockfile, so the heavy prebuilt wheels
|
||||
# (flash-attn, deep-ep, mamba-ssm, ...) are never rebuilt. A container
|
||||
# starts from a fresh filesystem, so mutating /app/.venv in place is safe.
|
||||
# The pods of the prime-rl-fft chart run this with a sha pinned by the
|
||||
# dispatcher; the exported PRIME_RL_SOURCE_COMMIT records what ran.
|
||||
if [ -n "$PRIME_RL_REF" ]; then
|
||||
PRIME_RL_REPO="${PRIME_RL_REPO:-https://github.com/PrimeIntellect-ai/prime-rl.git}"
|
||||
# Slug + content hash for the cache dir name. Slug keeps the path
|
||||
# Slug + content hash for the checkout dir name. Slug keeps the path
|
||||
# human-readable; the hash (over repo + ref) prevents collisions
|
||||
# between distinct refs that slugify the same way (e.g. `feat/foo`
|
||||
# vs `feat-foo`) and between the same ref on different forks.
|
||||
REF_SLUG="${PRIME_RL_REF//\//-}"
|
||||
REF_HASH=$(echo -n "${PRIME_RL_REPO}|${PRIME_RL_REF}" | md5sum | cut -c1-12)
|
||||
DEST="/tmp/prime-rl-${REF_SLUG}-${REF_HASH}"
|
||||
# Rewrite ssh://git@github.com URLs to https so submodules listed
|
||||
# with SSH URLs (deps/verifiers, deps/renderers, deps/research-envs)
|
||||
# can be cloned from the pod without ssh keys.
|
||||
git config --global url."https://github.com/".insteadOf "git@github.com:"
|
||||
if [ ! -d "$DEST/.git" ]; then
|
||||
echo "[prime-rl] cloning ${PRIME_RL_REPO} for ${PRIME_RL_REF}"
|
||||
rm -rf "$DEST"
|
||||
git clone --recurse-submodules "$PRIME_RL_REPO" "$DEST"
|
||||
# Rewrite git@github.com URLs to https so submodules listed with SSH
|
||||
# URLs (deps/verifiers, deps/renderers, deps/prime-envs) clone from the
|
||||
# pod without ssh keys. Via GIT_CONFIG_* rather than `git config
|
||||
# --global`: the pod's HOME may not be writable by its uid.
|
||||
export GIT_CONFIG_COUNT=1
|
||||
export GIT_CONFIG_KEY_0="url.https://github.com/.insteadOf"
|
||||
export GIT_CONFIG_VALUE_0="git@github.com:"
|
||||
rm -rf "$DEST"
|
||||
git init --quiet "$DEST"
|
||||
git -C "$DEST" remote add origin "$PRIME_RL_REPO"
|
||||
# Depth-1 fetch of the ref itself: GitHub serves branches, tags and
|
||||
# full commit shas alike (abbreviated shas are not fetchable), and
|
||||
# prime-rl's history (~700 MB of .git) is not needed to run it.
|
||||
echo "[prime-rl] fetching ${PRIME_RL_REF} from ${PRIME_RL_REPO}"
|
||||
git -C "$DEST" fetch --quiet --depth 1 origin "$PRIME_RL_REF"
|
||||
git -C "$DEST" checkout --quiet --force --detach FETCH_HEAD
|
||||
# Same public submodules the image build inits (build_image.yaml);
|
||||
# a pinned commit that isn't the submodule's branch tip is fetched by
|
||||
# sha, which GitHub allows.
|
||||
git -C "$DEST" submodule sync --quiet --recursive
|
||||
git -C "$DEST" submodule update --quiet --init --recursive --depth 1 -- \
|
||||
deps/pydantic-config deps/verifiers deps/renderers deps/prime-envs
|
||||
PRIME_RL_SOURCE_COMMIT=$(git -C "$DEST" rev-parse HEAD)
|
||||
export PRIME_RL_SOURCE_COMMIT
|
||||
echo "[prime-rl] source overlay at ${PRIME_RL_SOURCE_COMMIT}"
|
||||
|
||||
# Give the verifiers/renderers editables the same versions the image
|
||||
# build does (Dockerfile.cuda): resolve them with the repo's script
|
||||
# (git describe, else the highest `>=` floor any pyproject declares),
|
||||
# then bake them into hatch-vcs's fallback-version and drop the
|
||||
# submodules' git metadata so the fallback is what gets used. The
|
||||
# shallow clones carry no tags, so hatch-vcs would otherwise stamp
|
||||
# them 0.0.1.dev1 and every `verifiers>=…` floor in the tree would be
|
||||
# unmet, letting the CLI install below swap the editable for a wheel.
|
||||
if [ -f "$DEST/scripts/docker-editable-pretend-versions.sh" ]; then
|
||||
eval "$(bash "$DEST/scripts/docker-editable-pretend-versions.sh" --shell "$DEST")"
|
||||
rm -f "$DEST/deps/verifiers/.git" "$DEST/deps/renderers/.git"
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${VERIFIERS_PRETEND_VERSION}\"/" "$DEST/deps/verifiers/pyproject.toml"
|
||||
sed -i "s/fallback-version = \"0.0.0\"/fallback-version = \"${RENDERERS_PRETEND_VERSION}\"/" "$DEST/deps/renderers/pyproject.toml"
|
||||
fi
|
||||
# Always fetch + checkout so mutable refs (branches/tags) pick up new
|
||||
# commits between pod restarts. No-op for immutable SHAs.
|
||||
echo "[prime-rl] refreshing ${PRIME_RL_REF}"
|
||||
git -C "$DEST" fetch --quiet --tags --force origin
|
||||
git -C "$DEST" checkout --quiet --force "$PRIME_RL_REF"
|
||||
# Fast-forward to upstream tip when PRIME_RL_REF is a branch name.
|
||||
# Silently no-ops for SHAs/tags (no `origin/<sha>` exists).
|
||||
git -C "$DEST" reset --hard --quiet "origin/${PRIME_RL_REF}" 2>/dev/null || true
|
||||
# Refresh submodules to whatever the parent commit pins. `sync`
|
||||
# picks up URL changes in .gitmodules between checkouts on cache
|
||||
# hit; `update --init --recursive` applies the pinned SHAs.
|
||||
git -C "$DEST" submodule sync --recursive
|
||||
git -C "$DEST" submodule update --init --recursive
|
||||
if [ ! -d "$DEST/.venv" ]; then
|
||||
# Seed from the baked venv so the heavy wheels (flash-attn,
|
||||
# mamba-ssm, …) don't have to be rebuilt. Plain `cp -a` (no
|
||||
# hardlinks): a subsequent `uv sync` writes into this tree, and
|
||||
# hardlinks would leak those writes back into /app/.venv when
|
||||
# /tmp and /app share a filesystem.
|
||||
cp -a /app/.venv "$DEST/.venv"
|
||||
fi
|
||||
echo "[prime-rl] running uv sync --inexact (this may take a few minutes on cold checkout)"
|
||||
# --inexact keeps the seeded venv's pre-built wheels (flash-attn-3,
|
||||
# deep-ep, mamba-ssm) in place; uv only rebuilds them if the override's
|
||||
# lockfile pins different versions.
|
||||
( cd "$DEST" && uv sync --inexact --no-dev --all-packages --all-extras --group mamba-ssm )
|
||||
export VIRTUAL_ENV="$DEST/.venv"
|
||||
export PATH="$DEST/.venv/bin:$PATH"
|
||||
|
||||
# Wheels the in-place sync cannot rebuild: a lockfile that pins any of
|
||||
# these differently from the image needs a real image build. Fail here
|
||||
# rather than minutes later inside a half-installed torch. Stdlib only;
|
||||
# --project /app pins the interpreter to the baked venv whatever the cwd.
|
||||
uv run --no-sync --project /app python - "$DEST/uv.lock" /app/uv.lock <<'HEAVY_PINS_PY'
|
||||
import sys
|
||||
import tomllib
|
||||
|
||||
HEAVY = {
|
||||
"torch", "torchvision", "torchaudio", "triton", "vllm", "vllm-router",
|
||||
"flash-attn", "flash-attn-3", "flashinfer-python", "tilelang",
|
||||
"deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels",
|
||||
}
|
||||
|
||||
|
||||
def pins(path):
|
||||
with open(path, "rb") as f:
|
||||
lock = tomllib.load(f)
|
||||
out = {}
|
||||
for pkg in lock.get("package", []):
|
||||
if pkg.get("name") in HEAVY:
|
||||
source = repr(sorted((pkg.get("source") or {}).items()))
|
||||
out.setdefault(pkg["name"], set()).add((pkg.get("version"), source))
|
||||
return out
|
||||
|
||||
|
||||
ref_pins, image_pins = pins(sys.argv[1]), pins(sys.argv[2])
|
||||
drift = sorted(name for name in HEAVY if ref_pins.get(name) != image_pins.get(name))
|
||||
if drift:
|
||||
print(
|
||||
f"[prime-rl] {sys.argv[1]} pins {', '.join(drift)} differently from the image; "
|
||||
"the runtime source overlay cannot rebuild these. Build an image for this ref "
|
||||
"(build_image.yaml) or run it on an image whose lockfile matches.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
HEAVY_PINS_PY
|
||||
|
||||
# Sync the checkout into the baked venv. Same extras as Dockerfile.cuda
|
||||
# so an unchanged lockfile is a no-op for third-party packages (keep
|
||||
# the two lists in sync). --inexact leaves packages the checkout
|
||||
# doesn't declare in place instead of uninstalling them.
|
||||
export UV_PROJECT_ENVIRONMENT=/app/.venv
|
||||
export VIRTUAL_ENV=/app/.venv
|
||||
echo "[prime-rl] syncing ${DEST} into /app/.venv"
|
||||
( cd "$DEST" && uv sync --inexact --locked --no-dev --all-packages \
|
||||
--extra gpu --extra dashboard --extra flash-attn --extra flash-attn-3 \
|
||||
--extra flash-attn-cute --extra disagg --extra quack --extra kernels \
|
||||
--group mamba-ssm )
|
||||
# Replay the image's post-sync step (Dockerfile.cuda; keep the two in
|
||||
# sync): the prime CLI pulls prime-traces / prime-sandboxes / openai
|
||||
# past the lock's pins, and the --locked sync above just rolled them
|
||||
# back, which leaves `prime env install` unable to import.
|
||||
#
|
||||
# FIXME(prime#940): workaround, remove once the prime CLI drops
|
||||
# verifiers as a dependency
|
||||
# (https://github.com/PrimeIntellect-ai/prime/pull/940). The CLI pins
|
||||
# verifiers==0.2.0, which would swap the editable for the PyPI wheel
|
||||
# and break prime-rl's imports; the --overrides file ignores that one
|
||||
# requirement. When removing it, drop the overrides file and the
|
||||
# --overrides flag here and in Dockerfile.cuda.
|
||||
echo "[prime-rl] installing the prime CLI"
|
||||
printf 'verifiers\n' > /tmp/prime-cli-overrides.txt
|
||||
uv pip install --overrides /tmp/prime-cli-overrides.txt 'prime>=0.7'
|
||||
# The chart's `uv run --no-sync <entrypoint>` commands resolve the
|
||||
# project from the cwd; the venv itself stays /app/.venv via
|
||||
# UV_PROJECT_ENVIRONMENT above.
|
||||
cd "$DEST"
|
||||
fi
|
||||
|
||||
# Allow runtime override of the verifiers package version.
|
||||
# VERIFIERS_VERSION can be a git tag, branch, or commit hash. Runs after the
|
||||
# PRIME_RL_REF swap so when both are set the install lands in the override
|
||||
# venv (uv pip install targets $VIRTUAL_ENV when exported).
|
||||
# PRIME_RL_REF overlay so when both are set verifiers is installed last
|
||||
# (uv pip install targets $VIRTUAL_ENV, which is /app/.venv either way).
|
||||
if [ -n "$VERIFIERS_VERSION" ]; then
|
||||
echo "Installing verifiers version: $VERIFIERS_VERSION"
|
||||
uv pip install --reinstall-package verifiers \
|
||||
|
||||
@@ -82,6 +82,10 @@ else
|
||||
fi
|
||||
cd "$NIXL_SRC"
|
||||
git checkout "$NIXL_VERSION"
|
||||
# Name the wheel nixl-cu13 (pyproject says nixl-cu12): the `nixl` shim imports
|
||||
# nixl_cu13 first, so a nixl_cu12 build would sit unused next to the PyPI wheel.
|
||||
git checkout -- pyproject.toml
|
||||
uv run --no-project --with tomlkit python contrib/tomlutil.py --wheel-name nixl-cu13 pyproject.toml
|
||||
|
||||
export PKG_CONFIG_PATH="$UCX_INSTALL/lib/pkgconfig"
|
||||
export LD_LIBRARY_PATH="$UCX_INSTALL/lib:$UCX_INSTALL/lib/ucx:${LD_LIBRARY_PATH:-}"
|
||||
@@ -92,5 +96,5 @@ mkdir -p "$WHEEL_DIR"
|
||||
uv pip install pip 2>/dev/null
|
||||
"$PYTHON" -m pip wheel . --no-deps --wheel-dir="$WHEEL_DIR"
|
||||
|
||||
WHEEL=$(ls "$WHEEL_DIR"/nixl*.whl | head -1)
|
||||
WHEEL=$(ls "$WHEEL_DIR"/nixl_cu13-"$NIXL_VERSION"-*.whl | head -1)
|
||||
echo "=== NIXL wheel built at: $WHEEL ==="
|
||||
|
||||
@@ -125,54 +125,64 @@ def shift_tensor_right(t: Float[Tensor, "batch seq"], pad_value: float | None =
|
||||
def _safe_mean(values: Tensor, mask: Tensor) -> Tensor:
|
||||
"""Mean of values over a boolean mask; returns 0 when mask is empty."""
|
||||
denom = torch.clamp_min(mask.sum(), 1)
|
||||
return values[mask].sum() / denom
|
||||
return (values[mask] / denom).sum()
|
||||
|
||||
|
||||
def compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs: Tensor, inference_logprobs: Tensor
|
||||
) -> tuple[Tensor, Tensor, Tensor]:
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
importance_ratio = torch.exp(log_importance_ratio)
|
||||
mismatch_kl = importance_ratio - log_importance_ratio - 1
|
||||
return log_importance_ratio, importance_ratio, mismatch_kl
|
||||
def _mismatch_kl_from_log_ratio(log_importance_ratio: Tensor) -> Tensor:
|
||||
# Keep headroom for FP32 reductions across tokens and ranks.
|
||||
metric_limit = log_importance_ratio.new_tensor(1e30)
|
||||
mismatch_kl = torch.expm1(log_importance_ratio.clamp(max=metric_limit.log())) - log_importance_ratio
|
||||
return mismatch_kl.clamp(max=metric_limit)
|
||||
|
||||
|
||||
def _capped_importance_ratio(log_importance_ratio: Tensor, max_ratio: float) -> Tensor:
|
||||
capped_log_ratio = log_importance_ratio.detach().clamp(max=log_importance_ratio.new_tensor(max_ratio).log())
|
||||
return torch.exp(capped_log_ratio + (log_importance_ratio - log_importance_ratio.detach()))
|
||||
|
||||
|
||||
class IPOLoss:
|
||||
"""IPO loss type: a symmetric trust region (mask tokens whose probability
|
||||
moved more than ``eps`` in absolute terms), policy gradient via
|
||||
the importance ratio, and a squared-log-ratio KL regularizer."""
|
||||
a capped importance ratio, and a squared-log-ratio KL regularizer."""
|
||||
|
||||
def __init__(self, config: IPOLossConfig):
|
||||
self.config = config
|
||||
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs:
|
||||
loss_config = self.config
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
advantages = inputs.advantages
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
|
||||
abs_probs_diff = torch.abs(torch.exp(trainer_logprobs) - torch.exp(inference_logprobs))
|
||||
trainer_logprobs = inputs.trainer_logprobs[inputs.loss_mask]
|
||||
inference_logprobs = inputs.inference_logprobs[inputs.loss_mask]
|
||||
advantages = inputs.advantages[inputs.loss_mask]
|
||||
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
|
||||
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
larger_logprob = torch.maximum(trainer_logprobs, inference_logprobs)
|
||||
smaller_logprob = torch.minimum(trainer_logprobs, inference_logprobs)
|
||||
# |e^logp - e^logq| = e^max(logp, logq) - e^min(logp, logq)
|
||||
# = e^max(logp, logq) * (1 - e^(min(logp, logq) - max(logp, logq)))
|
||||
# = e^max(logp, logq) * -expm1(min(logp, logq) - max(logp, logq)).
|
||||
# expm1 avoids cancellation in 1 - e^x when x is near zero.
|
||||
abs_probs_diff = torch.exp(larger_logprob) * -torch.expm1(smaller_logprob - larger_logprob)
|
||||
is_masked = abs_probs_diff > loss_config.eps
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
keep_mask = ~is_masked
|
||||
|
||||
advantages = loss_config.adv_tau * advantages
|
||||
pg_loss = keep_mask * advantages * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
per_token_loss = -pg_loss + loss_config.kl_tau * kl_loss
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
loss = per_token_loss.sum()
|
||||
importance_ratio = _capped_importance_ratio(log_importance_ratio[keep_mask], loss_config.max_importance_ratio)
|
||||
pg_loss = -loss_config.adv_tau * advantages[keep_mask] * importance_ratio
|
||||
if weights is not None:
|
||||
pg_loss = pg_loss * weights[keep_mask]
|
||||
loss = pg_loss.sum()
|
||||
if loss_config.kl_tau:
|
||||
kl_loss = loss_config.kl_tau * log_importance_ratio.clamp(-1e4, 1e4).square()
|
||||
if weights is not None:
|
||||
kl_loss = kl_loss * weights
|
||||
loss = loss + kl_loss.sum()
|
||||
|
||||
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, loss_mask & is_masked), # all trainable, masked tokens
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask), # all trainable, unmasked tokens
|
||||
"is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
|
||||
"is_masked": is_masked.sum() / max(is_masked.numel(), 1),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
@@ -187,28 +197,27 @@ class IcePopLoss:
|
||||
|
||||
def loss(self, inputs: LossInputs) -> LossOutputs:
|
||||
loss_config = self.config
|
||||
log_importance_ratio, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
inputs.trainer_logprobs, inputs.inference_logprobs
|
||||
)
|
||||
log_importance_ratio = inputs.trainer_logprobs[inputs.loss_mask] - inputs.inference_logprobs[inputs.loss_mask]
|
||||
advantages = inputs.advantages[inputs.loss_mask]
|
||||
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
|
||||
|
||||
log_ratio_low = log_importance_ratio.new_tensor(loss_config.ratio_low).log()
|
||||
log_ratio_high = log_importance_ratio.new_tensor(loss_config.ratio_high).log()
|
||||
detached_log_ratio = log_importance_ratio.detach()
|
||||
is_masked = (detached_log_ratio < log_ratio_low) | (detached_log_ratio > log_ratio_high)
|
||||
keep_mask = inputs.loss_mask & ~is_masked
|
||||
keep_mask = ~is_masked
|
||||
|
||||
# Mask before exponentiation so rejected extreme ratios cannot produce
|
||||
# 0 * inf = NaN in the loss or its gradient.
|
||||
safe_log_ratio = torch.where(keep_mask, log_importance_ratio, torch.zeros_like(log_importance_ratio))
|
||||
importance_ratio = torch.exp(safe_log_ratio)
|
||||
per_token_loss = -(keep_mask * loss_config.adv_tau * inputs.advantages * importance_ratio)
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
importance_ratio = torch.exp(log_importance_ratio[keep_mask])
|
||||
per_token_loss = -loss_config.adv_tau * advantages[keep_mask] * importance_ratio
|
||||
if weights is not None:
|
||||
per_token_loss = per_token_loss * weights[keep_mask]
|
||||
|
||||
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
|
||||
|
||||
metrics = {
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, inputs.loss_mask & is_masked),
|
||||
"masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
|
||||
"unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
|
||||
"is_masked": _safe_mean(is_masked, inputs.loss_mask),
|
||||
"is_masked": is_masked.sum() / max(is_masked.numel(), 1),
|
||||
}
|
||||
return LossOutputs(loss=per_token_loss.sum(), metrics=metrics)
|
||||
|
||||
@@ -222,39 +231,37 @@ def ref_kl_loss_fn(inputs: LossInputs) -> LossOutputs:
|
||||
inference probability; a squared-log-ratio term regularizes drift. Scalar
|
||||
advantages are not read — ref_kl algorithms ship none.
|
||||
"""
|
||||
trainer_logprobs = inputs.trainer_logprobs
|
||||
inference_logprobs = inputs.inference_logprobs
|
||||
ref_logprobs = inputs.ref_logprobs
|
||||
loss_mask = inputs.loss_mask
|
||||
|
||||
if ref_logprobs is None:
|
||||
if inputs.ref_logprobs is None:
|
||||
raise ValueError("ref_kl loss type requires ref_logprobs — use the 'opd' or 'opsd' algorithm.")
|
||||
|
||||
log_importance_ratio, importance_ratio, mismatch_kl = compute_importance_ratio_and_mismatch_kl(
|
||||
trainer_logprobs, inference_logprobs
|
||||
)
|
||||
trainer_logprobs = inputs.trainer_logprobs[inputs.loss_mask]
|
||||
inference_logprobs = inputs.inference_logprobs[inputs.loss_mask]
|
||||
ref_logprobs = inputs.ref_logprobs[inputs.loss_mask]
|
||||
weights = inputs.loss_weights[inputs.loss_mask] if inputs.loss_weights is not None else None
|
||||
log_importance_ratio = trainer_logprobs - inference_logprobs
|
||||
|
||||
probs_diff = torch.exp(trainer_logprobs) - torch.exp(inference_logprobs)
|
||||
is_masked = probs_diff < -0.2
|
||||
drop_mask = loss_mask & is_masked
|
||||
keep_mask = loss_mask & ~is_masked
|
||||
keep_mask = ~is_masked
|
||||
|
||||
ref_kl = ref_logprobs - trainer_logprobs
|
||||
|
||||
pg_loss = keep_mask * ref_kl.detach() * importance_ratio
|
||||
kl_loss = loss_mask * log_importance_ratio**2
|
||||
per_token_loss = -pg_loss + 1e-3 * kl_loss
|
||||
if inputs.loss_weights is not None:
|
||||
per_token_loss = per_token_loss * inputs.loss_weights
|
||||
loss = per_token_loss.sum()
|
||||
importance_ratio = _capped_importance_ratio(log_importance_ratio[keep_mask], 1e4)
|
||||
pg_loss = -ref_kl[keep_mask].detach() * importance_ratio
|
||||
kl_loss = 1e-3 * log_importance_ratio.clamp(-1e4, 1e4).square()
|
||||
if weights is not None:
|
||||
pg_loss = pg_loss * weights[keep_mask]
|
||||
kl_loss = kl_loss * weights
|
||||
loss = pg_loss.sum() + kl_loss.sum()
|
||||
mismatch_kl = _mismatch_kl_from_log_ratio(log_importance_ratio)
|
||||
|
||||
# Namespaced: the rl loss fn emits same-named trust-region metrics with a
|
||||
# different definition, and mixed batches run both fns in one step.
|
||||
metrics = {
|
||||
"ref_kl/masked_mismatch_kl": _safe_mean(mismatch_kl, drop_mask),
|
||||
"ref_kl/masked_mismatch_kl": _safe_mean(mismatch_kl, is_masked),
|
||||
"ref_kl/unmasked_mismatch_kl": _safe_mean(mismatch_kl, keep_mask),
|
||||
"ref_kl/is_masked": _safe_mean(is_masked, loss_mask),
|
||||
"ref_kl": _safe_mean(ref_kl, loss_mask),
|
||||
"ref_kl/is_masked": is_masked.sum() / max(is_masked.numel(), 1),
|
||||
"ref_kl": ref_kl.sum() / max(ref_kl.numel(), 1),
|
||||
}
|
||||
|
||||
return LossOutputs(loss=loss, metrics=metrics)
|
||||
|
||||
@@ -29,7 +29,7 @@ from prime_rl.utils.logger import format_time, setup_logger
|
||||
from prime_rl.trainer.rl.loss import (
|
||||
compute_entropy,
|
||||
compute_loss,
|
||||
compute_importance_ratio_and_mismatch_kl,
|
||||
_mismatch_kl_from_log_ratio,
|
||||
selective_log_softmax,
|
||||
selective_log_softmax_with_sampling_mask,
|
||||
setup_rl_loss_fn,
|
||||
@@ -528,8 +528,9 @@ def train(config: TrainerConfig):
|
||||
has_mismatch_tokens = bool(mismatch_mask.any())
|
||||
if has_mismatch_tokens:
|
||||
with torch.no_grad():
|
||||
_, _, mismatch_kl = compute_importance_ratio_and_mismatch_kl(out["logprobs"], inference_logprobs)
|
||||
mismatch_kl = mismatch_kl[mismatch_mask].detach().to("cpu")
|
||||
log_ratio = out["logprobs"][mismatch_mask] - inference_logprobs[mismatch_mask]
|
||||
mismatch_kl = _mismatch_kl_from_log_ratio(log_ratio)
|
||||
mismatch_kl = mismatch_kl.detach().to("cpu")
|
||||
tensors["mismatch_kl/all"].append(mismatch_kl)
|
||||
mismatch_env_names = [
|
||||
env_name for env_name, keep in zip(env_names, mismatch_mask.flatten().tolist()) if keep
|
||||
|
||||
@@ -6,8 +6,10 @@ from prime_rl.trainer.rl.loss import (
|
||||
IcePopLoss,
|
||||
LossInputs,
|
||||
LossOutputs,
|
||||
_mismatch_kl_from_log_ratio,
|
||||
compute_entropy,
|
||||
compute_loss,
|
||||
ref_kl_loss_fn,
|
||||
setup_rl_loss_fn,
|
||||
)
|
||||
|
||||
@@ -124,10 +126,86 @@ def test_icepop_loss_masks_extreme_ratio_without_nan():
|
||||
result = IcePopLoss(IcePopLossConfig()).loss(inputs)
|
||||
|
||||
assert torch.equal(result.loss, torch.zeros_like(result.loss))
|
||||
assert all(torch.isfinite(value) for value in result.metrics.values())
|
||||
result.loss.backward()
|
||||
assert torch.equal(trainer_logprobs.grad, torch.zeros_like(trainer_logprobs.grad))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config", [IPOLossConfig(kl_tau=0.01), IcePopLossConfig()])
|
||||
def test_ipo_icepop_match_original_on_finite_ratios(config):
|
||||
torch.manual_seed(23)
|
||||
trainer_logprobs = (-8 * torch.rand(128, device="cuda")).requires_grad_()
|
||||
inference_logprobs = -8 * torch.rand(128, device="cuda")
|
||||
advantages = torch.randn(128, device="cuda")
|
||||
loss_mask = torch.rand(128, device="cuda") > 0.3
|
||||
weights = torch.rand(128, device="cuda")
|
||||
inputs = LossInputs(trainer_logprobs, inference_logprobs, None, advantages, loss_mask, weights)
|
||||
|
||||
result = setup_rl_loss_fn(config).loss(inputs)
|
||||
log_ratio = trainer_logprobs - inference_logprobs
|
||||
ratio = log_ratio.exp()
|
||||
if isinstance(config, IPOLossConfig):
|
||||
keep = loss_mask & ((trainer_logprobs.exp() - inference_logprobs.exp()).abs() <= config.eps)
|
||||
expected = (
|
||||
(-(keep * config.adv_tau * advantages * ratio) + loss_mask * config.kl_tau * log_ratio.square()) * weights
|
||||
).sum()
|
||||
else:
|
||||
keep = (
|
||||
loss_mask
|
||||
& (log_ratio.detach() >= torch.tensor(config.ratio_low, device="cuda").log())
|
||||
& (log_ratio.detach() <= torch.tensor(config.ratio_high, device="cuda").log())
|
||||
)
|
||||
expected = (-(keep * config.adv_tau * advantages * ratio) * weights).sum()
|
||||
|
||||
torch.testing.assert_close(result.loss, expected, rtol=1e-5, atol=1e-5)
|
||||
actual_grad = torch.autograd.grad(result.loss, trainer_logprobs, retain_graph=True)[0]
|
||||
expected_grad = torch.autograd.grad(expected, trainer_logprobs)[0]
|
||||
torch.testing.assert_close(actual_grad, expected_grad, rtol=1e-5, atol=1e-5)
|
||||
|
||||
|
||||
def test_ipo_excludes_masked_tokens_and_caps_accepted_extreme_ratio():
|
||||
trainer_logprobs = torch.tensor([-10.0, 0.0, float("nan")], device="cuda", requires_grad=True)
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=torch.tensor([-100.0, -100.0, float("nan")], device="cuda"),
|
||||
ref_logprobs=None,
|
||||
advantages=torch.ones(3, device="cuda"),
|
||||
loss_mask=torch.tensor([True, True, False], device="cuda"),
|
||||
)
|
||||
|
||||
result = setup_rl_loss_fn(IPOLossConfig()).loss(inputs)
|
||||
|
||||
torch.testing.assert_close(result.loss, torch.tensor(-1e4, device="cuda"))
|
||||
assert all(torch.isfinite(value) for value in result.metrics.values())
|
||||
result.loss.backward()
|
||||
torch.testing.assert_close(trainer_logprobs.grad, torch.tensor([-1e4, 0.0, 0.0], device="cuda"))
|
||||
|
||||
|
||||
def test_ref_kl_loss_stays_finite_with_extreme_ratios_and_masked_nan():
|
||||
trainer_logprobs = torch.tensor([-10.0, 0.0, float("nan")], device="cuda", requires_grad=True)
|
||||
inputs = LossInputs(
|
||||
trainer_logprobs=trainer_logprobs,
|
||||
inference_logprobs=torch.tensor([-100.0, -100.0, float("nan")], device="cuda"),
|
||||
ref_logprobs=torch.tensor([-1.0, -1.0, float("nan")], device="cuda"),
|
||||
advantages=torch.zeros(3, device="cuda"),
|
||||
loss_mask=torch.tensor([True, True, False], device="cuda"),
|
||||
)
|
||||
|
||||
result = ref_kl_loss_fn(inputs)
|
||||
|
||||
assert torch.isfinite(result.loss)
|
||||
assert all(torch.isfinite(value) for value in result.metrics.values())
|
||||
result.loss.backward()
|
||||
assert torch.isfinite(trainer_logprobs.grad).all()
|
||||
|
||||
|
||||
def test_mismatch_kl_retains_small_positive_values():
|
||||
log_ratio = torch.tensor([1e-4], device="cuda")
|
||||
torch.testing.assert_close(
|
||||
_mismatch_kl_from_log_ratio(log_ratio), torch.tensor([5e-9], device="cuda"), rtol=1e-3, atol=0
|
||||
)
|
||||
|
||||
|
||||
def test_ce_component_matches_masked_nll():
|
||||
trainer_logprobs = [torch.tensor([-0.1, -0.5, -0.2], dtype=torch.float32).cuda()]
|
||||
inference_logprobs = [torch.zeros(3, dtype=torch.float32).cuda()]
|
||||
|
||||
@@ -5049,7 +5049,7 @@ requires-dist = [
|
||||
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
|
||||
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
|
||||
{ name = "prime-runs", extras = ["train"], specifier = ">=0.1.3" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.3.0" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.3.2" },
|
||||
{ name = "prometheus-client", specifier = ">=0.20.0" },
|
||||
{ name = "psutil", specifier = ">=7.0.0" },
|
||||
{ name = "pyarrow", specifier = ">=21.0.0" },
|
||||
@@ -5141,7 +5141,7 @@ train = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-sandboxes"
|
||||
version = "0.3.0"
|
||||
version = "0.3.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiofiles" },
|
||||
@@ -5153,9 +5153,9 @@ dependencies = [
|
||||
{ name = "pyqwest" },
|
||||
{ name = "tenacity" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/b6/46/2d118d8bbb901b729f3bc0678725eb28088d757a872db04cffa1492d0208/prime_sandboxes-0.3.0.tar.gz", hash = "sha256:c99075ed82a9bbfe5a453cee84b9f09565a7f6b07fd5ace072401cce59a1fe08", size = 132759, upload-time = "2026-09-18T01:32:31.263Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f8/fe/69195c7c9e3d0f938e84ae54a8ffd386529019fb7635cad65d318e96271d/prime_sandboxes-0.3.2.tar.gz", hash = "sha256:6ded2497cbff8b5760e3f7897e1f00f2b789463daa397481620361bb148bfc45", size = 135266, upload-time = "2026-09-25T21:35:16.33Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5f/04/c77c7f260babf93978f912b85511e76f63a3cfa5bb11a8c34108177d5825/prime_sandboxes-0.3.0-py3-none-any.whl", hash = "sha256:19078ff508fa72de8f565422918faf367e2831ed8a2f26a5a6a98110e4062941", size = 71441, upload-time = "2026-09-18T01:32:30.062Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/26/fc/6eefb673bbcbdd33105b5d14e8d7329a0b10a30c893ac8c74a8f2373a477/prime_sandboxes-0.3.2-py3-none-any.whl", hash = "sha256:d47f07fe90e662464ddd33468fa538f37c962e7bec5c2cbbbd170eb57d0ef89e", size = 72421, upload-time = "2026-09-25T21:35:14.99Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in New Issue
Block a user