From 03936714612914e9423aae2ff94ae7f53eecb600 Mon Sep 17 00:00:00 2001 From: Vales Date: Wed, 19 Aug 2026 00:02:36 +0100 Subject: [PATCH] Add cheap generic Tuner through S24 Complete S20-S24 with fail-closed TunableRegistry validation, allocation-free champion/challenger selection, Welford evidence, explicit baseline-only/reset mode, context/crossover champions and versioned provenance persistence. --- CMakeLists.txt | 10 ++ Tuner/Champion.cpp | 204 +++++++++++++++++++++++ Tuner/Context.cpp | 45 +++++ Tuner/Persistence.cpp | 108 ++++++++++++ Tuner/README.md | 15 +- Tuner/TunableRegistry.cpp | 45 +++++ docs/STATUS.md | 5 +- docs/TUNER.md | 45 +++++ include/sc2opt/tuner/Champion.hpp | 74 ++++++++ include/sc2opt/tuner/Context.hpp | 48 ++++++ include/sc2opt/tuner/Persistence.hpp | 38 +++++ include/sc2opt/tuner/TunableRegistry.hpp | 31 +++- tests/tuner_tests.cpp | 178 ++++++++++++++++++++ 13 files changed, 842 insertions(+), 4 deletions(-) create mode 100644 Tuner/Champion.cpp create mode 100644 Tuner/Context.cpp create mode 100644 Tuner/Persistence.cpp create mode 100644 Tuner/TunableRegistry.cpp create mode 100644 docs/TUNER.md create mode 100644 include/sc2opt/tuner/Champion.hpp create mode 100644 include/sc2opt/tuner/Context.hpp create mode 100644 include/sc2opt/tuner/Persistence.hpp create mode 100644 tests/tuner_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7d16c64..63154fc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -47,6 +47,10 @@ sc2opt_apply_warnings(sc2opt_kernel) add_library(sc2opt_tuner STATIC Tuner/NetBenefit.cpp + Tuner/TunableRegistry.cpp + Tuner/Champion.cpp + Tuner/Context.cpp + Tuner/Persistence.cpp ) add_library(sc2opt::tuner ALIAS sc2opt_tuner) target_include_directories(sc2opt_tuner PUBLIC include) @@ -111,6 +115,12 @@ if(SC2OPT_BUILD_TESTS) sc2opt_apply_warnings(sc2opt_compute_tests) add_test(NAME sc2opt_compute_tests COMMAND sc2opt_compute_tests) + add_executable(sc2opt_tuner_tests tests/tuner_tests.cpp) + target_link_libraries(sc2opt_tuner_tests PRIVATE sc2opt) + target_compile_features(sc2opt_tuner_tests PRIVATE cxx_std_20) + sc2opt_apply_warnings(sc2opt_tuner_tests) + add_test(NAME sc2opt_tuner_tests COMMAND sc2opt_tuner_tests) + add_executable(sc2opt_synthetic_cpp_consumer examples/synthetic_cpp_consumer.cpp) target_link_libraries(sc2opt_synthetic_cpp_consumer PRIVATE sc2opt) target_compile_features(sc2opt_synthetic_cpp_consumer PRIVATE cxx_std_20) diff --git a/Tuner/Champion.cpp b/Tuner/Champion.cpp new file mode 100644 index 0000000..d92632a --- /dev/null +++ b/Tuner/Champion.cpp @@ -0,0 +1,204 @@ +#include "sc2opt/tuner/Champion.hpp" + +#include +#include +#include + +namespace sc2opt::tuner { +namespace { + +bool PolicyValid(const ChampionPolicy& policy) noexcept +{ + return policy.minimum_samples > 0 && + std::isfinite(policy.minimum_absolute_gain_ns) && + policy.minimum_absolute_gain_ns >= 0.0 && + std::isfinite(policy.minimum_relative_gain) && + policy.minimum_relative_gain >= 0.0 && + (!policy.require_confidence_separation || + (std::isfinite(policy.z_score) && policy.z_score >= 0.0)); +} + +bool DuplicateIds(std::span candidates) noexcept +{ + for (std::size_t i = 0; i < candidates.size(); ++i) + { + for (std::size_t j = 0; j < i; ++j) + { + if (candidates[i].id == candidates[j].id) + return true; + } + } + return false; +} + +bool Eligible(const CandidateStats& candidate, const ChampionPolicy& policy) noexcept +{ + return candidate.correctness_passed && + candidate.total_cost_ns.samples >= policy.minimum_samples && + std::isfinite(candidate.total_cost_ns.mean) && + candidate.total_cost_ns.mean >= 0.0 && + std::isfinite(candidate.total_cost_ns.m2) && + candidate.total_cost_ns.m2 >= 0.0; +} + +const CandidateStats* Find(std::span candidates, CandidateId id) noexcept +{ + for (const CandidateStats& candidate : candidates) + { + if (candidate.id == id) + return &candidate; + } + return nullptr; +} + +double LowerBound(const CandidateStats& candidate, double z_score) noexcept +{ + const double se = candidate.total_cost_ns.StandardError(); + return std::isfinite(se) ? candidate.total_cost_ns.mean - z_score * se + : -std::numeric_limits::infinity(); +} + +double UpperBound(const CandidateStats& candidate, double z_score) noexcept +{ + const double se = candidate.total_cost_ns.StandardError(); + return std::isfinite(se) ? candidate.total_cost_ns.mean + z_score * se + : std::numeric_limits::infinity(); +} + +} // namespace + +void RunningStats::Reset() noexcept +{ + samples = 0; + mean = 0.0; + m2 = 0.0; +} + +bool RunningStats::Add(double value) noexcept +{ + if (!std::isfinite(value) || value < 0.0 || + samples == std::numeric_limits::max()) + { + return false; + } + + const std::uint64_t new_samples = samples + 1; + const double delta = value - mean; + const double new_mean = mean + delta / static_cast(new_samples); + const double delta2 = value - new_mean; + const double new_m2 = m2 + delta * delta2; + + if (!std::isfinite(new_mean) || !std::isfinite(new_m2)) + return false; + + samples = new_samples; + mean = new_mean; + m2 = std::max(0.0, new_m2); + return true; +} + +double RunningStats::SampleVariance() const noexcept +{ + if (samples < 2 || !std::isfinite(m2)) + return 0.0; + return std::max(0.0, m2 / static_cast(samples - 1)); +} + +double RunningStats::StandardError() const noexcept +{ + if (samples < 2) + return std::numeric_limits::infinity(); + return std::sqrt(SampleVariance() / static_cast(samples)); +} + +void ResetToBaseline(ChampionState& state, TuningMode mode) noexcept +{ + state.champion = kBaselineCandidate; + state.mode = mode; +} + +void ResetEvidence(std::span candidates) noexcept +{ + for (CandidateStats& candidate : candidates) + { + candidate.total_cost_ns.Reset(); + candidate.correctness_passed = false; + } +} + +void ApplyChampionDecision(ChampionState& state, const ChampionDecision& decision) noexcept +{ + state.champion = state.mode == TuningMode::BaselineOnly ? kBaselineCandidate : decision.champion; +} + +ChampionDecision EvaluateChampion(std::span candidates, + ChampionState state, + ChampionPolicy policy) noexcept +{ + if (!PolicyValid(policy) || DuplicateIds(candidates)) + return {kBaselineCandidate, kBaselineCandidate, 0.0, 0.0, + ChampionReason::EvidenceInvalid}; + + if (state.mode == TuningMode::BaselineOnly) + return {kBaselineCandidate, kBaselineCandidate, 0.0, 0.0, ChampionReason::BaselineMode}; + + const CandidateStats* baseline = Find(candidates, kBaselineCandidate); + if (baseline == nullptr || !Eligible(*baseline, policy)) + return {}; + + const CandidateStats* current = Find(candidates, state.champion); + ChampionReason current_reason = ChampionReason::NoEligibleChallenger; + if (current == nullptr || !Eligible(*current, policy)) + { + current = baseline; + current_reason = ChampionReason::CurrentChampionInvalid; + } + + const CandidateStats* challenger = nullptr; + bool saw_eligible_challenger = false; + for (const CandidateStats& candidate : candidates) + { + if (&candidate == current || !Eligible(candidate, policy)) + continue; + + saw_eligible_challenger = true; + if (challenger == nullptr || candidate.total_cost_ns.mean < challenger->total_cost_ns.mean) + challenger = &candidate; + } + + if (!saw_eligible_challenger) + return {current->id, kBaselineCandidate, 0.0, 0.0, current_reason}; + + if (challenger == nullptr || challenger->total_cost_ns.mean >= current->total_cost_ns.mean) + return {current->id, challenger != nullptr ? challenger->id : kBaselineCandidate, + 0.0, 0.0, ChampionReason::NoBetterChallenger}; + + const double gain_ns = current->total_cost_ns.mean - challenger->total_cost_ns.mean; + const double relative_gain = current->total_cost_ns.mean > 0.0 + ? gain_ns / current->total_cost_ns.mean + : 0.0; + + if (!(gain_ns > 0.0) || gain_ns < policy.minimum_absolute_gain_ns || + relative_gain < policy.minimum_relative_gain) + { + return {current->id, challenger->id, gain_ns, 0.0, + ChampionReason::ChallengerInsufficientGain}; + } + + double conservative_gain_ns = gain_ns; + if (policy.require_confidence_separation) + { + conservative_gain_ns = + LowerBound(*current, policy.z_score) - UpperBound(*challenger, policy.z_score); + if (!(conservative_gain_ns > 0.0)) + { + return {current->id, challenger->id, gain_ns, conservative_gain_ns, + ChampionReason::ChallengerInsufficientConfidence}; + } + } + + return {challenger->id, challenger->id, gain_ns, conservative_gain_ns, + ChampionReason::ChallengerWon}; +} + +} // namespace sc2opt::tuner diff --git a/Tuner/Context.cpp b/Tuner/Context.cpp new file mode 100644 index 0000000..4765a25 --- /dev/null +++ b/Tuner/Context.cpp @@ -0,0 +1,45 @@ +#include "sc2opt/tuner/Context.hpp" + +namespace sc2opt::tuner { + +CandidateId SelectContextChampion(std::span champions, + ContextKey context, + CandidateId fallback) noexcept +{ + for (const ContextChampion& entry : champions) + { + if (entry.context == context) + return entry.champion; + } + return fallback; +} + +CrossoverValidationIssue ValidateCrossoverBands(std::span bands) noexcept +{ + if (bands.empty()) + return CrossoverValidationIssue::Empty; + + for (std::size_t i = 1; i < bands.size(); ++i) + { + if (bands[i].maximum_workload_size <= bands[i - 1].maximum_workload_size) + return CrossoverValidationIssue::NonIncreasingMaximum; + } + return CrossoverValidationIssue::None; +} + +CandidateId SelectCrossoverChampion(std::span bands, + std::size_t workload_size, + CandidateId fallback) noexcept +{ + if (ValidateCrossoverBands(bands) != CrossoverValidationIssue::None) + return fallback; + + for (const CrossoverBand& band : bands) + { + if (workload_size <= band.maximum_workload_size) + return band.champion; + } + return fallback; +} + +} // namespace sc2opt::tuner diff --git a/Tuner/Persistence.cpp b/Tuner/Persistence.cpp new file mode 100644 index 0000000..f4f8d30 --- /dev/null +++ b/Tuner/Persistence.cpp @@ -0,0 +1,108 @@ +#include "sc2opt/tuner/Persistence.hpp" + +#include +#include +#include +#include +#include +#include + +namespace sc2opt::tuner { +namespace { + +bool ProvenanceValid(const EvidenceProvenance& provenance) noexcept +{ + return !provenance.source_revision.empty() && !provenance.sc2_build.empty() && + !provenance.data_version.empty() && !provenance.compiler_profile.empty() && + !provenance.hardware_profile.empty() && !provenance.workload_profile.empty(); +} + +} // namespace + +bool IsValid(const ChampionRecord& record) noexcept +{ + return record.schema_version == kChampionRecordSchemaVersion && + record.decision_id != kInvalidDecisionId && + record.samples > 0 && + std::isfinite(record.mean_total_cost_ns) && + record.mean_total_cost_ns >= 0.0 && + std::isfinite(record.sample_variance_ns2) && + record.sample_variance_ns2 >= 0.0 && + ProvenanceValid(record.provenance); +} + +bool WriteChampionRecord(std::ostream& out, const ChampionRecord& record) +{ + if (!IsValid(record)) + return false; + + std::ostringstream line; + line.imbue(std::locale::classic()); + line << "SC2OPT_CHAMPION " + << record.schema_version << ' ' + << record.decision_id << ' ' + << record.context.workload << ' ' + << record.context.hardware << ' ' + << record.context.state_flags << ' ' + << record.champion << ' ' + << record.samples << ' ' + << std::setprecision(std::numeric_limits::max_digits10) + << record.mean_total_cost_ns << ' ' + << record.sample_variance_ns2 << ' ' + << std::quoted(record.provenance.source_revision) << ' ' + << std::quoted(record.provenance.sc2_build) << ' ' + << std::quoted(record.provenance.data_version) << ' ' + << std::quoted(record.provenance.compiler_profile) << ' ' + << std::quoted(record.provenance.hardware_profile) << ' ' + << std::quoted(record.provenance.workload_profile) + << '\n'; + + if (!line) + return false; + + out << line.str(); + return static_cast(out); +} + +bool ReadChampionRecord(std::istream& in, ChampionRecord& record) +{ + std::string line; + if (!std::getline(in, line)) + return false; + + std::istringstream parser(line); + parser.imbue(std::locale::classic()); + + std::string magic; + ChampionRecord parsed{}; + if (!(parser >> magic) || magic != "SC2OPT_CHAMPION") + return false; + + if (!(parser >> parsed.schema_version + >> parsed.decision_id + >> parsed.context.workload + >> parsed.context.hardware + >> parsed.context.state_flags + >> parsed.champion + >> parsed.samples + >> parsed.mean_total_cost_ns + >> parsed.sample_variance_ns2 + >> std::quoted(parsed.provenance.source_revision) + >> std::quoted(parsed.provenance.sc2_build) + >> std::quoted(parsed.provenance.data_version) + >> std::quoted(parsed.provenance.compiler_profile) + >> std::quoted(parsed.provenance.hardware_profile) + >> std::quoted(parsed.provenance.workload_profile))) + { + return false; + } + + parser >> std::ws; + if (!parser.eof() || !IsValid(parsed)) + return false; + + record = std::move(parsed); + return true; +} + +} // namespace sc2opt::tuner diff --git a/Tuner/README.md b/Tuner/README.md index bd601da..685a07a 100644 --- a/Tuner/README.md +++ b/Tuner/README.md @@ -1,3 +1,16 @@ # Tuner -Tuner machinery is generic and cheap. Consumers register legal tunables; the Tuner owns evidence and selection, not gameplay meaning. The baseline is always eligible to remain champion when challengers do not prove positive net benefit. +The Tuner is generic control-plane machinery. Consumers register legal knobs and candidate implementations; SC2AIOptimize owns evidence aggregation and selection, not gameplay meaning. + +Rules: + +- `Baseline` / `OFF` is candidate `0` and remains a valid champion. +- Measurement inputs are total cost: kernel + adapter + dispatch + bookkeeping. +- Invalid/duplicate evidence fails closed. +- Default champion promotion requires repeated samples and conservative confidence separation. +- `BaselineOnly` mode and deterministic reset are explicit. +- Context/crossover selection uses compact numeric IDs and can choose different champions by workload/hardware/state. +- Persistence is versioned and provenance-bound; stale evidence is not silently reused. +- Tuning/search is not performed inside hot kernel loops. + +See `docs/TUNER.md`. diff --git a/Tuner/TunableRegistry.cpp b/Tuner/TunableRegistry.cpp new file mode 100644 index 0000000..31c0133 --- /dev/null +++ b/Tuner/TunableRegistry.cpp @@ -0,0 +1,45 @@ +#include "sc2opt/tuner/TunableRegistry.hpp" + +namespace sc2opt::tuner { + +TunableRegistryValidation ValidateTunableRegistry(std::span specs) noexcept +{ + for (std::size_t i = 0; i < specs.size(); ++i) + { + if (!IsValid(specs[i])) + return {TunableRegistryIssue::InvalidSpec, i, i}; + + for (std::size_t j = 0; j < i; ++j) + { + if (specs[i].id == specs[j].id) + return {TunableRegistryIssue::DuplicateId, i, j}; + if (specs[i].name == specs[j].name) + return {TunableRegistryIssue::DuplicateName, i, j}; + } + } + + return {}; +} + +const TunableSpec* FindTunableById(std::span specs, std::uint32_t id) noexcept +{ + for (const TunableSpec& spec : specs) + { + if (spec.id == id) + return &spec; + } + return nullptr; +} + +const TunableSpec* FindTunableByName(std::span specs, + std::string_view name) noexcept +{ + for (const TunableSpec& spec : specs) + { + if (spec.name == name) + return &spec; + } + return nullptr; +} + +} // namespace sc2opt::tuner diff --git a/docs/STATUS.md b/docs/STATUS.md index 6c5e21b..f6910ea 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -7,11 +7,12 @@ SC2AIOptimize is pre-V1. Implementation presence is not runtime/performance cert - **S01-S04 — foundation:** merged. Base75689 SC2Registry provenance is exact; Linux/Windows Release CI is green. - **S05-S08 — generic interfaces:** merged. Synthetic unrelated C++ consumer and optional Python buffer-protocol adapter are proven on Linux/Windows. - **S09-S14 — Kernel/Hot:** merged. Geometry, filtering and spatial baseline/candidate contracts are correctness-tested; spatial optimisation remains **certified OFF by default** until target-workload crossover evidence exists. +- **S15-S19 — Kernel/Compute:** merged. Deterministic score reduction, reference/bounded influence, Dijkstra/A* pathing, footprint placement and minimal caller-supplied combat evaluation are present with correctness contracts. ## Current work -- **S15-S19 — Kernel/Compute:** target-score reduction, reference/bounded influence, Dijkstra/A* pathing workspace, generic footprint placement and minimal effective-stat combat evaluation. +- **S20-S24 — Tuner:** net-benefit baseline/OFF selection, validated TunableRegistry, repeated champion/challenger evidence, baseline-only/reset mode, context/crossover selection and versioned provenance persistence. ## Not yet claimed -No target-hardware crossover, bot integration, ladder-runtime speedup, behavioural equivalence or V1 release certification is claimed yet. Those require the later benchmark/profile/output/hardening slices and representative consumer evidence. +No target-hardware crossover, bot integration, ladder-runtime speedup, behavioural equivalence or V1 release certification is claimed yet. Those require the later runtime optimisation, benchmark/profile/output and hardening slices plus representative consumer evidence. diff --git a/docs/TUNER.md b/docs/TUNER.md new file mode 100644 index 0000000..1916b35 --- /dev/null +++ b/docs/TUNER.md @@ -0,0 +1,45 @@ +# Tuner design + +## Purpose + +The Tuner answers a narrow question: **which already-correct implementation/configuration should be used for this declared context?** It does not own bot semantics and it does not run an ML framework. + +## S20 — net-benefit gate + +Candidate `0` is the baseline/OFF path. `ChooseNetBenefitChampion` consumes already-measured total-cost evidence and refuses to promote incorrect, under-sampled or non-beneficial candidates. + +## S21 — TunableRegistry + +Consumers own tunable meaning, storage and safety. `TunableSpec` carries only the legal numeric contract and flags such as online-safe, reset-required and strategic. Registry validation is startup/control-plane work: invalid specs, duplicate IDs and duplicate names fail closed. + +## S22 — champion/challenger + +`RunningStats` uses Welford accumulation and stores only sample count, mean and M2. No sample history is retained. `EvaluateChampion` is allocation-free and compares the current champion against the best eligible challenger. + +Default promotion requires at least five samples and conservative interval separation using a policy-supplied z score (`1.96` by default). This is deliberately a lightweight normal-approximation gate, not a claim of full statistical inference. Later benchmark/profile slices may impose stronger evidence rules. + +`BaselineOnly` is an explicit mode. `ResetToBaseline` and `ResetEvidence` make test/game lifecycle behavior deterministic. + +## S23 — context and crossovers + +`ContextKey` is three cheap numeric dimensions: workload, hardware and state flags. Unknown contexts fail to the supplied fallback, normally baseline. + +Ordered `CrossoverBand` records implement the useful case where baseline wins for small N and another kernel wins only after a measured crossover. Invalid/non-increasing bands fail closed. + +The intended steady state is: + +```text +context / N -> persisted champion or crossover band -> execute +``` + +not repeated benchmarking on every call. + +## S24 — persistence and provenance + +Champion evidence persists in a strict versioned standard-library text record. Records carry source revision, SC2 build/data version, compiler profile, hardware profile and workload profile. Missing identity, unsupported schema, invalid numeric values or malformed data is rejected. + +The persistence path may allocate because it is control-plane/I/O work; it is not part of the hot runtime path. S30 may add richer JSON/report outputs without changing the runtime selection contract. + +## Cheapness invariant + +The Tuner must never become the thing being optimised. Candidate measurement and discovery are infrequent/offline or explicitly scheduled. Once a champion is known, consumers should pay only a tiny context/ID lookup plus the chosen implementation. diff --git a/include/sc2opt/tuner/Champion.hpp b/include/sc2opt/tuner/Champion.hpp new file mode 100644 index 0000000..3772b4d --- /dev/null +++ b/include/sc2opt/tuner/Champion.hpp @@ -0,0 +1,74 @@ +#pragma once + +#include "sc2opt/tuner/NetBenefit.hpp" + +#include +#include + +namespace sc2opt::tuner { + +struct RunningStats { + std::uint64_t samples = 0; + double mean = 0.0; + double m2 = 0.0; + + void Reset() noexcept; + [[nodiscard]] bool Add(double value) noexcept; + [[nodiscard]] double SampleVariance() const noexcept; + [[nodiscard]] double StandardError() const noexcept; +}; + +struct CandidateStats { + CandidateId id = kBaselineCandidate; + RunningStats total_cost_ns{}; + bool correctness_passed = false; +}; + +enum class TuningMode : std::uint8_t { + Adaptive, + BaselineOnly +}; + +struct ChampionState { + CandidateId champion = kBaselineCandidate; + TuningMode mode = TuningMode::Adaptive; +}; + +struct ChampionPolicy { + std::uint64_t minimum_samples = 5; + double minimum_absolute_gain_ns = 0.0; + double minimum_relative_gain = 0.0; + double z_score = 1.96; + bool require_confidence_separation = true; +}; + +enum class ChampionReason : std::uint8_t { + EvidenceInvalid, + BaselineInvalid, + BaselineMode, + CurrentChampionInvalid, + NoEligibleChallenger, + NoBetterChallenger, + ChallengerInsufficientGain, + ChallengerInsufficientConfidence, + ChallengerWon +}; + +struct ChampionDecision { + CandidateId champion = kBaselineCandidate; + CandidateId challenger = kBaselineCandidate; + double estimated_gain_ns = 0.0; + double conservative_gain_ns = 0.0; + ChampionReason reason = ChampionReason::BaselineInvalid; +}; + +void ResetToBaseline(ChampionState& state, TuningMode mode = TuningMode::Adaptive) noexcept; +void ResetEvidence(std::span candidates) noexcept; +void ApplyChampionDecision(ChampionState& state, const ChampionDecision& decision) noexcept; + +[[nodiscard]] ChampionDecision EvaluateChampion( + std::span candidates, + ChampionState state, + ChampionPolicy policy = {}) noexcept; + +} // namespace sc2opt::tuner diff --git a/include/sc2opt/tuner/Context.hpp b/include/sc2opt/tuner/Context.hpp new file mode 100644 index 0000000..081b438 --- /dev/null +++ b/include/sc2opt/tuner/Context.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include "sc2opt/tuner/NetBenefit.hpp" + +#include +#include +#include + +namespace sc2opt::tuner { + +struct ContextKey { + std::uint64_t workload = 0; + std::uint64_t hardware = 0; + std::uint32_t state_flags = 0; + + [[nodiscard]] constexpr bool operator==(const ContextKey&) const noexcept = default; +}; + +struct ContextChampion { + ContextKey context{}; + CandidateId champion = kBaselineCandidate; +}; + +[[nodiscard]] CandidateId SelectContextChampion( + std::span champions, + ContextKey context, + CandidateId fallback = kBaselineCandidate) noexcept; + +struct CrossoverBand { + std::size_t maximum_workload_size = 0; + CandidateId champion = kBaselineCandidate; +}; + +enum class CrossoverValidationIssue : std::uint8_t { + None, + Empty, + NonIncreasingMaximum +}; + +[[nodiscard]] CrossoverValidationIssue ValidateCrossoverBands( + std::span bands) noexcept; + +[[nodiscard]] CandidateId SelectCrossoverChampion( + std::span bands, + std::size_t workload_size, + CandidateId fallback = kBaselineCandidate) noexcept; + +} // namespace sc2opt::tuner diff --git a/include/sc2opt/tuner/Persistence.hpp b/include/sc2opt/tuner/Persistence.hpp new file mode 100644 index 0000000..31c6a75 --- /dev/null +++ b/include/sc2opt/tuner/Persistence.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include "sc2opt/tuner/Context.hpp" + +#include +#include +#include + +namespace sc2opt::tuner { + +inline constexpr std::uint32_t kChampionRecordSchemaVersion = 1; +inline constexpr std::uint64_t kInvalidDecisionId = 0; + +struct EvidenceProvenance { + std::string source_revision; + std::string sc2_build; + std::string data_version; + std::string compiler_profile; + std::string hardware_profile; + std::string workload_profile; +}; + +struct ChampionRecord { + std::uint32_t schema_version = kChampionRecordSchemaVersion; + std::uint64_t decision_id = kInvalidDecisionId; + ContextKey context{}; + CandidateId champion = kBaselineCandidate; + std::uint64_t samples = 0; + double mean_total_cost_ns = 0.0; + double sample_variance_ns2 = 0.0; + EvidenceProvenance provenance{}; +}; + +[[nodiscard]] bool IsValid(const ChampionRecord& record) noexcept; +[[nodiscard]] bool WriteChampionRecord(std::ostream& out, const ChampionRecord& record); +[[nodiscard]] bool ReadChampionRecord(std::istream& in, ChampionRecord& record); + +} // namespace sc2opt::tuner diff --git a/include/sc2opt/tuner/TunableRegistry.hpp b/include/sc2opt/tuner/TunableRegistry.hpp index d66cfc9..3f5ea1d 100644 --- a/include/sc2opt/tuner/TunableRegistry.hpp +++ b/include/sc2opt/tuner/TunableRegistry.hpp @@ -1,6 +1,8 @@ #pragma once +#include #include +#include #include namespace sc2opt::tuner { @@ -30,7 +32,34 @@ struct TunableSpec { return false; if (spec.baseline < spec.minimum || spec.baseline > spec.maximum) return false; - return spec.kind == TunableKind::Boolean || spec.step >= 0.0; + if (spec.kind == TunableKind::Boolean) + return spec.minimum <= 0.0 && spec.maximum >= 1.0 && + (spec.baseline == 0.0 || spec.baseline == 1.0); + return spec.step > 0.0; } +enum class TunableRegistryIssue : std::uint8_t { + None, + InvalidSpec, + DuplicateId, + DuplicateName +}; + +struct TunableRegistryValidation { + TunableRegistryIssue issue = TunableRegistryIssue::None; + std::size_t index = 0; + std::size_t conflicting_index = 0; + + [[nodiscard]] constexpr bool ok() const noexcept { return issue == TunableRegistryIssue::None; } +}; + +[[nodiscard]] TunableRegistryValidation ValidateTunableRegistry( + std::span specs) noexcept; + +[[nodiscard]] const TunableSpec* FindTunableById(std::span specs, + std::uint32_t id) noexcept; + +[[nodiscard]] const TunableSpec* FindTunableByName(std::span specs, + std::string_view name) noexcept; + } // namespace sc2opt::tuner diff --git a/tests/tuner_tests.cpp b/tests/tuner_tests.cpp new file mode 100644 index 0000000..137b3f7 --- /dev/null +++ b/tests/tuner_tests.cpp @@ -0,0 +1,178 @@ +#include "sc2opt/tuner/Champion.hpp" +#include "sc2opt/tuner/Context.hpp" +#include "sc2opt/tuner/NetBenefit.hpp" +#include "sc2opt/tuner/Persistence.hpp" +#include "sc2opt/tuner/TunableRegistry.hpp" + +#include +#include +#include +#include +#include + +namespace { + +int failures = 0; + +void Check(bool condition, std::string_view message) +{ + if (!condition) + { + ++failures; + std::cerr << "FAIL: " << message << '\n'; + } +} + +void TestTunableRegistry() +{ + using namespace sc2opt::tuner; + const std::array specs{ + TunableSpec{1, "grid.cell", TunableKind::Continuous, 4.0, 2.0, 8.0, 0.5, + TunableOnlineSafe}, + TunableSpec{2, "budget.enabled", TunableKind::Boolean, 0.0, 0.0, 1.0, 0.0, + TunableOnlineSafe}, + }; + Check(ValidateTunableRegistry(specs).ok(), "valid registry"); + Check(FindTunableById(specs, 2) != nullptr, "find tunable by id"); + Check(FindTunableByName(specs, "grid.cell") != nullptr, "find tunable by name"); + + const std::array duplicate{ + TunableSpec{1, "a", TunableKind::Integer, 1.0, 0.0, 2.0, 1.0, 0}, + TunableSpec{1, "b", TunableKind::Integer, 1.0, 0.0, 2.0, 1.0, 0}, + }; + Check(ValidateTunableRegistry(duplicate).issue == TunableRegistryIssue::DuplicateId, + "duplicate tunable id rejected"); +} + +void AddSamples(sc2opt::tuner::CandidateStats& stats, double value, int count) +{ + for (int i = 0; i < count; ++i) + Check(stats.total_cost_ns.Add(value), "sample accepted"); +} + +void TestChampion() +{ + using namespace sc2opt::tuner; + std::array stats{{ + CandidateStats{0, {}, true}, + CandidateStats{1, {}, true}, + }}; + AddSamples(stats[0], 100.0, 10); + AddSamples(stats[1], 70.0, 10); + + ChampionState state{}; + const auto decision = EvaluateChampion(stats, state); + Check(decision.champion == 1, "confident faster challenger wins"); + Check(decision.reason == ChampionReason::ChallengerWon, "challenger win reason"); + + ApplyChampionDecision(state, decision); + Check(state.champion == 1, "champion decision applies deterministically"); + + state.mode = TuningMode::BaselineOnly; + const auto baseline = EvaluateChampion(stats, state); + Check(baseline.champion == kBaselineCandidate, "baseline-only mode"); + + ResetToBaseline(state); + Check(state.champion == kBaselineCandidate && state.mode == TuningMode::Adaptive, + "deterministic reset to baseline"); + + ResetEvidence(stats); + Check(stats[0].total_cost_ns.samples == 0 && !stats[0].correctness_passed, + "evidence reset"); + + std::array noisy{{ + CandidateStats{0, {}, true}, + CandidateStats{1, {}, true}, + }}; + for (double value : {90.0, 110.0, 95.0, 105.0, 100.0}) + Check(noisy[0].total_cost_ns.Add(value), "baseline noisy sample"); + for (double value : {80.0, 120.0, 90.0, 110.0, 95.0}) + Check(noisy[1].total_cost_ns.Add(value), "challenger noisy sample"); + const auto uncertain = EvaluateChampion(noisy, {}); + Check(uncertain.champion == kBaselineCandidate, + "overlapping confidence keeps baseline"); + + const std::array duplicate{{ + CandidateStats{0, RunningStats{5, 100.0, 0.0}, true}, + CandidateStats{0, RunningStats{5, 50.0, 0.0}, true}, + }}; + Check(EvaluateChampion(duplicate, {}).reason == ChampionReason::EvidenceInvalid, + "duplicate candidate ids fail closed"); +} + +void TestContext() +{ + using namespace sc2opt::tuner; + const ContextKey macro{10, 20, 1}; + const ContextKey fight{10, 20, 2}; + const std::array contexts{ + ContextChampion{macro, 1}, + ContextChampion{fight, 2}, + }; + Check(SelectContextChampion(contexts, fight) == 2, "context champion"); + Check(SelectContextChampion(contexts, ContextKey{99, 99, 0}) == kBaselineCandidate, + "unknown context fails to baseline"); + + const std::array bands{ + CrossoverBand{16, 0}, + CrossoverBand{96, 1}, + CrossoverBand{256, 2}, + }; + Check(ValidateCrossoverBands(bands) == CrossoverValidationIssue::None, + "valid crossover bands"); + Check(SelectCrossoverChampion(bands, 8) == 0, "small workload baseline"); + Check(SelectCrossoverChampion(bands, 50) == 1, "medium workload candidate one"); + Check(SelectCrossoverChampion(bands, 200) == 2, "large workload candidate two"); + Check(SelectCrossoverChampion(bands, 1000) == 0, + "uncovered size fails to baseline"); +} + +void TestPersistence() +{ + using namespace sc2opt::tuner; + ChampionRecord record{}; + record.decision_id = 42; + record.context = {11, 22, 3}; + record.champion = 2; + record.samples = 100; + record.mean_total_cost_ns = 123.5; + record.sample_variance_ns2 = 4.25; + record.provenance = {"abcdef", "75689", "B89", "gcc14-release", "ryzen-test", + "dense-fight"}; + + std::stringstream stream; + Check(WriteChampionRecord(stream, record), "write champion record"); + + ChampionRecord round_trip{}; + Check(ReadChampionRecord(stream, round_trip), "read champion record"); + Check(round_trip.decision_id == record.decision_id, "persist decision id"); + Check(round_trip.context == record.context, "persist context"); + Check(round_trip.champion == record.champion, "persist champion"); + Check(std::fabs(round_trip.mean_total_cost_ns - record.mean_total_cost_ns) < 1e-12, + "persist mean"); + Check(round_trip.provenance.hardware_profile == "ryzen-test", "persist provenance"); + + std::stringstream bad( + "SC2OPT_CHAMPION 999 1 0 0 0 0 1 1 0 \"x\" \"x\" \"x\" \"x\" \"x\" \"x\"\n"); + ChampionRecord rejected{}; + Check(!ReadChampionRecord(bad, rejected), "wrong schema rejected"); +} + +} // namespace + +int main() +{ + TestTunableRegistry(); + TestChampion(); + TestContext(); + TestPersistence(); + + if (failures == 0) + { + std::cout << "SC2AIOptimize tuner tests passed\n"; + return 0; + } + + std::cerr << failures << " tuner test(s) failed\n"; + return 1; +}