feat: improve route throughput and reconcile delayed validation outcomes

This commit is contained in:
CoolBoy committed 2026-11-12 03:10:51 +08:00
1 parent 5dead8172c
commit 43ecd36c0e
13 files changed
+468 -83

No files matched your search

+53 -50
View File
@@ -8,6 +8,7 @@ from typing import Any
from common import read_json, utc_now, write_json
from gpu_strategy import wilson_lower_bound
from submission_claims import candidate_key
from profile_admission import profile_key
ROUTING_STATE_VERSION = 1
@@ -15,7 +16,7 @@ DEFAULT_ROUTING_STATE_PATH = Path(".modelhub_state/routing_intelligence.json")
class SuccessFirstRoutingEngine:
"""Deterministic success-first routing; queue speed only breaks close races."""
"""Evidence-shrunk routing retaining alternatives through batch admission."""
def __init__(
self,
@@ -45,7 +46,7 @@ class SuccessFirstRoutingEngine:
}
return value
def _evidence(self, candidate: dict[str, Any]) -> tuple[str, int, int, float]:
def _evidence(self, candidate: dict[str, Any]) -> tuple[str, float, float, float]:
def observed_total(item: dict[str, Any]) -> int:
if "failureCount" in item:
return max(0, int(item.get("successCount") or 0) + int(item.get("failureCount") or 0)
@@ -70,18 +71,16 @@ class SuccessFirstRoutingEngine:
total = observed_total(item)
if total:
sparse = ("local_profile_size_shrunk", item, total)
if total >= 20:
success = int(item.get("successCount") or 0)
return "local_profile_size", success, total, wilson_lower_bound(success, total)
if model_type:
key = f"{gpu}|{framework}|{task_type}|{model_type}|{quantization}"
item = (self.outcome_stats.get("profileCombinationStats") or {}).get(key) or {}
total = observed_total(item)
if total and sparse is None:
sparse = ("local_profile_shrunk", item, total)
if total >= 40:
success = int(item.get("successCount") or 0)
return "local_profile", success, total, wilson_lower_bound(success, total)
exact = (self.outcome_stats.get("encodingCombinationStats") or {}).get(
"|".join(profile_key(candidate) or ())) or {}
if observed_total(exact):
sparse = ("local_encoding_shrunk", exact, observed_total(exact))
public_samples = max(0, int(candidate.get("frameworkMarketSamples") or 0))
public_rate = candidate.get("frameworkMarketSuccessRate")
if public_rate is None:
@@ -92,27 +91,26 @@ class SuccessFirstRoutingEngine:
local_rate = candidate.get("frameworkLocalSuccessRate")
local_success = 0 if local_rate is None else max(0, min(local_samples, round(float(local_rate) * local_samples)))
if local_samples >= 100:
total = local_samples
success = local_success
level = "local_task_gpu_framework"
elif public_samples >= 300:
if public_samples > 0:
total = public_samples
success = public_success
level = "official_task_gpu_framework"
elif public_samples > 0:
total = public_samples
success = public_success
level = "official_low_sample"
else:
total = 2
success = 1
level = "global_conservative_prior"
if local_samples:
# Public and local populations may overlap. Public evidence is a
# bounded prior, not thousands of additional independent trials.
strength = min(12, total)
success = local_success + strength * success / max(1, total)
total = local_samples + strength
level = "local_task_gpu_framework_shrunk"
if sparse is not None:
level, item, samples = sparse
# Eight prior observations stabilize small groups without hiding
# their failures behind an unreachable hard sample threshold.
prior_success = round(8 * success / max(1, total))
prior_success = 8 * success / max(1, total)
success = int(item.get("successCount") or 0) + prior_success
total = samples + 8
return level, success, total, wilson_lower_bound(success, total)
@@ -125,26 +123,35 @@ class SuccessFirstRoutingEngine:
eta = max(0.25, float(raw_eta))
if not math.isfinite(eta) or eta >= 9999:
raise ValueError
eta_unknown = False
# total/pages-based backlog estimates are not validated durations.
eta_unknown = not bool(candidate.get("queueEtaValidated"))
except (TypeError, ValueError):
eta = 36.0
eta = None
eta_unknown = True
success_band = int(lower / 0.05)
expected = (lower * lower) / eta
mean = success / max(1, total)
platform_failures = max(0, int(candidate.get("frameworkRecentPlatformFailures") or 0))
recent_total = max(platform_failures, int(candidate.get("frameworkRecentTerminalSamples") or 0))
health = 1 - platform_failures / (recent_total + 8)
mean *= health
lower *= health
success_band = int(lower / 0.05) # Legacy report field, not a ranking key.
expected = mean / eta if not eta_unknown else None
annotated.update(
{
"routingEvidenceLevel": evidence,
"routingSuccesses": success,
"routingSamples": total,
"routingSuccessLowerBound": lower,
"routingSuccessEstimate": mean,
"routingPlatformHealth": health,
"routingSuccessBand": success_band,
"routingEtaHours": eta,
"routingEtaHours": eta if not eta_unknown else None,
"routingEtaUnknown": eta_unknown,
"routingExpectedSuccessPerHour": expected,
"routingCommunityModelSuccesses": max(
0, int(candidate.get("communitySuccessfulGpuCount") or 0)
),
"strategyCategory": "unified_success_first",
"strategyCategory": "evidence_throughput_v2",
}
)
return annotated
@@ -173,30 +180,26 @@ class SuccessFirstRoutingEngine:
)
if non_transformers and not transformers_unlocked:
routes = non_transformers
best = max(float(item["routingSuccessLowerBound"]) for item in routes)
close = [item for item in routes if best - float(item["routingSuccessLowerBound"]) <= 0.05]
close.sort(
key=lambda item: (
-int(item["routingSuccessBand"]),
-float(item["routingExpectedSuccessPerHour"]),
-int(item["routingSamples"]),
str(item.get("targetGpu") or ""),
str(item.get("framework") or ""),
)
)
selected.append(close[0])
# Keep alternatives until admission, not just the top route.
selected.extend(routes)
selected.sort(
key=lambda item: (
-int(item["routingSuccessBand"]),
-float(item["routingExpectedSuccessPerHour"]),
-int(item.get("routingCommunityModelSuccesses") or 0),
-int(item["routingSamples"]),
-int(item.get("downloads") or 0),
str(item.get("repoId") or ""),
)
)
return selected
# Continuous quality frontiers, anchored to the best remaining route:
# no fixed 5% bin boundaries. Only validated duration estimates may
# trade off quality within a three-percentage-point frontier.
remaining = sorted(selected, key=lambda item: -item["routingSuccessLowerBound"])
ordered = []
while remaining:
best = remaining[0]["routingSuccessLowerBound"]
split = next((i for i, r in enumerate(remaining)
if best - r["routingSuccessLowerBound"] > 0.03), len(remaining))
front, remaining = remaining[:split], remaining[split:]
if all(not r["routingEtaUnknown"] for r in front):
front.sort(key=lambda r: (-r["routingExpectedSuccessPerHour"], -r["routingSuccessLowerBound"]))
else:
front.sort(key=lambda r: (-r["routingSuccessLowerBound"], -r["routingSuccessEstimate"],
-r["routingCommunityModelSuccesses"], str(r.get("repoId"))))
ordered.extend(front)
return ordered
@property
def submissions_until_refresh(self) -> int:
@@ -212,8 +215,8 @@ class SuccessFirstRoutingEngine:
routes[key] = int(routes.get(key) or 0) + 1
self.state["acceptedTotal"] = int(self.state.get("acceptedTotal") or 0) + len(candidates)
self.state["acceptedSinceRefresh"] = int(self.state.get("acceptedSinceRefresh") or 0) + len(candidates)
categories = self.state.setdefault("acceptedByCategory", {"unified_success_first": 0})
categories["unified_success_first"] = int(categories.get("unified_success_first") or 0) + len(candidates)
categories = self.state.setdefault("acceptedByCategory", {})
categories["evidence_throughput_v2"] = int(categories.get("evidence_throughput_v2") or 0) + len(candidates)
self.state["generatedAt"] = utc_now().isoformat()
write_json(self.path, self.state)
return self.state
@@ -221,7 +224,7 @@ class SuccessFirstRoutingEngine:
def summary(self) -> dict[str, Any]:
return {
"enabled": True,
"mode": "unified_success_first",
"mode": "evidence_throughput_v2",
"statePath": str(self.path),
"acceptedTotal": int(self.state.get("acceptedTotal") or 0),
"routeCount": len(self.state.get("acceptedByRoute") or {}),