Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
753cfb5a42 | ||
|
|
33e02a7a18 | ||
|
|
94f359e8d6 | ||
|
|
cf400e7db9 | ||
|
|
8da21f16b8 | ||
|
|
ae37b35a34 | ||
|
|
77788ba020 | ||
|
|
ab85b3b369 | ||
|
|
de5cdb8bae |
@@ -137,6 +137,10 @@ RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
&& \
|
||||
/app/.venv/bin/python -c 'from importlib.metadata import version; [version(name) for name in ("deep-ep", "deep-gemm", "mamba-ssm", "nixl", "prime-kernels", "quack-kernels", "vllm", "vllm-router")]'
|
||||
|
||||
# Needed for private environments hub auth
|
||||
RUN --mount=type=cache,target=/usr/local/share/uv/cache \
|
||||
VIRTUAL_ENV=/app/.venv uv pip install 'prime>=0.7'
|
||||
|
||||
# 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
|
||||
|
||||
Vendored
+1
-1
Submodule deps/verifiers updated: ceecc4d422...9cf0df22bd
@@ -21,6 +21,11 @@ class ServedEvalConfig(EvalSourcesConfig):
|
||||
"""Adaptive in-flight episode concurrency, sized by the same controller as
|
||||
``[orchestrator.concurrency]``. Set ``min_inflight = max_inflight`` to pin it."""
|
||||
|
||||
tasks_per_minute: int | None = Field(None, ge=1)
|
||||
"""Global rate limit on episode dispatch, in tasks per minute. Use it for
|
||||
sandbox-backed environments to pace provisioning during autoscaling. None disables
|
||||
rate limiting."""
|
||||
|
||||
@property
|
||||
def env_addresses(self) -> dict[tuple[str, str], str | None]:
|
||||
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
|
||||
|
||||
@@ -1536,7 +1536,7 @@ def row_filter(
|
||||
return False
|
||||
if episode is not None and row.get("id") != episode:
|
||||
return False
|
||||
if errors_only and not (row.get("num_errors") or not row.get("ok")):
|
||||
if errors_only and row.get("ok"):
|
||||
return False
|
||||
arrival = row.get("arrival") or 0
|
||||
return not ((start is not None and arrival < start) or (end is not None and arrival >= end))
|
||||
|
||||
@@ -1176,7 +1176,7 @@ function summaryTilesHtml(idx, all, scoreEntries) {
|
||||
}
|
||||
// failure rates count every landed episode, the errors filter notwithstanding
|
||||
if (all.length) {
|
||||
const errored = all.filter((i) => series.ok?.[i] === false || (series.num_errors?.[i] ?? 0) > 0).length;
|
||||
const errored = all.filter((i) => series.ok?.[i] === false).length;
|
||||
const truncated = all.filter((i) => (series.truncated?.[i] ?? TRUNCATING_STOPS.has(series.stop_condition?.[i])) === true).length;
|
||||
for (const [label, n, what] of [["error rate", errored, "errored"], ["truncation rate", truncated, "truncated"]]) {
|
||||
const rate = n / all.length;
|
||||
@@ -3022,10 +3022,12 @@ function fmtSpan(dispatched, arrived, elapsed) {
|
||||
}
|
||||
|
||||
function episodeRowHtml(ep) {
|
||||
const failed = !ep.ok || !!ep.num_errors;
|
||||
// an ok episode keeps the errors of the attempts it recovered from; they mark the
|
||||
// row as retried, not as failed
|
||||
const failed = !ep.ok;
|
||||
const phase = failed ? "error" : "done";
|
||||
const dispatched = ep.dispatch ?? (ep.arrival != null && ep.duration != null ? ep.arrival - ep.duration : null);
|
||||
return `<tr data-line="${ep.line}" class="${failed ? "err" : ""}"${failed ? ` title="${ep.num_errors || 1} error${ep.num_errors === 1 ? "" : "s"}"` : ""}>
|
||||
return `<tr data-line="${ep.line}" class="${episodeRowClass(ep)}" title="${esc(episodeRowTitle(ep))}">
|
||||
<td class="muted">${ep.line}</td>
|
||||
<td><span class="badge stage stage-${phase}">${phase}</span></td>
|
||||
<td class="muted nowrap">${fmtSpan(dispatched, ep.arrival, ep.duration)}</td>
|
||||
@@ -3209,7 +3211,7 @@ async function openLiveTrace(traceId, { refresh = false } = {}) {
|
||||
semanticExpandedRuns.clear();
|
||||
clearSemanticTranscriptOrigin();
|
||||
$("#sg-inspector").hidden = true;
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading live trace…</div>`;
|
||||
resetTranscript(`<div class="chart-empty">loading live trace…</div>`);
|
||||
$("#tm-timeline").innerHTML = "";
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
@@ -3325,7 +3327,7 @@ function tmItemHtml(item) {
|
||||
}
|
||||
const e = item;
|
||||
return (
|
||||
`<div class="tm-item ${rolloutActive(item) ? "active" : ""}${e.num_errors || !e.ok ? " err" : ""}" data-line="${e.line}">` +
|
||||
`<div class="tm-item ${rolloutActive(item) ? "active" : ""} ${episodeRowClass(e)}" data-line="${e.line}" title="${esc(episodeRowTitle(e))}">` +
|
||||
`<span class="tm-num">#${e.line}</span><span class="tm-env muted" title="${esc(e.env ?? "")}">${esc(e.env ?? "")}</span>` +
|
||||
`<span class="tm-reward ${rewardClass(e.reward)}">${fmtReward(e.reward)}</span></div>`
|
||||
);
|
||||
@@ -3426,7 +3428,7 @@ async function modalStep(delta) {
|
||||
currentLine = null;
|
||||
currentEpisode = null;
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = emptyState("no episodes", "this step has no rollouts for the current filters");
|
||||
resetTranscript(emptyState("no episodes", "this step has no rollouts for the current filters"));
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
}
|
||||
@@ -3474,6 +3476,15 @@ async function ensureTokens() {
|
||||
currentEpisode = episode;
|
||||
}
|
||||
|
||||
/* Every path that replaces the transcript with a placeholder goes through here, so the
|
||||
previous episode's error strip never outlives its episode. */
|
||||
function resetTranscript(html) {
|
||||
const episodeErrors = $("#tm-episode-errors");
|
||||
episodeErrors.hidden = true;
|
||||
episodeErrors.innerHTML = "";
|
||||
$("#tm-messages").innerHTML = html;
|
||||
}
|
||||
|
||||
async function openEpisode(line, target = {}) {
|
||||
currentLive = null;
|
||||
$("#tm-live-label").textContent = "";
|
||||
@@ -3486,7 +3497,7 @@ async function openEpisode(line, target = {}) {
|
||||
currentEpisode = null;
|
||||
renderModalStep();
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = `<div class="chart-empty">loading episode…</div>`;
|
||||
resetTranscript(`<div class="chart-empty">loading episode…</div>`);
|
||||
const timelineTarget = $("#tm-timeline");
|
||||
timelineTarget.classList.remove("semantic-canvas");
|
||||
delete timelineTarget.dataset.semanticEpisode;
|
||||
@@ -3940,7 +3951,7 @@ function judgeEvidenceHtml(trace) {
|
||||
|
||||
function renderedTokensHtml(trace, branches) {
|
||||
const rendered = trace.rendered_tokens;
|
||||
const errors = errorBannersHtml(episodeErrors(currentEpisode, trace));
|
||||
const errors = scopedErrorsHtml("trace", scopedErrors(currentEpisode, trace).trace);
|
||||
if (!rendered) return errors + emptyState("rendered text not loaded", "select this view again to load recorded token IDs");
|
||||
const path = currentPath(trace, branches);
|
||||
const tokenCount = path.reduce((count, index) => count + (trace.nodes[index]?.token_ids?.length || 0), 0);
|
||||
@@ -3980,43 +3991,67 @@ function renderedBoxHtml(tokenCount, body, canCopyText) {
|
||||
|
||||
let entriesObserver = null;
|
||||
|
||||
function episodeErrors(ep, trace) {
|
||||
// one failure is often recorded twice, on the episode and on its trace; show it
|
||||
// once, keeping whichever copy carries the traceback
|
||||
const byMessage = new Map();
|
||||
for (const error of [...(ep.errors || []), ...(trace?.errors || [])]) {
|
||||
const record = error && typeof error === "object" ? error : { message: String(error) };
|
||||
const key = `${record.type ?? "Error"}|${record.message ?? ""}`;
|
||||
const kept = byMessage.get(key);
|
||||
if (!kept || (!kept.traceback && record.traceback)) byMessage.set(key, record);
|
||||
/* Errors carried by the episode and by the open trace, each split by what they mean.
|
||||
Verifiers keeps every attempt's errors on the final record and stamps success as `ok`,
|
||||
so the errors of an ok episode or trace are history it recovered from, while a failed
|
||||
one's errors describe its outcome. A failure recorded on both the episode and its
|
||||
trace shows once, as the trace's, keeping whichever copy carries the traceback. */
|
||||
function scopedErrors(ep, trace) {
|
||||
const record = (error) => (error && typeof error === "object" ? error : { message: String(error) });
|
||||
const key = (r) => `${r.type ?? "Error"}|${r.message ?? ""}`;
|
||||
const keep = (map, r) => {
|
||||
const kept = map.get(key(r));
|
||||
if (!kept || (!kept.traceback && r.traceback)) map.set(key(r), r);
|
||||
};
|
||||
const onTrace = new Map();
|
||||
for (const error of trace?.errors || []) keep(onTrace, record(error));
|
||||
const onEpisode = new Map();
|
||||
for (const error of ep.errors || []) {
|
||||
const r = record(error);
|
||||
if (onTrace.has(key(r))) keep(onTrace, r);
|
||||
else keep(onEpisode, r);
|
||||
}
|
||||
return [...byMessage.values()];
|
||||
const split = (records, ok) => ({ failed: ok ? [] : records, recovered: ok ? records : [] });
|
||||
return { episode: split([...onEpisode.values()], ep.ok), trace: split([...onTrace.values()], trace?.ok) };
|
||||
}
|
||||
|
||||
function errorBannersHtml(errors) {
|
||||
if (!errors.length) return "";
|
||||
function errorEntryHtml(scope, record) {
|
||||
const type = record.type ?? "Error";
|
||||
const message = record.message ?? "No error message";
|
||||
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
|
||||
return (
|
||||
`<div class="trace-errors">` +
|
||||
errors
|
||||
.map((error) => {
|
||||
const record = error && typeof error === "object" ? error : { message: String(error) };
|
||||
const type = record.type ?? "Error";
|
||||
const message = record.message ?? "No error message";
|
||||
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
|
||||
return (
|
||||
`<section class="trace-error-banner">` +
|
||||
`<div class="trace-error-message"><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
|
||||
(traceback
|
||||
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
|
||||
: "") +
|
||||
`</section>`
|
||||
);
|
||||
})
|
||||
.join("") +
|
||||
`</div>`
|
||||
`<div class="trace-error-message"><span class="trace-error-scope">${scope} error</span><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
|
||||
(traceback
|
||||
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
|
||||
: "")
|
||||
);
|
||||
}
|
||||
|
||||
function scopedErrorsHtml(scope, { failed, recovered }) {
|
||||
const banners = failed.length
|
||||
? `<div class="trace-errors">${failed.map((record) => `<section class="trace-error-banner">${errorEntryHtml(scope, record)}</section>`).join("")}</div>`
|
||||
: "";
|
||||
const history = recovered.length
|
||||
? `<details class="trace-recovered"><summary><span>recovered from ${recovered.length} ${scope} error${recovered.length === 1 ? "" : "s"} in earlier attempts</span><span class="entry-chev">›</span></summary>` +
|
||||
recovered.map((record) => `<section class="trace-recovered-item">${errorEntryHtml(scope, record)}</section>`).join("") +
|
||||
`</details>`
|
||||
: "";
|
||||
return banners + history;
|
||||
}
|
||||
|
||||
function episodeRowClass(ep) {
|
||||
if (!ep.ok) return "err";
|
||||
return ep.num_errors ? "retried" : "";
|
||||
}
|
||||
|
||||
function episodeRowTitle(ep) {
|
||||
const n = ep.num_errors || 0;
|
||||
const errors = `${n || 1} error${n === 1 ? "" : "s"}`;
|
||||
if (!ep.ok) return errors;
|
||||
return n ? `recovered from ${errors} in earlier attempts` : "";
|
||||
}
|
||||
|
||||
|
||||
function normalizedCallUsage(usage = {}) {
|
||||
let input = usage.prompt_tokens;
|
||||
let cached = usage.cached_input_tokens;
|
||||
@@ -4036,7 +4071,7 @@ function normalizedCallUsage(usage = {}) {
|
||||
function renderMessages(ep, trace, branches) {
|
||||
const container = $("#tm-messages");
|
||||
entriesObserver?.disconnect();
|
||||
const errorsHtml = errorBannersHtml(episodeErrors(ep, trace));
|
||||
const errorsHtml = scopedErrorsHtml("trace", scopedErrors(ep, trace).trace);
|
||||
if (!trace) {
|
||||
container.innerHTML = errorsHtml + emptyState("no traces", "this episode carries no trace data");
|
||||
return;
|
||||
@@ -5487,12 +5522,17 @@ function renderEpisode() {
|
||||
const trace = traces[currentTraceIdx];
|
||||
const branches = trace ? traceBranches(trace) : [];
|
||||
if (currentBranchIdx >= branches.length) currentBranchIdx = 0;
|
||||
// the episode's own errors sit above the agent and branch selectors: they belong to
|
||||
// the whole episode, not to whichever trace is open
|
||||
const episodeErrors = $("#tm-episode-errors");
|
||||
episodeErrors.innerHTML = scopedErrorsHtml("episode", scopedErrors(ep, trace).episode);
|
||||
episodeErrors.hidden = !episodeErrors.innerHTML;
|
||||
const traceTabs = $("#tm-trace-tabs");
|
||||
traceTabs.hidden = traces.length <= 1;
|
||||
traceTabs.innerHTML =
|
||||
traces.length > 1
|
||||
? traces
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.map((trace, i) => `<button data-trace="${i}" class="${i === currentTraceIdx ? "active" : ""}${trace.ok ? "" : " err"}">${esc(trace.agent?.name || "agent")}</button>`)
|
||||
.join("")
|
||||
: "";
|
||||
const branchTabs = $("#tm-branch-tabs");
|
||||
@@ -6538,7 +6578,7 @@ async function reopenFirstEpisode() {
|
||||
currentLine = null;
|
||||
currentEpisode = null;
|
||||
renderRolloutList();
|
||||
$("#tm-messages").innerHTML = emptyState("no episodes", "nothing here for the current filters");
|
||||
resetTranscript(emptyState("no episodes", "nothing here for the current filters"));
|
||||
$("#tm-meta").innerHTML = "";
|
||||
}
|
||||
|
||||
|
||||
@@ -302,6 +302,7 @@
|
||||
<button id="tm-expand" class="btn">expand</button>
|
||||
<button id="drawer-close" class="btn">✕</button>
|
||||
</div>
|
||||
<div id="tm-episode-errors" hidden></div>
|
||||
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
|
||||
<div id="tm-trace-tabs" class="seg" hidden></div>
|
||||
<div id="tm-branch-tabs" class="seg" hidden></div>
|
||||
|
||||
@@ -834,6 +834,7 @@ mark.hit {
|
||||
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
|
||||
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
|
||||
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
|
||||
.tm-item.retried { border-left: 2px dotted var(--grey-4); }
|
||||
.tm-item .tm-reward { margin-left: auto; }
|
||||
.tm-nav { padding: 0 8px; height: 24px; }
|
||||
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
|
||||
@@ -1169,7 +1170,7 @@ mark.hit {
|
||||
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
|
||||
|
||||
/* the banners lead the transcript, so they stand off the first entry */
|
||||
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
|
||||
.trace-errors { margin-top: auto; margin-bottom: 14px; }
|
||||
.trace-error-banner {
|
||||
border: 1px solid var(--negative);
|
||||
background: rgba(255, 69, 57, 0.08);
|
||||
@@ -1178,6 +1179,39 @@ mark.hit {
|
||||
.trace-error-banner + .trace-error-banner { margin-top: 8px; }
|
||||
.trace-error-message { padding: 10px 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
|
||||
.trace-error-type { font-weight: 500; color: var(--negative); }
|
||||
.trace-error-scope {
|
||||
display: inline-block;
|
||||
margin-right: 8px;
|
||||
padding: 1px 6px;
|
||||
border: 1px solid currentColor;
|
||||
font-size: 9px;
|
||||
line-height: 11px;
|
||||
letter-spacing: var(--track-mono);
|
||||
text-transform: uppercase;
|
||||
color: var(--grey-4);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.trace-error-banner .trace-error-scope { color: var(--negative); }
|
||||
#tm-episode-errors { padding: 12px 16px 0; border-bottom: 1px solid var(--hairline); }
|
||||
#tm-episode-errors .trace-errors { margin-top: 0; margin-bottom: 12px; }
|
||||
#tm-episode-errors .trace-recovered { margin-bottom: 12px; }
|
||||
.trace-recovered { margin-bottom: 14px; border: 1px solid var(--grey-3); color: var(--grey-6); }
|
||||
.trace-recovered > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 6px 12px;
|
||||
font-size: 11px;
|
||||
color: var(--grey-4);
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
}
|
||||
.trace-recovered > summary::-webkit-details-marker { display: none; }
|
||||
.trace-recovered[open] > summary .entry-chev { transform: rotate(90deg); }
|
||||
.trace-recovered-item { border-top: 1px solid var(--grey-3); }
|
||||
.trace-recovered-item .trace-error-type { color: var(--grey-4); }
|
||||
.trace-recovered-item .trace-error-tb > summary { border-top-color: var(--grey-3); }
|
||||
.seg button.err, .seg button.err.active { color: var(--negative); }
|
||||
.trace-error-tb > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1697,6 +1731,7 @@ details.entry.hl-entry { border-color: rgba(182, 255, 60, 0.5); animation: hl-pu
|
||||
place of their number set them apart */
|
||||
.live-dot { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); animation: live-pulse 2s ease-out infinite; }
|
||||
#episode-table tr.err td:first-child { border-left: 2px solid var(--negative); }
|
||||
#episode-table tr.retried td:first-child { border-left: 2px dotted var(--grey-4); }
|
||||
#episode-table tr.live.landing .live-dot { animation: none; opacity: 0.45; }
|
||||
.badge.stage { font-size: 9px; padding: 2px 5px; line-height: 12px; border-radius: 3px; background: var(--hairline); border-color: transparent; color: var(--accent); }
|
||||
#tm-live-label { margin-left: 8px; }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
import uuid
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
|
||||
@@ -53,6 +54,10 @@ def run_server(config: EnvServerConfig):
|
||||
def main():
|
||||
"""Main entry-point for the env server. Run using `uv run env-server`"""
|
||||
set_proc_title("EnvServer")
|
||||
# verifiers keys run-scoped state (creation limiters) by $VF_RUN_ID. Every launcher,
|
||||
# the Python entrypoints and the SLURM templates alike, hands env servers $PRL_RUN_ID;
|
||||
# a standalone server is a run of its own.
|
||||
os.environ.setdefault("VF_RUN_ID", os.environ.get("PRL_RUN_ID") or uuid.uuid4().hex)
|
||||
run_server(cli(EnvServerConfig))
|
||||
|
||||
|
||||
|
||||
@@ -137,7 +137,7 @@ def write_eval_subconfigs(config: SFTConfig, config_dir: Path, strip_router: boo
|
||||
|
||||
|
||||
def write_slurm_script(
|
||||
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str | None = None
|
||||
config: SFTConfig, config_path: Path, log_dir: Path, script_path: Path, prl_run_id: str, wandb_shared: bool
|
||||
) -> None:
|
||||
"""Write the SLURM script to disk."""
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
@@ -210,6 +210,7 @@ def write_slurm_script(
|
||||
gpus_per_node=config.deployment.gpus_per_node,
|
||||
ranks_filter=",".join(map(str, config.log.ranks_filter)),
|
||||
prl_run_id=prl_run_id,
|
||||
wandb_shared=wandb_shared,
|
||||
run_name=config.run.name,
|
||||
online_eval=online_eval,
|
||||
use_nccl_broadcast=(
|
||||
@@ -249,16 +250,14 @@ def sft_slurm(config: SFTConfig):
|
||||
write_config(config, config_path, exclude=exclude)
|
||||
|
||||
# Trainer and online-eval processes log to a single shared W&B run.
|
||||
prl_run_id: str | None = None
|
||||
if online_eval and config.monitors.wandb is not None:
|
||||
prl_run_id = os.environ["PRL_RUN_ID"]
|
||||
wandb_shared = online_eval and config.monitors.wandb is not None
|
||||
|
||||
launcher_dir = get_launcher_dir(config.run_dir)
|
||||
if online_eval:
|
||||
write_eval_subconfigs(config, config_dir, strip_router=True)
|
||||
logger.info(f"Configs:\n{format_config_message(config_dir, 'sft', sft_config_components(config, config_dir))}")
|
||||
script_path = launcher_dir / SFT_SBATCH
|
||||
write_slurm_script(config, config_path, log_dir, script_path, prl_run_id)
|
||||
write_slurm_script(config, config_path, log_dir, script_path, os.environ["PRL_RUN_ID"], wandb_shared)
|
||||
logger.info(f"Wrote SLURM script to {script_path}")
|
||||
|
||||
num_nodes = config.deployment.num_train_nodes if config.deployment.type == "multi_node" else 1
|
||||
|
||||
@@ -114,7 +114,7 @@ class EvalRunner:
|
||||
progress=None,
|
||||
initial_max_inflight=self.concurrency.max_inflight,
|
||||
max_inflight_ceiling=config.concurrency.max_inflight,
|
||||
tasks_per_minute=None,
|
||||
tasks_per_minute=config.tasks_per_minute,
|
||||
max_off_policy_steps=0,
|
||||
run_id=self.run_id,
|
||||
run_name=self.run_name,
|
||||
|
||||
@@ -50,7 +50,9 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
``line`` numbers the episode within the stream from 1, so the last of n reads as
|
||||
n — it is what a reader sees and what addresses the episode."""
|
||||
rewards, advantages = [], []
|
||||
input_tokens = output_tokens = turns = branches = 0
|
||||
input_tokens = rec.get("num_input_tokens")
|
||||
output_tokens = rec.get("num_output_tokens")
|
||||
turns = branches = 0
|
||||
stop_condition = None
|
||||
truncated = False
|
||||
reward_parts: dict[str, list[float]] = {}
|
||||
@@ -86,20 +88,10 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
|
||||
if advantage is not None:
|
||||
advantages.append(advantage)
|
||||
for node in nodes:
|
||||
n_tokens = len(node.get("token_ids") or [])
|
||||
if node.get("sampled"):
|
||||
output_tokens += n_tokens
|
||||
else:
|
||||
input_tokens += n_tokens
|
||||
if (node.get("message") or {}).get("role") == "assistant":
|
||||
turns += 1
|
||||
stop_condition = trace.get("stop_condition", stop_condition)
|
||||
truncated = truncated or trace_truncated(trace)
|
||||
if input_tokens == 0 and output_tokens == 0: # some eval traces carry no token arrays
|
||||
for call in trace.get("calls") or []:
|
||||
usage = call.get("usage") or {}
|
||||
input_tokens += usage.get("prompt_tokens") or 0
|
||||
output_tokens += usage.get("completion_tokens") or 0
|
||||
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
|
||||
return {
|
||||
"rewards": {name: sum(v) / len(v) for name, v in reward_parts.items()},
|
||||
|
||||
@@ -176,31 +176,31 @@ def message_text(message: dict[str, Any]) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def trace_row(trace: dict[str, Any]) -> dict[str, Any]:
|
||||
def trace_row(record: dict[str, Any]) -> dict[str, Any]:
|
||||
"""The live table's view of one trace: phase, turns, tokens, cost, last message."""
|
||||
calls = trace.get("calls") or []
|
||||
calls = record.get("calls") or []
|
||||
usage = [call.get("usage") or {} for call in calls]
|
||||
# The newest node is usually a tool result; the assistant's latest words say more.
|
||||
last = ""
|
||||
for node in reversed(trace.get("nodes") or []):
|
||||
for node in reversed(record.get("nodes") or []):
|
||||
message = node.get("message") or {}
|
||||
if message.get("role") == "assistant" and (last := " ".join(message_text(message).split())):
|
||||
break
|
||||
costs = [u["cost"] for u in usage if u.get("cost") is not None]
|
||||
nodes = trace.get("nodes") or []
|
||||
nodes = record.get("nodes") or []
|
||||
parents = {node.get("parent") for node in nodes if node.get("parent") is not None}
|
||||
return {
|
||||
"trace": trace.get("id"),
|
||||
"agent": (trace.get("agent") or {}).get("name", "agent"),
|
||||
"stage": stage(trace),
|
||||
"trace": record.get("id"),
|
||||
"agent": (record.get("agent") or {}).get("name", "agent"),
|
||||
"stage": stage(record),
|
||||
"turns": len(calls),
|
||||
"branches": sum(1 for index in range(len(nodes)) if index not in parents),
|
||||
"input_tokens": sum(u.get("prompt_tokens") or 0 for u in usage),
|
||||
"output_tokens": sum(u.get("completion_tokens") or 0 for u in usage),
|
||||
"input_tokens": record.get("num_input_tokens"),
|
||||
"output_tokens": record.get("num_output_tokens"),
|
||||
"cost": sum(costs) if costs else None,
|
||||
"stop_condition": trace.get("stop_condition"),
|
||||
"errors": len(trace.get("errors") or []),
|
||||
"pending": len(trace.get("pending") or []),
|
||||
"stop_condition": record.get("stop_condition"),
|
||||
"errors": len(record.get("errors") or []),
|
||||
"pending": len(record.get("pending") or []),
|
||||
"last": last[:SNIPPET_CHARS],
|
||||
}
|
||||
|
||||
|
||||
@@ -60,11 +60,11 @@ export EVAL_DONE=$LAUNCHER_DIR/.sft_eval_done_$SLURM_JOB_ID
|
||||
mkdir -p "$LAUNCHER_DIR"
|
||||
rm -f "$TRAINER_DONE"{% if online_eval %} "$EVAL_DONE"{% endif %}
|
||||
|
||||
{% if prl_run_id %}
|
||||
# Trainer and online-eval log to one shared W&B run. The trainer creates the run,
|
||||
# and the online-eval process finalizes it after the final epoch.
|
||||
export PRL_RUN_ID={{ prl_run_id }}
|
||||
export PRL_RUN_NAME={{ run_name }}
|
||||
{% if wandb_shared %}
|
||||
# Trainer and online-eval log to one shared W&B run. The trainer creates the run,
|
||||
# and the online-eval process finalizes it after the final epoch.
|
||||
export WANDB_RUN_ID=$PRL_RUN_ID
|
||||
export WANDB_SHARED_MODE=1
|
||||
export WANDB_SHARED_PRIMARY=trainer
|
||||
|
||||
@@ -32,6 +32,7 @@ MANDATORY_SAVE_NAMESPACES = frozenset({"deepep"})
|
||||
MANDATORY_SAVE_OPERATIONS = frozenset(
|
||||
{
|
||||
"aten::topk",
|
||||
"prime_rl::fp8_indexer",
|
||||
"prime_rl::record_moe_routing_statistics",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -520,6 +520,8 @@ def setup_fsdp(model: nn.Module, config: ModelConfig, parallel_dims: ParallelDim
|
||||
reshard_after_forward=config.reshard_after_forward,
|
||||
shard_placement_fn=shard_placement_fn,
|
||||
)
|
||||
# Keep the router reduction from waiting for the expert reduction's input buffer.
|
||||
block_mlp.router.set_reduce_scatter_max_input_buffers(2)
|
||||
|
||||
fully_shard(
|
||||
transformer_block,
|
||||
|
||||
@@ -128,6 +128,7 @@ from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.distributed._functional_collectives as funcol
|
||||
from torch import Tensor, nn
|
||||
|
||||
from prime_rl.trainer.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config
|
||||
@@ -540,8 +541,8 @@ class DeepseekV4Indexer(nn.Module):
|
||||
n_entries = compressed_kv.shape[1]
|
||||
|
||||
cos, sin = packed.position_embeddings[self.compressor.rope_layer_type]
|
||||
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim).transpose(1, 2)
|
||||
q = apply_rotary_pos_emb_interleaved(q, cos, sin).transpose(1, 2)
|
||||
q = self.q_b_proj(q_residual).view(batch, seq_len, -1, self.head_dim)
|
||||
q = apply_rotary_pos_emb_interleaved(q, cos, sin, unsqueeze_dim=2)
|
||||
w = self.weights_proj(hidden_states)
|
||||
|
||||
layout = packed.compression_layouts[self.compressor.compress_rate]
|
||||
@@ -712,17 +713,21 @@ class DeepseekV4Attention(nn.Module):
|
||||
hidden_shape = (*input_shape, -1, self.head_dim) # (b, t, h, d), the query view
|
||||
cos, sin = packed.position_embeddings[self.rope_layer_type] # (1, t, qk_rope_head_dim // 2) each
|
||||
|
||||
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
|
||||
# Normalizing before the transpose keeps the input contiguous for the quack kernel.
|
||||
q = self.q_b_norm(self.q_b_proj(q_residual).view(*hidden_shape)).transpose(1, 2) # (b, h, t, d)
|
||||
q = apply_rotary_pos_emb_interleaved(q, cos, sin)
|
||||
|
||||
kv = self.kv_norm(self.kv_proj(hidden_states)) # (b, t, d)
|
||||
kv = kv.view(*kv.shape[:2], 1, self.head_dim) # (b, t, 1, d)
|
||||
kv = apply_rotary_pos_emb_interleaved(kv, cos, sin, unsqueeze_dim=2)
|
||||
if self.cp_context.cp_enabled:
|
||||
kv = gather_for_cp(kv, self.cp_context.cp_group) # (b, T, 1, d)
|
||||
kv = kv.transpose(1, 2) # (b, 1, T, d)
|
||||
# Launch on NCCL's communication stream; query/compressor work does not read KV.
|
||||
kv = torch.ops._c10d_functional.all_gather_into_tensor(
|
||||
kv.movedim(1, 0).contiguous(),
|
||||
self.cp_context.cp_world_size,
|
||||
self.cp_context.cp_group.group_name,
|
||||
)
|
||||
|
||||
q_residual = self.q_a_norm(self.q_a_proj(hidden_states)) # (b, t, r)
|
||||
# Keep the query in the sparse kernel's (batch, tokens, heads, dim) layout.
|
||||
q = self.q_b_norm(self.q_b_proj(q_residual).view(*hidden_shape))
|
||||
q = apply_rotary_pos_emb_interleaved(q, cos, sin, unsqueeze_dim=2)
|
||||
|
||||
compressed = (
|
||||
self.compressor(
|
||||
@@ -736,6 +741,9 @@ class DeepseekV4Attention(nn.Module):
|
||||
else None
|
||||
)
|
||||
compressed_kv, top_k_indices = compressed if compressed is not None else (None, None)
|
||||
if self.cp_context.cp_enabled:
|
||||
kv = funcol.wait_tensor(kv).movedim(0, 1).contiguous() # (b, T, 1, d)
|
||||
kv = kv.transpose(1, 2) # (b, 1, T, d)
|
||||
inputs = SparseAttnInputs.build(
|
||||
kv=kv,
|
||||
compressed_kv=compressed_kv,
|
||||
@@ -743,7 +751,7 @@ class DeepseekV4Attention(nn.Module):
|
||||
window_indices=packed.window_indices,
|
||||
)
|
||||
attn_output, _ = dsv4_sparse_attn(
|
||||
q.transpose(1, 2).contiguous(),
|
||||
q,
|
||||
inputs.kv_buf,
|
||||
inputs.indices,
|
||||
self.sinks,
|
||||
|
||||
@@ -97,7 +97,7 @@ def per_token_group_quant_fp8(
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=8, num_stages=3),
|
||||
triton.Config({"BLOCK_M": 64, "BLOCK_N": 128}, num_warps=8, num_stages=3),
|
||||
],
|
||||
key=["S_Q", "S_K"],
|
||||
key=["S_Q", "S_K_BUCKET", "H", "D"],
|
||||
)
|
||||
@triton.jit
|
||||
def _triton_fp8_indexer_kernel(
|
||||
@@ -116,6 +116,7 @@ def _triton_fp8_indexer_kernel(
|
||||
stride_ws,
|
||||
H: tl.constexpr,
|
||||
D: tl.constexpr,
|
||||
S_K_BUCKET: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
):
|
||||
@@ -168,7 +169,16 @@ def _triton_fp8_indexer_kernel(
|
||||
tl.store(out_ptrs, acc, mask=out_mask)
|
||||
|
||||
|
||||
def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
@torch.library.custom_op("prime_rl::fp8_indexer", mutates_args=())
|
||||
def fp8_indexer(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
w: torch.Tensor,
|
||||
ks: torch.Tensor,
|
||||
ke: torch.Tensor,
|
||||
topk: int,
|
||||
weight_scale: float = 1.0,
|
||||
) -> torch.Tensor:
|
||||
"""Triton FP8 indexer: UE8M0 quantization + fused scoring kernel + topk.
|
||||
|
||||
Args:
|
||||
@@ -221,6 +231,9 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
w.stride(0),
|
||||
H=H,
|
||||
D=D,
|
||||
# Packed document tails change S_k between batches. Reuse tuning within
|
||||
# a size bucket; exact S_k still controls strides and all bounds masks.
|
||||
S_K_BUCKET=triton.next_power_of_2(S_k),
|
||||
)
|
||||
|
||||
actual_topk = min(topk, S_k)
|
||||
@@ -236,3 +249,8 @@ def fp8_indexer(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
indices = indices.masked_fill(out_of_range, S_k)
|
||||
|
||||
return indices.to(torch.int32)
|
||||
|
||||
|
||||
@fp8_indexer.register_fake
|
||||
def _fp8_indexer_fake(q, k, w, ks, ke, topk, weight_scale=1.0):
|
||||
return q.new_empty((q.shape[0], topk), dtype=torch.int32)
|
||||
|
||||
@@ -6,7 +6,8 @@ import torch
|
||||
import triton
|
||||
import triton.language as tl
|
||||
|
||||
FP8_MAX = 448.0
|
||||
FP8_MAX = tl.constexpr(448.0)
|
||||
FP8_MIN = tl.constexpr(-448.0)
|
||||
MIN_SCALE = 1e-4
|
||||
GROUP_ALIGNMENT = 128
|
||||
|
||||
@@ -188,11 +189,11 @@ def _per_token_fp8_kernel(
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x), axis=1)
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
amax = tl.maximum(tl.max(tl.abs(x), axis=1), 1e-10)
|
||||
scale = tl.math.div_rn(amax, FP8_MAX)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[:, None]
|
||||
y = tl.clamp(tl.math.div_rn(x, scale[:, None]), FP8_MIN, FP8_MAX)
|
||||
tl.store(
|
||||
out_ptr + row_offsets_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
|
||||
y.to(tl.float8e4nv),
|
||||
@@ -242,11 +243,11 @@ def _grouped_per_token_fp8_kernel(
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x), axis=1)
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
amax = tl.maximum(tl.max(tl.abs(x), axis=1), 1e-10)
|
||||
scale = tl.math.div_rn(amax, FP8_MAX)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[:, None]
|
||||
y = tl.clamp(tl.math.div_rn(x, scale[:, None]), FP8_MIN, FP8_MAX)
|
||||
tl.store(
|
||||
out_ptr + dst_rows_i64[:, None] * stride_ym + col_offsets_i64[None, :] * stride_yn,
|
||||
y.to(tl.float8e4nv),
|
||||
@@ -295,11 +296,11 @@ def _grouped_per_channel_fp8_kernel(
|
||||
mask=valid_rows[:, None] & valid_cols[None, :],
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x), axis=0)
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
amax = tl.maximum(tl.max(tl.abs(x), axis=0), 1e-10)
|
||||
scale = tl.math.div_rn(amax, FP8_MAX)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale[None, :]
|
||||
y = tl.clamp(tl.math.div_rn(x, scale[None, :]), FP8_MIN, FP8_MAX)
|
||||
flat_base = block_start.to(tl.int64) * BLOCK_K * cols
|
||||
if K_MAJOR:
|
||||
out_ptrs = out_ptr + flat_base + col_offsets_i64[:, None] * aligned_m + row_offsets_i64[None, :]
|
||||
@@ -355,7 +356,7 @@ def _grouped_per_block_fp8_kernel(
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
amax = tl.max(tl.abs(x))
|
||||
scale = tl.maximum(amax / 448.0, 1e-4)
|
||||
scale = tl.maximum(amax / FP8_MAX, 1e-4)
|
||||
if USE_UE8M0:
|
||||
scale = tl.exp2(tl.ceil(tl.log2(scale)))
|
||||
y = x / scale
|
||||
@@ -426,7 +427,7 @@ def per_token_cast_to_fp8_triton(
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=8,
|
||||
BLOCK_M=32,
|
||||
BLOCK_K=gran_k,
|
||||
num_warps=4,
|
||||
)
|
||||
@@ -453,7 +454,7 @@ def grouped_per_token_cast_to_fp8_triton(
|
||||
)
|
||||
if block_to_group.numel() == 0:
|
||||
return out, sf
|
||||
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 8, ceil_div(x.size(1), gran_k))
|
||||
grid = (block_to_group.numel(), GROUP_ALIGNMENT // 32, ceil_div(x.size(1), gran_k))
|
||||
_grouped_per_token_fp8_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
@@ -470,7 +471,7 @@ def grouped_per_token_cast_to_fp8_triton(
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=8,
|
||||
BLOCK_M=32,
|
||||
BLOCK_K=gran_k,
|
||||
GROUP_BLOCK_M=GROUP_ALIGNMENT,
|
||||
num_warps=4,
|
||||
@@ -496,7 +497,8 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
|
||||
if block_to_group.numel() == 0:
|
||||
return out, sf.T
|
||||
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
|
||||
block_n = 16
|
||||
grid = (block_to_group.numel(), ceil_div(x.size(1), block_n))
|
||||
_grouped_per_channel_fp8_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
@@ -514,8 +516,8 @@ def grouped_per_channel_cast_to_fp8_sm90_kmajor_triton(
|
||||
USE_UE8M0=use_ue8m0,
|
||||
K_MAJOR=True,
|
||||
BLOCK_K=gran_k,
|
||||
BLOCK_N=128,
|
||||
num_warps=4,
|
||||
BLOCK_N=block_n,
|
||||
num_warps=2,
|
||||
)
|
||||
return out, sf.T
|
||||
|
||||
@@ -538,7 +540,8 @@ def grouped_per_channel_cast_to_fp8_rowmajor_triton(
|
||||
sf = torch.empty((total_blocks, x.size(1)), device=x.device, dtype=torch.float32)
|
||||
if block_to_group.numel() == 0:
|
||||
return out, sf
|
||||
grid = (block_to_group.numel(), ceil_div(x.size(1), 128))
|
||||
block_n = 64
|
||||
grid = (block_to_group.numel(), ceil_div(x.size(1), block_n))
|
||||
_grouped_per_channel_fp8_kernel[grid](
|
||||
x,
|
||||
block_to_group,
|
||||
@@ -556,7 +559,7 @@ def grouped_per_channel_cast_to_fp8_rowmajor_triton(
|
||||
USE_UE8M0=use_ue8m0,
|
||||
K_MAJOR=False,
|
||||
BLOCK_K=gran_k,
|
||||
BLOCK_N=128,
|
||||
BLOCK_N=block_n,
|
||||
num_warps=4,
|
||||
)
|
||||
return out, sf
|
||||
@@ -672,7 +675,7 @@ def per_token_cast_to_fp8_tp_triton(
|
||||
sf.stride(0),
|
||||
sf.stride(1),
|
||||
USE_UE8M0=use_ue8m0,
|
||||
BLOCK_M=8,
|
||||
BLOCK_M=32,
|
||||
BLOCK_K=gran_k,
|
||||
num_warps=4,
|
||||
)
|
||||
|
||||
@@ -105,8 +105,8 @@ class NemotronHMamba2(nn.Module):
|
||||
bias=config.use_conv_bias,
|
||||
)
|
||||
self.dt_bias = nn.Parameter(torch.empty(self.num_heads))
|
||||
self.A_log = nn.Parameter(torch.log(torch.arange(1, self.num_heads + 1, dtype=torch.float32)))
|
||||
self.D = nn.Parameter(torch.ones(self.num_heads, dtype=torch.float32))
|
||||
self.A_log = nn.Parameter(torch.arange(1, self.num_heads + 1, dtype=torch.get_default_dtype()).log())
|
||||
self.D = nn.Parameter(torch.ones(self.num_heads))
|
||||
self.norm = GatedRMSNorm(
|
||||
self.intermediate_size,
|
||||
group_size=self.intermediate_size // self.num_groups,
|
||||
@@ -142,7 +142,7 @@ class NemotronHMamba2(nn.Module):
|
||||
conv_weight = self.conv1d.weight
|
||||
conv_bias = self.conv1d.bias
|
||||
state_decay = -torch.exp(self.A_log.float())
|
||||
skip = self.D
|
||||
skip = self.D.float()
|
||||
dt_bias = self.dt_bias
|
||||
norm_weight = self.norm.weight
|
||||
|
||||
|
||||
@@ -63,6 +63,10 @@ def test_selective_policy_saves_default_and_custom_targets():
|
||||
_selective_checkpoint_policy(context, torch.ops.aten.topk.default, targets=custom_targets)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
)
|
||||
assert (
|
||||
_selective_checkpoint_policy(context, torch.ops.prime_rl.fp8_indexer.default, targets=custom_targets)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["full", "selective"])
|
||||
@@ -99,6 +103,7 @@ def test_mandatory_policy_only_retains_non_replayable_ops():
|
||||
context = SelectiveCheckpointContext(is_recompute=False)
|
||||
|
||||
assert _mandatory_checkpoint_policy(context, torch.ops.aten.topk.default) is CheckpointPolicy.MUST_SAVE
|
||||
assert _mandatory_checkpoint_policy(context, torch.ops.prime_rl.fp8_indexer.default) is CheckpointPolicy.MUST_SAVE
|
||||
assert (
|
||||
_mandatory_checkpoint_policy(context, torch.ops.prime_rl.record_moe_routing_statistics.default)
|
||||
is CheckpointPolicy.MUST_SAVE
|
||||
|
||||
@@ -1246,6 +1246,12 @@ def test_context_parallel_shards_reproduce_the_whole_row(layer_idx, cp_world_siz
|
||||
for cp_rank, chunk in enumerate(chunks):
|
||||
gather, pending = _fake_gather_for_cp(projections, chunks, cp_rank)
|
||||
monkeypatch.setattr(dsv4_attention, "gather_for_cp", gather)
|
||||
monkeypatch.setattr(
|
||||
torch.ops._c10d_functional,
|
||||
"all_gather_into_tensor",
|
||||
lambda tensor, group_size, group_name: gather(tensor.movedim(0, 1), None).movedim(1, 0).contiguous(),
|
||||
)
|
||||
monkeypatch.setattr(dsv4_attention.funcol, "wait_tensor", lambda tensor: tensor)
|
||||
module.cp_context = CPContext(MagicMock(), cp_rank, cp_world_size, "ring")
|
||||
|
||||
packed = _packed_context(doc_lens, torch.float32, V4FLASH_CONFIG, cp_rank=cp_rank, cp_world_size=cp_world_size)
|
||||
|
||||
@@ -47,3 +47,25 @@ def test_token_tp_cast_matches_materialized_transpose(rows, cols):
|
||||
assert tp_q.is_contiguous()
|
||||
assert torch.equal(tp_q.view(torch.uint8), ref_q.view(torch.uint8))
|
||||
assert torch.equal(tp_s, ref_s)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rows,cols,input_scale",
|
||||
[(256, 256, 1.0), (256, 512, 0.3), (512, 256, 0.02), (1024, 768, 0.02), (384, 128, 0.005)],
|
||||
)
|
||||
def test_token_cast_matches_vllm_cuda_quant(rows, cols, input_scale):
|
||||
"""The per-token cast is *bit-identical* to vLLM's production CUDA quantizer."""
|
||||
pytest.importorskip("vllm")
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import per_token_group_quant_fp8
|
||||
|
||||
torch.manual_seed(rows + cols)
|
||||
x = torch.randn(rows, cols, device="cuda", dtype=torch.bfloat16) * input_scale
|
||||
assert x.is_contiguous()
|
||||
|
||||
ref_q, ref_s = per_token_group_quant_fp8(x, 128, use_ue8m0=False)
|
||||
q, s = per_token_cast_to_fp8_triton(x, False)
|
||||
|
||||
assert q.shape == ref_q.shape == (rows, cols)
|
||||
assert s.shape == ref_s.shape == (rows, cols // 128)
|
||||
assert torch.equal(s, ref_s)
|
||||
assert torch.equal(q.view(torch.uint8), ref_q.view(torch.uint8))
|
||||
|
||||
@@ -125,6 +125,17 @@ def test_nemotron_h_context_parallel_setup_finds_wrapped_mamba_layer():
|
||||
assert mamba_layer.mamba.cp_context.cp_world_size == 2
|
||||
|
||||
|
||||
def test_nemotron_h_mamba_parameters_follow_default_dtype():
|
||||
config = NemotronHConfig(**_BASE, hybrid_override_pattern="ME*E")
|
||||
with torch.device("meta"), default_dtype(torch.bfloat16):
|
||||
model = NemotronHForCausalLM(config)
|
||||
|
||||
mamba = model.model.layers[0].mamba
|
||||
assert isinstance(mamba, NemotronHMamba2)
|
||||
assert mamba.A_log.dtype == torch.bfloat16
|
||||
assert mamba.D.dtype == torch.bfloat16
|
||||
|
||||
|
||||
def test_nemotron_h_no_latent_projection():
|
||||
"""Verify model works without latent projections (moe_latent_size=None)."""
|
||||
prime_config = NemotronHConfig(
|
||||
|
||||
@@ -7740,7 +7740,6 @@ ta = [
|
||||
requires-dist = [
|
||||
{ name = "aiohttp", specifier = ">=3.14.1" },
|
||||
{ name = "anthropic", specifier = ">=1.0.0" },
|
||||
{ name = "datasets", marker = "extra == 'lean'", specifier = ">=3.3.0,<6.0.0" },
|
||||
{ name = "gepa", specifier = ">=0.0.6" },
|
||||
{ name = "h11", specifier = ">=0.16.0" },
|
||||
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.21.0" },
|
||||
@@ -7769,7 +7768,7 @@ requires-dist = [
|
||||
{ name = "typing-extensions", specifier = ">=4.12.2" },
|
||||
{ name = "uvicorn", specifier = ">=0.52.0" },
|
||||
]
|
||||
provides-extras = ["harbor", "lean", "modal", "openenv", "ta"]
|
||||
provides-extras = ["harbor", "modal", "openenv", "ta"]
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [
|
||||
|
||||
Reference in New Issue
Block a user