feat: improve route throughput and reconcile delayed validation outcomes
This commit is contained in:
1 parent
5dead8172c
commit
43ecd36c0e
13 files changed
+468
-83
No files matched your search
@@ -41,6 +41,7 @@ TARGET_DOCKER_IMAGE_PATTERN = re.compile(
|
||||
re.IGNORECASE,
|
||||
)
|
||||
FRAMEWORK_IMAGE_MARKERS = (
|
||||
("vllm_tokenizer_patch", ("vllm-tokenizer-patch", "vllm_tokenizer_patch")),
|
||||
("vllm-customized", ("vllm-customized", "vllm_customized")),
|
||||
("vllm_fix_tokenizer", ("vllm-fix-tokenizer", "vllm_fix_tokenizer")),
|
||||
("sentence-transformers", ("sentence-transformers", "sentence_transformers")),
|
||||
|
||||
@@ -64,6 +64,7 @@ SEMANTIC_POLICIES: dict[str, FailureClassification] = {
|
||||
}
|
||||
|
||||
PLATFORM_PATTERNS = (
|
||||
(re.compile(r"fork/exec\s+/[^\n]*container-runtime:\s*no such file or directory", re.I), "missing_host_container_runtime"),
|
||||
(re.compile(r"welcome\.sh: No such file|data: command not found", re.I), "broken_platform_launch_script"),
|
||||
(re.compile(r"id_rsa.*No such file", re.I), "missing_platform_credential"),
|
||||
(re.compile(r"找不到空闲卡|no idle (?:gpu|card)", re.I), "no_idle_device"),
|
||||
|
||||
@@ -1699,7 +1699,10 @@ def run_submission(
|
||||
capacity_saturated = False
|
||||
|
||||
if args.dry_run:
|
||||
attempted_candidates = diversified_candidates[:target_submit_count]
|
||||
attempted_candidates = filter_profile_batch(
|
||||
diversified_candidates, outcome_tracker.pending_records(), outcome_tracker.get_stats_report(),
|
||||
max_selected=target_submit_count,
|
||||
)[0]
|
||||
else:
|
||||
claim_store = SubmissionClaimStore(
|
||||
Path(getattr(args, "claims_path", DEFAULT_CLAIMS_PATH)),
|
||||
@@ -1718,28 +1721,38 @@ def run_submission(
|
||||
# already-scanned pool until the desired number of real submissions is
|
||||
# reached or account capacity is genuinely exhausted.
|
||||
while len(submitted) < target_submit_count and len(attempted_candidates) < max_submit_attempts:
|
||||
submitted_models = {row["repoId"] for row in submitted}
|
||||
remaining_candidates = [
|
||||
candidate
|
||||
for candidate in diversified_candidates
|
||||
if candidate_key(candidate) not in attempted_keys
|
||||
and candidate["repoId"] not in submitted_models
|
||||
and not submission_exclusion_store.is_blocked(candidate["repoId"], candidate["targetGpu"])
|
||||
]
|
||||
remaining_candidates = one_candidate_per_model(remaining_candidates)
|
||||
remaining_candidates, profile_deferred = filter_profile_batch(
|
||||
remaining_candidates, outcome_tracker.pending_records(), profile_stats,
|
||||
)
|
||||
for candidate in profile_deferred:
|
||||
attempted_keys.add(candidate_key(candidate))
|
||||
skipped.append({"repoId": candidate["repoId"], "targetGpu": candidate["targetGpu"],
|
||||
"reason": "profile_feedback_deferred", "deferred": True})
|
||||
desired_count = min(
|
||||
target_submit_count - len(submitted),
|
||||
max_submit_attempts - len(attempted_candidates),
|
||||
)
|
||||
if state_sync is not None:
|
||||
desired_count = min(desired_count, int(state_sync.batch_size))
|
||||
remaining_candidates, profile_deferred = filter_profile_batch(
|
||||
remaining_candidates, outcome_tracker.pending_records(), profile_stats,
|
||||
max_selected=desired_count,
|
||||
)
|
||||
for candidate in profile_deferred:
|
||||
attempted_keys.add(candidate_key(candidate))
|
||||
skipped.append({"repoId": candidate["repoId"], "targetGpu": candidate["targetGpu"],
|
||||
"reason": "profile_feedback_deferred", "deferred": True})
|
||||
batch_candidates = claim_store.claim(remaining_candidates, limit=desired_count)
|
||||
claimed_keys = {candidate_key(candidate) for candidate in batch_candidates}
|
||||
for candidate in remaining_candidates:
|
||||
if candidate_key(candidate) not in claimed_keys:
|
||||
attempted_keys.add(candidate_key(candidate))
|
||||
skipped.append({"repoId": candidate["repoId"], "targetGpu": candidate["targetGpu"],
|
||||
"reason": "route_claim_deferred", "deferred": True})
|
||||
if not batch_candidates:
|
||||
if remaining_candidates:
|
||||
continue # A claimed first choice must not hide alternatives.
|
||||
break
|
||||
attempted_candidates.extend(batch_candidates)
|
||||
attempted_keys.update(candidate_key(candidate) for candidate in batch_candidates)
|
||||
|
||||
@@ -833,6 +833,8 @@ class MarketIntelligenceManager:
|
||||
"localScore": local_score if local_samples else None,
|
||||
"recentLocalSamples": recent_samples,
|
||||
"recentLocalSuccessRate": recent_rate,
|
||||
"recentPlatformFailures": max(0, int(recent_item.get("platformFailureCount") or 0)),
|
||||
"recentTerminalSamples": recent_success + recent_all_failures,
|
||||
"consecutiveLocalFailures": consecutive_failures,
|
||||
"consecutivePlatformFailures": consecutive_platform_failures,
|
||||
"circuitOpen": circuit_open,
|
||||
@@ -1008,6 +1010,8 @@ class MarketIntelligenceManager:
|
||||
"frameworkLocalSuccessRate": evidence["localSuccessRate"],
|
||||
"frameworkRecentLocalSamples": evidence["recentLocalSamples"],
|
||||
"frameworkRecentLocalSuccessRate": evidence["recentLocalSuccessRate"],
|
||||
"frameworkRecentPlatformFailures": evidence["recentPlatformFailures"],
|
||||
"frameworkRecentTerminalSamples": evidence["recentTerminalSamples"],
|
||||
"frameworkConsecutiveLocalFailures": evidence["consecutiveLocalFailures"],
|
||||
"frameworkCombinedScore": evidence["combinedScore"],
|
||||
"frameworkMarketQualified": evidence["publicQualified"],
|
||||
|
||||
@@ -216,7 +216,8 @@ class ModelHubClient:
|
||||
) -> list[dict[str, Any]]:
|
||||
current = 1
|
||||
records: list[dict[str, Any]] = []
|
||||
while True:
|
||||
seen: set[str] = set()
|
||||
while current <= 1000:
|
||||
page = self.list_tasks_page(
|
||||
current=current,
|
||||
page_size=page_size,
|
||||
@@ -228,16 +229,26 @@ class ModelHubClient:
|
||||
status=status,
|
||||
verify_result=verify_result,
|
||||
)
|
||||
page_data = page.get("data") or {}
|
||||
page_records = page_data.get("records") or []
|
||||
records.extend(page_records)
|
||||
page_data = page.get("data")
|
||||
if not isinstance(page_data, dict) or not isinstance(page_data.get("records"), list):
|
||||
raise ModelHubAPIError("Invalid task history page")
|
||||
page_records = page_data["records"]
|
||||
if not page_records:
|
||||
return records
|
||||
before = len(seen)
|
||||
for task in page_records:
|
||||
if not isinstance(task, dict) or not task.get("taskId"):
|
||||
raise ModelHubAPIError("Invalid task history record")
|
||||
task_id = str(task["taskId"])
|
||||
if task_id not in seen:
|
||||
seen.add(task_id)
|
||||
records.append(task)
|
||||
if len(seen) == before:
|
||||
raise ModelHubAPIError("Task history pagination made no progress")
|
||||
if max_records > 0 and len(records) >= max_records:
|
||||
return records[:max_records]
|
||||
pages = int(page_data.get("pages") or 0)
|
||||
if pages <= current or not page_records:
|
||||
break
|
||||
current += 1
|
||||
return records
|
||||
raise ModelHubAPIError("Task history pagination budget exhausted")
|
||||
|
||||
def add_task(self, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return self._request("POST", "/api/adapt/task/add", data=payload)
|
||||
@@ -923,17 +934,26 @@ class ModelHubClientPool:
|
||||
# Default: use only the reader client to avoid fanout amplification.
|
||||
# The fanout_all parameter allows explicit cross-account merging when needed.
|
||||
fanout_all = kwargs.pop("_fanout_all", False)
|
||||
strict = kwargs.pop("_strict", False)
|
||||
if not fanout_all:
|
||||
if strict:
|
||||
return self._reader.list_tasks(**kwargs)
|
||||
return self._safe_list_tasks(self._reader, kwargs)
|
||||
|
||||
merged: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
with ThreadPoolExecutor(max_workers=min(len(self.clients), 12)) as executor:
|
||||
futures = {executor.submit(self._safe_list_tasks, client, kwargs): index for index, client in enumerate(self.clients)}
|
||||
futures = {
|
||||
(executor.submit(client.list_tasks, **kwargs) if strict else
|
||||
executor.submit(self._safe_list_tasks, client, kwargs)): index
|
||||
for index, client in enumerate(self.clients)
|
||||
}
|
||||
for future in as_completed(futures):
|
||||
try:
|
||||
tasks = future.result()
|
||||
except Exception:
|
||||
if strict:
|
||||
raise ModelHubAPIError("Incomplete cross-account task history") from None
|
||||
tasks = []
|
||||
for task in tasks:
|
||||
task_id = str(task.get("taskId")) if task.get("taskId") is not None else None
|
||||
|
||||
@@ -46,6 +46,7 @@ DECISION_RECORD_FIELDS = {
|
||||
"taskType",
|
||||
"submitTime",
|
||||
"lastSyncTime",
|
||||
"lastOutcomeReconcileAt",
|
||||
"status",
|
||||
"verifyResult",
|
||||
"outcome",
|
||||
@@ -436,16 +437,49 @@ class OutcomeTracker:
|
||||
task_contexts: dict[str, dict[str, Any]] | None = None,
|
||||
) -> int:
|
||||
try:
|
||||
begin = self._last_sync_time
|
||||
# A small overlap tolerates delayed publication and boundary timestamps.
|
||||
begin = self._last_sync_time - timedelta(hours=24)
|
||||
end = utc_now()
|
||||
# Use fanout for pools to sync outcomes across all accounts
|
||||
list_kwargs: dict[str, Any] = {"begin_time": begin, "end_time": end, "page_size": 100, "only_mine": True}
|
||||
if isinstance(client, ModelHubClientPool):
|
||||
list_kwargs["_fanout_all"] = True
|
||||
tasks = client.list_tasks(**list_kwargs)
|
||||
except Exception:
|
||||
list_kwargs["_strict"] = True
|
||||
tasks = list(client.list_tasks(**list_kwargs))
|
||||
except Exception as exc:
|
||||
print(f"[outcome-sync] status=deferred reason=history_read_failed error={type(exc).__name__} cursor_advanced=false", flush=True)
|
||||
return 0
|
||||
|
||||
# Time filters are not sufficient to discover old tasks completing late.
|
||||
# Reconcile a bounded, rotating set of known pending models without a
|
||||
# time filter. Never infer completion from disappearance alone.
|
||||
pending_by_model: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
for record in self._records:
|
||||
if record.get("outcome") == "pending" and record.get("modelId"):
|
||||
pending_by_model[str(record["modelId"])].append(record)
|
||||
floor = datetime.min.replace(tzinfo=end.tzinfo)
|
||||
def checked_at(rows):
|
||||
return max((parse_datetime(r.get("lastOutcomeReconcileAt")) or floor for r in rows), default=floor)
|
||||
eligible = [(model, rows) for model, rows in pending_by_model.items()
|
||||
if checked_at(rows) < end - timedelta(minutes=15)]
|
||||
eligible.sort(key=lambda item: (checked_at(item[1]), item[0]))
|
||||
reconciled = 0
|
||||
for model, rows in eligible[:4]:
|
||||
kwargs = {"model_id": model, "page_size": 100, "only_mine": True}
|
||||
if isinstance(client, ModelHubClientPool):
|
||||
kwargs.update({"_fanout_all": True, "_strict": True})
|
||||
for row in rows:
|
||||
row["lastOutcomeReconcileAt"] = end.isoformat()
|
||||
reconciled += 1
|
||||
try:
|
||||
wanted = {str(row.get("taskId")) for row in rows}
|
||||
tasks.extend(task for task in client.list_tasks(**kwargs)
|
||||
if str(task.get("taskId")) in wanted)
|
||||
except Exception as exc:
|
||||
print(f"[outcome-sync] reconciliation=deferred error={type(exc).__name__}", flush=True)
|
||||
# Overlap and model reconciliation may return the same task more than once.
|
||||
tasks = list({str(t.get("taskId")): t for t in tasks if t.get("taskId")}.values())
|
||||
|
||||
updated_count = 0
|
||||
enrichment_candidates: list[dict[str, Any]] = []
|
||||
for task in tasks:
|
||||
@@ -481,6 +515,11 @@ class OutcomeTracker:
|
||||
updated_count += 1
|
||||
else:
|
||||
status = str(task.get("status") or "").lower()
|
||||
# Overlap is for refreshing known tasks, not re-importing old
|
||||
# terminal rows already folded into a compact checkpoint.
|
||||
timestamp = parse_datetime(task.get("updateTime"))
|
||||
if self._checkpoint and timestamp and timestamp < self._last_sync_time:
|
||||
continue
|
||||
if status in TERMINAL_TASK_STATUSES:
|
||||
record = self._create_record_from_task(task)
|
||||
self._records.append(record)
|
||||
@@ -512,12 +551,14 @@ class OutcomeTracker:
|
||||
enrichment_candidates[:FAILURE_ENRICHMENT_LIMIT]
|
||||
)
|
||||
|
||||
if updated_count or enrichment_attempts:
|
||||
if updated_count or enrichment_attempts or reconciled:
|
||||
self._last_sync_time = end
|
||||
self._rebuild_failed_index()
|
||||
write_jsonl(self.recent_path, self._recent_records)
|
||||
self.save()
|
||||
|
||||
print(f"[outcome-sync] tasks={len(tasks)} updated={updated_count} reconciled_models={reconciled} pending={len(self.pending_records())}", flush=True)
|
||||
|
||||
return updated_count
|
||||
|
||||
def bootstrap_from_history_tasks(
|
||||
|
||||
@@ -13,29 +13,62 @@ def profile_key(row: dict[str, Any]) -> tuple[str, ...] | None:
|
||||
model_type, str(profile.get("quantizationSignature") or profile.get("quantizationMethod") or "none"))
|
||||
|
||||
|
||||
def filter_profile_batch(candidates, pending, stats, *, limit=2):
|
||||
def profile_budget(candidate, stats, *, limit=2):
|
||||
"""Expand useful public-evidence routes without requiring local exploration.
|
||||
|
||||
Broad evidence earns modest concurrency, not unlimited profile trust.
|
||||
Specific negative evidence prevents that expansion.
|
||||
"""
|
||||
key = profile_key(candidate)
|
||||
evidence = (stats.get("encodingCombinationStats") or {}).get("|".join(key or ())) or {}
|
||||
successes = int(evidence.get("successCount") or 0)
|
||||
failures = max(0, int(evidence.get("failureCount") or 0) - int(evidence.get("platformFailureCount") or 0))
|
||||
if successes >= 3 and successes / max(1, successes + failures) >= 0.5:
|
||||
return None, "proven_encoding"
|
||||
profile = candidate.get("preflightMetadata") or {}
|
||||
family = "|".join((*key[:4], str(profile.get("quantizationMethod") or "none"))) if key else ""
|
||||
broad = (stats.get("profileCombinationStats") or {}).get(family) or {}
|
||||
negative = failures > successes or int(broad.get("failureCount") or 0) > int(broad.get("successCount") or 0)
|
||||
public_strong = (candidate.get("frameworkEvidenceQualified")
|
||||
and candidate.get("frameworkOfficialConfigValid")
|
||||
and not candidate.get("frameworkCircuitOpen")
|
||||
and float(candidate.get("frameworkMarketWilsonLowerBound") or 0) >= 0.60
|
||||
and int(candidate.get("frameworkMarketSamples") or 0) >= 300)
|
||||
if public_strong and not negative:
|
||||
return max(limit, 4), "strong_public_evidence"
|
||||
return limit, "limited_profile_evidence"
|
||||
|
||||
|
||||
def filter_profile_batch(candidates, pending, stats, *, limit=2, max_selected=None):
|
||||
"""Reservations include the whole proposed batch; deferred rows are retryable.
|
||||
|
||||
Broad public framework statistics are not proof for a specific encoding.
|
||||
Exact-encoding successes can lift the cap, provided the observed success
|
||||
rate remains at least 50%. Missing legacy signatures cannot grant this.
|
||||
Public evidence can expand the cap modestly; exact-encoding successes can
|
||||
lift it. Model alternatives are considered only until a route is admitted.
|
||||
Reservations are made only for the requested batch, not the whole pool.
|
||||
"""
|
||||
counts = Counter(profile_key(row) for row in pending if row.get("outcome") == "pending")
|
||||
selected, deferred = [], []
|
||||
selected_models = set()
|
||||
for candidate in candidates:
|
||||
if max_selected is not None and len(selected) >= max_selected:
|
||||
break
|
||||
model = candidate.get("repoId") or candidate.get("modelAddress")
|
||||
if model and model in selected_models:
|
||||
continue
|
||||
key = profile_key(candidate)
|
||||
evidence = (stats.get("encodingCombinationStats") or {}).get("|".join(key or ())) or {}
|
||||
successes = int(evidence.get("successCount") or 0)
|
||||
failures = max(0, int(evidence.get("failureCount") or 0) - int(evidence.get("platformFailureCount") or 0))
|
||||
proven = successes >= 3 and successes / max(1, successes + failures) >= 0.5
|
||||
budget, reason = profile_budget(candidate, stats, limit=limit)
|
||||
candidate["profileAdmissionBudget"] = budget
|
||||
candidate["profileAdmissionReason"] = reason
|
||||
# Count legacy records with the same method as well, conservatively.
|
||||
legacy = 0
|
||||
if key and ":" in key[-1]:
|
||||
legacy = counts.get((*key[:-1], key[-1].split(":", 1)[0]), 0)
|
||||
if key and not proven and counts[key] + legacy >= limit:
|
||||
if key and budget is not None and counts[key] + legacy >= budget:
|
||||
deferred.append(candidate)
|
||||
continue
|
||||
selected.append(candidate)
|
||||
if model:
|
||||
selected_models.add(model)
|
||||
if key:
|
||||
counts[key] += 1
|
||||
return selected, deferred
|
||||
@@ -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 {}),
|
||||
|
||||
@@ -37,7 +37,7 @@ DEFAULT_CRASH_RECORDS = 50
|
||||
STATE_OUTCOME_FIELDS = {
|
||||
"agentVersion", "instanceId", "strategyId",
|
||||
"taskId", "modelId", "targetGpu", "framework", "taskType", "submitTime",
|
||||
"lastSyncTime", "status", "verifyResult", "outcome", "failReason",
|
||||
"lastSyncTime", "lastOutcomeReconcileAt", "status", "verifyResult", "outcome", "failReason",
|
||||
"modelProfile", "failureCode", "failureCategory", "failureScope",
|
||||
"failureAction", "failureDeterministic", "failureNeedsLlm",
|
||||
"failureClassificationReason", "failureObservedGpuMemoryGiB",
|
||||
|
||||
@@ -1 +1 @@
|
||||
AGENT_VERSION = "2026.10.28.1"
|
||||
AGENT_VERSION = "2026.11.12.1"
|
||||
Reference in new issue
Block a user