Skip to content

Python API

The command-line interface is HarborRL's primary user surface. harborrl.config explicitly declares its public exports. The additional symbols below are curated, CPU-testable integration contracts used by adapters and tests; they may evolve with the native contract version.

Configuration

harborrl.config

Native schema-2 configuration loading.

load_config

load_config(path, overrides=None, task_ids=None)
Source code in harborrl/config/__init__.py
def load_config(path, overrides=None, task_ids=None):
    from .native import load_config as _load_config

    return _load_config(path, overrides, task_ids)

launch_plan

launch_plan(config)
Source code in harborrl/config/__init__.py
def launch_plan(config):
    from .native import launch_plan as _launch_plan

    return _launch_plan(config)

MATH registry

harborrl.math_registry

Explicit MATH component contracts and startup compatibility checks.

ModelSpec dataclass

Source code in harborrl/math_registry.py
@dataclass(frozen=True)
class ModelSpec:
    id: str
    display_name: str
    preset_prefix: str
    serving_backend: str
    tool_protocol: str
    gateway_protocols: frozenset[str]
    training_backend_contracts: frozenset[str]
    adapter: QwenModelAdapter
    version: str
    evidence: tuple[str, ...]
    limitations: tuple[str, ...]

AlgorithmSpec dataclass

Source code in harborrl/math_registry.py
@dataclass(frozen=True)
class AlgorithmSpec:
    id: str
    display_name: str
    training_backend_contracts: frozenset[str]
    minimum_group_size: int
    requires_audited_raw_logprobs: bool
    reduction: str
    adapter: GRPOAlgorithmAdapter
    backend_hooks: dict[str, str]
    version: str
    evidence: tuple[str, ...]
    limitations: tuple[str, ...]

TaskProviderSpec dataclass

Source code in harborrl/math_registry.py
@dataclass(frozen=True)
class TaskProviderSpec:
    id: str
    display_name: str
    execution_backends: frozenset[str]
    task_format: str
    adapter: TaskProviderAdapter
    version: str
    evidence: tuple[str, ...]
    limitations: tuple[str, ...]

HarnessSpec dataclass

Source code in harborrl/math_registry.py
@dataclass(frozen=True)
class HarnessSpec:
    id: str
    display_name: str
    request_protocol: str
    tool_protocol: str
    harbor_versions: frozenset[str]
    adapter: ClaudeCodeHarnessAdapter
    version: str
    evidence: tuple[str, ...]
    limitations: tuple[str, ...]

MATHSelection dataclass

Source code in harborrl/math_registry.py
@dataclass(frozen=True)
class MATHSelection:
    model: ModelSpec
    algorithm: AlgorithmSpec
    task: TaskProviderSpec
    harness: HarnessSpec

    def asdict(self):
        return {
            "model": _describe(self.model),
            "algorithm": _describe(self.algorithm),
            "task": _describe(self.task),
            "harness": _describe(self.harness),
        }

select_math

select_math(config)
Source code in harborrl/math_registry.py
def select_math(config):
    return MATHSelection(
        model=MATH_REGISTRY.model_for_preset(config["model"]["args_file"]),
        algorithm=MATH_REGISTRY.algorithm_for_contract(
            config["training"]["backend_contract"]
        ),
        task=MATH_REGISTRY.tasks.get(
            "harbor_jsonl"
            if str(config.get("tasks", {}).get("catalog", "")).endswith(".jsonl")
            else "native_harbor"
        ),
        harness=MATH_REGISTRY.harnesses.get(config["harness"]["name"]),
    )

validate_combination

validate_combination(selection, config)
Source code in harborrl/math_registry.py
def validate_combination(selection, config):
    contract = config["training"]["backend_contract"]
    if contract not in selection.model.training_backend_contracts:
        raise ValueError(
            f"model {selection.model.id} does not support training backend {contract}"
        )
    if contract not in selection.algorithm.training_backend_contracts:
        raise ValueError(
            f"algorithm {selection.algorithm.id} does not support training backend {contract}"
        )
    if config["execution"]["backend"] not in selection.task.execution_backends:
        raise ValueError(
            f"task provider {selection.task.id} does not support execution backend "
            f"{config['execution']['backend']}"
        )
    if config["harbor"]["version"] not in selection.harness.harbor_versions:
        raise ValueError(
            f"harness {selection.harness.id} does not support Harbor "
            f"{config['harbor']['version']}"
        )
    if selection.model.tool_protocol != selection.harness.tool_protocol:
        raise ValueError("model and harness tool protocols do not match")
    if selection.harness.request_protocol not in selection.model.gateway_protocols:
        raise ValueError(
            f"model gateway does not support harness protocol {selection.harness.request_protocol}"
        )
    if config["sampling"]["group_size"] < selection.algorithm.minimum_group_size:
        raise ValueError(
            f"algorithm {selection.algorithm.id} requires group size >= "
            f"{selection.algorithm.minimum_group_size}"
        )
    if (
        selection.algorithm.requires_audited_raw_logprobs
        and not config["gateway"]["audited_raw_logprobs"]
    ):
        raise ValueError(
            f"algorithm {selection.algorithm.id} requires audited raw logprobs"
        )
    return selection

list_components

list_components()
Source code in harborrl/math_registry.py
def list_components():
    return {
        dimension: [_describe(spec) for spec in registry.items()]
        for dimension, registry in (
            ("models", MATH_REGISTRY.models),
            ("algorithms", MATH_REGISTRY.algorithms),
            ("tasks", MATH_REGISTRY.tasks),
            ("harnesses", MATH_REGISTRY.harnesses),
        )
    }

Task providers

harborrl.tasks.provider.NativeTaskProvider

Source code in harborrl/tasks/provider.py
class NativeTaskProvider:
    provider_id = "native_harbor"

    def discover(self, tasks_dir):
        return sorted(path.parent for path in Path(tasks_dir).rglob("task.toml"))

    def inspect(self, path, *, expected_digest=None):
        return inspect_native(path, expected_digest=expected_digest)

    def catalog(self, config):
        path = Path(config["tasks"]["catalog"])
        entries = read_json(path)
        if not isinstance(entries, list) or not entries:
            raise ValueError("catalog must be a nonempty JSON list")
        seen = set()
        for entry in entries:
            if (
                not isinstance(entry, dict)
                or set(entry)
                != {"id", "revision", "path", "task_digest", "reward_profile"}
                or not isinstance(entry["id"], str)
                or not entry["id"].strip()
                or not isinstance(entry["revision"], str)
                or not entry["revision"].strip()
                or entry["id"] in seen
            ):
                raise ValueError("invalid or duplicate catalog identity")
            if (
                not isinstance(entry["path"], str)
                or not entry["path"].strip()
                or not isinstance(entry["task_digest"], str)
                or not re.fullmatch(r"[0-9a-f]{64}", entry["task_digest"])
                or not isinstance(entry["reward_profile"], dict)
            ):
                raise ValueError(f'invalid native task lock: {entry["id"]}')
            seen.add(entry["id"])
            entry["path"] = str((path.parent / entry["path"]).resolve())
            report = self.inspect(entry["path"], expected_digest=entry["task_digest"])
            if report["status"] != "NEEDS_PROBE":
                raise ValueError(
                    f'task preflight failed: {entry["id"]}: {report["reasons"]}'
                )
            RewardProfile(**entry["reward_profile"])
        selected = set(getattr(config, "task_ids", ()))
        if selected:
            missing = selected - {entry["id"] for entry in entries}
            if missing:
                raise ValueError(f"task selector not found in catalog: {min(missing)}")
            entries = [entry for entry in entries if entry["id"] in selected]
        return entries

    def prompt_rows(self, entries):
        rows = []
        for entry in entries:
            instruction = (Path(entry["path"]) / "instruction.md").read_text()
            rows.append(
                {
                    "task": instruction,
                    "metadata": {"harborrl_native": True, "native_task": entry},
                }
            )
        return rows

harborrl.tasks.jsonl_provider.JsonlTaskProvider

