|
| 1 | +"""Build owner-signed network-v2 manifests offline; emit tiny public example inputs.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import json |
| 7 | +import sys |
| 8 | +from pathlib import Path |
| 9 | +from typing import Any, Never |
| 10 | + |
| 11 | +from pydantic import JsonValue, ValidationError |
| 12 | + |
| 13 | +from hypertrain.data.store import CorruptObjectError, LocalFSStore |
| 14 | +from hypertrain.ledger.escrow_v2 import genesis_allocation_hash |
| 15 | +from hypertrain.protocol.envelope_v2 import Intake, load_json, parse_envelope, seal |
| 16 | +from hypertrain.protocol.example import example_manifest |
| 17 | +from hypertrain.protocol.hashing import MerkleTree, sha256_hex |
| 18 | +from hypertrain.protocol.jcs import canonicalize |
| 19 | +from hypertrain.protocol.keys import encode_hotkey |
| 20 | +from hypertrain.protocol.messages import f32hex |
| 21 | +from hypertrain.protocol.messages_v2 import ( |
| 22 | + AdmissionPolicyV2, |
| 23 | + AggregationPolicyV2, |
| 24 | + ArtifactLimits, |
| 25 | + AuditPolicyV2, |
| 26 | + DisputePolicyV2, |
| 27 | + EconomicsPolicyV2, |
| 28 | + RunManifestV2, |
| 29 | + TrainingManifestV2, |
| 30 | + WireModel, |
| 31 | +) |
| 32 | +from hypertrain.protocol.relay_messages import RelayRegistryV1 |
| 33 | + |
| 34 | +POLICIES: dict[str, type[WireModel]] = { |
| 35 | + "admission": AdmissionPolicyV2, |
| 36 | + "economics": EconomicsPolicyV2, |
| 37 | + "aggregation": AggregationPolicyV2, |
| 38 | + "audit": AuditPolicyV2, |
| 39 | + "dispute": DisputePolicyV2, |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | +class _Parser(argparse.ArgumentParser): |
| 44 | + def error(self, message: str) -> Never: |
| 45 | + raise ValueError("invalid command arguments; use --help") |
| 46 | + |
| 47 | + |
| 48 | +def _read(path: Path) -> dict[str, JsonValue]: |
| 49 | + raw = path.read_bytes() |
| 50 | + try: |
| 51 | + return load_json(raw) |
| 52 | + except (ValueError, RecursionError): |
| 53 | + raise ValueError( |
| 54 | + "invalid JSON input: expected a bounded object without duplicates or floats" |
| 55 | + ) from None |
| 56 | + |
| 57 | + |
| 58 | +def _check_out(out: Path) -> None: |
| 59 | + if out.is_symlink() or (out.exists() and (not out.is_dir() or any(out.iterdir()))): |
| 60 | + raise ValueError("--out must not exist or be empty") |
| 61 | + |
| 62 | + |
| 63 | +def _write(out: Path, files: dict[str, bytes]) -> None: |
| 64 | + _check_out(out) |
| 65 | + out.mkdir(parents=True, exist_ok=True) |
| 66 | + for name, raw in files.items(): |
| 67 | + with (out / name).open("xb") as target: |
| 68 | + target.write(raw) |
| 69 | + |
| 70 | + |
| 71 | +def _build(args: argparse.Namespace) -> dict[str, JsonValue]: |
| 72 | + if args.exp_round <= 0: |
| 73 | + raise ValueError("--exp-round must be positive") |
| 74 | + _check_out(args.out) |
| 75 | + raw_policies = _read(args.policies) |
| 76 | + if raw_policies.keys() != POLICIES.keys(): |
| 77 | + raise ValueError( |
| 78 | + "--policies requires exactly admission, economics, aggregation, audit, dispute" |
| 79 | + ) |
| 80 | + objects = {name: model.model_validate(raw_policies[name]) for name, model in POLICIES.items()} |
| 81 | + objects["relay_registry"] = RelayRegistryV1.model_validate(_read(args.relays)) |
| 82 | + training = _read(args.training) |
| 83 | + supplied_hash = training.get("init_state_hash") |
| 84 | + training.setdefault("init_state_hash", "0" * 64) |
| 85 | + validated = TrainingManifestV2.model_validate(training) |
| 86 | + audit = objects["audit"] |
| 87 | + assert isinstance(audit, AuditPolicyV2) |
| 88 | + audit.validate_training(validated) |
| 89 | + if len(set(validated.auditors)) < 2: |
| 90 | + raise ValueError("two distinct audit reference identities required") |
| 91 | + if validated.inner.state_policy == "derived": |
| 92 | + raise ValueError("v2 derived-state influence requires authenticated v0 integration") |
| 93 | + economics = objects["economics"] |
| 94 | + assert isinstance(economics, EconomicsPolicyV2) |
| 95 | + if economics.round_reward_units != validated.budget.epochs_per_round * 1_000_000: |
| 96 | + raise ValueError("MANIFEST_REWARD_BUDGET") |
| 97 | + if economics.reward_authority != validated.coord_pubkey: |
| 98 | + raise ValueError("PINNED_AUTHORITIES") |
| 99 | + hashes = {name: model.digest() for name, model in objects.items()} |
| 100 | + network = { |
| 101 | + **{f"{name}_policy_hash": hashes[name] for name in POLICIES}, |
| 102 | + "relay_registry_hash": hashes["relay_registry"], |
| 103 | + "audit_mode": "anchored-full", |
| 104 | + "full_anchor_version": 1, |
| 105 | + "capabilities": ["island-replay", "all-level-disputes", "transport-receipts"], |
| 106 | + } |
| 107 | + draft = RunManifestV2.model_validate( |
| 108 | + {"manifest_version": 2, "training": validated.body(), "network": network} |
| 109 | + ) |
| 110 | + from hypertrain.miner.core import KeyfileError, load_keyfile |
| 111 | + from hypertrain.trainer.compress import state_hash |
| 112 | + from hypertrain.trainer.config import TrainConfig |
| 113 | + from hypertrain.trainer.model import init_params |
| 114 | + |
| 115 | + try: |
| 116 | + owner = load_keyfile(args.owner_seed) |
| 117 | + except KeyfileError as error: |
| 118 | + raise ValueError(str(error)) from None |
| 119 | + initial_hash = state_hash(init_params(TrainConfig.from_manifest_v2(draft).model)) |
| 120 | + if supplied_hash is not None and supplied_hash != initial_hash: |
| 121 | + raise ValueError("init_state_hash does not match computed initial state") |
| 122 | + final_training = validated.body() |
| 123 | + final_training["init_state_hash"] = initial_hash |
| 124 | + manifest = RunManifestV2.model_validate( |
| 125 | + {"manifest_version": 2, "training": final_training, "network": network} |
| 126 | + ) |
| 127 | + run_id = manifest.run_id() |
| 128 | + envelope = canonicalize(seal(owner, "RunManifestV2", run_id, manifest, args.exp_round)) |
| 129 | + parsed = parse_envelope(envelope) |
| 130 | + RunManifestV2.model_validate(parsed.body).validate_run_id(parsed.run_id) |
| 131 | + Intake(run_id, {"RunManifestV2": lambda signer: signer == owner.ss58}).accept(envelope, 1) |
| 132 | + files = { |
| 133 | + "manifest.json": canonicalize(manifest.body(), allow_float=False), |
| 134 | + "manifest-envelope.json": envelope, |
| 135 | + **{ |
| 136 | + f"policy-{name}.json": canonicalize(objects[name].body(), allow_float=False) |
| 137 | + for name in POLICIES |
| 138 | + }, |
| 139 | + "relay-registry.json": canonicalize(objects["relay_registry"].body(), allow_float=False), |
| 140 | + } |
| 141 | + index: dict[str, JsonValue] = { |
| 142 | + "run_id": run_id, |
| 143 | + "owner_ss58": owner.ss58, |
| 144 | + "objects": dict(hashes), |
| 145 | + "files": {name: sha256_hex(raw) for name, raw in files.items()}, |
| 146 | + } |
| 147 | + files["index.json"] = canonicalize(index, allow_float=False) |
| 148 | + if args.state_dir is not None: |
| 149 | + store = LocalFSStore(args.state_dir / "objects") |
| 150 | + for model in objects.values(): |
| 151 | + store.get(store.put(canonicalize(model.body(), allow_float=False))) |
| 152 | + _write(args.out, files) |
| 153 | + return index |
| 154 | + |
| 155 | + |
| 156 | +def _example() -> dict[str, bytes]: |
| 157 | + coord, auditor0, auditor1, referee, relay, cold, other = ( |
| 158 | + encode_hotkey(bytes([i]) * 32) for i in range(1, 8) |
| 159 | + ) |
| 160 | + training: dict[str, Any] = example_manifest().body() |
| 161 | + training["model"].update( |
| 162 | + n_layers=1, |
| 163 | + d_model=8, |
| 164 | + n_heads=2, |
| 165 | + n_kv_heads=2, |
| 166 | + d_ff=12, |
| 167 | + vocab=16, |
| 168 | + seq_len=4, |
| 169 | + n_experts=1, |
| 170 | + top_k_experts=1, |
| 171 | + param_count=824, |
| 172 | + ) |
| 173 | + training["inner"].update(H=1, J=1, micro_batch=1, grad_accum=1, state_policy="reset") |
| 174 | + training["inner"]["lr_schedule"].update(warmup=0, stable=100, peak_lr=f32hex(0.001)) |
| 175 | + rows = [b"".join(((i * 5 + j) % 16).to_bytes(4, "little") for j in range(5)) for i in range(16)] |
| 176 | + training["dataset"].update(merkle_root=MerkleTree(rows).root.hex(), n_samples=16, depth=4) |
| 177 | + training["reference_spec"]["driver_allowlist"] = ["cpu-test"] |
| 178 | + training["coord_pubkey"] = coord |
| 179 | + training["auditors"] = [auditor0, auditor1] |
| 180 | + training["init_state_hash"] = "0" * 64 |
| 181 | + training = TrainingManifestV2.model_validate(training).body() |
| 182 | + del training["init_state_hash"] |
| 183 | + admission = AdmissionPolicyV2( |
| 184 | + q_base="0000803e", |
| 185 | + E=4, |
| 186 | + clean_finalizations=12, |
| 187 | + work_screen_epoch_rounds=1000, |
| 188 | + max_pending=32, |
| 189 | + max_trial_replays=2, |
| 190 | + max_trials_per_beacon=2, |
| 191 | + join_per_beacon=2, |
| 192 | + join_burst=4, |
| 193 | + ip_prefix_per_beacon=32, |
| 194 | + ip_prefix_burst=64, |
| 195 | + challenge_rounds=100, |
| 196 | + artifact_limits=ArtifactLimits( |
| 197 | + max_object_bytes=1_000_000, max_body_bytes=65536, max_chunk_manifest_bytes=1048576 |
| 198 | + ), |
| 199 | + ) |
| 200 | + economics = EconomicsPolicyV2( |
| 201 | + ledger_mode="test", |
| 202 | + G_max_units=100, |
| 203 | + R_collectible_units=100, |
| 204 | + S_min_units=1000, |
| 205 | + beta_ppm=1_000_000, |
| 206 | + gammaV_units=0, |
| 207 | + s_lower_ppm=1_000_000, |
| 208 | + q_floor=1_000_000, |
| 209 | + genesis_allocation_hash=genesis_allocation_hash([(cold, 20000, 1), (other, 10000, 1)]), |
| 210 | + reward_authority=coord, |
| 211 | + round_reward_units=1_000_000, |
| 212 | + max_total_issuance=20_000_000, |
| 213 | + shadow_bootstrap_rounds=12, |
| 214 | + ) |
| 215 | + aggregation = AggregationPolicyV2( |
| 216 | + arithmetic="flat-cclip-cap-v1", |
| 217 | + order="utf8", |
| 218 | + center="prev_outer_update", |
| 219 | + trust_mode="uniform-verified", |
| 220 | + weight_quantum=16777216, |
| 221 | + miner_cap_units=4194304, |
| 222 | + probation_cap_units=4194304, |
| 223 | + owner_group_caps={}, |
| 224 | + preclip_norm=f32hex(1), |
| 225 | + cclip_tau=f32hex(1), |
| 226 | + cclip_iters=2, |
| 227 | + ) |
| 228 | + audit = AuditPolicyV2( |
| 229 | + lease_rounds=100, |
| 230 | + max_attempts=2, |
| 231 | + max_concurrent_per_auditor=1, |
| 232 | + max_running_jobs=2, |
| 233 | + max_queued_jobs=32, |
| 234 | + max_anchor_age_rounds=1, |
| 235 | + max_steps_per_attempt=2, |
| 236 | + ) |
| 237 | + dispute = DisputePolicyV2( |
| 238 | + referees=[referee], |
| 239 | + max_open=32, |
| 240 | + max_transcript_entries=256, |
| 241 | + max_entry_bytes=65536, |
| 242 | + fanout=2, |
| 243 | + max_referee_reassignments=1, |
| 244 | + max_referee_cost_units=100, |
| 245 | + ) |
| 246 | + registry = RelayRegistryV1.model_validate( |
| 247 | + { |
| 248 | + "registry_version": 1, |
| 249 | + "epoch": 0, |
| 250 | + "previous_registry_hash": None, |
| 251 | + "specs": [ |
| 252 | + { |
| 253 | + "id": "local", |
| 254 | + "region": "local", |
| 255 | + "https_url": "https://relay.test", |
| 256 | + "pubkeys": [ |
| 257 | + { |
| 258 | + "key_id": "k1", |
| 259 | + "pubkey": relay, |
| 260 | + "valid_from_round": 0, |
| 261 | + "valid_until_round": 10000, |
| 262 | + } |
| 263 | + ], |
| 264 | + "max_object_bytes": 1000000, |
| 265 | + "max_inflight_bytes": 1000000, |
| 266 | + "codecs": ["ht-sparse-v1", "ht-dense-int8-v1"], |
| 267 | + "mode": "transport", |
| 268 | + } |
| 269 | + ], |
| 270 | + } |
| 271 | + ) |
| 272 | + policies = dict( |
| 273 | + admission=admission, |
| 274 | + economics=economics, |
| 275 | + aggregation=aggregation, |
| 276 | + audit=audit, |
| 277 | + dispute=dispute, |
| 278 | + ) |
| 279 | + return { |
| 280 | + "training.json": canonicalize(training, allow_float=False), |
| 281 | + "policies.json": canonicalize( |
| 282 | + {k: v.body() for k, v in policies.items()}, allow_float=False |
| 283 | + ), |
| 284 | + "relays.json": canonicalize(registry.body(), allow_float=False), |
| 285 | + } |
| 286 | + |
| 287 | + |
| 288 | +def main(argv: list[str] | None = None) -> int: |
| 289 | + parser = _Parser(prog="python -m hypertrain.ops.manifest_v2") |
| 290 | + sub = parser.add_subparsers(dest="cmd", required=True) |
| 291 | + build = sub.add_parser("build", help="validate, initialize, sign, and write a v2 run") |
| 292 | + for name in ("training", "policies", "relays", "owner-seed", "out"): |
| 293 | + build.add_argument(f"--{name}", type=Path, required=True) |
| 294 | + build.add_argument("--exp-round", type=int, required=True) |
| 295 | + build.add_argument("--state-dir", type=Path) |
| 296 | + example = sub.add_parser("example", help="write tiny CPU inputs with public placeholders") |
| 297 | + example.add_argument("--out", type=Path, required=True) |
| 298 | + try: |
| 299 | + args = parser.parse_args(argv) |
| 300 | + if args.cmd == "build": |
| 301 | + result = _build(args) |
| 302 | + else: |
| 303 | + _check_out(args.out) |
| 304 | + files = _example() |
| 305 | + _write(args.out, files) |
| 306 | + result = {"files": {name: sha256_hex(raw) for name, raw in files.items()}} |
| 307 | + except ValidationError as error: |
| 308 | + detail = error.errors(include_input=False, include_context=False, include_url=False)[0] |
| 309 | + location = " ".join(".".join(map(str, detail["loc"])).splitlines()) or "input" |
| 310 | + print(f"error: {location}: {detail['type']}", file=sys.stderr) |
| 311 | + return 2 |
| 312 | + except ValueError as error: |
| 313 | + print("error: " + " ".join(str(error).splitlines()), file=sys.stderr) |
| 314 | + return 2 |
| 315 | + except CorruptObjectError: |
| 316 | + print("error: object store contains corrupt content", file=sys.stderr) |
| 317 | + return 2 |
| 318 | + except OSError: |
| 319 | + print("error: file access failed", file=sys.stderr) |
| 320 | + return 2 |
| 321 | + except Exception: |
| 322 | + print("error: unexpected failure", file=sys.stderr) |
| 323 | + return 1 |
| 324 | + print(json.dumps(result, sort_keys=True)) |
| 325 | + return 0 |
| 326 | + |
| 327 | + |
| 328 | +if __name__ == "__main__": |
| 329 | + sys.exit(main()) |