Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions experiments/evaluation/launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
ModelConfigRef,
ModelRef,
PromptFormat,
RLAttemptRef,
RunStatus,
TaskEvidence,
list_records,
Expand Down Expand Up @@ -176,6 +177,7 @@ class LaunchSpec:
"""Reuse evaluation records for this key and the same resolved configuration."""
run_id: str | None = None
policy_finalization: PolicyFinalization | None = None
rl_attempt: RLAttemptRef | None = None


# EvalDash scans these record roots (`DEFAULT_SCAN_PREFIXES` adds read-only legacy roots).
Expand Down Expand Up @@ -542,6 +544,7 @@ def build_evaluation_batch(
user=user,
version=spec.version,
description=spec.description,
rl_attempt=spec.rl_attempt,
records_prefix=records_prefix,
model=model,
accelerator=accelerator,
Expand Down
6 changes: 5 additions & 1 deletion experiments/evaluation/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from collections.abc import Callable
from dataclasses import dataclass

from evalrecords.records import read_record, record_path
from evalrecords.records import RLAttemptRef, read_record, record_path
from iris.client.client import iris_ctx
from iris.rpc import job_pb2
from marin.evaluation.hardware import default_platform
Expand Down Expand Up @@ -68,6 +68,7 @@ class EvalStepConfig:
federated_cluster: str | None
version: str
instances: int = 1
rl_attempt: RLAttemptRef | None = None


@dataclass(frozen=True)
Expand Down Expand Up @@ -104,6 +105,7 @@ def run_eval_pipeline_step(config: EvalStepConfig) -> EvaluationResult:
federated_cluster=config.federated_cluster,
priority_band=job_pb2.PRIORITY_BAND_INHERIT,
version=config.version,
rl_attempt=config.rl_attempt,
cache_key=None if is_mutable_version(config.version) else config.artifact_path,
)
submitted = launch_group(prepare_evaluation_batch(spec), iris_ctx().client)
Expand All @@ -127,6 +129,7 @@ def eval_step(
version: str,
deps: tuple[ArtifactStep, ...] = (),
resolve_model: Callable[[StepContext], ModelConfig] | None = None,
resolve_rl_attempt: Callable[[StepContext], RLAttemptRef | None] | None = None,
limit: int | None = None,
max_concurrent: int = DEFAULT_EVAL_CONCURRENCY,
instances: int = 1,
Expand Down Expand Up @@ -163,6 +166,7 @@ def build_config(ctx: StepContext) -> EvalStepConfig | EvalStepFingerprint:
submission_cluster=ctx.runtime_arg(_SUBMISSION_CLUSTER_RUNTIME_ARG),
federated_cluster=ctx.runtime_arg(_FEDERATED_CLUSTER_RUNTIME_ARG),
version=version,
rl_attempt=resolve_rl_attempt(ctx) if resolve_rl_attempt is not None else None,
)

return ArtifactStep(
Expand Down
13 changes: 6 additions & 7 deletions experiments/post_training/curriculum_rl/launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
ArtifactHfModel,
IrisSkyRLExecution,
MegatronGeometry,
SkyRLPolicyModel,
SkyRLRetentionPolicy,
SkyRLRolePlan,
SkyRLRun,
Expand All @@ -66,7 +67,7 @@
VALIDATION_FILENAME,
pool_step,
)
from experiments.post_training.skyrl_evaluation import SKYRL_POLICY_LOCATION, skyrl_eval_step
from experiments.post_training.skyrl_evaluation import evaluate_model

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -595,12 +596,10 @@ class CurriculumArm:


def evaluation_model_config(policy: PolicySpec, preset: ScalePreset, name: str) -> ModelConfig:
"""Model configuration for the trained policy checkpoint, from the policy's
``serve_*`` fields and the preset's context window."""
"""Build serving settings from the policy's profile and the preset's context window."""
return ModelConfig(
name=name,
location=SKYRL_POLICY_LOCATION,
tokenizer=policy.tokenizer_uri,
location="",
apply_chat_template=True,
resource_hint=ResourceHint(gpu={GPU_VARIANT: policy.serve_gpus}, memory=policy.serve_memory),
serve=ServeConfig(
Expand Down Expand Up @@ -678,8 +677,8 @@ def build_arm(
evaluation_base_name = f"evals/{evaluation_model_name}/{preset.evals}"
evaluation_version = version or resolve_version(evaluation_base_name, None)
evaluation_model = evaluation_model_config(policy, preset, evaluation_model_name)
evaluation = skyrl_eval_step(
rl,
evaluation = evaluate_model(
SkyRLPolicyModel(rl),
evaluation_model,
resolve_evaluations(preset.evals),
version=evaluation_version,
Expand Down
10 changes: 5 additions & 5 deletions experiments/post_training/iceball_micro.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
ArtifactDataSource,
ArtifactHfModel,
IrisSkyRLExecution,
SkyRLPolicyModel,
SkyRLRetentionPolicy,
SkyRLRolePlan,
SkyRLRun,
Expand All @@ -68,7 +69,7 @@

from experiments.evaluation.evals import resolve_evaluations
from experiments.evaluation.pipeline import EvaluationResult
from experiments.post_training.skyrl_evaluation import SKYRL_POLICY_LOCATION, skyrl_eval_step
from experiments.post_training.skyrl_evaluation import evaluate_model
from experiments.sft.launcher import DatasetSpec, LevanterCheckpointModel, SFTSpec, resources_from_accelerator, sft_step

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -445,8 +446,7 @@ def build_workflow(*, version: str | None = None) -> IceballMicroWorkflow:
evaluation_version = version or resolve_version(evaluation_name, None)
evaluation_model = ModelConfig(
name=ICEBALL_MODEL_NAME,
location=SKYRL_POLICY_LOCATION,
tokenizer=QWEN_TOKENIZER,
location="",
apply_chat_template=True,
resource_hint=ResourceHint(gpu={ICEBALL_GPU_VARIANT: 1}),
serve=ServeConfig(
Expand All @@ -459,8 +459,8 @@ def build_workflow(*, version: str | None = None) -> IceballMicroWorkflow:
),
generation=GenerationConfig(max_gen_toks=256),
)
evaluation = skyrl_eval_step(
rl,
evaluation = evaluate_model(
SkyRLPolicyModel(rl),
evaluation_model,
resolve_evaluations(ICEBALL_EVALS),
version=evaluation_version,
Expand Down
77 changes: 74 additions & 3 deletions experiments/post_training/rl.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@

from __future__ import annotations

import io
import json
import logging
import os
import subprocess
import sys
import tarfile
import tempfile
import time
from collections.abc import Callable, Sequence
Expand All @@ -37,7 +39,7 @@
from marin.execution.step_status import get_status_path
from marin.experiment.cli import build_options_with_runner
from marin.experiment.namespacing import user_owned_name
from marin.rl.cli import RUN_INDEX_ENV, submit_or_run, validate_coordinator_graph
from marin.rl.cli import BASE_PRESET_REVISION_ENV, RUN_INDEX_ENV, submit_or_run, validate_coordinator_graph
from marin.rl.skyrl import (
IRIS_HUB_CLUSTER_CONFIG,
SkyRLModelSource,
Expand Down Expand Up @@ -118,13 +120,15 @@ def _run_rl(
index = _SUBMITTED_INDEX.validate_json(metadata).get(config.run_id) if metadata is not None else None
if issue is not None or index is not None:
issue = rl_publication.reserve_issue(config.output.export_root, issue)
base_revision = os.environ.get(BASE_PRESET_REVISION_ENV) if index is not None else None
write_attempt(
config.output.export_root,
AttemptRecord(
run_id=config.run_id,
attempt_id=config.attempt_id,
issue=issue,
index=index,
base_preset_revision=base_revision or None,
),
)
return run_skyrl(config, forward_env=forward_env)
Expand Down Expand Up @@ -431,6 +435,69 @@ def run_index_identity(
)


def _base_preset_revision(module: str, model: str, preset: str, source_revision: str) -> str | None:
root = recipe.REPO_ROOT
program = """
import sys
from importlib import import_module
from pathlib import Path
from experiments.post_training.rl_presets import ModelPresets

module, model, preset = sys.argv[1:]
entry = import_module(module)
if not Path(entry.__file__).resolve().is_relative_to(Path.cwd()):
raise ImportError(f"{module} did not load from the main snapshot")
revisions = {value.by_name[preset].revision for value in vars(entry).values()
if isinstance(value, ModelPresets) and value.model == model and preset in value.by_name}
if len(revisions) == 1:
print(revisions.pop())
"""
try:
base = git_output(["merge-base", source_revision, "origin/main"], cwd=root, timeout=4)
except (OSError, RuntimeError):
logger.debug("Git could not resolve the main merge base for preset %s", preset)
return None
try:
snapshot = subprocess.run(
[
"git",
"archive",
base,
"experiments/__init__.py",
"experiments/post_training",
"experiments/evaluation",
"pyproject.toml",
"infra/marina/apps/rl_progress/applet.toml",
"lib",
],
cwd=root,
capture_output=True,
check=True,
timeout=8,
).stdout
with tempfile.TemporaryDirectory(prefix="rl-main-base-") as directory:
path = Path(directory)
with tarfile.open(fileobj=io.BytesIO(snapshot)) as archive:
archive.extractall(path, filter="data")
result = subprocess.run(
[sys.executable, "-c", program, module, model, preset],
text=True,
capture_output=True,
check=True,
cwd=path,
env={
"PATH": os.defpath,
"PYTHONNOUSERSITE": "1",
"PYTHONPATH": os.pathsep.join(str(source) for source in sorted(path.glob("lib/*/src"))),
},
timeout=30,
)
return result.stdout.strip() or None
except (OSError, subprocess.SubprocessError, tarfile.TarError) as error:
logger.debug("Could not load preset %s from main commit %s (%s)", preset, base, type(error).__name__)
return None


class _PublicationWatch(BaseModel):
job: str
preset: str
Expand Down Expand Up @@ -560,13 +627,16 @@ def _submit_from_launcher(
if not module:
raise click.UsageError("submit from python -m MODULE, or pass entry_module to rl.main")
submitted_at = datetime.now(UTC).isoformat()
index = context.meta["rl_index"].model_copy(update={"submitted_at": submitted_at})
index: RunIndexIdentity = context.meta["rl_index"]
base_preset_revision = _base_preset_revision(module, index.model, index.preset, index.source_revision)
index = index.model_copy(update={"submitted_at": submitted_at})
runs = _from_handles(handles).runs
indexed_runs = {
step.build_config(StepContext.for_fingerprint(step.runtime_args, step.deps)).run_id: index for step in runs
}
metadata = _SUBMITTED_INDEX.dump_json(indexed_runs).decode()
job = submit_or_run(module, handles, max_concurrent, {**os.environ, RUN_INDEX_ENV: metadata}, argv=argv)
environment = {**os.environ, RUN_INDEX_ENV: metadata, BASE_PRESET_REVISION_ENV: base_preset_revision or ""}
job = submit_or_run(module, handles, max_concurrent, environment, argv=argv)
submitted = [
{
"name": step.name,
Expand All @@ -581,6 +651,7 @@ def _submit_from_launcher(
"coordinator_job_id": str(job),
"iris_url": job.dashboard_url(_IRIS_DASHBOARD_URL),
"submitted_at": submitted_at,
"base_preset_revision": base_preset_revision,
"runs": submitted,
}
_print_status(result)
Expand Down
2 changes: 1 addition & 1 deletion experiments/post_training/rl_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -718,7 +718,7 @@ def _write_gate(
update={"attempt_ids": tuple(receipt.attempt_id for receipt in receipts if receipt)}
)
runs = [
with_requirements(with_objectives(read_measurements(path, preset, inputs), preset), inputs.requirements)
with_requirements(with_objectives(read_measurements(path, preset), preset), inputs.requirements)
for path in run_paths
]
if runs:
Expand Down
33 changes: 11 additions & 22 deletions experiments/post_training/rl_measurements.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,17 +298,17 @@ def count(*outcomes: str) -> float:
def _session_invariants(
name: str,
table: pa.Table,
evaluation: presets.Evaluation,
preset: presets.Preset,
expected: int,
task_ids: Sequence[str],
answers_per_task: int,
required_coverage: bool,
) -> list[Invariant]:
rows = table.to_pylist()
counts = Counter(row["task_id"] for row in rows)
holds = len(rows) == expected and set(counts.values()) == {evaluation.answers} and set(counts) == set(task_ids)
expected = len(task_ids) * answers_per_task
holds = len(rows) == expected and set(counts.values()) == {answers_per_task} and set(counts) == set(task_ids)
result = [Invariant(name=f"{name}/answers_complete", value=len(rows), limit=expected, comparator="==", holds=holds)]
if evaluation == preset.guarded or (preset.checkpoint_every and evaluation.held_out):
coverage = len({row["task_id"] for row in rows if row["scored"]}) / (expected // evaluation.answers)
if required_coverage:
coverage = len({row["task_id"] for row in rows if row["scored"]}) / len(task_ids) if task_ids else 0.0
result.append(
Invariant(
name=f"{name}/task_coverage",
Expand Down Expand Up @@ -352,11 +352,7 @@ def evaluation_status(
return EvaluationStatus()
try:
effective = preset.with_updates(launch.max_steps if launch.max_steps is not None else preset.updates)
try:
inputs = read_run_inputs(path)
except FileNotFoundError:
inputs = None
data = read_measurements(path, effective, inputs, attempt=attempt)
data = read_measurements(path, effective, attempt=attempt)
return EvaluationStatus(
evaluations=data.evaluations,
evaluation_invariants=tuple(
Expand All @@ -382,11 +378,9 @@ def training_invariants(preset: presets.Preset, metrics: Mapping[int, Mapping[st
def read_measurements(
path: str,
preset: presets.Preset,
inputs: RunInputs | None = None,
*,
attempt: AttemptRecord | None = None,
) -> RunMeasurements:
inputs = inputs or RunInputs(preset_name=preset.name)
terminal = attempt or read_skyrl_attempt(path)
if terminal is None:
raise FileNotFoundError(f"no terminal attempt record at {path}")
Expand Down Expand Up @@ -414,19 +408,16 @@ def read_measurements(
}
except (KeyError, TypeError, ValueError) as error:
raise InvalidComparison(f"recorded evaluation identity is malformed: {error}") from error
default, selection = recipe.task_selections(
preset, recipe.selection_artifact(inputs.tasks) if inputs.tasks else None
)
task_set = preset.held_out_tasks if preset.held_out is not None else None
scores, initial_scores = [ANSWER_SCHEMA.empty_table()], []
evaluations = []
response_token_counts: set[int | None] = set()
primary_answers = 0
for index, evaluation in enumerate(preset.evaluations):
quality = evaluation.held_out and (evaluation == preset.guarded or bool(preset.checkpoint_every))
expected = recipe.evaluation_answer_count(
evaluation, recipe.evaluation_source(evaluation, selection, default, preset.held_out_tasks)
)
required_coverage = evaluation == preset.guarded or bool(preset.checkpoint_every and evaluation.held_out)
recorded_tasks = recorded_task_sets[evaluation.name].task_ids
recorded_answers = identities[evaluation.name][1]["n_samples_per_prompt"]
all_scores = read_answers(evaluation, path, launch=launch, attempt=terminal)
if index == 0:
primary_answers = all_scores.num_rows
Expand Down Expand Up @@ -466,9 +457,7 @@ def read_measurements(
)
)
invariants.extend(
_session_invariants(
session_name, session, evaluation, preset, expected, recorded_task_sets[evaluation.name].task_ids
)
_session_invariants(session_name, session, recorded_tasks, recorded_answers, required_coverage)
)
if quality:
invariants.append(
Expand Down
Loading
Loading