Source code in harborrl/tasks/jsonl_provider.py
class JsonlTaskProvider:
    provider_id = "harbor_jsonl"

    def discover(self, tasks_dir):
        return sorted(path.parent for path in Path(tasks_dir).rglob("task.toml"))

    def inspect(self, path, *, expected_digest=None):
        return inspect_native(path, expected_digest=expected_digest)

    def catalog(self, config):
        path = Path(config["tasks"]["catalog"])
        entries, seen = [], set()
        with path.open(encoding="utf-8") as source:
            for line_number, line in enumerate(source, start=1):
                if not line.strip():
                    raise ValueError(f"blank JSONL catalog line: {line_number}")
                try:
                    entry = json.loads(line)
                except json.JSONDecodeError as exc:
                    raise ValueError(
                        f"invalid JSONL catalog line {line_number}: {exc.msg}"
                    ) from exc
                if (
                    not isinstance(entry, dict)
                    or set(entry)
                    != {"id", "revision", "path", "task_digest", "reward_profile"}
                    or not isinstance(entry["id"], str)
                    or not entry["id"].strip()
                    or not isinstance(entry["revision"], str)
                    or not entry["revision"].strip()
                    or entry["id"] in seen
                ):
                    raise ValueError(
                        f"invalid or duplicate JSONL catalog identity: {line_number}"
                    )
                if (
                    not isinstance(entry["path"], str)
                    or not entry["path"].strip()
                    or not isinstance(entry["task_digest"], str)
                    or not re.fullmatch(r"[0-9a-f]{64}", entry["task_digest"])
                    or not isinstance(entry["reward_profile"], dict)
                ):
                    raise ValueError(f'invalid native task lock: {entry["id"]}')
                seen.add(entry["id"])
                entry["path"] = str((path.parent / entry["path"]).resolve())
                report = self.inspect(
                    entry["path"], expected_digest=entry["task_digest"]
                )
                if report["status"] != "NEEDS_PROBE":
                    raise ValueError(
                        f'task preflight failed: {entry["id"]}: {report["reasons"]}'
                    )
                RewardProfile(**entry["reward_profile"])
                entries.append(entry)
        if not entries:
            raise ValueError("catalog must contain at least one JSONL task lock")
        selected = set(getattr(config, "task_ids", ()))
        if selected:
            missing = selected - {entry["id"] for entry in entries}
            if missing:
                raise ValueError(
                    f"task selector not found in catalog: {min(missing)}"
                )
            entries = [entry for entry in entries if entry["id"] in selected]
        return entries

    def prompt_rows(self, entries):
        rows = []
        for entry in entries:
            instruction = (Path(entry["path"]) / "instruction.md").read_text()
            rows.append(
                {
                    "task": instruction,
                    "metadata": {
                        "harborrl_native": True,
                        "task_provider": self.provider_id,
                        "native_task": entry,
                    },
                }
            )
        return rows

Native trajectory contracts

harborrl.trajectories.native

Strict, runtime-independent contracts for native trajectories (IR v2).

Identity dataclass

Source code in harborrl/trajectories/native.py
@dataclass(frozen=True)
class Identity:
    run_id: str
    batch_id: str
    group_id: str
    slot_id: str
    attempt_id: str
    trajectory_id: str
    task_digest: str
    policy_version: str
    harness_digest: str
    reward_digest: str
    sampling_digest: str

    def __post_init__(self):
        if any(not isinstance(v, str) or not v.strip() for v in asdict(self).values()):
            raise ValueError("identity fields must be nonempty strings")

    def to_dict(self):
        return asdict(self)

    @property
    def group_key(self):
        value = self.to_dict()
        for key in ("slot_id", "attempt_id", "trajectory_id"):
            value.pop(key)
        return digest(value)

RewardProfile dataclass

Source code in harborrl/trajectories/native.py
@dataclass(frozen=True)
class RewardProfile:
    key: str = "reward"
    scale: float = 1.0
    offset: float = 0.0
    raw_range: tuple[float, float] | None = (0.0, 1.0)

    def __post_init__(self):
        if not isinstance(self.key, str) or not self.key:
            raise ValueError("reward key is required")
        if not finite(self.scale) or not finite(self.offset):
            raise ValueError("reward transform must be finite")
        if self.raw_range is not None:
            if (len(self.raw_range) != 2 or not all(finite(x) for x in self.raw_range)
                    or self.raw_range[0] > self.raw_range[1]):
                raise ValueError("invalid raw reward range")
            object.__setattr__(self, "raw_range", tuple(self.raw_range))

    @property
    def digest(self):
        return digest(asdict(self))

    def resolve(self, rewards):
        if not isinstance(rewards, dict) or not rewards or any(not finite(v) for v in rewards.values()):
            raise ValueError("all raw rewards must be finite numbers, not bools")
        if self.key not in rewards:
            raise ValueError(f"missing selected reward key: {self.key}")
        raw = rewards[self.key]
        if self.raw_range is not None and not self.raw_range[0] <= raw <= self.raw_range[1]:
            raise ValueError("reward outside declared range")
        training = self.scale * raw + self.offset
        if not finite(training):
            raise ValueError("nonfinite transformed reward")
        return {"raw_rewards": rewards, "selected_key": self.key, "raw_reward": raw,
                "training_reward": training, "reward_profile": json.loads(encode(asdict(self))),
                "reward_profile_digest": self.digest}

digest

digest(value)
Source code in harborrl/trajectories/native.py
def digest(value):
    return hashlib.sha256(encode(value)).hexdigest()

read_json

read_json(path)
Source code in harborrl/trajectories/native.py
def read_json(path):
    def reject(value):
        raise ValueError(f"nonfinite JSON constant: {value}")
    def unique(pairs):
        out = {}
        for key, value in pairs:
            if key in out:
                raise ValueError(f"duplicate JSON key: {key}")
            out[key] = value
        return out
    return json.loads(Path(path).read_bytes(), parse_constant=reject, object_pairs_hook=unique)

publish

publish(path, value)

Publish once, idempotently; concurrent conflicting writers never overwrite.

Source code in harborrl/trajectories/native.py
def publish(path, value):
    """Publish once, idempotently; concurrent conflicting writers never overwrite."""
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    payload = encode(value) + b"\n"
    fd, temp = tempfile.mkstemp(prefix=".pending-", dir=path.parent)
    try:
        with os.fdopen(fd, "wb") as stream:
            stream.write(payload)
            stream.flush()
            os.fsync(stream.fileno())
        try:
            os.link(temp, path)
        except FileExistsError:
            if path.read_bytes() != payload:
                raise ValueError(f"conflicting immutable record: {path.name}")
        if os.name == "posix":
            directory = os.open(path.parent, os.O_RDONLY)
            try:
                os.fsync(directory)
            finally:
                os.close(directory)
    finally:
        os.unlink(temp)
    return path

validate_v2

validate_v2(ir)

Recompute eligibility; never trust a caller-supplied readiness flag.

Source code in harborrl/trajectories/native.py
def validate_v2(ir):
    """Recompute eligibility; never trust a caller-supplied readiness flag."""
    errors = []
    try:
        identity = Identity(**ir["identity"])
        trial = ir["harbor_trial_id"]
        if ir.get("schema_version") != "2" or not isinstance(trial, str) or not trial:
            errors.append("schema_or_trial")
        receipt, seal, turns = ir["evaluation"], ir["trace_seal"], ir["turns"]
        if receipt.get("identity") != identity.to_dict() or receipt.get("harbor_trial_id") != trial:
            errors.append("evaluation_identity")
        if receipt.get("evaluation_status") != "valid":
            errors.append("evaluation_status")
        profile = RewardProfile(**receipt["reward_profile"])
        resolved = profile.resolve(receipt["raw_rewards"])
        if profile.digest != identity.reward_digest or any(receipt.get(k) != v for k, v in resolved.items()):
            errors.append("reward_recompute")
        if not receipt.get("source_result_digest") or not receipt.get("source_artifact_digest"):
            errors.append("evaluation_evidence")
        if seal.get("identity") != identity.to_dict() or seal.get("harbor_trial_id") != trial:
            errors.append("seal_identity")
        if seal.get("pending_requests") != 0 or seal.get("status") != "sealed" or seal.get("errors"):
            errors.append("trace_not_sealed")
        if not isinstance(turns, list) or not turns:
            errors.append("empty_turns")
            return errors
        request_ids = [t["request_id"] for t in turns]
        if (len(set(request_ids)) != len(request_ids) or seal.get("request_ids") != request_ids
                or seal.get("turns_digest") != digest(turns)):
            errors.append("request_completeness")
        if len({t["response_id"] for t in turns}) != len(turns):
            errors.append("duplicate_response")
        for turn in turns:
            errors.extend(validate_turn(turn, identity, trial))
        if len({(t["tokenizer_digest"], t["template_digest"]) for t in turns}) != 1:
            errors.append("mixed_tokenizer_template")
        if ir.get("termination") not in ("completed", "budget_truncated"):
            errors.append("termination")
        if ir.get("termination") == "budget_truncated" and not ir.get("termination_evidence"):
            errors.append("truncation_evidence")
    except (KeyError, TypeError, ValueError, AttributeError) as exc:
        errors.append(f"malformed_contract:{type(exc).__name__}")
    return sorted(set(errors))

assemble

assemble(
    identity,
    trial_id,
    turns,
    seal,
    receipt,
    *,
    termination="completed",
    termination_evidence=None,
)
Source code in harborrl/trajectories/native.py
def assemble(identity, trial_id, turns, seal, receipt, *, termination="completed", termination_evidence=None):
    ir = {"schema_version": "2", "identity": identity.to_dict(), "harbor_trial_id": trial_id,
          "turns": turns, "trace_seal": seal, "evaluation": receipt, "termination": termination,
          "termination_evidence": termination_evidence}
    errors = validate_v2(ir)
    # Synthetic transport/serving tests are useful but never eligible for real training.
    synthetic = any(t.get("evidence_kind") != "serving" for t in turns) or receipt.get("evidence_kind") != "harbor"
    ir.update(integrity_errors=errors, readiness="EVAL_ONLY" if errors else ("CONTRACT_READY" if synthetic else "RL_READY"))
    return ir

require_ready

require_ready(ir, *, allow_synthetic=False)
Source code in harborrl/trajectories/native.py
def require_ready(ir, *, allow_synthetic=False):
    errors = validate_v2(ir)
    real = (ir.get("evaluation", {}).get("evidence_kind") == "harbor"
            and all(t.get("evidence_kind") == "serving" for t in ir.get("turns", [])))
    if not real and not allow_synthetic:
        errors.append("synthetic_evidence")
    if errors:
        raise ValueError("native IR rejected: " + ", ".join(errors))

Training export contracts

harborrl.export.contract

Backend-neutral schemas for Native IR v2 training export.

The schemas are immutable and dependency free on purpose: Slime, Torch, and Megatron types must stay inside a backend adapter so the same CPU-testable contract can serve future training backends.

TokenSpan dataclass

One policy turn expanded from a Native trajectory.

Source code in harborrl/export/contract.py
@dataclass(frozen=True)
class TokenSpan:
    """One policy turn expanded from a Native trajectory."""

    turn_index: int
    tokens: tuple[int, ...]
    prompt_length: int
    response_length: int
    loss_mask: tuple[bool, ...]
    old_logprobs: tuple[float, ...]
    policy_version: str

    def __post_init__(self):
        object.__setattr__(self, "tokens", _as_tuple(self.tokens, "tokens"))
        object.__setattr__(self, "loss_mask", _as_tuple(self.loss_mask, "loss_mask"))
        object.__setattr__(self, "old_logprobs", _as_tuple(self.old_logprobs, "old_logprobs"))

TrajectoryTrainingUnit dataclass

A complete trajectory with its group-normalized training semantics.

Source code in harborrl/export/contract.py
@dataclass(frozen=True)
class TrajectoryTrainingUnit:
    """A complete trajectory with its group-normalized training semantics."""

    trajectory_id: str
    rollout_id: int
    group_key: str
    reward: float
    advantage: float
    token_count: int
    turns: tuple[TokenSpan, ...]

    def __post_init__(self):
        object.__setattr__(self, "turns", _as_tuple(self.turns, "turns"))

TrainingGroup dataclass

A complete prompt group of exactly group_size trajectories.

Source code in harborrl/export/contract.py
@dataclass(frozen=True)
class TrainingGroup:
    """A complete prompt group of exactly ``group_size`` trajectories."""

    group_key: str
    group_size: int
    reward_mean: float
    reward_std: float
    trajectories: tuple[TrajectoryTrainingUnit, ...]

    def __post_init__(self):
        object.__setattr__(self, "trajectories", _as_tuple(self.trajectories, "trajectories"))

TrainingBatch dataclass

The only object a training backend adapter is allowed to consume.

Source code in harborrl/export/contract.py
@dataclass(frozen=True)
class TrainingBatch:
    """The only object a training backend adapter is allowed to consume."""

    schema_version: str
    groups: tuple[TrainingGroup, ...]
    reduction: str
    policy_versions: frozenset[str]

    def __post_init__(self):
        object.__setattr__(self, "groups", _as_tuple(self.groups, "groups"))
        object.__setattr__(self, "policy_versions", frozenset(self.policy_versions))

harborrl.export.native

Native IR v2 to backend-neutral TrainingBatch export (pure Python).

group_statistics

group_statistics(rewards, *, epsilon=1e-06)

Population mean/std and GRPO advantages for one complete group.

Source code in harborrl/export/native.py
def group_statistics(rewards, *, epsilon=1e-6):
    """Population mean/std and GRPO advantages for one complete group."""
    values = list(rewards)
    if len(values) < 2:
        raise ValueError("a complete group of at least two trajectories is required")
    if any(not finite(value) for value in values):
        raise ValueError("nonfinite group statistics")
    if not finite(epsilon) or epsilon <= 0:
        raise ValueError("epsilon must be positive and finite")
    mean = math.fsum(values) / len(values)
    std = math.sqrt(math.fsum((value - mean) ** 2 for value in values) / len(values))
    if not finite(mean) or not finite(std):
        raise ValueError("nonfinite group statistics")
    advantages = [0.0 if std == 0 else (value - mean) / (std + epsilon) for value in values]
    return mean, std, advantages

export_training_batch

export_training_batch(
    ir_groups,
    *,
    group_size=None,
    rollout_ids=None,
    rollout_id_base=0,
    epsilon=1e-06,
    allow_synthetic=False,
) -> TrainingBatch

Validate complete Native IR groups and export immutable training units.

Source code in harborrl/export/native.py
def export_training_batch(
    ir_groups,
    *,
    group_size=None,
    rollout_ids=None,
    rollout_id_base=0,
    epsilon=1e-6,
    allow_synthetic=False,
) -> TrainingBatch:
    """Validate complete Native IR groups and export immutable training units."""
    groups = [list(group) for group in ir_groups]
    if not groups:
        raise ValueError("native training batch requires at least one group")
    ids = _rollout_ids(groups, rollout_ids, rollout_id_base)
    exported_groups = []
    policy_versions = set()
    for trajectories, rollout_id in zip(groups, ids):
        if group_size is None:
            expected_size = len(trajectories)
        else:
            expected_size = group_size
            if type(expected_size) is not int:
                raise ValueError("group_size must be an integer")
        if expected_size < 2 or len(trajectories) != expected_size:
            raise ValueError("a complete group of at least two trajectories is required")
        for ir in trajectories:
            require_ready(ir, allow_synthetic=allow_synthetic)
        identities = [Identity(**ir["identity"]) for ir in trajectories]
        if len({identity.group_key for identity in identities}) != 1:
            raise ValueError("mixed group, policy, task or profiles")
        for key in ("slot_id", "attempt_id", "trajectory_id"):
            if len({getattr(identity, key) for identity in identities}) != expected_size:
                raise ValueError(f"duplicate {key}")
        rewards = [ir["evaluation"]["training_reward"] for ir in trajectories]
        mean, std, advantages = group_statistics(rewards, epsilon=epsilon)
        units = []
        for ir, identity, reward, advantage in zip(trajectories, identities, rewards, advantages):
            turns = []
            token_count = 0
            for turn_index, turn in enumerate(ir["turns"]):
                prompt = turn["input_ids"]
                response = turn["output_ids"]
                turns.append(TokenSpan(
                    turn_index=turn_index,
                    tokens=prompt + response,
                    prompt_length=len(prompt),
                    response_length=len(response),
                    loss_mask=[False] * len(prompt) + [True] * len(response),
                    old_logprobs=turn["logprobs"],
                    policy_version=identity.policy_version,
                ))
                token_count += len(response)
            units.append(TrajectoryTrainingUnit(
                trajectory_id=identity.trajectory_id,
                rollout_id=rollout_id,
                group_key=identity.group_key,
                reward=float(reward),
                advantage=float(advantage),
                token_count=token_count,
                turns=tuple(turns),
            ))
            policy_versions.add(identity.policy_version)
        exported_groups.append(TrainingGroup(
            group_key=identities[0].group_key,
            group_size=expected_size,
            reward_mean=mean,
            reward_std=std,
            trajectories=tuple(units),
        ))
    batch = TrainingBatch(
        schema_version=SCHEMA_VERSION,
        groups=tuple(exported_groups),
        reduction=REDUCTION,
        policy_versions=frozenset(policy_versions),
    )
    validate_batch(batch, epsilon=epsilon)
    return batch

harborrl.export.validate

Fail-closed validation for backend-neutral training batches.

validate_token_span

validate_token_span(span: TokenSpan)
Source code in harborrl/export/validate.py
def validate_token_span(span: TokenSpan):
    _plain_int(span.turn_index, "turn_index")
    if span.turn_index < 0:
        raise ValueError("turn_index must be nonnegative")
    _plain_int(span.prompt_length, "prompt_length")
    _plain_int(span.response_length, "response_length")
    if span.prompt_length < 1 or span.response_length < 1:
        raise ValueError("a token span requires prompt and response tokens")
    if len(span.tokens) != span.prompt_length + span.response_length:
        raise ValueError("token length differs from prompt plus response length")
    if any(type(token) is not int or token < 0 for token in span.tokens):
        raise ValueError("tokens must be nonnegative integers")
    if len(span.loss_mask) != len(span.tokens):
        raise ValueError("loss mask length differs from token length")
    if any(type(flag) is not bool for flag in span.loss_mask):
        raise ValueError("loss mask entries must be booleans")
    if any(flag for flag in span.loss_mask[:span.prompt_length]):
        raise ValueError("prompt tokens must not enter the policy loss")
    if not all(span.loss_mask[span.prompt_length:]):
        raise ValueError("native response tokens must all be trainable")
    if len(span.old_logprobs) != span.response_length:
        raise ValueError("old logprob length differs from response length")
    if any(not finite(value) or value > 0 for value in span.old_logprobs):
        raise ValueError("old logprobs must be finite and nonpositive")
    _nonempty_str(span.policy_version, "policy_version")

validate_trajectory

validate_trajectory(unit: TrajectoryTrainingUnit)
Source code in harborrl/export/validate.py
def validate_trajectory(unit: TrajectoryTrainingUnit):
    _nonempty_str(unit.trajectory_id, "trajectory_id")
    _nonempty_str(unit.group_key, "group_key")
    _plain_int(unit.rollout_id, "rollout_id")
    if unit.rollout_id < 0:
        raise ValueError("rollout_id must be nonnegative")
    if not finite(unit.reward) or not finite(unit.advantage):
        raise ValueError("trajectory reward and advantage must be finite")
    _plain_int(unit.token_count, "token_count")
    if not unit.turns:
        raise ValueError("a trajectory requires at least one turn")
    if [span.turn_index for span in unit.turns] != list(range(len(unit.turns))):
        raise ValueError("trajectory turn indices must be dense and ordered")
    versions = set()
    for span in unit.turns:
        validate_token_span(span)
        versions.add(span.policy_version)
    if len(versions) != 1:
        raise ValueError("a trajectory mixes policy versions")
    if unit.token_count != sum(span.response_length for span in unit.turns):
        raise ValueError("trajectory token count differs from its turns")

validate_group

validate_group(group: TrainingGroup, *, epsilon=1e-06)
Source code in harborrl/export/validate.py
def validate_group(group: TrainingGroup, *, epsilon=1e-6):
    _nonempty_str(group.group_key, "group_key")
    _plain_int(group.group_size, "group_size")
    if group.group_size < 2 or len(group.trajectories) != group.group_size:
        raise ValueError("a complete group of at least two trajectories is required")
    if not all(unit.group_key == group.group_key for unit in group.trajectories):
        raise ValueError("mixed group, policy, task or profiles")
    trajectory_ids = [unit.trajectory_id for unit in group.trajectories]
    if len(set(trajectory_ids)) != group.group_size:
        raise ValueError("duplicate trajectory_id")
    rollout_ids = [unit.rollout_id for unit in group.trajectories]
    if len(set(rollout_ids)) != 1:
        raise ValueError("one native group must share exactly one rollout id")
    if not finite(group.reward_mean) or not finite(group.reward_std) or group.reward_std < 0:
        raise ValueError("nonfinite or negative group statistics")
    rewards = [unit.reward for unit in group.trajectories]
    mean = math.fsum(rewards) / group.group_size
    std = math.sqrt(math.fsum((reward - mean) ** 2 for reward in rewards) / group.group_size)
    if not math.isclose(mean, group.reward_mean, rel_tol=1e-9, abs_tol=1e-9):
        raise ValueError("group reward mean differs from its trajectories")
    if not math.isclose(std, group.reward_std, rel_tol=1e-9, abs_tol=1e-9):
        raise ValueError("group reward std differs from its trajectories")
    if group.reward_std == 0 and any(unit.advantage != 0.0 for unit in group.trajectories):
        raise ValueError("zero-std groups must produce zero advantages")
    for unit in group.trajectories:
        validate_trajectory(unit)
        weight_sum = math.fsum(
            token_weight(group.group_size, unit.token_count) for span in unit.turns for _ in range(span.response_length)
        )
        if not math.isclose(weight_sum, 1.0 / group.group_size, rel_tol=1e-9, abs_tol=1e-12):
            raise ValueError("trajectory weights must sum to 1 / group_size")

validate_batch

validate_batch(batch: TrainingBatch, *, epsilon=1e-06)
Source code in harborrl/export/validate.py
def validate_batch(batch: TrainingBatch, *, epsilon=1e-6):
    if batch.schema_version != SCHEMA_VERSION:
        raise ValueError(f"unsupported training batch schema: {batch.schema_version}")
    if batch.reduction != REDUCTION:
        raise ValueError(f"unsupported training reduction: {batch.reduction}")
    if not batch.groups:
        raise ValueError("native training batch requires at least one group")
    if len(batch.policy_versions) != 1:
        raise ValueError("incomplete native turns or mixed policy batch")
    group_keys = [group.group_key for group in batch.groups]
    rollout_ids = [group.trajectories[0].rollout_id for group in batch.groups]
    if len(set(group_keys)) != len(group_keys):
        raise ValueError("duplicate native group")
    if len(set(rollout_ids)) != len(rollout_ids):
        raise ValueError("each native group needs a distinct rollout id")
    for group in batch.groups:
        validate_group(group, epsilon=epsilon)
        versions = {span.policy_version for unit in group.trajectories for span in unit.turns}
        if versions != batch.policy_versions:
            raise ValueError("training batch mixes policy versions")

batch_weight_sum

batch_weight_sum(batch: TrainingBatch)

Sum of trajectory weights; each complete group contributes exactly one.

Source code in harborrl/export/validate.py
def batch_weight_sum(batch: TrainingBatch):
    """Sum of trajectory weights; each complete group contributes exactly one."""
    return math.fsum(
        token_weight(group.group_size, unit.token_count)
        for group in batch.groups
        for unit in group.trajectories
        for span in unit.turns
        for _ in range(span.response_length)
    )

Rollout runtime

harborrl.rollout.runtime

Extracted rollout core (P2): gateway, traces and complete groups.

This module owns rollout execution and must not import Slime or Ray: training frameworks live in harborrl.backends.* adapters that build a RolloutRuntimeConfig and hand over a tokenizer. Group semantics, worker scheduling, retries and the RL_READY contract stay exactly as the embedded pipeline enforced them.

RuntimeLifecycleError

Bases: RuntimeError

An async resource was used outside its owning runtime lifecycle.

Source code in harborrl/rollout/runtime.py
class RuntimeLifecycleError(RuntimeError):
    """An async resource was used outside its owning runtime lifecycle."""

CleanupRequiredError

Bases: RuntimeError

Harbor resources must be inspected before admitting more attempts.

Source code in harborrl/rollout/runtime.py
class CleanupRequiredError(RuntimeError):
    """Harbor resources must be inspected before admitting more attempts."""

CleanupAdmission

Source code in harborrl/rollout/runtime.py
class CleanupAdmission:
    def __init__(self, root):
        self.markers = set(Path(root).rglob("cleanup-required.json"))

    def observe(self, root):
        self.markers.update(Path(root).rglob("cleanup-required.json"))

    def check(self):
        self.markers = {path for path in self.markers if path.exists()}
        if self.markers:
            paths = ", ".join(str(path) for path in sorted(self.markers))
            raise CleanupRequiredError(
                "rollout cleanup unresolved; automatic retry blocked. "
                "Inspect Harbor resources, then remove resolved cleanup-required.json "
                f"markers before resuming: {paths}")

RolloutRuntimeConfig dataclass

Deployment-independent description of one run's rollout machinery.

