载入中...
搜索中...
未找到
Balance.cpp
浏览该文件的文档.
1#include "agent/Balance.h"
2#include "agent/Learning.h"
3
4#include <algorithm>
5#include <cmath>
6#include <exception>
7#include <set>
8
10namespace {
11Diagnostic invalid(std::string message) {
12 return Diagnostic::error(DiagnosticCode::InvalidArgument, std::move(message), {}, {}, "agent.balance");
13}
14bool finite(double v) { return std::isfinite(v) && std::abs(v) <= 1e9; }
15bool valid(const Problem& p) {
16 if (p.parameters.empty() || p.parameters.size() > 64 || p.targets.empty() || p.targets.size() > 128 ||
17 p.trainingSeeds.empty() || p.trainingSeeds.size() > 128 || p.validationSeeds.empty() ||
18 p.validationSeeds.size() > 128 || p.candidates < 1 || p.candidates > 4096 ||
19 std::uint64_t(p.candidates) * p.trainingSeeds.size() + 2 * p.validationSeeds.size() > 65536 || p.steps < 1 ||
20 p.steps > 100000 || !finite(p.dt) || p.dt <= 0 || p.dt > 60 || !finite(p.changeWeight) || p.changeWeight < 0 ||
21 p.changeWeight > 1e6)
22 return false;
23 std::set<std::string> names;
24 for (const auto& x : p.parameters) {
25 if (x.name.empty() || x.name.size() > 128 || !names.insert(x.name).second || !finite(x.initial) ||
26 !finite(x.minimum) || !finite(x.maximum) || x.minimum > x.initial || x.initial > x.maximum)
27 return false;
28 }
29 names.clear();
30 for (const auto& t : p.targets) {
31 if (t.name.empty() || t.name.size() > 128 || !names.insert(t.name).second || !finite(t.minimum) ||
32 !finite(t.maximum) || t.minimum > t.maximum || !finite(t.scale) || t.scale < 1e-9 || !finite(t.weight) ||
33 t.weight <= 0 || t.weight > 1e6)
34 return false;
35 }
36 std::set<std::uint64_t> seeds;
37 for (auto s : p.trainingSeeds)
38 if (!seeds.insert(s).second) return false;
39 for (auto s : p.validationSeeds)
40 if (!seeds.insert(s).second) return false;
41 return true;
42}
43
44Result<Assessment> assess(const Problem& p, const std::vector<double>& values, const std::vector<std::uint64_t>& seeds,
45 IEvaluator& evaluator, std::uint64_t& evaluations) {
47 a.metrics.resize(p.targets.size());
48 std::size_t count = 0;
49 for (auto seed : seeds) {
50 auto sample = [&]() -> Result<std::vector<double>> {
51 try {
52 return evaluator.evaluate(values, seed, p.dt, p.steps);
53 } catch (const std::exception& error) {
54 return Result<std::vector<double>>::failure(
55 Diagnostic::error(DiagnosticCode::CallbackFailure, error.what(), {}, {}, "agent.balance"));
56 }
57 }();
58 ++evaluations;
59 if (!sample) return Result<Assessment>::failure(sample.status());
60 if (sample.value().size() != p.targets.size())
61 return Result<Assessment>::failure(invalid("Evaluator metric count differs from targets"));
62 ++count;
63 for (std::size_t i = 0; i < a.metrics.size(); ++i) {
64 const double value = sample.value()[i];
65 if (!finite(value))
66 return Result<Assessment>::failure(invalid("Evaluator returned nonfinite/oversized metric"));
67 auto& m = a.metrics[i];
68 const double delta = value - m.mean;
69 m.mean += delta / double(count);
70 m.deviation += delta * (value - m.mean);
71 }
72 }
73 for (std::size_t i = 0; i < a.metrics.size(); ++i) {
74 auto& m = a.metrics[i];
75 m.deviation = count > 1 ? std::sqrt(std::max(0.0, m.deviation / double(count - 1))) : 0;
76 const auto& t = p.targets[i];
77 const double distance = (m.mean - std::clamp(m.mean, t.minimum, t.maximum)) / t.scale;
78 a.loss += t.weight * distance * distance;
79 }
80 double drift = 0;
81 for (std::size_t i = 0; i < values.size(); ++i) {
82 const auto& x = p.parameters[i];
83 if (x.maximum == x.minimum) continue;
84 const double delta = (values[i] - x.initial) / (x.maximum - x.minimum);
85 drift += delta * delta;
86 }
87 a.score = a.loss + p.changeWeight * drift / double(values.size());
88 return Result<Assessment>::success(std::move(a));
89}
90} // namespace
91
93 if (active_) return Result<void>::failure(Diagnostic::error(DiagnosticCode::Conflict, "Balance search is active"));
94 if (!valid(p)) return Result<void>::failure(invalid("Invalid balance bounds, names, targets, seeds or budget"));
95 problem_ = p;
96 return Result<void>::success();
97}
98
100 if (active_) return Result<Report>::failure(Diagnostic::error(DiagnosticCode::Conflict, "Balance search reentry"));
101 if (!problem_) return Result<Report>::failure(invalid("Configure the balance search before run"));
102 struct Guard {
103 bool& active;
104 explicit Guard(bool& a) : active(a) { active = true; }
105 ~Guard() { active = false; }
106 } guard(active_);
107 Report report;
108 report.problem = *problem_;
109 const auto& p = report.problem;
110 std::vector<double> initial;
111 initial.reserve(p.parameters.size());
112 for (const auto& x : p.parameters) initial.push_back(x.initial);
113 report.parameters = initial;
114 auto baseline = assess(p, initial, p.trainingSeeds, evaluator, report.evaluations);
115 if (!baseline) return Result<Report>::failure(baseline.status());
116 report.baseline = std::move(baseline).takeValue();
117 report.tuned = report.baseline;
118 detail::Random random(p.searchSeed);
119 for (std::uint32_t trial = 1; trial < p.candidates; ++trial) {
120 auto values = report.parameters;
121 if (trial <= 2) {
122 // Boundary anchors expose interactions that small local mutations cannot reach.
123 for (std::size_t i = 0; i < values.size(); ++i)
124 values[i] = trial == 1 ? p.parameters[i].minimum : p.parameters[i].maximum;
125 } else if (trial == 3 && values.size() >= 4) {
126 // Probe a sparse corner: the outer parameters stay at their initial values.
127 // This can cross a coupled plateau that single-coordinate repairs cannot.
128 for (std::size_t i = 0; i < values.size(); ++i) values[i] = p.parameters[i].minimum;
129 values.front() = p.parameters.front().initial;
130 values.back() = p.parameters.back().initial;
131 } else if (report.tuned.loss == 0 && trial - 3 < values.size()) {
132 // Once feasible, spend bounded probes restoring one parameter at a time.
133 const auto index = std::size_t(trial - 3);
134 values[index] = p.parameters[index].initial;
135 } else {
136 const bool explore = random.unit() < 0.25;
137 const double radius = 0.25 * (1.0 - double(trial) / double(p.candidates)) + 0.01;
138 for (std::size_t i = 0; i < values.size(); ++i) {
139 const auto& x = p.parameters[i];
140 const double width = x.maximum - x.minimum;
141 values[i] =
142 explore ? x.minimum + random.unit() * width
143 : std::clamp(values[i] + (random.unit() * 2 - 1) * width * radius, x.minimum, x.maximum);
144 }
145 }
146 auto measured = assess(p, values, p.trainingSeeds, evaluator, report.evaluations);
147 if (!measured) return Result<Report>::failure(measured.status());
148 if (measured.value().score < report.tuned.score) {
149 report.parameters = std::move(values);
150 report.tuned = std::move(measured).takeValue();
151 }
152 }
153 auto before = assess(p, initial, p.validationSeeds, evaluator, report.evaluations);
154 if (!before) return Result<Report>::failure(before.status());
155 report.baselineValidation = std::move(before).takeValue();
156 auto after = assess(p, report.parameters, p.validationSeeds, evaluator, report.evaluations);
157 if (!after) return Result<Report>::failure(after.status());
158 report.validation = std::move(after).takeValue();
160 for (std::size_t i = 0; i < p.targets.size(); ++i) {
161 const double mean = report.validation.metrics[i].mean;
162 if (mean < p.targets[i].minimum || mean > p.targets[i].maximum) report.verdict = Verdict::OutsideTargets;
163 }
164 return Result<Report>::success(std::move(report));
165}
166} // namespace eve::agent::balance
double m[16]
double x
bool & active
const std::string & s
glm::vec4 p[6]
std::string message
float v
std::uint32_t width
bool valid
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
bool finite
std::string error
Definition Package.cpp:174
std::set< std::string > values
Object::Ptr value
float t
int count
Battle::Random random
uint32_t seed
Definition TreeMesh.cpp:276
uint32_t index
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Result< void > configure(const Problem &problem)
Validate and copy a problem atomically; a failed configuration preserves the previous one.
Definition Balance.cpp:92
Result< Report > run(IEvaluator &evaluator)
Search on training seeds, then assess initial and best parameters on untouched holdout seeds.
Definition Balance.cpp:99
Game-owned isolated simulation adapter, not a second combat implementation. @ownership Caller owns th...
Definition Balance.h:57
virtual Result< std::vector< double > > evaluate(std::span< const double > parameters, std::uint64_t seed, double dt, std::uint32_t steps)=0
Reset and simulate a single candidate and seed. @cost One domain rollout per call; amortize by reusin...
Random public API.
Definition Learning.h:14
Owning measurements; score includes parameter drift, loss contains only target violations.
Definition Balance.h:76
std::vector< Metric > metrics
Definition Balance.h:77
Owning search specification. Seeds for tuning and holdout must be unique and disjoint.
Definition Balance.h:37
Owning proposal and evidence. No game configuration is modified by the search.
Definition Balance.h:86
Assessment baselineValidation
Definition Balance.h:91
std::uint64_t evaluations
Definition Balance.h:93
std::vector< double > parameters
Definition Balance.h:88