Files
2026-10-29 20:48:09 +07:00

313 lines
12 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// agent.cpp — реализации агентного слоя (см. agent.h).
#include "agent.h"
#include "config.h" // engine_info/engine_warn
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <numeric>
namespace xt {
// ===========================================================================
// (3) RouterScheduler
// ===========================================================================
RouterRule& RouterScheduler::add_rule(const std::string& name,
std::function<bool(const AgentContext&)> when,
std::vector<std::string> agents,
bool rerun_after, bool exclusive) {
rules_.push_back(RouterRule{name, std::move(when), std::move(agents), rerun_after, exclusive});
return rules_.back();
}
std::vector<size_t> RouterScheduler::resolve(const std::vector<std::string>& names,
size_t n_agents) const {
std::vector<size_t> idx;
for (const std::string& nm : names) {
for (size_t i = 0; i < n_agents && i < names_.size(); ++i) {
if (names_[i] == nm) {
if (std::find(idx.begin(), idx.end(), i) == idx.end()) idx.push_back(i);
break;
}
}
}
return idx;
}
std::vector<size_t> RouterScheduler::plan(const AgentContext& ctx, size_t n_agents) {
last_fired_.clear();
std::vector<size_t> plan;
bool any = false;
bool rerun = false;
for (const RouterRule& r : rules_) {
if (r.when && !r.when(ctx)) continue;
any = true;
last_fired_.push_back(r.name);
if (r.rerun_after) rerun = true;
for (size_t i : resolve(r.agents, n_agents))
if (std::find(plan.begin(), plan.end(), i) == plan.end()) plan.push_back(i);
if (r.exclusive) break;
}
if (!any && fallback_all_) {
plan.clear();
for (size_t i = 0; i < n_agents; ++i) plan.push_back(i);
}
if (rerun) {
// rerun запрашивает ПЛАНИРОВЩИК: взводим флаг для engine (агенты могут
// выставить его дополнительно сами)
const_cast<AgentContext&>(ctx).rerun = true;
}
return plan;
}
// ===========================================================================
// (5) NeuralAgent
// ===========================================================================
NeuralAgent::NeuralAgent(std::string name, std::shared_ptr<Checkpoint> ck)
: name_(std::move(name)), owned_(std::move(ck)) {
p_ = &owned_->params;
tok_ = &owned_->tok;
gen.seed = 1234;
}
NeuralAgent::NeuralAgent(std::string name, const Params* p, const Tokenizer* tok)
: name_(std::move(name)), p_(p), tok_(tok) {
gen.seed = 1234;
}
bool NeuralAgent::process(AgentContext& ctx) {
if (!p_) { ctx.text[output_text_key] = ""; return false; }
// --- выбор входа: мультимодальный эмбеддинг приоритетнее токенов ---
bool have_embed = false;
if (!input_embed_key.empty() && ctx.has(input_embed_key)) {
const Tensor& t = ctx.tensors[input_embed_key];
if (t.n() > 0 && t.C() == p_->cfg.n_embd) have_embed = true;
}
if (have_embed) {
const Tensor& x = ctx.tensors[input_embed_key];
if (max_new_tokens > 0 && tok_) {
GenConfig g = gen;
g.max_new_tokens = max_new_tokens;
GenOutStats st;
std::vector<int> generated = generate_from_embedding(*p_, *tok_, x, g, &st);
history_.insert(history_.end(), generated.begin(), generated.end());
Tensor logits;
forward_embed_last(*p_, x, logits); // логиты исходного входа — для наблюдателей
ctx.tensors[output_logits_key] = logits;
ctx.text[output_text_key] = tok_->decode(generated, /*skip_bos=*/false);
ctx.state[output_tokens_state_key] = (double)generated.size();
ctx.state["output.last_token"] = generated.empty() ? -1 : generated.back();
return true;
}
Tensor logits;
forward_embed_last(*p_, x, logits);
backend()->materialize(logits);
ctx.tensors[output_logits_key] = logits;
// argmax в состояние
int best = 0;
float bv = logits.at(0);
for (int j = 1; j < logits.C(); ++j)
if (logits.at(j) > bv) { bv = logits.at(j); best = j; }
ctx.state["output.argmax"] = best;
ctx.state["output.logit"] = bv;
return true;
}
// --- токенный вход ---
if (ctx.tokens.empty()) {
ctx.state[output_tokens_state_key] = 0;
return true; // нечего обрабатывать — не ошибка
}
if (max_new_tokens > 0 && tok_) {
if (!use_ctx_history) history_.clear();
history_.insert(history_.end(), ctx.tokens.begin(), ctx.tokens.end());
GenConfig g = gen;
g.max_new_tokens = max_new_tokens;
g.stream = false;
GenOutStats st;
generate_from(*p_, *tok_, history_, g, &st);
history_.insert(history_.end(), st.tokens.begin(), st.tokens.end());
ctx.text[output_text_key] = tok_->decode(st.tokens, /*skip_bos=*/true);
ctx.state[output_tokens_state_key] = (double)st.tokens.size();
ctx.state["output.last_token"] = st.tokens.empty() ? -1 : st.tokens.back();
return true;
}
// одиночный прямой проход: логиты последнего положения
Tensor logits;
forward_last(*p_, ctx.tokens.data(), (int)ctx.tokens.size(), logits);
backend()->materialize(logits);
ctx.tensors[output_logits_key] = logits;
int best = 0;
float bv = logits.at(0);
for (int j = 1; j < logits.C(); ++j)
if (logits.at(j) > bv) { bv = logits.at(j); best = j; }
ctx.state["output.argmax"] = best;
ctx.state["output.logit"] = bv;
return true;
}
// ===========================================================================
// MoE
// ===========================================================================
void MoEParams::init(int d_, int ffn, int n_experts, int top_k_, uint64_t seed) {
Rng rng(seed);
top_k = std::max(1, std::min(top_k_, std::max(1, n_experts)));
gate.resize(d_, n_experts);
for (auto& v : gate.d) v = rng.normal() * 0.02f;
w1.assign(n_experts, Tensor(d_, ffn));
w2.assign(n_experts, Tensor(ffn, d_));
w3.assign(n_experts, Tensor(d_, ffn));
const float s = 0.02f;
for (int e = 0; e < n_experts; ++e) {
for (auto& v : w1[e].d) v = rng.normal() * s;
for (auto& v : w2[e].d) v = rng.normal() * s;
for (auto& v : w3[e].d) v = rng.normal() * s;
}
}
MoEAgent::MoEAgent(std::string name, MoEParams params,
std::string in_key, std::string out_key)
: name_(std::move(name)), in_key_(std::move(in_key)),
out_key_(std::move(out_key)), p_(std::move(params)) {}
bool MoEAgent::process(AgentContext& ctx) {
if (!ctx.has(in_key_)) return true; // нет входа — молча пропускаем
const Tensor& xin = ctx.tensors[in_key_];
const int64_t B = xin.R(), d = xin.C();
const int E = (int)p_.n_experts();
if (B <= 0 || d != p_.d() || E <= 0) {
ctx.tensors[out_key_] = Tensor((int)B, (int)d);
return true;
}
// gate-логиты [B][E]
Tensor gates;
gemm_nn(xin, p_.gate, gates);
backend()->materialize(gates);
Tensor y((int)B, (int)d);
y.zero();
const int ffn = p_.w1[0].C();
std::vector<float> h1((size_t)ffn), h3((size_t)ffn), ha((size_t)ffn), fo((size_t)d);
parallel_for((int)B, [&](int a, int b) {
std::vector<float> lh1((size_t)ffn), lh3((size_t)ffn), lha((size_t)ffn), lfo((size_t)d);
std::vector<int> order((size_t)E);
for (int row = a; row < b; ++row) {
const float* g = gates.row(row);
// top-k по логитам, затем softmax по выбранным (ренормировка, Mixtral-style)
std::iota(order.begin(), order.end(), 0);
std::partial_sort(order.begin(),
order.begin() + std::min<int>(p_.top_k, E),
order.end(),
[g](int i, int j) { return g[i] > g[j]; });
const int K = std::min<int>(p_.top_k, E);
float mx = -1e30f;
for (int t = 0; t < K; ++t) mx = std::max(mx, g[order[t]]);
float wsum = 0.f;
std::vector<float> w((size_t)K);
for (int t = 0; t < K; ++t) { w[t] = std::exp(g[order[t]] - mx); wsum += w[t]; }
if (wsum <= 0.f) wsum = 1.f;
const float* x = xin.row(row);
float* yrow = y.row(row);
for (int t = 0; t < K; ++t) {
const int e = order[t];
const float we = w[t] / wsum;
// h1 = x·w1[e], h3 = x·w3[e] (gemv на хосте)
const Tensor& W1 = p_.w1[e];
const Tensor& W3 = p_.w3[e];
const Tensor& W2 = p_.w2[e];
for (int j = 0; j < ffn; ++j) {
float s1 = 0.f, s3 = 0.f;
const float* c1 = W1.ptr() + (size_t)j; // w1[in][out]: столбец j с шагом ffn
const float* c3 = W3.ptr() + (size_t)j;
for (int64_t i = 0; i < d; ++i) {
s1 += x[i] * c1[(size_t)i * (size_t)ffn];
s3 += x[i] * c3[(size_t)i * (size_t)ffn];
}
lh1[j] = s1; lh3[j] = s3;
}
for (int j = 0; j < ffn; ++j)
lha[j] = silu(lh1[j]) * lh3[j];
// fo = ha·w2[e]; w2[e]: [ffn строк][d колонок] → fo[j] = Σ_f ha[f]·w2[f][j]
for (int64_t j = 0; j < d; ++j) {
float s = 0.f;
const float* col = W2.ptr() + (size_t)j;
for (int f = 0; f < ffn; ++f) s += lha[f] * col[(size_t)f * (size_t)d];
yrow[j] += we * s;
}
}
}
});
(void)h1; (void)h3; (void)ha; (void)fo;
ctx.tensors[out_key_] = std::move(y);
ctx.state["moe.experts"] = (double)E;
ctx.state["moe.top_k"] = (double)p_.top_k;
return true;
}
// ===========================================================================
// (6) AgentEngine
// ===========================================================================
void AgentEngine::add_agent(std::shared_ptr<IAgent> a) {
if (!a) return;
agents_.push_back(std::move(a));
names_synced_ = false;
}
void AgentEngine::set_scheduler(std::shared_ptr<IScheduler> s) {
sched_ = std::move(s);
names_synced_ = false;
}
IAgent* AgentEngine::find(const std::string& name) const {
for (const auto& a : agents_)
if (a && a->name() == name) return a.get();
return nullptr;
}
bool AgentEngine::run(AgentContext& ctx, std::string& err) {
if (!sched_) sched_ = std::make_shared<SequentialScheduler>();
if (!names_synced_) {
std::vector<std::string> names;
names.reserve(agents_.size());
for (const auto& a : agents_) names.push_back(a ? a->name() : std::string());
sched_->set_agent_names(std::move(names));
names_synced_ = true;
}
ctx.iterations = 0;
for (;;) {
ctx.rerun = false;
const std::vector<size_t> plan = sched_->plan(ctx, agents_.size());
for (size_t idx : plan) {
if (idx >= agents_.size() || !agents_[idx]) continue;
if (!agents_[idx]->process(ctx)) {
err = "агент '" + agents_[idx]->name() + "' завершился с ошибкой";
ctx.stop = true;
break;
}
if (ctx.stop) break;
}
++ctx.iterations;
++ctx.tick;
if (ctx.stop) break;
if (!ctx.rerun) break;
if (ctx.iterations >= max_iterations) {
char b[128];
snprintf(b, sizeof b,
"engine: достигнут предел итераций (%d) при взведённом rerun",
max_iterations);
engine_warn(b);
break;
}
}
return !ctx.stop;
}
} // namespace xt