Source code in harborrl/rollout/runtime.py
@dataclass(frozen=True)
class RolloutRuntimeConfig:
    """Deployment-independent description of one run's rollout machinery."""

    run_id: str
    run_root: str
    catalog_path: str
    profile_path: str
    gateway_host: str
    gateway_port: int
    gateway_url: str
    runner_python: str
    workers: tuple
    task_worker_overrides: dict
    max_attempts: int
    max_output_tokens: int
    max_context: int
    concurrency_limit: int
    group_size: int
    expected_tokenizer_digest: str
    expected_template_digest: str
    audited_raw_logprobs: bool
    drain_timeout: float
    model_tag: str
    endpoint: str
    sandbox: dict = None
    runner_transport: str = 'ssh'

    @staticmethod
    def _required(env, name):
        value = env.get(name)
        if not isinstance(value, str) or not value.strip():
            raise ValueError(f"rollout runtime requires {name}")
        return value

    @classmethod
    def from_environment(cls, env, *, endpoint, concurrency_limit, group_size,
                         gateway_host=None, gateway_port=None, gateway_url=None,
                         workers=None, runner_python=None):
        if not isinstance(endpoint, str) or not endpoint.strip():
            raise ValueError("rollout runtime requires a serving endpoint")
        if type(group_size) is not int or group_size < 2:
            raise ValueError("rollout runtime requires a group size of at least two")
        if workers is None:
            workers = json.loads(cls._required(env, "HARBORRL_NATIVE_RUNNER_WORKERS"))
        if runner_python is None:
            runner_python = cls._required(env, "HARBORRL_NATIVE_RUNNER_PYTHON")
        try:
            overrides = json.loads(env.get("HARBORRL_NATIVE_TASK_WORKER_OVERRIDES") or "{}")
        except ValueError as exc:
            raise ValueError("invalid HARBORRL_NATIVE_TASK_WORKER_OVERRIDES") from exc
        return cls(
            run_id=cls._required(env, "RUN_ID"),
            run_root=cls._required(env, "RUN_DIR"),
            catalog_path=cls._required(env, "HARBORRL_NATIVE_CATALOG"),
            profile_path=cls._required(env, "HARBORRL_NATIVE_PROFILE"),
            gateway_host=gateway_host or env.get("HARBORRL_NATIVE_GATEWAY_HOST", "0.0.0.0"),
            gateway_port=int(gateway_port or cls._required(env, "HARBORRL_NATIVE_GATEWAY_PORT")),
            gateway_url=gateway_url or cls._required(env, "HARBORRL_NATIVE_GATEWAY_URL"),
            runner_python=runner_python,
            workers=tuple(workers),
            task_worker_overrides=dict(overrides),
            max_attempts=int(env.get("HARBORRL_NATIVE_MAX_ATTEMPTS", "2")),
            max_output_tokens=int(env.get("ROLLOUT_MAX_RESPONSE_LEN", "8192")),
            max_context=int(env.get("ROLLOUT_MAX_CONTEXT_LEN", "32768")),
            concurrency_limit=max(1, int(concurrency_limit)),
            group_size=int(group_size),
            expected_tokenizer_digest=cls._required(env, "HARBORRL_NATIVE_TOKENIZER_DIGEST"),
            expected_template_digest=cls._required(env, "HARBORRL_NATIVE_TEMPLATE_DIGEST"),
            audited_raw_logprobs=env.get("HARBORRL_NATIVE_AUDITED_LOGPROBS") == "1",
            drain_timeout=float(env.get("HARBORRL_NATIVE_DRAIN_TIMEOUT", "30")),
            model_tag=env.get("MODEL_TAG", env.get("MODEL_ARGS_FILE", "qwen3-8B")),
            endpoint=endpoint.rstrip("/"),
            sandbox=json.loads(env.get('HARBORRL_NATIVE_SANDBOX', 'null')),
            runner_transport=env.get('HARBORRL_NATIVE_RUNNER_TRANSPORT', 'ssh'),
        )

    def environment(self):
        """Render the environment mapping this config was built from."""
        return {
            "RUN_ID": self.run_id, "RUN_DIR": self.run_root,
            "HARBORRL_NATIVE_CATALOG": self.catalog_path,
            "HARBORRL_NATIVE_PROFILE": self.profile_path,
            "HARBORRL_NATIVE_GATEWAY_HOST": self.gateway_host,
            "HARBORRL_NATIVE_GATEWAY_PORT": str(self.gateway_port),
            "HARBORRL_NATIVE_GATEWAY_URL": self.gateway_url,
            "HARBORRL_NATIVE_RUNNER_PYTHON": self.runner_python,
            "HARBORRL_NATIVE_RUNNER_WORKERS": json.dumps(list(self.workers)),
            "HARBORRL_NATIVE_TASK_WORKER_OVERRIDES": json.dumps(
                self.task_worker_overrides, sort_keys=True),
            "HARBORRL_NATIVE_MAX_ATTEMPTS": str(self.max_attempts),
            "ROLLOUT_MAX_RESPONSE_LEN": str(self.max_output_tokens),
            "ROLLOUT_MAX_CONTEXT_LEN": str(self.max_context),
            "HARBORRL_NATIVE_TOKENIZER_DIGEST": self.expected_tokenizer_digest,
            "HARBORRL_NATIVE_TEMPLATE_DIGEST": self.expected_template_digest,
            "HARBORRL_NATIVE_AUDITED_LOGPROBS": str(int(self.audited_raw_logprobs)),
            "HARBORRL_NATIVE_DRAIN_TIMEOUT": str(self.drain_timeout),
            "MODEL_TAG": self.model_tag,
            "HARBORRL_NATIVE_SANDBOX": json.dumps(self.sandbox),
            "HARBORRL_NATIVE_RUNNER_TRANSPORT": self.runner_transport,
        }

environment

environment()

Render the environment mapping this config was built from.

Source code in harborrl/rollout/runtime.py
def environment(self):
    """Render the environment mapping this config was built from."""
    return {
        "RUN_ID": self.run_id, "RUN_DIR": self.run_root,
        "HARBORRL_NATIVE_CATALOG": self.catalog_path,
        "HARBORRL_NATIVE_PROFILE": self.profile_path,
        "HARBORRL_NATIVE_GATEWAY_HOST": self.gateway_host,
        "HARBORRL_NATIVE_GATEWAY_PORT": str(self.gateway_port),
        "HARBORRL_NATIVE_GATEWAY_URL": self.gateway_url,
        "HARBORRL_NATIVE_RUNNER_PYTHON": self.runner_python,
        "HARBORRL_NATIVE_RUNNER_WORKERS": json.dumps(list(self.workers)),
        "HARBORRL_NATIVE_TASK_WORKER_OVERRIDES": json.dumps(
            self.task_worker_overrides, sort_keys=True),
        "HARBORRL_NATIVE_MAX_ATTEMPTS": str(self.max_attempts),
        "ROLLOUT_MAX_RESPONSE_LEN": str(self.max_output_tokens),
        "ROLLOUT_MAX_CONTEXT_LEN": str(self.max_context),
        "HARBORRL_NATIVE_TOKENIZER_DIGEST": self.expected_tokenizer_digest,
        "HARBORRL_NATIVE_TEMPLATE_DIGEST": self.expected_template_digest,
        "HARBORRL_NATIVE_AUDITED_LOGPROBS": str(int(self.audited_raw_logprobs)),
        "HARBORRL_NATIVE_DRAIN_TIMEOUT": str(self.drain_timeout),
        "MODEL_TAG": self.model_tag,
        "HARBORRL_NATIVE_SANDBOX": json.dumps(self.sandbox),
        "HARBORRL_NATIVE_RUNNER_TRANSPORT": self.runner_transport,
    }

RolloutRuntime

One gateway, one trace registry and one rollout root per run.

Source code in harborrl/rollout/runtime.py
class RolloutRuntime:
    """One gateway, one trace registry and one rollout root per run."""

    def __init__(self, config, tokenizer, *, backend=None):
        from harborrl.gateway.server import Gateway, make_server
        from harborrl.gateway.sglang_backend import SGLangBackend
        from harborrl.gateway.trace import TraceRegistry
        from harborrl.math_registry import MATH_REGISTRY

        self.config = config
        self.run_root = Path(config.run_root).resolve()
        self.catalog = read_json(config.catalog_path)
        self.profile = read_json(config.profile_path)
        self.rollout_root = self.run_root / "native-rollouts"
        self.rollout_root.mkdir(parents=True, exist_ok=True)
        self.cleanup = CleanupAdmission(self.rollout_root)
        self.cleanup.check()
        self._loop = None
        self.registry = TraceRegistry(self.run_root / "native-traces")
        self.semaphore = asyncio.Semaphore(config.concurrency_limit)
        if config.sandbox:
            from harborrl.rollout.harbor_job.sandbox_config import SandboxAdmission
            self.sandbox_admission = SandboxAdmission(config.sandbox)
        tokenizer_digest, template_digest = tokenizer_fingerprint(tokenizer)
        if (tokenizer_digest != config.expected_tokenizer_digest
                or template_digest != config.expected_template_digest):
            raise ValueError("live tokenizer/template digest differs from the native lock")
        model = MATH_REGISTRY.model_for_preset(config.model_tag)
        self.backend = backend or SGLangBackend(
            config.endpoint, tokenizer, model.adapter,
            tokenizer_digest=tokenizer_digest, template_digest=template_digest,
            max_context=config.max_context,
            audited_raw_logprobs=config.audited_raw_logprobs,
        )
        gateway = Gateway(self.registry, self.backend, model=self.profile["model"],
                          max_output_tokens=config.max_output_tokens)
        self.server = make_server(gateway, host=config.gateway_host,
                                  port=config.gateway_port)
        self._start_gateway()

    def check_event_loop(self):
        loop = asyncio.get_running_loop()
        if self._loop is None:
            self._loop = loop
        elif self._loop is not loop:
            raise RuntimeLifecycleError("rollout runtime belongs to a different event loop")

    def _start_gateway(self):
        self.thread = threading.Thread(
            target=self.server.serve_forever, name="harborrl-native-gateway", daemon=True
        )
        self.thread.start()

    def close(self):
        self.server.shutdown()
        if getattr(self.thread, "is_alive", lambda: False)():
            self.thread.join(5)
        self.server.server_close()

    def manifest_path(self, identity):
        """Deterministic shared-storage path of one trajectory manifest."""
        if isinstance(identity, dict):
            identity = Identity(**identity)
        return self.rollout_root / identity.group_id / identity.attempt_id / "trajectory.v2.json"

manifest_path

manifest_path(identity)

Deterministic shared-storage path of one trajectory manifest.

Source code in harborrl/rollout/runtime.py
def manifest_path(self, identity):
    """Deterministic shared-storage path of one trajectory manifest."""
    if isinstance(identity, dict):
        identity = Identity(**identity)
    return self.rollout_root / identity.group_id / identity.attempt_id / "trajectory.v2.json"

tokenizer_fingerprint

tokenizer_fingerprint(tokenizer)
Source code in harborrl/rollout/runtime.py
def tokenizer_fingerprint(tokenizer):
    messages = [{"role": "user", "content": "HarborRL native tokenizer/template fingerprint"}]
    kwargs = {"tokenize": True, "add_generation_prompt": True, "enable_thinking": False}
    rendered_ids = normalize_chat_template_ids(
        tokenizer.apply_chat_template(messages, **kwargs))
    vocabulary = tokenizer.get_vocab()
    tokenizer_digest = digest({
        "class": type(tokenizer).__name__,
        "vocab": sorted((str(key), int(value)) for key, value in vocabulary.items()),
    })
    template = digest({"messages": messages, "kwargs": kwargs, "token_ids": rendered_ids})
    return tokenizer_digest, template

runtime async

