Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ add_library(sc2opt_tuner STATIC
Tuner/Champion.cpp
Tuner/Context.cpp
Tuner/Persistence.cpp
Tuner/Telemetry.cpp
Tuner/BudgetGovernor.cpp
Tuner/Calibration.cpp
)
add_library(sc2opt::tuner ALIAS sc2opt_tuner)
target_include_directories(sc2opt_tuner PUBLIC include)
Expand Down Expand Up @@ -121,6 +124,12 @@ if(SC2OPT_BUILD_TESTS)
sc2opt_apply_warnings(sc2opt_tuner_tests)
add_test(NAME sc2opt_tuner_tests COMMAND sc2opt_tuner_tests)

add_executable(sc2opt_runtime_optimization_tests tests/runtime_optimization_tests.cpp)
target_link_libraries(sc2opt_runtime_optimization_tests PRIVATE sc2opt)
target_compile_features(sc2opt_runtime_optimization_tests PRIVATE cxx_std_20)
sc2opt_apply_warnings(sc2opt_runtime_optimization_tests)
add_test(NAME sc2opt_runtime_optimization_tests COMMAND sc2opt_runtime_optimization_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)
Expand Down
29 changes: 29 additions & 0 deletions Tuner/BudgetGovernor.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include "sc2opt/tuner/BudgetGovernor.hpp"

namespace sc2opt::tuner {

BudgetState UpdateBudgetState(BudgetState previous,
std::uint64_t completed_duration_ns,
BudgetPolicy policy) noexcept
{
BudgetState next = previous;
next.previous_duration_ns = completed_duration_ns;
next.policy_valid = IsValid(policy);

if (!next.policy_valid)
{
next.pressure = BudgetPressure::Hard;
return next;
}

if (completed_duration_ns >= policy.hard_ns)
next.pressure = BudgetPressure::Hard;
else if (completed_duration_ns >= policy.soft_ns)
next.pressure = BudgetPressure::Soft;
else if (completed_duration_ns <= policy.resume_ns)
next.pressure = BudgetPressure::Normal;

return next;
}

} // namespace sc2opt::tuner
96 changes: 96 additions & 0 deletions Tuner/Calibration.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#include "sc2opt/tuner/Calibration.hpp"

#include <cmath>

namespace sc2opt::tuner {
namespace {

CalibrationIssue ValidateCandidates(std::span<const CandidateEvidence> candidates) noexcept
{
bool baseline_present = false;
for (std::size_t i = 0; i < candidates.size(); ++i)
{
if (candidates[i].id == kBaselineCandidate)
{
if (baseline_present)
return CalibrationIssue::DuplicateCandidate;
baseline_present = true;
}

for (std::size_t j = 0; j < i; ++j)
{
if (candidates[i].id == candidates[j].id)
return CalibrationIssue::DuplicateCandidate;
}
}

return baseline_present ? CalibrationIssue::None : CalibrationIssue::MissingBaseline;
}

} // namespace

CalibrationResult BuildCrossoverCalibration(std::span<const CalibrationPoint> points,
std::span<CrossoverBand> output,
NetBenefitPolicy policy) noexcept
{
if (points.empty())
return {CalibrationIssue::EmptyEvidence, 0, 0};

CalibrationResult result{};
CandidateId previous_champion = kBaselineCandidate;
bool have_previous = false;

for (std::size_t i = 0; i < points.size(); ++i)
{
const CalibrationPoint& point = points[i];
if (i > 0 && point.workload_size <= points[i - 1].workload_size)
return {CalibrationIssue::UnsortedWorkload, result.workload_points,
result.bands_written};
if (point.candidates.empty())
return {CalibrationIssue::EmptyEvidence, result.workload_points, result.bands_written};

const CalibrationIssue validation = ValidateCandidates(point.candidates);
if (validation != CalibrationIssue::None)
return {validation, result.workload_points, result.bands_written};

const NetBenefitDecision decision = ChooseNetBenefitChampion(point.candidates, policy);
const CandidateId champion = decision.champion;

++result.workload_points;
if (!have_previous || champion != previous_champion)
{
if (result.bands_written >= output.size())
return {CalibrationIssue::OutputTooSmall, result.workload_points,
result.bands_written};

output[result.bands_written++] = {point.workload_size, champion};
previous_champion = champion;
have_previous = true;
}
else
{
output[result.bands_written - 1].maximum_workload_size = point.workload_size;
}
}

return result;
}

ControlOverheadDecision CheckControlOverhead(std::uint64_t control_overhead_ns,
std::uint64_t chosen_work_ns,
ControlOverheadPolicy policy) noexcept
{
if (!std::isfinite(policy.maximum_fraction_of_work) ||
policy.maximum_fraction_of_work < 0.0 || chosen_work_ns == 0)
{
return {};
}

const double fraction =
static_cast<double>(control_overhead_ns) / static_cast<double>(chosen_work_ns);
const bool absolute_ok = policy.maximum_absolute_ns == 0 ||
control_overhead_ns <= policy.maximum_absolute_ns;
return {absolute_ok && fraction <= policy.maximum_fraction_of_work, fraction};
}

} // namespace sc2opt::tuner
13 changes: 12 additions & 1 deletion Tuner/NetBenefit.cpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
#include "sc2opt/tuner/NetBenefit.hpp"

#include <cmath>
#include <limits>

namespace sc2opt::tuner {
namespace {

bool PolicyValid(const NetBenefitPolicy& 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;
}

bool Eligible(const CandidateEvidence& candidate, const NetBenefitPolicy& policy) noexcept
{
return candidate.correctness_passed && candidate.samples >= policy.minimum_samples &&
Expand All @@ -17,6 +25,9 @@ bool Eligible(const CandidateEvidence& candidate, const NetBenefitPolicy& policy
NetBenefitDecision ChooseNetBenefitChampion(std::span<const CandidateEvidence> evidence,
NetBenefitPolicy policy) noexcept
{
if (!PolicyValid(policy))
return {kBaselineCandidate, 0.0, 0.0, DecisionReason::PolicyInvalid};

const CandidateEvidence* baseline = nullptr;
for (const CandidateEvidence& candidate : evidence)
{
Expand Down
8 changes: 6 additions & 2 deletions Tuner/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ 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.
- Invalid/duplicate evidence and invalid policies fail 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.
- Runtime telemetry uses fixed storage; compile-time-disabled timers perform no clock call or mutation.
- The budget governor operates on the previous completed duration and only sheds work the consumer declared non-critical.
- Auto-calibration delegates winner selection to the single net-benefit authority and may produce baseline crossover bands.
- Tuner/control overhead must itself pass a measured cheapness gate.
- 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`.
See `docs/TUNER.md` and `docs/RUNTIME_OPTIMIZATION.md`.
76 changes: 76 additions & 0 deletions Tuner/Telemetry.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#include "sc2opt/tuner/Telemetry.hpp"

#include <algorithm>
#include <bit>

namespace sc2opt::tuner {

void FixedLatencyHistogram::Reset() noexcept
{
buckets_.fill(0);
samples_ = 0;
total_ns_ = 0;
minimum_ns_ = std::numeric_limits<std::uint64_t>::max();
maximum_ns_ = 0;
}

std::size_t FixedLatencyHistogram::BucketFor(std::uint64_t value) noexcept
{
return static_cast<std::size_t>(std::bit_width(value));
}

std::uint64_t FixedLatencyHistogram::BucketUpper(std::size_t bucket) noexcept
{
if (bucket == 0)
return 0;
if (bucket >= 64)
return std::numeric_limits<std::uint64_t>::max();
return (std::uint64_t{1} << bucket) - 1;
}

void FixedLatencyHistogram::Observe(std::uint64_t duration_ns) noexcept
{
if (samples_ == std::numeric_limits<std::uint64_t>::max())
return;

const std::size_t bucket = BucketFor(duration_ns);
++buckets_[bucket];
++samples_;
minimum_ns_ = std::min(minimum_ns_, duration_ns);
maximum_ns_ = std::max(maximum_ns_, duration_ns);

if (duration_ns <= std::numeric_limits<std::uint64_t>::max() - total_ns_)
total_ns_ += duration_ns;
else
total_ns_ = std::numeric_limits<std::uint64_t>::max();
}

std::uint64_t FixedLatencyHistogram::PercentileUpper(std::uint32_t percentile) const noexcept
{
if (samples_ == 0 || percentile == 0 || percentile > 100)
return 0;

const std::uint64_t quotient = samples_ / 100;
const std::uint64_t remainder = samples_ % 100;
const std::uint64_t rank = quotient * percentile + (remainder * percentile + 99) / 100;

std::uint64_t cumulative = 0;
for (std::size_t i = 0; i < buckets_.size(); ++i)
{
cumulative += buckets_[i];
if (cumulative >= rank)
return BucketUpper(i);
}
return maximum_ns_;
}

LatencySummary FixedLatencyHistogram::Summary() const noexcept
{
if (samples_ == 0)
return {};

return {samples_, total_ns_, minimum_ns_, maximum_ns_, PercentileUpper(50),
PercentileUpper(95), PercentileUpper(99)};
}

} // namespace sc2opt::tuner
43 changes: 43 additions & 0 deletions docs/RUNTIME_OPTIMIZATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Runtime optimisation — S25-S27

## S25 — profiling / telemetry

`FixedLatencyHistogram` is a 65-bucket log2 histogram with fixed storage, allocation-free observation and saturating counters. It reports sample count, total/min/max and conservative p50/p95/p99 bucket upper bounds. The coarse quantiles are intentional: live telemetry should be cheap; exact distribution analysis belongs in benchmark/proof tooling.

`ScopedLatencyTimer<false>` is a compile-time-disabled empty type: no clock read and no histogram mutation. Consumers can therefore compile telemetry out of genuinely hot paths rather than paying a runtime feature switch on every call.

## S26 — compute-budget governor

The governor generalises the MMEvo Z7 latency-hysteresis pattern without importing MME policy. The default thresholds retain the proven seed values (22 ms resume, 28 ms soft, 38 ms hard), but consumers own the budget policy and classify their own work as `Critical`, `Important` or `Optional`.

- Normal: all declared work is allowed.
- Soft: Optional work is shed.
- Hard: only Critical work is allowed.
- Between resume and soft thresholds, previous pressure is retained to prevent oscillation.
- Invalid threshold ordering fails closed to Hard.

The governor never decides what gameplay work *means* and never times work itself; it consumes the previous completed duration.

## S27 — auto-calibration

`BuildCrossoverCalibration` accepts caller-owned workload points and already-measured candidate evidence. It validates grouping, requires a baseline at every point, delegates candidate selection to `ChooseNetBenefitChampion`, and compresses adjacent equal champions into tiny `CrossoverBand` outputs.

This preserves one authority for net-benefit semantics. Calibration does not duplicate the selection rule and may produce baseline/OFF for any workload range.

`CheckControlOverhead` makes the optimiser measure itself: a selector/calibration/control path can be rejected when measured overhead exceeds an absolute and/or fractional budget. The default fractional ceiling is 1% of chosen work; target projects may choose stricter values.

## Runtime target

```text
fixed/compiled telemetry when justified
-> previous completed duration
-> tiny hysteresis state
-> context/crossover champion ID
-> chosen implementation
```

Discovery and benchmarking remain control-plane/offline operations. The hot path should execute an already-resolved choice, not search for one.

## Evidence status

S25-S27 implementation and component tests do not certify a target-hardware speedup. Representative benchmark profiles, target-hardware crossover values and consumer integration evidence remain S28-S32 work.
5 changes: 3 additions & 2 deletions docs/STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ SC2AIOptimize is pre-V1. Implementation presence is not runtime/performance cert
- **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.
- **S20-S24 — Tuner:** merged. Net-benefit baseline/OFF selection, validated TunableRegistry, repeated champion/challenger evidence, baseline-only/reset mode, context/crossover selection and versioned provenance persistence are present.

## Current work

- **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.
- **S25-S27 — runtime optimisation:** fixed-storage telemetry, compile-time-disabled instrumentation, generic latency hysteresis governor, crossover auto-calibration and explicit tuner/control-overhead cheapness gate.

## 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 runtime optimisation, benchmark/profile/output and hardening slices plus 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 deep-test, benchmark/profile/output and hardening slices plus representative consumer evidence.
44 changes: 44 additions & 0 deletions include/sc2opt/tuner/BudgetGovernor.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#pragma once

#include <cstdint>

namespace sc2opt::tuner {

enum class BudgetPressure : std::uint8_t { Normal, Soft, Hard };
enum class WorkClass : std::uint8_t { Critical, Important, Optional };

struct BudgetPolicy {
std::uint64_t resume_ns = 22'000'000;
std::uint64_t soft_ns = 28'000'000;
std::uint64_t hard_ns = 38'000'000;
};

struct BudgetState {
BudgetPressure pressure = BudgetPressure::Normal;
std::uint64_t previous_duration_ns = 0;
bool policy_valid = true;
};

[[nodiscard]] constexpr bool IsValid(const BudgetPolicy& policy) noexcept
{
return policy.resume_ns < policy.soft_ns && policy.soft_ns < policy.hard_ns;
}

// Uses the previous completed duration; it never times work itself. Invalid policies fail hard
// so only consumer-declared Critical work is allowed.
[[nodiscard]] BudgetState UpdateBudgetState(BudgetState previous,
std::uint64_t completed_duration_ns,
BudgetPolicy policy = {}) noexcept;

[[nodiscard]] constexpr bool AllowsWork(BudgetState state, WorkClass work) noexcept
{
if (!state.policy_valid)
return work == WorkClass::Critical;
if (state.pressure == BudgetPressure::Hard)
return work == WorkClass::Critical;
if (state.pressure == BudgetPressure::Soft)
return work != WorkClass::Optional;
return true;
}

} // namespace sc2opt::tuner
Loading
Loading