Spaces:
Paused
Paused
Sync GitHub main 4a6eb9887255ebb2ede0a5f2e13460c4b5878946 (part 6)
Browse filesFiles changed (6)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476"""Benchmark bounded plastic-network stability and throughput.
The deterministic regular graph is an engineering load profile, not ascientific workload or evidence of general plastic-network stability."""
from __future__ import annotations
import argparseimport hashlibimport jsonimport mathimport osimport platformimport randomimport sysimport timeimport tracemallocfrom pathlib import Pathfrom typing import Any
REPO_ROOT = Path(__file__).resolve().parent.parentif str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT))
BYTES_PER_NEURON_ESTIMATE = 4_096BYTES_PER_SYNAPSE_ESTIMATE = 2_048DEFAULT_MEMORY_BUDGET_BYTES = 2 * 1024**3STAGE3_NEURON_RANGE = (10_000, 100_000)STAGE3_SYNAPSE_RANGE = (100_000, 10_000_000)INITIAL_WEIGHT = 0.05MIN_WEIGHT = 0.0MAX_WEIGHT = 0.5SOURCE_CURRENT = 100.0REWARD_VALUE = 1.0STDP_A_PLUS = 0.1STDP_A_MINUS = 0.12STDP_TAU_TICKS = 20.0ELIGIBILITY_TAU_TICKS = 200.0REWARD_LEARNING_RATE = 0.01PLASTICITY_MODES = {"asymmetric", "symmetric", "off"}ACTIVITY_PROFILES = {"uniform", "heterogeneous_cohorts"}COHORT_COUNT = 4WEIGHT_VARIANCE_TOLERANCE = 1e-12
def estimate_peak_bytes(neuron_count: int, synapse_count: int) -> int: """Conservatively estimate Python object-graph memory before allocation.""" return ( neuron_count * BYTES_PER_NEURON_ESTIMATE + synapse_count * BYTES_PER_SYNAPSE_ESTIMATE )
def _build_network( neuron_count: int, synapse_count: int, seed: int) -> tuple[Any, list[int], list[int]]: from src.core.network import Brain5DConfig, NeuralNetwork from src.core.spatial_index import linear_to_5d
side = math.ceil(neuron_count ** (1.0 / 5.0)) while side**5 < neuron_count: side += 1 dimensions = (side, side, side, side, side) config = Brain5DConfig.from_dict( { "dimensions": dimensions, "simulation": {"max_delay": 1}, "network": { "initial_connections_per_neuron": 0, "weight_min": MIN_WEIGHT, "weight_max": MAX_WEIGHT, }, "stdp": { "a_plus": STDP_A_PLUS, "a_minus": STDP_A_MINUS, "tau_plus": STDP_TAU_TICKS, "tau_minus": STDP_TAU_TICKS, }, } ) network = NeuralNetwork(config, random.Random(seed)) neuron_ids = [ network.add_neuron(linear_to_5d(index, dimensions)) for index in range(neuron_count) ] source_count = neuron_count // 2 source_ids = neuron_ids[:source_count] target_ids = neuron_ids[source_count:] random.Random(seed).shuffle(target_ids) if not source_ids or not target_ids: raise ValueError("at least two neurons are required") if synapse_count % source_count: raise ValueError("synapse_count must be divisible by the source population") degree = synapse_count // source_count if degree > len(target_ids): raise ValueError("synapse_count would create duplicate source-target edges")
for source_index, source_id in enumerate(source_ids): first_target = source_index * degree for edge_index in range(degree): target_id = target_ids[(first_target + edge_index) % len(target_ids)] network.connect(source_id, target_id, weight=INITIAL_WEIGHT, delay=1) return network, source_ids, target_ids
def _weight_snapshot(network: Any, epoch: int) -> dict[str, Any]: weights = [ synapse.weight for outgoing in network.synapses.values() for synapse in outgoing ] finite = all(math.isfinite(weight) for weight in weights) mean_weight = sum(weights) / len(weights) if weights else None variance = ( sum((weight - mean_weight) ** 2 for weight in weights) / len(weights) if weights and mean_weight is not None else None ) active_count = sum(weight > MIN_WEIGHT + 1e-12 for weight in weights) return { "epoch": epoch, "finite_weights": finite, "min_weight": min(weights, default=None), "max_weight": max(weights, default=None), "mean_weight": mean_weight, "weight_variance": variance, "active_weight_count": active_count, "active_weight_fraction": active_count / len(weights) if weights else None, "all_weights_equal": variance is not None and variance <= WEIGHT_VARIANCE_TOLERANCE, "at_lower_bound_count": sum(weight <= MIN_WEIGHT + 1e-12 for weight in weights), "at_upper_bound_count": sum(weight >= MAX_WEIGHT - 1e-12 for weight in weights), "out_of_bounds_weights": sum( weight < MIN_WEIGHT or weight > MAX_WEIGHT for weight in weights ), }
def _topology_digest(network: Any) -> str: edges = sorted( (source_id, synapse.target_id) for source_id, outgoing in network.synapses.items() for synapse in outgoing ) payload = json.dumps(edges, separators=(",", ":")).encode("ascii") return hashlib.sha256(payload).hexdigest()
def _assess_stability( snapshots: list[dict[str, Any]], *, final_epoch_source_spikes: int, final_epoch_target_spikes: int, weight_diversity_required: bool,) -> dict[str, bool]: final_snapshot = snapshots[-1] numeric_passed = all( bool(snapshot["finite_weights"]) and int(snapshot["out_of_bounds_weights"]) == 0 for snapshot in snapshots ) active_weight_fraction = float(final_snapshot["active_weight_fraction"] or 0.0) functional_passed = ( final_epoch_source_spikes > 0 and final_epoch_target_spikes > 0 and active_weight_fraction > 0.0 ) final_variance = final_snapshot["weight_variance"] diversity_passed = not weight_diversity_required or ( final_variance is not None and float(final_variance) > WEIGHT_VARIANCE_TOLERANCE ) return { "numeric_stability_passed": numeric_passed, "functional_activity_passed": functional_passed, "weight_diversity_passed": diversity_passed, "stability_invariants_passed": ( numeric_passed and functional_passed and diversity_passed ), }
def run_benchmark( *, neuron_count: int = 10_000, synapse_count: int = 100_000, epochs: int = 100, seed: int = 42, memory_budget_bytes: int = DEFAULT_MEMORY_BUDGET_BYTES, stability_interval: int = 10, plasticity_mode: str = "asymmetric", activity_profile: str = "heterogeneous_cohorts",) -> dict[str, Any]: """Run repeated causal spike/reward phases and report engineering metrics.""" if neuron_count < 4 or neuron_count % 2: raise ValueError("neuron_count must be an even integer >= 4") if synapse_count <= 0 or epochs <= 0 or stability_interval <= 0: raise ValueError( "synapse_count, epochs and stability_interval must be positive" ) if isinstance(seed, bool) or not isinstance(seed, int): raise ValueError("seed must be an integer") if plasticity_mode not in PLASTICITY_MODES: raise ValueError(f"plasticity_mode must be one of {sorted(PLASTICITY_MODES)}") if activity_profile not in ACTIVITY_PROFILES: raise ValueError(f"activity_profile must be one of {sorted(ACTIVITY_PROFILES)}") estimated_bytes = estimate_peak_bytes(neuron_count, synapse_count) if estimated_bytes > memory_budget_bytes: raise ValueError( f"estimated allocation {estimated_bytes} bytes exceeds memory budget " f"{memory_budget_bytes} bytes" )
from src.learning.learning_engine import LearningEngine
learning_enabled = plasticity_mode != "off" a_minus = STDP_A_PLUS if plasticity_mode == "symmetric" else STDP_A_MINUS learning_config = { "stdp": { "enabled": learning_enabled, "a_plus": STDP_A_PLUS, "a_minus": a_minus, "tau_plus": STDP_TAU_TICKS, "tau_minus": STDP_TAU_TICKS, "min_weight": MIN_WEIGHT, "max_weight": MAX_WEIGHT, }, "eligibility": { "enabled": learning_enabled, "tau_ticks": ELIGIBILITY_TAU_TICKS, }, "reward": { "enabled": learning_enabled, "learning_rate": REWARD_LEARNING_RATE, "delay_ticks": 0, "clamp_weights": True, "reset_trace_after_reward": True, }, }
tracemalloc.start() setup_started = time.perf_counter() try: network, source_ids, target_ids = _build_network( neuron_count, synapse_count, seed ) learning = LearningEngine(network, learning_config) learning.attach() _, peak_bytes = tracemalloc.get_traced_memory() finally: tracemalloc.stop() setup_seconds = time.perf_counter() - setup_started
initial_weights = { (source_id, synapse.target_id): synapse.weight for source_id, outgoing in network.synapses.items() for synapse in outgoing } incoming_degree: dict[int, int] = {} for outgoing in network.synapses.values(): for synapse in outgoing: incoming_degree[synapse.target_id] = ( incoming_degree.get(synapse.target_id, 0) + 1 )
estimated_synapse_candidate_visits = 0 source_spikes = 0 target_spikes = 0 final_epoch_source_spikes = 0 final_epoch_target_spikes = 0 core_step_seconds = 0.0 stability: list[dict[str, Any]] = [] run_started = time.perf_counter() for epoch in range(1, epochs + 1): cohort = epoch % COHORT_COUNT active_sources = ( source_ids if activity_profile == "uniform" else source_ids[cohort::COHORT_COUNT] ) active_targets = ( target_ids if activity_profile == "uniform" else target_ids[(cohort + 1) % COHORT_COUNT :: COHORT_COUNT] ) network.inject_current_batch(dict.fromkeys(active_sources, SOURCE_CURRENT)) source_result = network.step() core_step_seconds += source_result.core_step_ms / 1000.0 source_spikes += len(source_result.spike_ids) final_epoch_source_spikes = len(source_result.spike_ids) estimated_synapse_candidate_visits += sum( len(network.synapses[neuron_id]) for neuron_id in source_result.spike_ids )
network.inject_current_batch(dict.fromkeys(active_targets, SOURCE_CURRENT)) target_result = network.step() core_step_seconds += target_result.core_step_ms / 1000.0 target_spikes += len(target_result.spike_ids) final_epoch_target_spikes = len(target_result.spike_ids) if learning_enabled: estimated_synapse_candidate_visits += sum( incoming_degree.get(neuron_id, 0) for neuron_id in target_result.spike_ids ) learning.set_reward(REWARD_VALUE, target_result.tick) estimated_synapse_candidate_visits += synapse_count
if epoch % stability_interval == 0 or epoch == epochs: stability.append(_weight_snapshot(network, epoch)) elapsed_seconds = time.perf_counter() - run_started
final_snapshot = stability[-1] final_weight_count = network.synapse_count weight_diversity_required = ( activity_profile == "heterogeneous_cohorts" and learning_enabled ) stability_assessment = _assess_stability( stability, final_epoch_source_spikes=final_epoch_source_spikes, final_epoch_target_spikes=final_epoch_target_spikes, weight_diversity_required=weight_diversity_required, ) maximum_weight_drift = max( ( abs(synapse.weight - initial_weights[(source_id, synapse.target_id)]) for source_id, outgoing in network.synapses.items() for synapse in outgoing ), default=0.0, ) stats = learning.stats return { "schema_version": 2, "benchmark": "stage3_plastic_network_scale", "scope": "engineering_verification_only", "scientific_evidence": False, "python": platform.python_version(), "platform": platform.platform(), "cpu": platform.processor() or None, "logical_processors": os.cpu_count(), "seed": seed, "topology_sha256": _topology_digest(network), "plasticity_mode": plasticity_mode, "activity_profile": activity_profile, "topology": "deterministic_regular_bipartite", "neurons": neuron_count, "synapses": network.synapse_count, "out_degree": synapse_count // len(source_ids), "epochs": epochs, "ticks": epochs * 2, "estimated_peak_bytes": estimated_bytes, "tracemalloc_peak_bytes": int(peak_bytes), "memory_budget_bytes": memory_budget_bytes, "setup_seconds": setup_seconds, "simulation_seconds": elapsed_seconds, "core_step_seconds": core_step_seconds, "ticks_per_second": epochs * 2 / elapsed_seconds if elapsed_seconds else None, "estimated_synapse_candidate_visits": estimated_synapse_candidate_visits, "estimated_synapse_candidate_visits_per_second": ( estimated_synapse_candidate_visits / elapsed_seconds if elapsed_seconds else None ), "candidate_visit_estimate": ( "Outgoing adjacency traversals for source spikes, incoming learning " "event traversals for target spikes, plus one full reward scan per epoch." ), "source_spikes": source_spikes, "target_spikes": target_spikes, "final_epoch_source_spikes": final_epoch_source_spikes, "final_epoch_target_spikes": final_epoch_target_spikes, "learning_stats": stats.to_dict(), "maximum_absolute_weight_drift": maximum_weight_drift, "weight_bounds": {"minimum": MIN_WEIGHT, "maximum": MAX_WEIGHT}, "final_weights_finite": final_snapshot["finite_weights"], "final_out_of_bounds_weights": final_snapshot["out_of_bounds_weights"], "weight_diversity_required": weight_diversity_required, **stability_assessment, "final_at_lower_bound_fraction": ( final_snapshot["at_lower_bound_count"] / final_weight_count if final_weight_count else None ), "final_at_upper_bound_fraction": ( final_snapshot["at_upper_bound_count"] / final_weight_count if final_weight_count else None ), "stability_snapshots": stability, "workload": { "topology": "source_i_to_targets[(i * out_degree + edge) % target_count]", "seed_effect": "seeded permutation of target node order before edge assignment", "initial_weight": INITIAL_WEIGHT, "connection_delay_ticks": 1, "source_and_target_current": SOURCE_CURRENT, "reward_per_epoch": REWARD_VALUE, "stdp": { "a_plus": STDP_A_PLUS, "a_minus": a_minus, "tau_ticks": STDP_TAU_TICKS, }, "eligibility_tau_ticks": ELIGIBILITY_TAU_TICKS, "reward_learning_rate": REWARD_LEARNING_RATE, "reward_trace_reset": True, "plasticity_mode": plasticity_mode, "activity_profile": activity_profile, "cohort_count": COHORT_COUNT, "heterogeneous_profile_rule": ( "sources: index mod 4 = epoch mod 4; targets: index mod 4 = " "(epoch + 1) mod 4" ), }, "stage3_target_range": { "neurons": list(STAGE3_NEURON_RANGE), "synapses": list(STAGE3_SYNAPSE_RANGE), "lower_bound_covered": ( neuron_count >= STAGE3_NEURON_RANGE[0] and synapse_count >= STAGE3_SYNAPSE_RANGE[0] ), "upper_bound_covered": ( neuron_count >= STAGE3_NEURON_RANGE[1] and synapse_count >= STAGE3_SYNAPSE_RANGE[1] ), }, "interpretation_limit": ( "One deterministic topology/load profile; not general stability, " "scientific evidence, or full-range Stage-3 acceptance." ), }
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--neurons", type=int, default=10_000) parser.add_argument("--synapses", type=int, default=100_000) parser.add_argument("--epochs", type=int, default=100) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--memory-budget-mib", type=int, default=2048) parser.add_argument("--stability-interval", type=int, default=10) parser.add_argument( "--plasticity-mode", choices=sorted(PLASTICITY_MODES), default="asymmetric" ) parser.add_argument( "--activity-profile", choices=sorted(ACTIVITY_PROFILES), default="heterogeneous_cohorts", ) parser.add_argument("--output", type=Path) return parser.parse_args()
def main() -> int: args = parse_args() if args.memory_budget_mib <= 0: raise SystemExit("--memory-budget-mib must be positive") try: report = run_benchmark( neuron_count=args.neurons, synapse_count=args.synapses, epochs=args.epochs, seed=args.seed, memory_budget_bytes=args.memory_budget_mib * 1024**2, stability_interval=args.stability_interval, plasticity_mode=args.plasticity_mode, activity_profile=args.activity_profile, ) except ValueError as exc: raise SystemExit(str(exc)) from exc
payload = json.dumps(report, indent=2) if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(payload + "\n", encoding="utf-8") print(payload) return 0
if __name__ == "__main__": sys.exit(main())1 unmodified line23456789101112131415161726 unmodified lines444546474849505152535455419 unmodified lines47547647747847948020 unmodified lines50150250350450550650750850951011 unmodified lines5225235245255265275285295305315325335345355365375385395401 unmodified linefrom __future__ import annotationsimport shutilimport threadingimport timefrom collections import dequefrom collections.abc import Callable, Mappingfrom dataclasses import replacefrom pathlib import Pathfrom typing import castfrom src.dashboard.verification import current_git_headfrom src.playground import servicefrom src.playground.cuda import (CompileBundle,26 unmodified lines_MAX_CONCURRENT_RUNS = 2_RUNS_PER_MINUTE = 20_RUN_WINDOW_SECONDS = 60.0_RUN_SEMAPHORE = threading.BoundedSemaphore(_MAX_CONCURRENT_RUNS)_RATE_LOCK = threading.Lock()_RECENT_RUNS: deque[float] = deque()def _payload_int(payload: Mapping[str, object],name: str,419 unmodified linesif path.startswith("/api/playground/sessions/"):session_id = path[len("/api/playground/sessions/") :]return service.replay(session_id)if path == "/api/playground/night":return _NIGHT_RUN.status()if path == "/api/playground/cuda/status":20 unmodified linesreturn transfer_element(payload)if path == "/api/playground/research/synaptic-transfer":return _bounded_operation(lambda: run_synaptic_transfer(payload))if path == "/api/playground/research/cue-controls":return _bounded_operation(lambda: run_cue_controls(payload))if path == "/api/playground/determinism":return service.determinism(payload)11 unmodified lines).to_mapping()if path == "/api/playground/cuda/preflight":return _bounded_operation(lambda: _cuda_preflight(payload))if path == "/api/playground/cuda/smoke":return _bounded_operation(lambda: _cuda_smoke(payload))if path == "/api/playground/cuda/rng-parity":return _bounded_operation(lambda: _cuda_rng_parity(payload))if path == "/api/playground/cuda/builder-parity":return _bounded_operation(lambda: run_builder_parity(payload))if path == "/api/playground/cuda/recurrent-parity":return _bounded_operation(lambda: _cuda_recurrent_parity(payload))if path == "/api/playground/night/start":return _NIGHT_RUN.start(1 unmodified line2345678910111213141516171819202122232425262728293031323326 unmodified lines60616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386419 unmodified lines80680780880981081181281381481581681781881920 unmodified lines84084184284384484584684784884985085185285311 unmodified lines8658668678688698708718728738748758768778788798808818828838848858868878888891 unmodified linefrom __future__ import annotationsimport csvimport hashlibimport hmacimport ioimport jsonimport osimport reimport shutilimport subprocessimport threadingimport timeimport uuidfrom collections import dequefrom collections.abc import Callable, Mappingfrom dataclasses import replacefrom datetime import datetime, timezonefrom http import HTTPStatusfrom pathlib import Pathfrom typing import castfrom src.dashboard.verification import (SCIENTIFIC_PATHS,TEST_PATHS,current_git_head,inspect_source_tree,)from src.playground import servicefrom src.playground.cuda import (CompileBundle,26 unmodified lines_MAX_CONCURRENT_RUNS = 2_RUNS_PER_MINUTE = 20_RUN_WINDOW_SECONDS = 60.0_CUDA_DIAGNOSTIC_ID = re.compile(r"[0-9a-f]{32}")_CUDA_DIAGNOSTIC_MAX_BYTES = 8 * 1024 * 1024_REPO_ROOT = Path(__file__).resolve().parents[2]_CUDA_DIAGNOSTIC_URL_PREFIX = "/api/playground/cuda/diagnostics/"_RUN_SEMAPHORE = threading.BoundedSemaphore(_MAX_CONCURRENT_RUNS)_RATE_LOCK = threading.Lock()_RECENT_RUNS: deque[float] = deque()def _canonical_artifact_bytes(artifact: Mapping[str, object]) -> bytes:return json.dumps(artifact, sort_keys=True, ensure_ascii=True, separators=(",", ":")).encode("utf-8")def _write_cuda_diagnostic_artifact(repo_root: Path, artifact: Mapping[str, object]) -> tuple[Path, str]:artifact_id = artifact.get("artifact_id")if not isinstance(artifact_id, str) or not _CUDA_DIAGNOSTIC_ID.fullmatch(artifact_id):raise ValueError("CUDA diagnostic artifact ID is invalid")directory = repo_root / "artifacts" / "cuda_diagnostics"directory.mkdir(mode=0o700, parents=True, exist_ok=True)if os.name != "nt":directory.chmod(0o700)record = dict(artifact)artifact_digest = hashlib.sha256(_canonical_artifact_bytes(record)).hexdigest()record["artifact_sha256"] = artifact_digestserialized = json.dumps(record, sort_keys=True, indent=2, ensure_ascii=True) + "\n"encoded = serialized.encode("utf-8")if len(encoded) > _CUDA_DIAGNOSTIC_MAX_BYTES:raise ValueError("CUDA diagnostic artifact exceeds the 8 MiB limit")destination = directory / f"{artifact_id}.json"temporary = directory / f".{artifact_id}.{uuid.uuid4().hex}.tmp"try:temporary.write_bytes(encoded)if os.name != "nt":temporary.chmod(0o600)os.replace(temporary, destination)finally:temporary.unlink(missing_ok=True)return destination, artifact_digestdef _load_cuda_diagnostic_artifact(repo_root: Path, artifact_id: str) -> dict[str, object]:if not _CUDA_DIAGNOSTIC_ID.fullmatch(artifact_id):raise ValueError("CUDA diagnostic artifact ID is invalid")path = repo_root / "artifacts" / "cuda_diagnostics" / f"{artifact_id}.json"value = json.loads(path.read_text(encoding="utf-8"))if not isinstance(value, dict):raise ValueError("CUDA diagnostic artifact is malformed")record = dict(cast(dict[str, object], value))if record.get("artifact_id") != artifact_id:raise ValueError("CUDA diagnostic artifact is malformed")recorded_digest = record.pop("artifact_sha256", None)actual_digest = hashlib.sha256(_canonical_artifact_bytes(record)).hexdigest()if not isinstance(recorded_digest, str) or not hmac.compare_digest(recorded_digest, actual_digest):raise ValueError("CUDA diagnostic artifact digest mismatch")record["artifact_sha256"] = recorded_digestreturn recorddef _cuda_hardware_identity(device_ordinal: int) -> dict[str, object]:executable = shutil.which("nvidia-smi")if executable is None:return {"status": "unavailable","source": "nvidia-smi","device_ordinal": device_ordinal,"reason": "nvidia-smi_not_found",}try:completed = subprocess.run([executable,"--query-gpu=index,name,uuid,pci.bus_id,driver_version","--format=csv,noheader,nounits",],capture_output=True,check=False,text=True,timeout=5,)except (OSError, subprocess.SubprocessError) as exc:return {"status": "unavailable","source": "nvidia-smi","device_ordinal": device_ordinal,"reason": type(exc).__name__,}if completed.returncode != 0:return {"status": "unavailable","source": "nvidia-smi","device_ordinal": device_ordinal,"reason": "query_failed",}rows = [[value.strip() for value in row]for row in csv.reader(io.StringIO(completed.stdout), skipinitialspace=True)if row]selector = os.environ.get("CUDA_VISIBLE_DEVICES")visible = selector.split(",") if selector is not None else Noneif visible is not None:if device_ordinal >= len(visible):return {"status": "unavailable","source": "nvidia-smi","device_ordinal": device_ordinal,"reason": "device_not_visible",}selected = visible[device_ordinal].strip()if selected.isdecimal():match = next((row for row in rows if row[0] == selected), None)elif selected.startswith("GPU-"):match = next((row for row in rows if len(row) > 2 and row[2] == selected), None)else:match = Noneelse:match = next((row for row in rows if row[0] == str(device_ordinal)), None)if match is None or len(match) < 5 or match[2] in {"", "N/A"}:return {"status": "unavailable","source": "nvidia-smi","device_ordinal": device_ordinal,"reason": "device_identity_unresolved",}return {"status": "captured","source": "nvidia-smi","device_ordinal": device_ordinal,"physical_index": match[0],"model": match[1],"device_uuid_sha256": hashlib.sha256(match[2].encode("utf-8")).hexdigest(),"pci_bus_id": match[3],"driver_version": match[4],}def _working_tree_provenance(repo_root: Path) -> dict[str, object]:try:inspection = inspect_source_tree(repo_root)except (OSError, ValueError, subprocess.SubprocessError) as exc:return {"git_commit": current_git_head(repo_root),"working_tree_digest": None,"working_tree_digest_status": type(exc).__name__,"working_tree_digest_scope": [*SCIENTIFIC_PATHS, *TEST_PATHS],}dirty = bool(inspection.dirty_relevant_pathsor inspection.untracked_relevant_pathsor inspection.missing_relevant_paths)return {"git_commit": current_git_head(repo_root),"working_tree_digest": inspection.digest,"working_tree_digest_status": ("captured" if inspection.digest else "unavailable"),"working_tree_state": ("unknown"if not inspection.git_availableelse "modified" if dirty else "clean"),"working_tree_digest_scope": [*SCIENTIFIC_PATHS, *TEST_PATHS],"dirty_relevant_paths": list(inspection.dirty_relevant_paths),"untracked_relevant_paths": list(inspection.untracked_relevant_paths),"missing_relevant_paths": list(inspection.missing_relevant_paths),}def _diagnostic_outcome(result: Mapping[str, object]) -> str:passed = result.get("passed")if isinstance(passed, bool):return "passed" if passed else "failed"parity = result.get("parity")if isinstance(parity, Mapping):parity_passed = cast(Mapping[str, object], parity).get("passed")if isinstance(parity_passed, bool):return "passed" if parity_passed else "failed"actions_exact = result.get("actions_exact")if isinstance(actions_exact, bool):return "passed" if actions_exact else "failed"return "not_evaluated"def _diagnostic_http_status(exc: Exception) -> int:if isinstance(exc, (ValueError, TypeError, json.JSONDecodeError)):return HTTPStatus.BAD_REQUESTif isinstance(exc, FileNotFoundError):return HTTPStatus.NOT_FOUNDif isinstance(exc, TimeoutError):return HTTPStatus.GATEWAY_TIMEOUTif isinstance(exc, RuntimeError):return HTTPStatus.SERVICE_UNAVAILABLEreturn HTTPStatus.INTERNAL_SERVER_ERRORdef _run_cuda_diagnostic(route: str,payload: Mapping[str, object],operation: Callable[[], dict[str, object]],*,repo_root: Path | None = None,) -> dict[str, object]:root = repo_root or _REPO_ROOTstarted = datetime.now(timezone.utc)artifact_id = uuid.uuid4().hexordinal = payload.get("device_ordinal", 0)device_ordinal = (ordinalif isinstance(ordinal, int) and not isinstance(ordinal, bool) and ordinal >= 0else 0)provenance = _working_tree_provenance(root)hardware = _cuda_hardware_identity(device_ordinal)try:result = operation()except Exception as exc:completed = datetime.now(timezone.utc)record: dict[str, object] = {"schema_version": "mhrn.cuda-diagnostic.v1","artifact_id": artifact_id,"route": route,"execution_status": "failed","outcome": "error","started_at": started.isoformat(),"completed_at": completed.isoformat(),"duration_seconds": (completed - started).total_seconds(),"request_sha256": hashlib.sha256(_canonical_artifact_bytes(payload)).hexdigest(),"provenance": provenance,"hardware_identity": hardware,"error_type": type(exc).__name__,"error": str(exc)[:1000],"scientific_evidence": False,}_attach_cuda_diagnostic_receipt(exc, root, record)raisecompleted = datetime.now(timezone.utc)record = {"schema_version": "mhrn.cuda-diagnostic.v1","artifact_id": artifact_id,"route": route,"execution_status": "completed","outcome": _diagnostic_outcome(result),"started_at": started.isoformat(),"completed_at": completed.isoformat(),"duration_seconds": (completed - started).total_seconds(),"request_sha256": hashlib.sha256(_canonical_artifact_bytes(payload)).hexdigest(),"provenance": provenance,"hardware_identity": hardware,"result": result,"scientific_evidence": False,}receipt = _attach_cuda_diagnostic_receipt(None, root, record)response = dict(result)response["run_evidence"] = receiptreturn responsedef _attach_cuda_diagnostic_receipt(error: Exception | None,repo_root: Path,record: dict[str, object],) -> dict[str, object]:artifact_id = cast(str, record["artifact_id"])receipt: dict[str, object] = {"artifact_id": artifact_id,"artifact_url": f"/api/playground/cuda/diagnostics/{artifact_id}","execution_status": record["execution_status"],"outcome": record["outcome"],"started_at": record["started_at"],"completed_at": record["completed_at"],"duration_seconds": record["duration_seconds"],"provenance": record["provenance"],"hardware_identity": record["hardware_identity"],}record["artifact_url"] = receipt["artifact_url"]try:_, artifact_digest = _write_cuda_diagnostic_artifact(repo_root, record)except (OSError, TypeError, ValueError) as exc:receipt["persistence_status"] = "failed"receipt["persistence_error"] = type(exc).__name__receipt["artifact_url"] = Noneelse:receipt["persistence_status"] = "persisted"receipt["artifact_sha256"] = artifact_digestif error is not None:setattr(error, "run_evidence", receipt)setattr(error, "run_http_status", _diagnostic_http_status(error))return receiptdef _bounded_cuda_diagnostic(route: str,payload: Mapping[str, object],operation: Callable[[], dict[str, object]],) -> dict[str, object]:return _bounded_operation(lambda: _run_cuda_diagnostic(route, payload, operation))def _payload_int(payload: Mapping[str, object],name: str,419 unmodified linesif path.startswith("/api/playground/sessions/"):session_id = path[len("/api/playground/sessions/") :]return service.replay(session_id)if path.startswith(_CUDA_DIAGNOSTIC_URL_PREFIX):artifact_id = path[len(_CUDA_DIAGNOSTIC_URL_PREFIX) :]if not _CUDA_DIAGNOSTIC_ID.fullmatch(artifact_id):return Nonetry:return _load_cuda_diagnostic_artifact(_REPO_ROOT, artifact_id)except FileNotFoundError:return Noneif path == "/api/playground/night":return _NIGHT_RUN.status()if path == "/api/playground/cuda/status":20 unmodified linesreturn transfer_element(payload)if path == "/api/playground/research/synaptic-transfer":return _bounded_cuda_diagnostic(path, payload, lambda: run_synaptic_transfer(payload))if path == "/api/playground/research/cue-controls":return _bounded_cuda_diagnostic(path, payload, lambda: run_cue_controls(payload))if path == "/api/playground/determinism":return service.determinism(payload)11 unmodified lines).to_mapping()if path == "/api/playground/cuda/preflight":return _bounded_cuda_diagnostic(path, payload, lambda: _cuda_preflight(payload))if path == "/api/playground/cuda/smoke":return _bounded_cuda_diagnostic(path, payload, lambda: _cuda_smoke(payload))if path == "/api/playground/cuda/rng-parity":return _bounded_cuda_diagnostic(path, payload, lambda: _cuda_rng_parity(payload))if path == "/api/playground/cuda/builder-parity":return _bounded_cuda_diagnostic(path, payload, lambda: run_builder_parity(payload))if path == "/api/playground/cuda/recurrent-parity":return _bounded_cuda_diagnostic(path, payload, lambda: _cuda_recurrent_parity(payload))if path == "/api/playground/night/start":return _NIGHT_RUN.start(
857 unmodified lines8588598608618628638644556 unmodified lines542154225423542454255426542754285429857 unmodified linesif path.startswith("/api/playground/"):body = self._read_json_object()payload = post_playground(path, body)if payload is None:self._send_api_not_found(path)else:4556 unmodified linesself._send_api_not_found(request_path)returnif request_path in {"", "/"}:relative = "index.html"elif request_path in {"/review", "/review/"}:relative = "review/index.html"else:relative = request_path.lstrip("/")857 unmodified lines8588598608618628638648658668678688698708718728738748758768778788798804556 unmodified lines5437543854395440544154425443544454455446544754485449545054515452857 unmodified linesif path.startswith("/api/playground/"):body = self._read_json_object()try:payload = post_playground(path, body)except Exception as exc:run_evidence = getattr(exc, "run_evidence", None)if not isinstance(run_evidence, Mapping):raisestatus_code = getattr(exc, "run_http_status", HTTPStatus.INTERNAL_SERVER_ERROR)self._send_json({"error": str(exc),"run_evidence": cast(JSONValue, run_evidence),},HTTPStatus(cast(int, status_code)),)returnif payload is None:self._send_api_not_found(path)else:4556 unmodified linesself._send_api_not_found(request_path)returnif request_path == "/review":self.send_response(HTTPStatus.MOVED_PERMANENTLY)self.send_header("Location", "/review/")self.send_header("Content-Length", "0")self.end_headers()returnif request_path in {"", "/"}:relative = "index.html"elif request_path == "/review/":relative = "review/index.html"else:relative = request_path.lstrip("/")
review-portal-screenshots/desktop-intro.pngAdded

review-portal-screenshots/desktop-questionnaire.pngAdded

review-portal-screenshots/mobile-questionnaire.pngAdded

scripts/benchmark_plastic_network.pyAdded+476
src/dashboard/playground_api.py+357-8
src/dashboard/server.py+25-2