runtime(config, *, tokenizer=None, tokenizer_loader=None)

Process-wide runtime cache for the embedded GPU-side rollout path.

Source code in harborrl/rollout/runtime.py
async def runtime(config, *, tokenizer=None, tokenizer_loader=None):
    """Process-wide runtime cache for the embedded GPU-side rollout path."""
    global _RUNTIME
    with _RUNTIME_LOCK:
        if _RUNTIME is None:
            if tokenizer is None:
                if tokenizer_loader is None:
                    raise ValueError("runtime requires a tokenizer or a loader")
                tokenizer = tokenizer_loader()
            _RUNTIME = RolloutRuntime(config, tokenizer)
        elif _RUNTIME.config != config:
            raise RuntimeLifecycleError("close the cached rollout runtime before changing its configuration")
        _RUNTIME.check_event_loop()
        return _RUNTIME

run_embedded

run_embedded(coroutine)

Run successive synchronous rollout calls on one Python 3.10-compatible loop.

Source code in harborrl/rollout/runtime.py
def run_embedded(coroutine):
    """Run successive synchronous rollout calls on one Python 3.10-compatible loop."""
    global _EMBEDDED_LOOP, _EMBEDDED_THREAD
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        pass
    else:
        coroutine.close()
        raise RuntimeLifecycleError("synchronous rollout cannot run inside an active event loop")
    with _EMBEDDED_LOCK:
        if _EMBEDDED_LOOP is None:
            _EMBEDDED_LOOP = asyncio.new_event_loop()
            _EMBEDDED_THREAD = threading.get_ident()
        elif _EMBEDDED_THREAD != threading.get_ident():
            coroutine.close()
            raise RuntimeLifecycleError("embedded rollout must stay on its owning thread")
        try:
            return _EMBEDDED_LOOP.run_until_complete(coroutine)
        except BaseException:
            try:
                close_runtime()
            except Exception:
                logging.getLogger(__name__).exception("embedded rollout shutdown failed")
            raise

publish_native_version

publish_native_version(runtime_, states, expected)

Open the next admission epoch only after the complete pool is healthy.

Source code in harborrl/rollout/runtime.py
def publish_native_version(runtime_, states, expected):
    """Open the next admission epoch only after the complete pool is healthy."""
    runtime_.registry.drain(runtime_.config.drain_timeout)
    runtime_.registry.publish_version(states, str(expected))

current_policy_version

current_policy_version(runtime_)

Publish and lock the version currently served by the rollout pool.

Source code in harborrl/rollout/runtime.py
def current_policy_version(runtime_):
    """Publish and lock the version currently served by the rollout pool."""
    states = runtime_.backend.pool_states()
    from harborrl.platform.policy_pool import publish_pool
    version = publish_pool(states)
    runtime_.registry.drain(runtime_.config.drain_timeout)
    runtime_.registry.publish_version(states, version)
    return version

close_runtime

close_runtime()

Drain embedded tasks, close the gateway, then release the owning loop.

Source code in harborrl/rollout/runtime.py
def close_runtime():
    """Drain embedded tasks, close the gateway, then release the owning loop."""
    global _RUNTIME, _EMBEDDED_LOOP, _EMBEDDED_THREAD
    with _EMBEDDED_LOCK:
        loop = _EMBEDDED_LOOP
        if loop is not None and loop.is_running():
            raise RuntimeLifecycleError("close embedded rollout between calls")
        if loop is not None:
            try:
                asyncio.get_running_loop()
            except RuntimeError:
                pass
            else:
                raise RuntimeLifecycleError("close embedded rollout outside an active event loop")

        async def cancel_pending():
            pending = asyncio.all_tasks() - {asyncio.current_task()}
            for task in pending:
                task.cancel()
            await asyncio.gather(*pending, return_exceptions=True)

        try:
            if loop is not None:
                loop.run_until_complete(cancel_pending())
            with _RUNTIME_LOCK:
                cached, _RUNTIME = _RUNTIME, None
                try:
                    if cached is not None:
                        cached.close()
                finally:
                    if loop is not None:
                        loop.run_until_complete(loop.shutdown_asyncgens())
                        loop.run_until_complete(loop.shutdown_default_executor())
        finally:
            if loop is not None:
                loop.close()
            _EMBEDDED_LOOP = None
            _EMBEDDED_THREAD = None

Deployment

harborrl.deployment.schema

Deployment schema v1: machine roles and access, never training semantics.

A deployment config describes WHERE the manager, GPU trainer and rollout workers live and HOW they reach each other. It deliberately excludes every training-side field (learning rate, sampling, task catalog) and never stores secrets: SSH targets must resolve through the invoking user's SSH config, agent or a restricted identity file.

DeploymentError

Bases: ValueError

Raised for any malformed or unsafe deployment configuration.

Source code in harborrl/deployment/schema.py
class DeploymentError(ValueError):
    """Raised for any malformed or unsafe deployment configuration."""

destination

destination(spec)

Render an ssh destination from a normalized spec (user@host).

Source code in harborrl/deployment/schema.py
def destination(spec):
    """Render an ssh destination from a normalized spec (user@host)."""
    return f"{spec['user']}@{spec['host']}" if spec.get("user") else spec["host"]

validate

validate(config)

Strictly validate and normalize a deployment mapping.

Source code in harborrl/deployment/schema.py
def validate(config):
    """Strictly validate and normalize a deployment mapping."""
    if not isinstance(config, dict):
        raise DeploymentError("deployment config must be a mapping")
    if set(config) != DEPLOYMENT_SECTIONS | {"schema_version"}:
        raise DeploymentError(
            "deployment config requires exactly schema_version and "
            + ", ".join(sorted(DEPLOYMENT_SECTIONS)))
    if config["schema_version"] != DEPLOYMENT_SCHEMA_VERSION or type(config["schema_version"]) is not int:
        raise DeploymentError(f"deployment schema_version must be {DEPLOYMENT_SCHEMA_VERSION}")
    return {
        "schema_version": DEPLOYMENT_SCHEMA_VERSION,
        "manager": _manager(config["manager"]),
        "gpu_target": _gpu_target(config["gpu_target"]),
        "storage": _storage(config["storage"]),
        "rollout": _rollout(config["rollout"]),
        "connectivity": _connectivity(config["connectivity"]),
    }

embedded_local

embedded_local(
    *, run_root=None, workers=(), expected_gpus=1
)

Default same-machine deployment; behavior matches the legacy pipeline.

Source code in harborrl/deployment/schema.py
def embedded_local(*, run_root=None, workers=(), expected_gpus=1):
    """Default same-machine deployment; behavior matches the legacy pipeline."""
    return validate({
        "schema_version": 1,
        "manager": {"id": "embedded-local", "mode": "embedded", "bind": "127.0.0.1",
                    "control_port": 49200, "control_url": "http://127.0.0.1:49200",
                    "gateway_port": 49184, "gateway_url": "http://127.0.0.1:49184",
                    "run_token_file": str(ROOT / "runs" / "run-token"),
                    "source_dir": str(ROOT), "controller_python": sys.executable},
        "gpu_target": {"id": "local", "transport": "local", "ssh": None,
                       "source_dir": str(ROOT), "train_python": sys.executable,
                       "environment_file": None, "expected_gpus": expected_gpus},
        "storage": {"mode": "shared_fs", "run_root": run_root or str(ROOT / "runs"),
                    "manager_writable": True, "gpu_writable": True, "worker_writable": True},
        "rollout": {"provider": "embedded", "workers": [
            {"id": f"worker-{index}", "ssh": {"host": worker}, "source_dir": str(ROOT),
             "runner_python": sys.executable, "docker": True, "task_roots": [str(ROOT)]}
            for index, worker in enumerate(workers)]},
        "connectivity": {"command_timeout_s": 30, "ssh_timeout_s": 15, "http_timeout_s": 10,
                         "gpu_to_controller": True, "worker_to_gateway": True,
                         "manager_to_gpu_inference": True},
    })

load_deployment

load_deployment(path=None, *, default_directory='.')

Load an explicit, default-discovered or embedded-local deployment config.

Returns (config, source) where source describes where the config came from; absent any file the embedded-local topology keeps legacy behavior.

Source code in harborrl/deployment/schema.py
def load_deployment(path=None, *, default_directory="."):
    """Load an explicit, default-discovered or embedded-local deployment config.

    Returns ``(config, source)`` where source describes where the config came
    from; absent any file the embedded-local topology keeps legacy behavior.
    """
    if path is not None:
        source = str(Path(path).expanduser())
        candidates = [source]
    else:
        candidates = [str(Path(default_directory) / DEFAULT_FILENAME), DEFAULT_FILENAME]
        source = candidates[0]
    for candidate in candidates:
        file = Path(candidate)
        if not file.is_file():
            continue
        try:
            text = file.read_text()
        except OSError as exc:
            raise DeploymentError(f"cannot read deployment config {candidate}: {exc}") from exc
        try:
            raw = yaml.safe_load(text)
        except yaml.YAMLError as exc:
            raise DeploymentError(f"deployment YAML {candidate}: {exc}") from exc
        return validate(raw), str(file.resolve())
    if path is not None:
        raise DeploymentError(f"deployment config not found: {path}")
    return embedded_local(), "embedded-local"

