GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — cortex/src/cortex/challenges/client.py at main · CortexLM/cortex Expand file tree/ Copy pathclient.pyMore file actions 128 lines (111 loc) · 5.32 KB / Copy pathclient.pyFile metadata and controls128 lines (111 loc) · 5.32 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 """Read container weights once per completed epoch and turn them into leaf scores.""" from __future__ import annotations import asyncio import json import math from dataclasses import dataclass from fractions import Fraction from pathlib import Path import httpx from cortex.errors import ServiceError from cortex.http import read_private_file from cortex.protocol.crypto import decode_hotkey from cortex.protocol.models import FULL_SHARE_SCORE, NoScore, NoScoreReason, Score from cortex.protocol.scale import uint from .registry import RegistryEntry MAX_RESPONSE_BYTES = 8 * 1024 * 1024 MAX_WEIGHTS = 65536 MAX_SCORE = 2**64 - 1 ATTEMPTS = 3 @dataclass(frozen=True) class ChallengeWeights: weights: dict[bytes, Fraction] full_share_mass: Fraction | None = None def parse_weights(body: bytes, *, slug: str, epoch: int) -> ChallengeWeights: def finite(value: object) -> Fraction: if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError("weight must be a number") if not math.isfinite(value) or value < 0: raise ValueError("weight must be finite and non-negative") return Fraction(value) document = json.loads(body, parse_constant=lambda _: math.nan) if ( not isinstance(document, dict) or document.get("challenge_slug") != slug or document.get("epoch") != epoch or not isinstance(document.get("weights"), dict) or len(document["weights"]) > MAX_WEIGHTS ): raise ValueError("weights response does not match the requested challenge epoch") weights: dict[bytes, Fraction] = {} for key, value in document["weights"].items(): hotkey = decode_hotkey(key) if hotkey in weights: raise ValueError("duplicate hotkey in weights response") weights[hotkey] = finite(value) mass = document.get("full_share_mass") return ChallengeWeights(weights, None if mass is None else finite(mass)) def leaf_scores( answer: ChallengeWeights, expected: set[bytes], *, algorithm_version: int ) -> dict[bytes, Score | NoScore]: """Exact-E scores. Hotkeys outside E are ignored and never change the denominator.""" kept = {key: value for key, value in answer.weights.items() if key in expected and value > 0} if algorithm_version == 3: denominator = max(sum(kept.values(), Fraction(0)), answer.full_share_mass or Fraction(0)) raw = { key: math.floor(FULL_SHARE_SCORE * value / denominator) for key, value in kept.items() } elif algorithm_version == 2: # Algorithm 2 signs raw integer counts; the protocol applies the Bounty cap. if any(value.denominator != 1 or value > MAX_SCORE for value in kept.values()): raise ValueError("algorithm 2 weights must be u64 integers") raw = {key: int(value) for key, value in kept.items()} else: # Algorithm 1 signed Bounty's legacy champion lattice, which a container never # computes; its share burns instead of paying a score with other semantics. raise ValueError("container challenges are not scored under algorithm 1") return { key: Score(raw[key]) if raw.get(key, 0) > 0 else NoScore(NoScoreReason.NOT_ATTEMPTED) for key in expected } class ChallengeClient: """The master's only call into a container; internal tokens never leave this process.""" def __init__(self, http: httpx.AsyncClient, secrets_dir: Path, *, retry_seconds: float = 5): self.http, self.secrets_dir, self.retry_seconds = http, secrets_dir, retry_seconds async def weights( self, entry: RegistryEntry, epoch: int, *, epoch_at: int | None = None ) -> ChallengeWeights: params = {"epoch": str(epoch)} if epoch_at is not None: uint(epoch_at, 8) if epoch_at == 0: raise ValueError("epoch_at must be positive") params["epoch_at"] = str(epoch_at) token = read_private_file(self.secrets_dir / entry.id / "internal.token") for attempt in range(ATTEMPTS): try: async with self.http.stream( "GET", f"{entry.url}/internal/v1/get_weights", params=params, headers={ "authorization": f"Bearer {token}", "x-platform-challenge-slug": entry.id, }, # Must exceed a container's own snapshot deadline (Bounty: 120 s). timeout=180, ) as response: if response.status_code != 200: raise ServiceError(503, f"challenge answered HTTP {response.status_code}") body = bytearray() async for chunk in response.aiter_bytes(): body.extend(chunk) if len(body) > MAX_RESPONSE_BYTES: raise ServiceError(503, "challenge weights response too large") return parse_weights(bytes(body), slug=entry.id, epoch=epoch) except httpx.TransportError: # A container restarting for an update must not burn a whole epoch. if attempt + 1 == ATTEMPTS: raise await asyncio.sleep(self.retry_seconds * (attempt + 1)) raise AssertionError("unreachable") |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |