Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1674ac93c | ||
|
|
b1d4f2fa6c | ||
|
|
d43e0f329b | ||
|
|
8c1f196dd3 | ||
|
|
753a3fec0a | ||
|
|
3ad13dd0bc | ||
|
|
ee06d333e4 | ||
|
|
91d4b92597 | ||
|
|
82acb12ed7 | ||
|
|
124f9694a6 |
Vendored
+1
-1
Submodule deps/prime-envs updated: 1f1f915a57...b30aad3637
Vendored
+1
-1
Submodule deps/verifiers updated: d53ab56f0c...7251c60934
+1
-1
@@ -234,7 +234,7 @@ The knobs (under `[trainer.loss]` with `type = "default"`):
|
||||
|
||||
| Knob | Default | What it does |
|
||||
|---|---|---|
|
||||
| `dppo_mask_low` / `dppo_mask_high` | 0.1 / 0.1 | Lower / upper thresholds for DPPO-style token-level masking. |
|
||||
| `dppo_mask_low` / `dppo_mask_high` | 0.2 / 0.2 | Lower / upper thresholds for DPPO-style token-level masking. |
|
||||
| `adv_tau` | 1.0 | Temperature on the advantage term. Set to 0 to drop the policy-gradient term, leaving only the KL regularizer. |
|
||||
| `kl_tau` | 1e-3 | Temperature on the KL regularizer. Set to 0 to disable. |
|
||||
|
||||
|
||||
@@ -223,8 +223,8 @@ uv run eval reverse-text --harness.id null \
|
||||
|
||||
```bash
|
||||
helm uninstall my-exp
|
||||
# Optionally delete shared data:
|
||||
kubectl delete pvc prime-rl-shared-data
|
||||
# Optionally delete shared data. The PVC is named <release-name>-shared-data:
|
||||
kubectl delete pvc my-exp-shared-data
|
||||
```
|
||||
|
||||
**What the Helm chart provides:**
|
||||
|
||||
+4
-6
@@ -2,8 +2,6 @@
|
||||
|
||||
This directory contains a Helm chart for deploying prime-rl training infrastructure on Kubernetes clusters.
|
||||
|
||||
For complete documentation, see the [Kubernetes guide](https://docs.primeintellect.ai/prime-rl/kubernetes).
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
@@ -64,11 +62,11 @@ helm install my-exp ./prime-rl \
|
||||
|
||||
```bash
|
||||
helm uninstall my-exp
|
||||
kubectl delete pvc prime-rl-shared-data # Warning: deletes data!
|
||||
|
||||
# The PVC is named <release-name>-shared-data (see templates/pvc.yaml)
|
||||
kubectl delete pvc my-exp-shared-data # Warning: deletes data!
|
||||
```
|
||||
|
||||
## Learn More
|
||||
|
||||
- [Full Kubernetes documentation](https://docs.primeintellect.ai/prime-rl/kubernetes) - Architecture, configuration, distributed training
|
||||
- [Deployment guide](https://docs.primeintellect.ai/prime-rl/deployment) - Non-Kubernetes deployments
|
||||
- [Troubleshooting](https://docs.primeintellect.ai/prime-rl/troubleshooting) - Common issues
|
||||
- [Scaling guide](https://docs.primeintellect.ai/prime-rl/scaling) - Non-Kubernetes multi-node deployment (SLURM), parallelism, benchmarking
|
||||
|
||||
@@ -456,10 +456,10 @@ class CheckpointConfig(BaseConfig):
|
||||
class DefaultLossConfig(BaseConfig):
|
||||
type: Literal["default"] = "default"
|
||||
|
||||
dppo_mask_low: float = Field(0.1, ge=0)
|
||||
dppo_mask_low: float = Field(0.2, ge=0)
|
||||
"""Lower DPPO masking threshold."""
|
||||
|
||||
dppo_mask_high: float = Field(0.1, ge=0)
|
||||
dppo_mask_high: float = Field(0.2, ge=0)
|
||||
"""Upper DPPO masking threshold."""
|
||||
|
||||
adv_tau: float = Field(1.0, ge=0)
|
||||
|
||||
@@ -261,6 +261,7 @@ select = ["F", "I"]
|
||||
# Without this, ruff classifies prime_rl.configs.* as third-party because it
|
||||
# doesn't live under src/.
|
||||
known-first-party = ["prime_rl"]
|
||||
known-third-party = ["verifiers", "renderers", "pydantic_config"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
|
||||
@@ -647,7 +647,7 @@ def rl(config: RLConfig):
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
|
||||
pre_download_model(config.trainer.model.name)
|
||||
pre_download_model(config.trainer.model.name, skip_weights=config.trainer.model.debug.random_init)
|
||||
|
||||
if config.slurm is not None:
|
||||
rl_slurm(config)
|
||||
|
||||
@@ -214,7 +214,7 @@ def sft(config: SFTConfig):
|
||||
if not config.dry_run:
|
||||
from prime_rl.trainer.model import pre_download_model
|
||||
|
||||
pre_download_model(config.model.name)
|
||||
pre_download_model(config.model.name, skip_weights=config.model.debug.random_init)
|
||||
|
||||
if config.slurm is not None:
|
||||
sft_slurm(config)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import math
|
||||
import time
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from statistics import mean, median
|
||||
|
||||
import wandb
|
||||
from httpx import AsyncClient
|
||||
@@ -12,105 +13,41 @@ from prometheus_client.parser import text_string_to_metric_families
|
||||
from prime_rl.utils.logger import get_logger
|
||||
|
||||
POLL_INTERVAL = 5.0
|
||||
WINDOW_SIZE = 20
|
||||
FETCH_TIMEOUT = 5.0
|
||||
METRIC_PREFIX = "vllm:"
|
||||
PD_ROLES = {"prefill", "decode"}
|
||||
QUANTILES = {"p50": 0.5, "p90": 0.9, "p99": 0.99}
|
||||
AGGREGATIONS = {"min": min, "max": max, "sum": sum, "mean": mean, "median": median}
|
||||
|
||||
COUNTER_KEYS = {
|
||||
"vllm:prompt_tokens": "prompt_tokens_total",
|
||||
"vllm:prompt_tokens_total": "prompt_tokens_total",
|
||||
"vllm:generation_tokens": "generation_tokens_total",
|
||||
"vllm:generation_tokens_total": "generation_tokens_total",
|
||||
"vllm:request_success": "request_success_total",
|
||||
"vllm:request_success_total": "request_success_total",
|
||||
"vllm:prefix_cache_queries": "prefix_cache_queries",
|
||||
"vllm:prefix_cache_queries_total": "prefix_cache_queries",
|
||||
"vllm:prefix_cache_hits": "prefix_cache_hits",
|
||||
"vllm:prefix_cache_hits_total": "prefix_cache_hits",
|
||||
"vllm:nixl_num_failed_transfers_total": "nixl_failed_transfers_total",
|
||||
"vllm:nixl_num_failed_notifications_total": "nixl_failed_notifications_total",
|
||||
"vllm:nixl_num_kv_expired_reqs_total": "nixl_kv_expired_requests_total",
|
||||
}
|
||||
|
||||
GAUGE_KEYS = {
|
||||
"vllm:num_requests_running": "running_requests",
|
||||
"vllm:num_requests_waiting": "waiting_requests",
|
||||
"vllm:kv_cache_usage_perc": "kv_cache_usage_perc",
|
||||
"vllm:gpu_cache_usage_perc": "kv_cache_usage_perc",
|
||||
"vllm:cpu_cache_usage_perc": "cpu_cache_usage_perc",
|
||||
"vllm:gpu_prefix_cache_hit_rate": "gpu_prefix_cache_hit_rate",
|
||||
"vllm:cpu_prefix_cache_hit_rate": "cpu_prefix_cache_hit_rate",
|
||||
}
|
||||
|
||||
HISTOGRAM_SUM_KEYS = {
|
||||
"vllm:request_prefill_time_seconds_sum": "request_prefill_time_seconds_sum",
|
||||
"vllm:request_decode_time_seconds_sum": "request_decode_time_seconds_sum",
|
||||
"vllm:request_queue_time_seconds_sum": "request_queue_time_seconds_sum",
|
||||
"vllm:time_to_first_token_seconds_sum": "time_to_first_token_seconds_sum",
|
||||
"vllm:inter_token_latency_seconds_sum": "inter_token_latency_seconds_sum",
|
||||
"vllm:e2e_request_latency_seconds_sum": "e2e_request_latency_seconds_sum",
|
||||
"vllm:nixl_xfer_time_seconds_sum": "nixl_xfer_time_seconds_sum",
|
||||
"vllm:nixl_bytes_transferred_sum": "nixl_bytes_transferred_sum",
|
||||
}
|
||||
|
||||
HISTOGRAM_COUNT_KEYS = {
|
||||
"vllm:request_prefill_time_seconds_count": "request_prefill_time_seconds_count",
|
||||
"vllm:request_decode_time_seconds_count": "request_decode_time_seconds_count",
|
||||
"vllm:request_queue_time_seconds_count": "request_queue_time_seconds_count",
|
||||
"vllm:time_to_first_token_seconds_count": "time_to_first_token_seconds_count",
|
||||
"vllm:inter_token_latency_seconds_count": "inter_token_latency_seconds_count",
|
||||
"vllm:e2e_request_latency_seconds_count": "e2e_request_latency_seconds_count",
|
||||
"vllm:nixl_xfer_time_seconds_count": "nixl_xfer_time_seconds_count",
|
||||
"vllm:nixl_bytes_transferred_count": "nixl_bytes_transferred_count",
|
||||
# Scope-level ratios derived from counter deltas; each operand lists legacy and
|
||||
# OpenMetrics sample names, whichever the running vLLM version emits.
|
||||
RATIO_METRICS = {
|
||||
"prefix_cache_hit_rate": (
|
||||
("prefix_cache_hits", "prefix_cache_hits_total"),
|
||||
("prefix_cache_queries", "prefix_cache_queries_total"),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineRollup:
|
||||
running_requests: float = 0.0
|
||||
waiting_requests: float = 0.0
|
||||
kv_cache_usage_perc: float = 0.0
|
||||
cpu_cache_usage_perc: float | None = None
|
||||
gpu_prefix_cache_hit_rate: float | None = None
|
||||
cpu_prefix_cache_hit_rate: float | None = None
|
||||
prompt_tokens_total: float = 0.0
|
||||
generation_tokens_total: float = 0.0
|
||||
request_success_total: float = 0.0
|
||||
prefix_cache_queries: float = 0.0
|
||||
prefix_cache_hits: float = 0.0
|
||||
nixl_failed_transfers_total: float = 0.0
|
||||
nixl_failed_notifications_total: float = 0.0
|
||||
nixl_kv_expired_requests_total: float = 0.0
|
||||
request_prefill_time_seconds_sum: float = 0.0
|
||||
request_prefill_time_seconds_count: float = 0.0
|
||||
request_decode_time_seconds_sum: float = 0.0
|
||||
request_decode_time_seconds_count: float = 0.0
|
||||
request_queue_time_seconds_sum: float = 0.0
|
||||
request_queue_time_seconds_count: float = 0.0
|
||||
time_to_first_token_seconds_sum: float = 0.0
|
||||
time_to_first_token_seconds_count: float = 0.0
|
||||
inter_token_latency_seconds_sum: float = 0.0
|
||||
inter_token_latency_seconds_count: float = 0.0
|
||||
e2e_request_latency_seconds_sum: float = 0.0
|
||||
e2e_request_latency_seconds_count: float = 0.0
|
||||
nixl_xfer_time_seconds_sum: float = 0.0
|
||||
nixl_xfer_time_seconds_count: float = 0.0
|
||||
nixl_bytes_transferred_sum: float = 0.0
|
||||
nixl_bytes_transferred_count: float = 0.0
|
||||
class HistogramSnapshot:
|
||||
sum: float = 0.0
|
||||
count: float = 0.0
|
||||
buckets: dict[float, float] = field(default_factory=dict)
|
||||
"""Upper bound (``le``) -> cumulative count."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class NodeRollup:
|
||||
engines: dict[str, EngineRollup] = field(default_factory=dict)
|
||||
class EngineSnapshot:
|
||||
"""All samples scraped for one engine, keyed by vLLM sample name.
|
||||
|
||||
@property
|
||||
def engine_count(self) -> int:
|
||||
return len(self.engines)
|
||||
Samples that carry extra labels (e.g. ``finished_reason``) are summed over
|
||||
those labels so each name maps to a single value per engine.
|
||||
"""
|
||||
|
||||
def summed(self, attribute: str) -> float:
|
||||
return sum(getattr(engine, attribute) for engine in self.engines.values())
|
||||
|
||||
def values(self, attribute: str) -> list[float]:
|
||||
return [value for engine in self.engines.values() if (value := getattr(engine, attribute)) is not None]
|
||||
gauges: dict[str, float] = field(default_factory=dict)
|
||||
counters: dict[str, float] = field(default_factory=dict)
|
||||
histograms: dict[str, HistogramSnapshot] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -118,284 +55,222 @@ class MetricsEndpoint:
|
||||
client: AsyncClient
|
||||
role: str | None
|
||||
key: str
|
||||
name: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TimedRollup:
|
||||
class TimedSnapshot:
|
||||
timestamp: float
|
||||
rollup: NodeRollup
|
||||
snapshot: EngineSnapshot
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EndpointSample:
|
||||
class EngineSample:
|
||||
endpoint: MetricsEndpoint
|
||||
engine_label: str
|
||||
timestamp: float
|
||||
rollup: NodeRollup
|
||||
snapshot: EngineSnapshot
|
||||
|
||||
@property
|
||||
def engine_id(self) -> str:
|
||||
return f"{self.endpoint.name}.{self.engine_label}"
|
||||
|
||||
@property
|
||||
def key(self) -> tuple[str, str]:
|
||||
return (self.endpoint.key, self.engine_label)
|
||||
|
||||
|
||||
def parse_prometheus_text(text: str) -> NodeRollup:
|
||||
"""Parse vLLM Prometheus metrics into per-engine counters, gauges, and histogram totals."""
|
||||
engines: dict[str, EngineRollup] = {}
|
||||
def parse_prometheus_text(text: str) -> dict[str, EngineSnapshot]:
|
||||
"""Parse a vLLM Prometheus exposition into one snapshot per engine label."""
|
||||
engines: dict[str, EngineSnapshot] = {}
|
||||
for family in text_string_to_metric_families(text):
|
||||
if not family.name.startswith(METRIC_PREFIX) or family.type not in ("counter", "gauge", "histogram"):
|
||||
continue
|
||||
for sample in family.samples:
|
||||
engine_id = sample.labels.get("engine", "aggregate")
|
||||
engine = engines.setdefault(engine_id, EngineRollup())
|
||||
if sample.name in GAUGE_KEYS:
|
||||
setattr(engine, GAUGE_KEYS[sample.name], float(sample.value))
|
||||
elif sample.name in COUNTER_KEYS:
|
||||
attribute = COUNTER_KEYS[sample.name]
|
||||
setattr(engine, attribute, getattr(engine, attribute) + float(sample.value))
|
||||
elif sample.name in HISTOGRAM_SUM_KEYS:
|
||||
setattr(engine, HISTOGRAM_SUM_KEYS[sample.name], float(sample.value))
|
||||
elif sample.name in HISTOGRAM_COUNT_KEYS:
|
||||
setattr(engine, HISTOGRAM_COUNT_KEYS[sample.name], float(sample.value))
|
||||
return NodeRollup(engines=engines)
|
||||
if sample.name.endswith("_created") or not math.isfinite(sample.value):
|
||||
continue
|
||||
engine = engines.setdefault(sample.labels.get("engine", "0"), EngineSnapshot())
|
||||
name = sample.name.removeprefix(METRIC_PREFIX)
|
||||
if family.type == "gauge":
|
||||
engine.gauges[name] = engine.gauges.get(name, 0.0) + sample.value
|
||||
elif family.type == "counter":
|
||||
engine.counters[name] = engine.counters.get(name, 0.0) + sample.value
|
||||
else:
|
||||
histogram = engine.histograms.setdefault(family.name.removeprefix(METRIC_PREFIX), HistogramSnapshot())
|
||||
if sample.name.endswith("_sum"):
|
||||
histogram.sum += sample.value
|
||||
elif sample.name.endswith("_count"):
|
||||
histogram.count += sample.value
|
||||
elif sample.name.endswith("_bucket"):
|
||||
le = float(sample.labels["le"])
|
||||
histogram.buckets[le] = histogram.buckets.get(le, 0.0) + sample.value
|
||||
return engines
|
||||
|
||||
|
||||
def build_metrics_endpoints(
|
||||
admin_clients: list[AsyncClient], roles: list[str | None] | None = None
|
||||
) -> list[MetricsEndpoint]:
|
||||
"""Attach optional P/D roles to admin clients used for metrics polling."""
|
||||
"""Attach optional P/D roles and stable display names to admin clients."""
|
||||
if roles is None:
|
||||
roles = [None] * len(admin_clients)
|
||||
if len(roles) != len(admin_clients):
|
||||
raise ValueError(f"Got {len(roles)} inference metric role(s) for {len(admin_clients)} admin client(s)")
|
||||
|
||||
endpoints: list[MetricsEndpoint] = []
|
||||
counts: dict[str, int] = {}
|
||||
for client, role in zip(admin_clients, roles):
|
||||
normalized_role = role if role in PD_ROLES else None
|
||||
if role is not None and normalized_role is None:
|
||||
if role is not None and role not in PD_ROLES:
|
||||
raise ValueError(f"Unsupported inference metrics role: {role}")
|
||||
endpoints.append(MetricsEndpoint(client=client, role=normalized_role, key=str(client.base_url).rstrip("/")))
|
||||
prefix = role or "server"
|
||||
index = counts.get(prefix, 0)
|
||||
counts[prefix] = index + 1
|
||||
endpoints.append(
|
||||
MetricsEndpoint(
|
||||
client=client,
|
||||
role=role,
|
||||
key=str(client.base_url).rstrip("/"),
|
||||
name=f"{prefix}{index}",
|
||||
)
|
||||
)
|
||||
return endpoints
|
||||
|
||||
|
||||
def max_vio(values: list[float]) -> float:
|
||||
"""Return the max-load violation used for MoE load-balance reporting."""
|
||||
if not values:
|
||||
return 0.0
|
||||
balanced_load = sum(values) / len(values)
|
||||
if balanced_load == 0:
|
||||
return 0.0
|
||||
return (max(values) - balanced_load) / balanced_load
|
||||
|
||||
|
||||
def counter_rate(samples: list[EndpointSample], previous: dict[str, TimedRollup], attribute: str) -> float | None:
|
||||
"""Sum per-endpoint counter rates for a scope."""
|
||||
rates: list[float] = []
|
||||
for sample in samples:
|
||||
previous_sample = previous.get(sample.endpoint.key)
|
||||
if previous_sample is None:
|
||||
continue
|
||||
dt = sample.timestamp - previous_sample.timestamp
|
||||
delta = sample.rollup.summed(attribute) - previous_sample.rollup.summed(attribute)
|
||||
if dt <= 0 or delta < 0:
|
||||
continue
|
||||
rates.append(delta / dt)
|
||||
if not rates:
|
||||
def histogram_quantile(buckets: dict[float, float], quantile: float) -> float | None:
|
||||
"""Estimate a quantile from cumulative bucket deltas, Prometheus-style."""
|
||||
total = max(buckets.values(), default=0.0)
|
||||
if total <= 0:
|
||||
return None
|
||||
return sum(rates)
|
||||
target = quantile * total
|
||||
previous_le, previous_cumulative = 0.0, 0.0
|
||||
for le, cumulative in sorted(buckets.items()):
|
||||
if cumulative >= target:
|
||||
if math.isinf(le) or cumulative == previous_cumulative:
|
||||
return previous_le
|
||||
return previous_le + (le - previous_le) * (target - previous_cumulative) / (
|
||||
cumulative - previous_cumulative
|
||||
)
|
||||
previous_le, previous_cumulative = le, cumulative
|
||||
return None
|
||||
|
||||
|
||||
def counter_ratio(
|
||||
samples: list[EndpointSample],
|
||||
previous: dict[str, TimedRollup],
|
||||
numerator_attribute: str,
|
||||
denominator_attribute: str,
|
||||
) -> float | None:
|
||||
"""Compute a scope-level ratio from counter deltas."""
|
||||
numerator_delta = 0.0
|
||||
denominator_delta = 0.0
|
||||
for sample in samples:
|
||||
previous_sample = previous.get(sample.endpoint.key)
|
||||
if previous_sample is None:
|
||||
continue
|
||||
endpoint_numerator_delta = sample.rollup.summed(numerator_attribute) - previous_sample.rollup.summed(
|
||||
numerator_attribute
|
||||
def engine_values(sample: EngineSample, previous: TimedSnapshot | None) -> dict[str, float]:
|
||||
"""Pass-through values plus interval-derived rates and means for one engine.
|
||||
|
||||
Counter rates use ``:rate`` (per second), histogram interval means use
|
||||
``:mean``, and histogram completion rates use ``:rate``, mirroring how one
|
||||
would express them as PromQL over the poll interval.
|
||||
"""
|
||||
values: dict[str, float] = dict(sample.snapshot.gauges)
|
||||
values.update(sample.snapshot.counters)
|
||||
for name, histogram in sample.snapshot.histograms.items():
|
||||
values[f"{name}_sum"] = histogram.sum
|
||||
values[f"{name}_count"] = histogram.count
|
||||
|
||||
if previous is None:
|
||||
return values
|
||||
dt = sample.timestamp - previous.timestamp
|
||||
if dt <= 0:
|
||||
return values
|
||||
|
||||
for name, value in sample.snapshot.counters.items():
|
||||
delta = value - previous.snapshot.counters.get(name, 0.0)
|
||||
if delta >= 0:
|
||||
values[f"{name}:rate"] = delta / dt
|
||||
for name, histogram in sample.snapshot.histograms.items():
|
||||
previous_histogram = previous.snapshot.histograms.get(name, HistogramSnapshot())
|
||||
sum_delta = histogram.sum - previous_histogram.sum
|
||||
count_delta = histogram.count - previous_histogram.count
|
||||
if count_delta >= 0:
|
||||
values[f"{name}:rate"] = count_delta / dt
|
||||
if count_delta > 0 and sum_delta >= 0:
|
||||
values[f"{name}:mean"] = sum_delta / count_delta
|
||||
# Per-engine ratios so the scope aggregations include min/max — the pooled
|
||||
# scope-level ratio alone hides a single engine's collapse (e.g. one engine
|
||||
# thrashing at a 5% prefix hit rate inside a healthy fleet average).
|
||||
for name, (numerator_names, denominator_names) in RATIO_METRICS.items():
|
||||
numerator = sum(
|
||||
sample.snapshot.counters.get(c, 0.0) - previous.snapshot.counters.get(c, 0.0) for c in numerator_names
|
||||
)
|
||||
endpoint_denominator_delta = sample.rollup.summed(denominator_attribute) - previous_sample.rollup.summed(
|
||||
denominator_attribute
|
||||
denominator = sum(
|
||||
sample.snapshot.counters.get(c, 0.0) - previous.snapshot.counters.get(c, 0.0) for c in denominator_names
|
||||
)
|
||||
if endpoint_numerator_delta < 0 or endpoint_denominator_delta < 0:
|
||||
continue
|
||||
numerator_delta += endpoint_numerator_delta
|
||||
denominator_delta += endpoint_denominator_delta
|
||||
if denominator_delta <= 0:
|
||||
return None
|
||||
return numerator_delta / denominator_delta
|
||||
if numerator >= 0 and denominator > 0:
|
||||
values[name] = numerator / denominator
|
||||
return values
|
||||
|
||||
|
||||
def histogram_average(
|
||||
samples: list[EndpointSample],
|
||||
previous: dict[str, TimedRollup],
|
||||
sum_attribute: str,
|
||||
count_attribute: str,
|
||||
) -> float | None:
|
||||
"""Compute a scope-level histogram average from sum/count deltas."""
|
||||
sum_delta = 0.0
|
||||
count_delta = 0.0
|
||||
for sample in samples:
|
||||
previous_sample = previous.get(sample.endpoint.key)
|
||||
if previous_sample is None:
|
||||
continue
|
||||
endpoint_sum_delta = sample.rollup.summed(sum_attribute) - previous_sample.rollup.summed(sum_attribute)
|
||||
endpoint_count_delta = sample.rollup.summed(count_attribute) - previous_sample.rollup.summed(count_attribute)
|
||||
if endpoint_sum_delta < 0 or endpoint_count_delta < 0:
|
||||
continue
|
||||
sum_delta += endpoint_sum_delta
|
||||
count_delta += endpoint_count_delta
|
||||
if count_delta <= 0:
|
||||
return None
|
||||
return sum_delta / count_delta
|
||||
|
||||
|
||||
def mean(values: list[float]) -> float | None:
|
||||
"""Return the arithmetic mean for non-empty metric value lists."""
|
||||
if not values:
|
||||
return None
|
||||
return sum(values) / len(values)
|
||||
def bucket_deltas(sample: EngineSample, previous: TimedSnapshot | None) -> dict[str, dict[float, float]]:
|
||||
"""Per-histogram cumulative bucket deltas since the previous scrape."""
|
||||
if previous is None:
|
||||
return {}
|
||||
deltas: dict[str, dict[float, float]] = {}
|
||||
for name, histogram in sample.snapshot.histograms.items():
|
||||
previous_buckets = previous.snapshot.histograms.get(name, HistogramSnapshot()).buckets
|
||||
delta = {le: count - previous_buckets.get(le, 0.0) for le, count in histogram.buckets.items()}
|
||||
if delta and all(count >= 0 for count in delta.values()):
|
||||
deltas[name] = delta
|
||||
return deltas
|
||||
|
||||
|
||||
def build_scope_metrics(
|
||||
scope: str,
|
||||
samples: list[EndpointSample],
|
||||
previous: dict[str, TimedRollup],
|
||||
values_per_engine: list[dict[str, float]],
|
||||
bucket_deltas_per_engine: list[dict[str, dict[float, float]]],
|
||||
counter_deltas: dict[str, float],
|
||||
) -> dict[str, float]:
|
||||
"""Build W&B metric values for one inference scope."""
|
||||
running_values = [value for sample in samples for value in sample.rollup.values("running_requests")]
|
||||
waiting_values = [value for sample in samples for value in sample.rollup.values("waiting_requests")]
|
||||
kv_values = [value for sample in samples for value in sample.rollup.values("kv_cache_usage_perc")]
|
||||
cpu_kv_values = [value for sample in samples for value in sample.rollup.values("cpu_cache_usage_perc")]
|
||||
prefix_gauge_values = [value for sample in samples for value in sample.rollup.values("gpu_prefix_cache_hit_rate")]
|
||||
cpu_prefix_values = [value for sample in samples for value in sample.rollup.values("cpu_prefix_cache_hit_rate")]
|
||||
|
||||
"""Aggregate per-engine values into ``inference/{scope}/{metric}/{agg}`` series."""
|
||||
prefix = f"inference/{scope}"
|
||||
metrics: dict[str, float] = {
|
||||
f"{prefix}/running_requests": sum(running_values),
|
||||
f"{prefix}/waiting_requests": sum(waiting_values),
|
||||
f"{prefix}/running_imbalance": max_vio(running_values),
|
||||
f"{prefix}/waiting_imbalance": max_vio(waiting_values),
|
||||
f"{prefix}/nixl_failed_transfers_total": sum(
|
||||
sample.rollup.summed("nixl_failed_transfers_total") for sample in samples
|
||||
),
|
||||
f"{prefix}/nixl_failed_notifications_total": sum(
|
||||
sample.rollup.summed("nixl_failed_notifications_total") for sample in samples
|
||||
),
|
||||
f"{prefix}/nixl_kv_expired_requests_total": sum(
|
||||
sample.rollup.summed("nixl_kv_expired_requests_total") for sample in samples
|
||||
),
|
||||
}
|
||||
metrics: dict[str, float] = {}
|
||||
|
||||
if kv_values:
|
||||
metrics[f"{prefix}/kv_cache_usage_mean"] = sum(kv_values) / len(kv_values)
|
||||
metrics[f"{prefix}/kv_cache_usage_max"] = max(kv_values)
|
||||
if cpu_kv_values:
|
||||
metrics[f"{prefix}/cpu_kv_cache_usage_mean"] = sum(cpu_kv_values) / len(cpu_kv_values)
|
||||
metrics[f"{prefix}/cpu_kv_cache_usage_max"] = max(cpu_kv_values)
|
||||
names = {name for values in values_per_engine for name in values}
|
||||
for name in sorted(names):
|
||||
engine_values_for_name = [values[name] for values in values_per_engine if name in values]
|
||||
for aggregation, fn in AGGREGATIONS.items():
|
||||
metrics[f"{prefix}/{name}/{aggregation}"] = fn(engine_values_for_name)
|
||||
|
||||
prefix_cache_hit_rate = counter_ratio(samples, previous, "prefix_cache_hits", "prefix_cache_queries")
|
||||
if prefix_cache_hit_rate is None:
|
||||
prefix_cache_hit_rate = mean(prefix_gauge_values)
|
||||
if prefix_cache_hit_rate is not None:
|
||||
metrics[f"{prefix}/prefix_cache_hit_rate"] = prefix_cache_hit_rate
|
||||
cpu_prefix_cache_hit_rate = mean(cpu_prefix_values)
|
||||
if cpu_prefix_cache_hit_rate is not None:
|
||||
metrics[f"{prefix}/cpu_prefix_cache_hit_rate"] = cpu_prefix_cache_hit_rate
|
||||
histogram_names = {name for deltas in bucket_deltas_per_engine for name in deltas}
|
||||
for name in sorted(histogram_names):
|
||||
pooled: dict[float, float] = {}
|
||||
for deltas in bucket_deltas_per_engine:
|
||||
for le, count in deltas.get(name, {}).items():
|
||||
pooled[le] = pooled.get(le, 0.0) + count
|
||||
for label, quantile in QUANTILES.items():
|
||||
value = histogram_quantile(pooled, quantile)
|
||||
if value is not None:
|
||||
metrics[f"{prefix}/{name}/{label}"] = value
|
||||
|
||||
prompt_token_rate = counter_rate(samples, previous, "prompt_tokens_total")
|
||||
generation_token_rate = counter_rate(samples, previous, "generation_tokens_total")
|
||||
if scope == "prefill":
|
||||
if prompt_token_rate is not None:
|
||||
metrics[f"{prefix}/throughput"] = prompt_token_rate
|
||||
elif scope == "decode":
|
||||
if generation_token_rate is not None:
|
||||
metrics[f"{prefix}/throughput"] = generation_token_rate
|
||||
else:
|
||||
token_rates = [rate for rate in (prompt_token_rate, generation_token_rate) if rate is not None]
|
||||
if token_rates:
|
||||
metrics[f"{prefix}/throughput"] = sum(token_rates)
|
||||
|
||||
counter_metrics = {
|
||||
"completed_requests": "request_success_total",
|
||||
"nixl_transfers_per_second": "nixl_xfer_time_seconds_count",
|
||||
"nixl_bytes_per_second": "nixl_bytes_transferred_sum",
|
||||
}
|
||||
for metric_name, attribute in counter_metrics.items():
|
||||
rate = counter_rate(samples, previous, attribute)
|
||||
if rate is not None:
|
||||
metrics[f"{prefix}/{metric_name}"] = rate
|
||||
|
||||
histogram_metrics = {
|
||||
"avg_queue_time_seconds": (
|
||||
"request_queue_time_seconds_sum",
|
||||
"request_queue_time_seconds_count",
|
||||
),
|
||||
"avg_ttft_seconds": (
|
||||
"time_to_first_token_seconds_sum",
|
||||
"time_to_first_token_seconds_count",
|
||||
),
|
||||
"avg_tpot_seconds": (
|
||||
"inter_token_latency_seconds_sum",
|
||||
"inter_token_latency_seconds_count",
|
||||
),
|
||||
"avg_e2e_latency_seconds": (
|
||||
"e2e_request_latency_seconds_sum",
|
||||
"e2e_request_latency_seconds_count",
|
||||
),
|
||||
"nixl_transfer_time_seconds": (
|
||||
"nixl_xfer_time_seconds_sum",
|
||||
"nixl_xfer_time_seconds_count",
|
||||
),
|
||||
"nixl_avg_bytes_per_transfer": (
|
||||
"nixl_bytes_transferred_sum",
|
||||
"nixl_bytes_transferred_count",
|
||||
),
|
||||
}
|
||||
for metric_name, (sum_attribute, count_attribute) in histogram_metrics.items():
|
||||
value = histogram_average(samples, previous, sum_attribute, count_attribute)
|
||||
if value is not None:
|
||||
metrics[f"{prefix}/{metric_name}"] = value
|
||||
|
||||
prefill_time = histogram_average(
|
||||
samples,
|
||||
previous,
|
||||
"request_prefill_time_seconds_sum",
|
||||
"request_prefill_time_seconds_count",
|
||||
)
|
||||
decode_time = histogram_average(
|
||||
samples,
|
||||
previous,
|
||||
"request_decode_time_seconds_sum",
|
||||
"request_decode_time_seconds_count",
|
||||
)
|
||||
if scope == "prefill":
|
||||
if prefill_time is not None:
|
||||
metrics[f"{prefix}/avg_time_seconds"] = prefill_time
|
||||
elif scope == "decode":
|
||||
if decode_time is not None:
|
||||
metrics[f"{prefix}/avg_time_seconds"] = decode_time
|
||||
else:
|
||||
time_values = [value for value in (prefill_time, decode_time) if value is not None]
|
||||
if time_values:
|
||||
metrics[f"{prefix}/avg_time_seconds"] = sum(time_values) / len(time_values)
|
||||
for name, (numerator_names, denominator_names) in RATIO_METRICS.items():
|
||||
numerator = sum(counter_deltas.get(candidate, 0.0) for candidate in numerator_names)
|
||||
denominator = sum(counter_deltas.get(candidate, 0.0) for candidate in denominator_names)
|
||||
if denominator > 0:
|
||||
metrics[f"{prefix}/{name}/pooled"] = numerator / denominator
|
||||
|
||||
return metrics
|
||||
|
||||
|
||||
class InferenceMetricsCollector:
|
||||
"""Polls vLLM Prometheus /metrics and logs smoothed role-aware values to W&B.
|
||||
"""Polls vLLM Prometheus /metrics and mirrors every engine metric to W&B.
|
||||
|
||||
The ``agg`` scope is always logged. The ``prefill`` and ``decode`` scopes are
|
||||
logged only when endpoints are explicitly or implicitly identified as a
|
||||
disaggregated P/D deployment.
|
||||
All ``vllm:*`` families are passed through dynamically (the ``vllm:``
|
||||
prefix is stripped): gauges and counters verbatim, histograms as
|
||||
``_sum``/``_count`` plus derived ``:rate``/``:mean`` and scope-level
|
||||
quantiles. Keys are ``inference/{scope}/{metric}/{stat}``: per-engine
|
||||
series under ``inference/{engine_id}/{metric}`` and cross-engine
|
||||
aggregations under ``inference/agg/{metric}/{stat}`` (plus
|
||||
``inference/prefill|decode/...`` for disaggregated deployments). Engine
|
||||
ids (``server0.0``, ``prefill0.1``, ...) never collide with the scope
|
||||
names.
|
||||
"""
|
||||
|
||||
def __init__(self, admin_clients: list[AsyncClient], roles: list[str | None] | None = None):
|
||||
self.endpoints = build_metrics_endpoints(admin_clients, roles=roles)
|
||||
self.metric_history: dict[str, deque[float]] = {}
|
||||
self.previous: dict[str, TimedRollup] = {}
|
||||
self.previous: dict[tuple[str, str], TimedSnapshot] = {}
|
||||
self.task: asyncio.Task | None = None
|
||||
self.has_pd_roles = {endpoint.role for endpoint in self.endpoints if endpoint.role is not None} == PD_ROLES
|
||||
get_logger().info(
|
||||
"Collecting inference metrics from "
|
||||
+ ", ".join(f"{endpoint.name}={endpoint.key}" for endpoint in self.endpoints)
|
||||
)
|
||||
|
||||
async def start(self):
|
||||
wandb.define_metric("inference/*", step_metric="_timestamp")
|
||||
@@ -415,7 +290,7 @@ class InferenceMetricsCollector:
|
||||
|
||||
async def fetch(endpoint: MetricsEndpoint) -> str | None:
|
||||
try:
|
||||
response = await endpoint.client.get("/metrics", timeout=5.0)
|
||||
response = await endpoint.client.get("/metrics", timeout=FETCH_TIMEOUT)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
except Exception as e:
|
||||
@@ -424,33 +299,57 @@ class InferenceMetricsCollector:
|
||||
|
||||
results = await asyncio.gather(*[fetch(endpoint) for endpoint in self.endpoints])
|
||||
samples = [
|
||||
EndpointSample(endpoint=endpoint, timestamp=now, rollup=parse_prometheus_text(text))
|
||||
EngineSample(endpoint=endpoint, engine_label=engine_label, timestamp=now, snapshot=snapshot)
|
||||
for endpoint, text in zip(self.endpoints, results)
|
||||
if text is not None
|
||||
for engine_label, snapshot in sorted(parse_prometheus_text(text).items())
|
||||
]
|
||||
if not samples:
|
||||
return
|
||||
|
||||
metrics = build_scope_metrics("agg", samples, self.previous)
|
||||
metrics = self.build_metrics(samples)
|
||||
for sample in samples:
|
||||
self.previous[sample.key] = TimedSnapshot(timestamp=sample.timestamp, snapshot=sample.snapshot)
|
||||
|
||||
if metrics:
|
||||
metrics["_timestamp"] = time.time()
|
||||
wandb.log(metrics)
|
||||
|
||||
def build_metrics(self, samples: list[EngineSample]) -> dict[str, float]:
|
||||
values_per_engine = [engine_values(sample, self.previous.get(sample.key)) for sample in samples]
|
||||
bucket_deltas_per_engine = [bucket_deltas(sample, self.previous.get(sample.key)) for sample in samples]
|
||||
|
||||
metrics: dict[str, float] = {}
|
||||
for sample, values in zip(samples, values_per_engine):
|
||||
for name, value in values.items():
|
||||
metrics[f"inference/{sample.engine_id}/{name}"] = value
|
||||
|
||||
scopes: list[tuple[str, list[int]]] = [("agg", list(range(len(samples))))]
|
||||
if self.has_pd_roles:
|
||||
for role in sorted(PD_ROLES):
|
||||
role_samples = [sample for sample in samples if sample.endpoint.role == role]
|
||||
if role_samples:
|
||||
metrics.update(build_scope_metrics(role, role_samples, self.previous))
|
||||
indices = [i for i, sample in enumerate(samples) if sample.endpoint.role == role]
|
||||
if indices:
|
||||
scopes.append((role, indices))
|
||||
|
||||
for sample in samples:
|
||||
self.previous[sample.endpoint.key] = TimedRollup(timestamp=sample.timestamp, rollup=sample.rollup)
|
||||
|
||||
smoothed_metrics = self.smooth_metrics(metrics)
|
||||
if smoothed_metrics:
|
||||
smoothed_metrics["_timestamp"] = time.time()
|
||||
wandb.log(smoothed_metrics)
|
||||
|
||||
def smooth_metrics(self, metrics: dict[str, float]) -> dict[str, float]:
|
||||
"""Add current values to the smoothing window and return W&B-ready metrics."""
|
||||
for key, value in metrics.items():
|
||||
self.metric_history.setdefault(key, deque(maxlen=WINDOW_SIZE)).append(value)
|
||||
return {key: sum(values) / len(values) for key, values in self.metric_history.items() if values}
|
||||
for scope, indices in scopes:
|
||||
counter_deltas: dict[str, float] = {}
|
||||
for i in indices:
|
||||
previous = self.previous.get(samples[i].key)
|
||||
if previous is None:
|
||||
continue
|
||||
for name, value in samples[i].snapshot.counters.items():
|
||||
delta = value - previous.snapshot.counters.get(name, 0.0)
|
||||
if delta >= 0:
|
||||
counter_deltas[name] = counter_deltas.get(name, 0.0) + delta
|
||||
metrics.update(
|
||||
build_scope_metrics(
|
||||
scope,
|
||||
[values_per_engine[i] for i in indices],
|
||||
[bucket_deltas_per_engine[i] for i in indices],
|
||||
counter_deltas,
|
||||
)
|
||||
)
|
||||
return metrics
|
||||
|
||||
async def stop(self):
|
||||
if self.task is not None:
|
||||
|
||||
@@ -27,7 +27,6 @@ import time
|
||||
import uuid
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import tomli_w
|
||||
import verifiers.v1 as vf
|
||||
from modelexpress import p2p_pb2
|
||||
from modelexpress.client import MxClient
|
||||
@@ -78,7 +77,6 @@ from prime_rl.trainer.rl.broadcast.nixl.model_express import ModelExpressSession
|
||||
from prime_rl.transport import setup_micro_batch_sender
|
||||
from prime_rl.utils.async_utils import EventLoopLagMonitor, EventLoopLagStats, safe_cancel
|
||||
from prime_rl.utils.client import init_nccl_broadcast, init_nixl_broadcast
|
||||
from prime_rl.utils.config import to_toml_dict
|
||||
from prime_rl.utils.heartbeat import Heartbeat
|
||||
from prime_rl.utils.logger import format_time, get_logger, setup_logger
|
||||
from prime_rl.utils.monitor import setup_monitor
|
||||
@@ -207,12 +205,6 @@ class Orchestrator:
|
||||
config = self.config
|
||||
set_default_executor()
|
||||
|
||||
# Persist the resolved config alongside the run
|
||||
config_dir = config.output_dir / "control"
|
||||
config_dir.mkdir(parents=True, exist_ok=True)
|
||||
with open(config_dir / "orch.toml", "wb") as f:
|
||||
tomli_w.dump(to_toml_dict(config), f)
|
||||
|
||||
get_logger().info(f"Initializing tokenizer ({config.tokenizer})")
|
||||
self.tokenizer = setup_tokenizer(config.tokenizer)
|
||||
|
||||
|
||||
@@ -68,14 +68,23 @@ from prime_rl.utils.utils import format_time
|
||||
from prime_rl.utils.vlm import get_language_model, get_vision_encoder, is_vlm_architecture
|
||||
|
||||
|
||||
def pre_download_model(model_name: str) -> None:
|
||||
"""Pre-download model from HuggingFace Hub so all nodes have cached weights before training."""
|
||||
def pre_download_model(model_name: str, *, skip_weights: bool = False) -> None:
|
||||
"""Pre-download model from HuggingFace Hub so all nodes have cached weights before training.
|
||||
|
||||
With ``skip_weights`` (random-init debug runs), only config and tokenizer files are fetched.
|
||||
"""
|
||||
if Path(model_name).exists():
|
||||
get_logger().info(f"Model {model_name} found at local path, skipping download")
|
||||
return
|
||||
get_logger().info(f"Pre-downloading model {model_name}")
|
||||
t0 = time.perf_counter()
|
||||
path = snapshot_download(repo_id=model_name, repo_type="model")
|
||||
if skip_weights:
|
||||
get_logger().info(f"Pre-downloading config and tokenizer for {model_name} (random init, skipping weights)")
|
||||
path = snapshot_download(
|
||||
repo_id=model_name, repo_type="model", allow_patterns=["*.json", "*.txt", "tokenizer*", "*.jinja"]
|
||||
)
|
||||
else:
|
||||
get_logger().info(f"Pre-downloading model {model_name}")
|
||||
path = snapshot_download(repo_id=model_name, repo_type="model")
|
||||
get_logger().debug(
|
||||
f"Finished pre-downloading model {model_name} to {path} in {format_time(time.perf_counter() - t0)}"
|
||||
)
|
||||
|
||||
@@ -50,7 +50,6 @@ from prime_rl.trainer.utils import (
|
||||
Tensors,
|
||||
export_benchmark_json,
|
||||
filter_rl_trainer_tensor_stats_for_wandb,
|
||||
get_zero_gradient_ratio,
|
||||
get_ckpt_disk_metrics,
|
||||
setup_torch_distributed,
|
||||
print_benchmark,
|
||||
@@ -544,8 +543,6 @@ def train(config: TrainerConfig):
|
||||
if grad_norm.device.type == "cpu":
|
||||
grad_norm = grad_norm.to(torch.device("cuda"))
|
||||
|
||||
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
|
||||
|
||||
# Update the model parameters
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
@@ -650,7 +647,6 @@ def train(config: TrainerConfig):
|
||||
# Log optimizer metrics
|
||||
optim_metrics = {
|
||||
"optim/lr": current_lr,
|
||||
"optim/zero_grad_ratio": zero_grad_ratio,
|
||||
"step": progress.step,
|
||||
}
|
||||
if grad_norm is not None:
|
||||
@@ -695,7 +691,6 @@ def train(config: TrainerConfig):
|
||||
mfu=mfu,
|
||||
entropy=tensor_stats.get("entropy/all/mean", 0.0),
|
||||
mismatch_kl=tensor_stats.get("mismatch_kl/all/mean", 0.0),
|
||||
zero_grad_ratio=zero_grad_ratio,
|
||||
)
|
||||
|
||||
# Send heartbeat if configured
|
||||
|
||||
@@ -40,7 +40,6 @@ from prime_rl.trainer.utils import (
|
||||
GarbageCollection,
|
||||
MemoryProfiler,
|
||||
export_benchmark_json,
|
||||
get_zero_gradient_ratio,
|
||||
get_ckpt_disk_metrics,
|
||||
print_sample,
|
||||
setup_torch_distributed,
|
||||
@@ -470,8 +469,6 @@ def train(config: SFTConfig):
|
||||
)
|
||||
if grad_norm.device.type == "cpu":
|
||||
grad_norm = grad_norm.to(torch.device("cuda"))
|
||||
zero_grad_ratio = get_zero_gradient_ratio(model.parameters(), parallel_dims.dp_replicate)
|
||||
|
||||
logger.debug("Optimizer step")
|
||||
optimizer.step()
|
||||
optimizer.zero_grad()
|
||||
@@ -578,7 +575,6 @@ def train(config: SFTConfig):
|
||||
# Log optimizer metrics
|
||||
optim_metrics = {
|
||||
"optim/lr": current_lr,
|
||||
"optim/zero_grad_ratio": zero_grad_ratio,
|
||||
"step": progress.step,
|
||||
}
|
||||
if grad_norm is not None:
|
||||
|
||||
@@ -4,7 +4,6 @@ import pickle
|
||||
import shutil
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -16,8 +15,7 @@ from rich import print as rich_print
|
||||
from rich.console import Console
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
from torch import Tensor, nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
from torch import Tensor
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
|
||||
from prime_rl.trainer.world import get_world
|
||||
@@ -55,62 +53,6 @@ class GarbageCollection:
|
||||
get_logger().info(f"[GC] collection took {time.monotonic() - begin:.2f}s")
|
||||
|
||||
|
||||
def _to_local_tensor(tensor: Tensor | DTensor) -> Tensor:
|
||||
if isinstance(tensor, DTensor):
|
||||
return tensor.to_local()
|
||||
return tensor
|
||||
|
||||
|
||||
def count_zero_gradient_elements(parameters: Iterable[nn.Parameter]) -> tuple[Tensor, Tensor]:
|
||||
"""Count zero-gradient parameter elements on the local distributed shards.
|
||||
|
||||
Parameters that require gradients but did not receive one in the current step
|
||||
are counted as fully zero. This makes inactive MoE experts visible in the
|
||||
metric instead of silently dropping them from the count.
|
||||
"""
|
||||
|
||||
device = torch.device("cuda", torch.cuda.current_device()) if torch.cuda.is_available() else torch.device("cpu")
|
||||
num_zeros = torch.zeros((), dtype=torch.long, device=device)
|
||||
num_tracked = torch.zeros((), dtype=torch.long, device=device)
|
||||
|
||||
for param in parameters:
|
||||
if not param.requires_grad:
|
||||
continue
|
||||
|
||||
local_param = _to_local_tensor(param.detach())
|
||||
if local_param.numel() == 0:
|
||||
continue
|
||||
|
||||
if local_param.device != num_zeros.device:
|
||||
num_zeros = num_zeros.to(local_param.device)
|
||||
num_tracked = num_tracked.to(local_param.device)
|
||||
|
||||
local_numel = torch.tensor(local_param.numel(), dtype=torch.long, device=local_param.device)
|
||||
num_tracked += local_numel
|
||||
|
||||
if param.grad is None:
|
||||
num_zeros += local_numel
|
||||
continue
|
||||
|
||||
local_grad = _to_local_tensor(param.grad.detach())
|
||||
if local_grad.numel() != local_param.numel():
|
||||
raise ValueError("Local gradient shape does not match the local parameter shape")
|
||||
|
||||
num_zeros += local_numel - torch.count_nonzero(local_grad)
|
||||
|
||||
return num_zeros, num_tracked
|
||||
|
||||
|
||||
def get_zero_gradient_ratio(parameters: Iterable[nn.Parameter], dp_replicate: int = 1) -> float:
|
||||
num_zero_grad, num_grad_elements = count_zero_gradient_elements(parameters)
|
||||
dist.all_reduce(num_zero_grad, op=dist.ReduceOp.SUM)
|
||||
dist.all_reduce(num_grad_elements, op=dist.ReduceOp.SUM)
|
||||
if dp_replicate > 1:
|
||||
num_zero_grad = torch.div(num_zero_grad, dp_replicate, rounding_mode="floor")
|
||||
num_grad_elements = torch.div(num_grad_elements, dp_replicate, rounding_mode="floor")
|
||||
return (num_zero_grad.float() / num_grad_elements.clamp_min(1).float()).item()
|
||||
|
||||
|
||||
def get_ckpt_disk_metrics(output_dir: Path) -> dict[str, float]:
|
||||
"""
|
||||
Disk usage metrics for the checkpoint directory (<output_dir>/checkpoints).
|
||||
|
||||
@@ -103,11 +103,6 @@ class MetricsServer(HealthServer):
|
||||
"trainer_mismatch_kl", "KL divergence between trainer and inference model", registry=self._registry
|
||||
)
|
||||
self._kl_ent_ratio = Gauge("trainer_kl_ent_ratio", "Ratio of mismatch KL to entropy", registry=self._registry)
|
||||
self._zero_grad_ratio = Gauge(
|
||||
"trainer_zero_grad_ratio",
|
||||
"Fraction of tracked parameter elements with zero gradient",
|
||||
registry=self._registry,
|
||||
)
|
||||
|
||||
def _make_handler(self) -> type[BaseHTTPRequestHandler]:
|
||||
"""Create handler with /metrics and /health endpoints."""
|
||||
@@ -164,7 +159,6 @@ class MetricsServer(HealthServer):
|
||||
mfu: float = 0.0,
|
||||
entropy: float = 0.0,
|
||||
mismatch_kl: float = 0.0,
|
||||
zero_grad_ratio: float = 0.0,
|
||||
) -> None:
|
||||
"""Update metrics after a training step."""
|
||||
self._step.set(step)
|
||||
@@ -177,7 +171,6 @@ class MetricsServer(HealthServer):
|
||||
self._mfu.set(mfu)
|
||||
self._entropy.set(entropy)
|
||||
self._mismatch_kl.set(mismatch_kl)
|
||||
self._zero_grad_ratio.set(zero_grad_ratio)
|
||||
if entropy > 0:
|
||||
self._kl_ent_ratio.set(mismatch_kl / entropy)
|
||||
self._last_step_ts.set(time.time())
|
||||
|
||||
@@ -322,11 +322,32 @@ PERFORMANCE_METRICS = [
|
||||
"time/step",
|
||||
"time/wait_for_batch",
|
||||
"time/wait_for_policy",
|
||||
"inference/agg/throughput",
|
||||
"inference/agg/running_requests",
|
||||
"inference/agg/waiting_requests",
|
||||
"inference/agg/kv_cache_usage_mean",
|
||||
"inference/agg/prefix_cache_hit_rate",
|
||||
]
|
||||
|
||||
# Inference health panels: each pairs the fleet aggregate (mean/sum) with the cross-engine
|
||||
# tail that flags a single sick engine - max for pressure metrics, min for health metrics.
|
||||
# One saturated engine thrashing its KV cache (preempt -> re-prefill -> cache eviction) hides
|
||||
# inside fleet means; the max/min series is what surfaces it.
|
||||
INFERENCE_PANELS = [
|
||||
[
|
||||
"inference/agg/kv_cache_usage_perc/mean",
|
||||
"inference/agg/kv_cache_usage_perc/min",
|
||||
"inference/agg/kv_cache_usage_perc/max",
|
||||
],
|
||||
["inference/agg/num_preemptions_total:rate/sum", "inference/agg/num_preemptions_total:rate/max"],
|
||||
[
|
||||
"inference/agg/num_requests_running/mean",
|
||||
"inference/agg/num_requests_running/min",
|
||||
"inference/agg/num_requests_running/max",
|
||||
],
|
||||
[
|
||||
"inference/agg/num_requests_waiting/mean",
|
||||
"inference/agg/num_requests_waiting/min",
|
||||
"inference/agg/num_requests_waiting/max",
|
||||
],
|
||||
["inference/agg/prefix_cache_hit_rate/pooled", "inference/agg/prefix_cache_hit_rate/min"],
|
||||
["inference/agg/generation_tokens_total:rate/sum", "inference/agg/generation_tokens_total:rate/min"],
|
||||
["inference/agg/prompt_tokens_total:rate/sum", "inference/agg/prompt_tokens_total:rate/max"],
|
||||
]
|
||||
|
||||
# Dense grid: more, smaller panels per row and enough rows that sections don't paginate.
|
||||
@@ -344,6 +365,16 @@ def line_panels(metrics: Sequence[str], regexes: Sequence[str]) -> list[wr.LineP
|
||||
]
|
||||
|
||||
|
||||
def inference_section() -> ws.Section:
|
||||
# Multi-series panels (aggregate + tail), on wall time like all inference/* metrics.
|
||||
return ws.Section(
|
||||
name="inference",
|
||||
is_open=True,
|
||||
panels=[wr.LinePlot(x="RelativeTime(Wall)", y=list(series)) for series in INFERENCE_PANELS],
|
||||
layout_settings=ws.SectionLayoutSettings(columns=COLUMNS, rows=ROWS),
|
||||
)
|
||||
|
||||
|
||||
def section(name: str, metrics: Sequence[str] = (), regexes: Sequence[str] = ()) -> ws.Section:
|
||||
return ws.Section(
|
||||
name=name,
|
||||
@@ -393,6 +424,7 @@ def build_sections(train_envs: Sequence[str] = (), eval_envs: Sequence[str] = ()
|
||||
# Env names unknown (e.g. SFT): one regex section matching any eval env.
|
||||
sections.append(eval_section("eval", ".*"))
|
||||
sections.append(section("stability", metrics=STABILITY_METRICS))
|
||||
sections.append(inference_section())
|
||||
sections.append(section("performance", metrics=PERFORMANCE_METRICS))
|
||||
return sections
|
||||
|
||||
|
||||
@@ -5014,19 +5014,21 @@ requires-dist = [
|
||||
|
||||
[[package]]
|
||||
name = "prime-sandboxes"
|
||||
version = "0.2.35"
|
||||
version = "0.2.36"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiofiles" },
|
||||
{ name = "certifi" },
|
||||
{ name = "connect-python" },
|
||||
{ name = "httpx" },
|
||||
{ name = "protobuf" },
|
||||
{ name = "pydantic" },
|
||||
{ name = "pyqwest" },
|
||||
{ name = "tenacity" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/57/cc/287c0db192ddbe003bd5882d1aab5461cdb3912d0c92db7b39734a9e828e/prime_sandboxes-0.2.35.tar.gz", hash = "sha256:e716bfccdcb51aefd5e2d48fdfc3a79bea8c6825bce1871f49f095ced03efc94", size = 86226, upload-time = "2026-08-05T14:29:53.33Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d5/c8/ca5261ff5d5c2e944e198866ead91b09bc88eb0390a905925bb6d7f9cd28/prime_sandboxes-0.2.36.tar.gz", hash = "sha256:3a5c8a7912b1ea0fb775674650835f7f86aac1a05aa8566c2db129b9a622fe55", size = 88415, upload-time = "2026-08-12T23:30:15.214Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/25/07/c186395925f780b1a18b350f562ebc4e8a64a182c37bd1e3db3948f297e2/prime_sandboxes-0.2.35-py3-none-any.whl", hash = "sha256:29d7057532b21545be5938d3aee822ae3a54085a45934d5c3ac55190e06c5bbb", size = 47189, upload-time = "2026-08-05T14:29:52.142Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0b/26/081296fc8e6d8ce962f2aee0e47ac843982094dedb34a1fad22d10086f37/prime_sandboxes-0.2.36-py3-none-any.whl", hash = "sha256:a5db92d927cf4a3dd37ce230027a9d83dbf21804d4f6ed2255d276c1962fa8f2", size = 49316, upload-time = "2026-08-12T23:30:14.047Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7461,7 +7463,7 @@ requires-dist = [
|
||||
{ name = "openai-agents", specifier = ">=0.8.2" },
|
||||
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
|
||||
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.2" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.35" },
|
||||
{ name = "prime-sandboxes", specifier = ">=0.2.36" },
|
||||
{ name = "prime-tunnel", specifier = ">=0.1.8" },
|
||||
{ name = "pydantic", specifier = ">=2.12.3" },
|
||||
{ name = "python-dotenv", marker = "extra == 'browser'", specifier = ">=1.0.0" },
|
||||
|
||||
Reference in New Issue
Block a user