summary

summary(config, source)

Plan-embedded deployment digest; the full config travels with it.

Source code in harborrl/deployment/schema.py
def summary(config, source):
    """Plan-embedded deployment digest; the full config travels with it."""
    from harborrl.trajectories.native import digest
    return {
        "schema_version": DEPLOYMENT_SCHEMA_VERSION,
        "source": source,
        "digest": digest(config),
        "mode": config["manager"]["mode"],
        "manager_id": config["manager"]["id"],
        "control_url": config["manager"]["control_url"],
        "gateway_url": config["manager"]["gateway_url"],
        "gpu": {"id": config["gpu_target"]["id"], "transport": config["gpu_target"]["transport"]},
        "worker_ids": [worker["id"] for worker in config["rollout"]["workers"]],
        "run_root": config["storage"]["run_root"],
        "config": config,
    }

harborrl.deployment.training_target

TrainingTarget (P1): launch, query and cancel one Slime training job.

local keeps the legacy in-process launcher byte-for-byte. ssh runs the same launcher script on the GPU machine through shared storage: the run directory is written by the manager, executed by the GPU target, and polled without holding an interactive session open.

TrainingTargetError

Bases: RuntimeError

Source code in harborrl/deployment/training_target.py
class TrainingTargetError(RuntimeError):
    pass

LocalTrainingTarget

Legacy target: the Slime job runs as a child of this process.

Source code in harborrl/deployment/training_target.py
class LocalTrainingTarget:
    """Legacy target: the Slime job runs as a child of this process."""

    def __init__(self, command, *, cwd, env):
        self.command = [str(part) for part in command]
        self.cwd = str(cwd)
        self.env = env
        self.child = None

    def launch(self):
        self.child = subprocess.Popen(self.command, cwd=self.cwd, env=self.env,
                                      start_new_session=True)
        return self.child.pid

    def wait(self):
        if self.child is None:
            raise TrainingTargetError("local target was never launched")

        def forward_signal(signum, frame):
            if self.child.poll() is None:
                try:
                    os.killpg(os.getpgid(self.child.pid), signum)
                except ProcessLookupError:
                    pass

        previous = {sig: signal.signal(sig, forward_signal)
                    for sig in (signal.SIGINT, signal.SIGTERM)}
        try:
            return self.child.wait()
        finally:
            for sig, handler in previous.items():
                signal.signal(sig, handler)

    def query(self):
        if self.child is None:
            return {"state": "not-launched"}
        return {"state": "running" if self.child.poll() is None else "exited",
                "exit_code": self.child.returncode}

    def cancel(self):
        if self.child is None or self.child.poll() is not None:
            return False
        try:
            os.killpg(os.getpgid(self.child.pid), signal.SIGINT)
        except (ProcessLookupError, PermissionError):
            self.child.terminate()
        return True

SshTrainingTarget

Remote target over shared storage; the launcher script is the contract.

Source code in harborrl/deployment/training_target.py
class SshTrainingTarget:
    """Remote target over shared storage; the launcher script is the contract."""

    def __init__(self, spec, *, source_dir, run_dir, environment_file=None,
                 command_timeout=60, ssh_timeout=15, poll_interval=2.0):
        self.spec = dict(spec)
        self.source_dir = str(source_dir)
        self.run_dir = Path(run_dir).resolve()
        self.environment_file = environment_file
        self.command_timeout = command_timeout
        self.ssh_timeout = ssh_timeout
        self.poll_interval = poll_interval
        self._launched = False

    def write_launcher(self, command, environment, *, path_rewrites=()):
        """Materialize the launcher; env values and paths are quoted, never interpolated."""
        command = [str(part) for part in command]
        for manager_path, target_path in path_rewrites:
            command = [str(part).replace(str(manager_path), str(target_path), 1)
                       if str(part).startswith(str(manager_path)) else part for part in command]
        lines = ["#!/usr/bin/env bash",
                 "# Generated by the HarborRL manager; executed on the GPU target.",
                 "set -uo pipefail",
                 f"cd {shlex.quote(self.source_dir)}",
                 f"export RUN_DIR={shlex.quote(str(self.run_dir))}"]
        if self.environment_file:
            # A controlled JSON mapping only; never an arbitrary remote shell.
            quoted_file = shlex.quote(str(self.environment_file))
            lines.append(
                "eval \"$(HARBORRL_ENV_FILE=" + quoted_file + " python3 - <<'HARBORRL_ENV_JSON'\n"
                "import json, os, shlex\n"
                "with open(os.environ['HARBORRL_ENV_FILE']) as stream:\n"
                "    for key, value in sorted(json.load(stream).items()):\n"
                "        print(f'export {key}={shlex.quote(str(value))}')\n"
                "HARBORRL_ENV_JSON\n"
                ")\"")
        for key in sorted(environment):
            lines.append(f"export {key}={shlex.quote(str(environment[key]))}")
        lines.append("status=0")
        # The command is a full argv (its first word is already the
        # interpreter); execute it as-is and capture the real exit code.
        lines.append(" ".join(shlex.quote(part) for part in command)
                     + " || status=$?")
        lines.append(f"printf '%s\\n' \"$status\" > {shlex.quote(str(self.run_dir / EXIT_CODE_NAME))}")
        lines.append("exit \"$status\"")
        launcher = self.run_dir / LAUNCHER_NAME
        launcher.write_text("\n".join(lines) + "\n")
        launcher.chmod(0o755)
        return launcher

    def launch(self):
        if self._launched:
            raise TrainingTargetError("ssh target was already launched")
        # The background job records its own session-leader pid: setsid execs
        # the launcher, so the recorded pid heads the cancellable process group.
        bootstrap = (f"cd {shlex.quote(str(self.run_dir))} && "
                     f"(setsid nohup bash {LAUNCHER_NAME} > {STDOUT_NAME} 2>&1"
                     f" < /dev/null & echo $! > {PID_NAME})")
        result = remote.run_ssh(self.spec, bootstrap, timeout=self.command_timeout,
                                connect_timeout=self.ssh_timeout)
        if result.returncode != 0:
            raise TrainingTargetError(
                f"remote launch failed on {destination(self.spec)}: "
                f"{result.stderr.strip()[-500:]}")
        self._launched = True
        return self.run_dir / PID_NAME

    def _pid(self):
        try:
            return int((self.run_dir / PID_NAME).read_text().strip())
        except (OSError, ValueError):
            return None

    def exit_code(self):
        try:
            return int((self.run_dir / EXIT_CODE_NAME).read_text().strip())
        except (OSError, ValueError):
            return None

    def alive(self):
        pid = self._pid()
        if pid is None:
            return False
        result = remote.run_ssh(self.spec, f"kill -0 {pid} 2>/dev/null && echo ok",
                                timeout=self.command_timeout, connect_timeout=self.ssh_timeout)
        return result.returncode == 0 and result.stdout.strip() == "ok"

    def wait(self, *, timeout=None):
        """Poll the shared exit-code record; never resubmit or restart."""
        deadline = None if timeout is None else time.monotonic() + timeout
        while True:
            code = self.exit_code()
            if code is not None:
                return code
            if deadline is not None and time.monotonic() >= deadline:
                raise TimeoutError(f"GPU job in {self.run_dir} did not finish in time")
            time.sleep(self.poll_interval)

    def query(self):
        code = self.exit_code()
        return {"state": "exited" if code is not None else
                ("running" if self.alive() else "unknown"),
                "exit_code": code, "pid": self._pid(),
                "run_dir": str(self.run_dir)}

    def cancel(self, *, grace_seconds=30):
        pid = self._pid()
        if pid is None:
            return False
        for signame in ("INT", "TERM", "KILL"):
            remote.run_ssh(self.spec, f"kill -{signame} -- -{pid} 2>/dev/null || "
                                       f"kill -{signame} {pid} 2>/dev/null || true",
                           timeout=self.command_timeout, connect_timeout=self.ssh_timeout)
            deadline = time.monotonic() + grace_seconds
            while time.monotonic() < deadline:
                if self.exit_code() is not None:
                    return True
                time.sleep(min(2.0, self.poll_interval))
        return self.exit_code() is not None

write_launcher

write_launcher(command, environment, *, path_rewrites=())

Materialize the launcher; env values and paths are quoted, never interpolated.

Source code in harborrl/deployment/training_target.py
def write_launcher(self, command, environment, *, path_rewrites=()):
    """Materialize the launcher; env values and paths are quoted, never interpolated."""
    command = [str(part) for part in command]
    for manager_path, target_path in path_rewrites:
        command = [str(part).replace(str(manager_path), str(target_path), 1)
                   if str(part).startswith(str(manager_path)) else part for part in command]
    lines = ["#!/usr/bin/env bash",
             "# Generated by the HarborRL manager; executed on the GPU target.",
             "set -uo pipefail",
             f"cd {shlex.quote(self.source_dir)}",
             f"export RUN_DIR={shlex.quote(str(self.run_dir))}"]
    if self.environment_file:
        # A controlled JSON mapping only; never an arbitrary remote shell.
        quoted_file = shlex.quote(str(self.environment_file))
        lines.append(
            "eval \"$(HARBORRL_ENV_FILE=" + quoted_file + " python3 - <<'HARBORRL_ENV_JSON'\n"
            "import json, os, shlex\n"
            "with open(os.environ['HARBORRL_ENV_FILE']) as stream:\n"
            "    for key, value in sorted(json.load(stream).items()):\n"
            "        print(f'export {key}={shlex.quote(str(value))}')\n"
            "HARBORRL_ENV_JSON\n"
            ")\"")
    for key in sorted(environment):
        lines.append(f"export {key}={shlex.quote(str(environment[key]))}")
    lines.append("status=0")
    # The command is a full argv (its first word is already the
    # interpreter); execute it as-is and capture the real exit code.
    lines.append(" ".join(shlex.quote(part) for part in command)
                 + " || status=$?")
    lines.append(f"printf '%s\\n' \"$status\" > {shlex.quote(str(self.run_dir / EXIT_CODE_NAME))}")
    lines.append("exit \"$status\"")
    launcher = self.run_dir / LAUNCHER_NAME
    launcher.write_text("\n".join(lines) + "\n")
    launcher.chmod(0o755)
    return launcher

wait

wait(*, timeout=None)

Poll the shared exit-code record; never resubmit or restart.

Source code in harborrl/deployment/training_target.py
def wait(self, *, timeout=None):
    """Poll the shared exit-code record; never resubmit or restart."""
    deadline = None if timeout is None else time.monotonic() + timeout
    while True:
        code = self.exit_code()
        if code is not None:
            return code
        if deadline is not None and time.monotonic() >= deadline:
            raise TimeoutError(f"GPU job in {self.run_dir} did not finish in time")
        time.sleep(self.poll_interval)

local_target

local_target(plan, *, environment)

Build the legacy in-process target from a resolved plan.

Source code in harborrl/deployment/training_target.py
def local_target(plan, *, environment):
    """Build the legacy in-process target from a resolved plan."""
    allowed = {"PATH", "HOME", "USER", "LANG", "LC_ALL", "TMPDIR", "LD_LIBRARY_PATH",
               "CUDA_VISIBLE_DEVICES", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY",
               "http_proxy", "https_proxy", "no_proxy", "PYTHONPATH",
               "SLIME_DIR", "MEGATRON_DIR", "SGLANG_IMAGE"}
    child_env = {key: value for key, value in os.environ.items() if key in allowed}
    child_env["PATH"] = os.pathsep.join(
        [str(Path(sys.executable).parent), child_env.get("PATH", os.defpath)])
    child_env["PYTHONPATH"] = os.pathsep.join(filter(None, [
        child_env.get("SLIME_DIR", ""), child_env.get("MEGATRON_DIR", ""),
        str(Path(__file__).resolve().parents[2]), child_env.get("PYTHONPATH", ""),
    ]))
    child_env.update(environment)
    from harborrl.config import ROOT

    return LocalTrainingTarget(plan["training_command"], cwd=ROOT, env=child_env)

Consistency configuration and metrics

harborrl.consistency.config

Explicit deployment-specific tolerances; no universal numeric threshold.

validate

validate(value=None)
Source code in harborrl/consistency/config.py
def validate(value=None):
    if value is None:
        value = {}
    if not isinstance(value, dict) or set(value) - set(DEFAULTS):
        raise ValueError("Unknown consistency configuration fields")
    result = {**DEFAULTS, **value}
    if result["mode"] not in ("off", "audit", "enforce"):
        raise ValueError("consistency.mode must be off, audit or enforce")
    for key in ("max_abs_delta", "max_mean_abs_delta", "bad_token_delta"):
        if result[key] is not None and (not finite(result[key]) or result[key] < 0):
            raise ValueError(f"consistency.{key} must be nonnegative and finite")
    if result["mode"] == "enforce" and result["max_abs_delta"] is None:
        raise ValueError("enforce requires an explicit max_abs_delta for this deployment")
    if not finite(result["max_bad_fraction"]) or not 0 <= result["max_bad_fraction"] <= 1:
        raise ValueError("max_bad_fraction must be in [0, 1]")
    if type(result["worst_tokens"]) is not int or not 0 <= result["worst_tokens"] <= 32:
        raise ValueError("worst_tokens must be an integer in [0, 32]")
    return result

require_raw_sampling

require_raw_sampling(sampling)
Source code in harborrl/consistency/config.py
def require_raw_sampling(sampling):
    allowed = {"temperature", "top_p", "top_k", "max_new_tokens", "stop", "raw_logprobs"}
    if (not isinstance(sampling, dict) or set(sampling) - allowed
            or sampling.get("temperature") != 1 or sampling.get("top_p") != 1
            or sampling.get("top_k", -1) not in (-1, 0)
            or sampling.get("raw_logprobs", True) is not True):
        raise ValueError("Consistency v1 requires untransformed raw-policy sampling")

violations

violations(metrics, config)
Source code in harborrl/consistency/config.py
def violations(metrics, config):
    errors = []
    for option, field in (("max_abs_delta", "max_abs_delta"), ("max_mean_abs_delta", "mean_abs_delta")):
        if config[option] is not None and metrics[field] > config[option]:
            errors.append(f"{field}={metrics[field]:.8g} exceeds {config[option]}")
    if config["bad_token_delta"] is not None and metrics["bad_fraction"] > config["max_bad_fraction"]:
        errors.append(f"bad_fraction={metrics['bad_fraction']:.8g} exceeds {config['max_bad_fraction']}")
    return errors

harborrl.consistency.metrics

Mergeable token statistics with bounded-memory percentile upper bounds.

statistics

statistics(rows, *, threshold=None, worst=8)
Source code in harborrl/consistency/metrics.py
def statistics(rows, *, threshold=None, worst=8):
    result = {"count": 0, "signed_sum": 0.0, "abs_sum": 0.0, "max_abs_delta": 0.0,
              "min_log_ratio": None, "max_log_ratio": None, "bad_count": 0,
              "histogram": [0] * (len(EDGES) + 1), "worst": []}
    for row_index, (current, behavior, mask) in enumerate(rows):
        if len(current) != len(behavior) or len(mask) != len(current) or not len(current):
            raise ValueError("Probability/mask length mismatch")
        if any(flag not in (0, 1) for flag in mask):
            raise ValueError("Loss mask must be binary")
        for position, (p, q, flag) in enumerate(zip(current, behavior, mask, strict=True)):
            if not finite(p) or not finite(q) or p > 0 or q > 0:
                raise ValueError("Log probabilities must be finite and nonpositive")
            if not flag:
                continue
            delta = float(p) - float(q)
            absolute = abs(delta)
            if not math.isfinite(delta):
                raise ValueError("Nonfinite log-probability difference")
            result["count"] += 1
            result["signed_sum"] += delta
            result["abs_sum"] += absolute
            result["max_abs_delta"] = max(result["max_abs_delta"], absolute)
            result["min_log_ratio"] = delta if result["min_log_ratio"] is None else min(result["min_log_ratio"], delta)
            result["max_log_ratio"] = delta if result["max_log_ratio"] is None else max(result["max_log_ratio"], delta)
            result["bad_count"] += int(threshold is not None and absolute > threshold)
            result["histogram"][bisect.bisect_left(EDGES, absolute)] += 1
            if worst:
                result["worst"].append({"row": row_index, "position": position, "delta": delta})
                result["worst"] = sorted(result["worst"], key=lambda x: abs(x["delta"]), reverse=True)[:worst]
    if not result["count"]:
        raise ValueError("No valid response tokens")
    if not math.isfinite(result["abs_sum"]) or not math.isfinite(result["signed_sum"]):
        raise ValueError("Probability statistics overflow")
    return result

merge

merge(parts)
Source code in harborrl/consistency/metrics.py
def merge(parts):
    if not parts:
        raise ValueError("No contributing ranks")
    count = sum(p["count"] for p in parts)
    bins = [sum(p["histogram"][i] for p in parts) for i in range(len(EDGES) + 1)]
    maximum = max(p["max_abs_delta"] for p in parts)
    def percentile(fraction):
        target, seen = math.ceil(count * fraction), 0
        for index, n in enumerate(bins):
            seen += n
            if seen >= target:
                return min(EDGES[index], maximum) if index < len(EDGES) else maximum
        raise ValueError("Corrupt histogram")
    return {"token_count": count, "signed_mean_delta": math.fsum(p["signed_sum"] for p in parts) / count,
            "mean_abs_delta": math.fsum(p["abs_sum"] for p in parts) / count,
            "max_abs_delta": maximum, "p95_abs_delta_upper": percentile(.95), "p99_abs_delta_upper": percentile(.99),
            "min_log_ratio": min(p["min_log_ratio"] for p in parts),
            "max_log_ratio": max(p["max_log_ratio"] for p in parts),
            "bad_fraction": sum(p["bad_count"] for p in parts) / count,
            "percentile_semantics": "logarithmic-histogram upper bound; not exact quantiles",
            "gap_semantics": "fixed-prefix token log-ratio; not full-sequence KL"}