Files
Xenith/tools/agent_test.cpp
T
2026-10-29 20:48:09 +07:00

273 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_test.cpp — проверки агентного движка (пункты 1–7) и мультимодальности.
// Запуск: cmake --build build --target agent_test && ./build/agent_test
#include "xenith/core/agent.h"
#include "xenith/core/multimodal.h"
#include "xenith/core/model.h"
#include <cmath>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <vector>
using namespace xt;
static int g_fail = 0;
#define CHECK(cond, ...) do { if (!(cond)) { printf(" FAIL: "); printf(__VA_ARGS__); printf("\n"); ++g_fail; } } while (0)
static Checkpoint make_small_model() {
Checkpoint ck;
ck.params.cfg.vocab_size = 64;
ck.params.cfg.n_layer = 2;
ck.params.cfg.n_head = 2;
ck.params.cfg.n_embd = 32;
ck.params.cfg.block_size = 64;
ck.params.cfg.n_vocab_out = 0;
ck.params.init(42);
ck.tok.id2tok.assign(64, "x");
ck.tok.id2tok[0] = "<unk>"; ck.tok.id2tok[1] = "<bos>"; ck.tok.id2tok[2] = "<eos>";
ck.tok.id2tok[3] = "<user>"; ck.tok.id2tok[4] = "<assistant>"; ck.tok.id2tok[5] = "\n";
return ck;
}
// (4) forward из тензора == forward из токенов
static void test_forward_embed() {
printf("[1] forward_embed == forward (логиты из эмбеддингов)\n");
Checkpoint ck = make_small_model();
const int d = ck.params.cfg.n_embd;
std::vector<int> tokens = {1, 7, 13, 21, 5};
Tensor lg_tok, lg_emb;
forward_last(ck.params, tokens.data(), (int)tokens.size(), lg_tok);
Tensor x((int)tokens.size(), d);
for (size_t i = 0; i < tokens.size(); ++i)
std::memcpy(x.row((int)i), ck.params.wte.row(tokens[i]), (size_t)d * sizeof(float));
forward_embed_last(ck.params, x, lg_emb);
CHECK(lg_tok.C() == lg_emb.C(), "размер логитов");
float maxd = 0;
for (int j = 0; j < lg_tok.C(); ++j)
maxd = std::max(maxd, std::fabs(lg_tok.at(j) - lg_emb.at(j)));
CHECK(maxd < 1e-4f, "логиты совпадают (maxdiff=%.3e)", maxd);
printf(" maxdiff=%.3e\n", maxd);
}
// (1)(2)(3)(5)(6) агенты, контекст, роутер, engine tick
static void test_engine_router() {
printf("[2] Engine: сенсор -> мозг -> критик (rerun)\n");
auto ck = std::make_shared<Checkpoint>(make_small_model());
AgentEngine engine;
auto sensor = std::make_shared<LambdaAgent>("sensor", [](AgentContext& c) {
if (c.tokens.empty()) c.tokens = {1, 9, 17, 33}; // «сенсор» выдаёт токены один раз
c.state["sensor.fired"] = c.num("sensor.fired") + 1;
return true;
});
auto brain = std::make_shared<NeuralAgent>("brain", ck);
brain->max_new_tokens = 0; // одиночный проход: логиты + argmax
auto critic = std::make_shared<LambdaAgent>("critic", [](AgentContext& c) {
const double round = c.num("critic.round");
if (round < 1) { // первый ответ «недостаточно уверен» → повтор
c.state["critic.round"] = round + 1;
c.rerun = true;
}
return true;
});
engine.add_agent(sensor);
engine.add_agent(brain);
engine.add_agent(critic);
auto router = std::make_shared<RouterScheduler>();
router->add_rule("main", [](const AgentContext&) { return true; },
{"sensor", "brain", "critic"});
engine.set_scheduler(router);
engine.max_iterations = 4;
AgentContext ctx;
std::string err;
const bool ok = engine.run(ctx, err);
CHECK(ok, "engine.run: %s", err.c_str());
CHECK(ctx.iterations == 2, "итераций %d (ожидалось 2: rerun критика)", ctx.iterations);
CHECK(ctx.num("sensor.fired") == 2, "сенсор вызван %d раз", (int)ctx.num("sensor.fired"));
CHECK(ctx.has("logits"), "логиты в контексте");
CHECK(ctx.tensors["logits"].C() == ck->params.cfg.vocab_out(), "форма логитов");
CHECK(ctx.state.count("output.argmax"), "argmax в состоянии");
printf(" iterations=%d argmax=%d logit=%.3f\n",
ctx.iterations, (int)ctx.num("output.argmax"), ctx.num("output.logit"));
// (3) роутер с exclusive-правилом по условию
AgentEngine e2;
e2.add_agent(std::make_shared<LambdaAgent>("a1", [](AgentContext& c){ c.state["a1"]=1; return true; }));
e2.add_agent(std::make_shared<LambdaAgent>("a2", [](AgentContext& c){ c.state["a2"]=1; return true; }));
auto r2 = std::make_shared<RouterScheduler>();
r2->add_rule("only-a2", [](const AgentContext& c) { return c.num("mode") == 2; }, {"a2"}, false, true);
r2->add_rule("all", [](const AgentContext&) { return true; }, {"a1", "a2"});
e2.set_scheduler(r2);
AgentContext c2; c2.state["mode"] = 2;
std::string e2err;
e2.run(c2, e2err);
CHECK(c2.state.count("a2") && !c2.state.count("a1"), "exclusive-правило отработало");
}
// (5)+(7) NeuralAgent с мультимодальным входом и генерацией
static void test_neural_embed_generation() {
printf("[3] NeuralAgent: эмбеддинг-вход + авторегрессия\n");
auto ck = std::make_shared<Checkpoint>(make_small_model());
const int d = ck->params.cfg.n_embd;
// «изображение» → патчи → проектор → эмбеддинги модели
mm::Image img; img.w = 8; img.h = 8; img.c = 1;
img.px.assign(64, 0.5f);
Tensor patches = mm::image_to_patches(img, 4); // [4][16]
CHECK(patches.R() == 4 && patches.C() == 16, "патчи 4x16");
mm::Projector pr; pr.init(16, d, 5);
Tensor emb; pr.apply(patches, emb); // [4][d]
CHECK(emb.R() == 4 && emb.C() == d, "проекция в d");
AgentEngine engine;
auto agent = std::make_shared<NeuralAgent>("mm-brain", ck);
agent->max_new_tokens = 3;
agent->gen.temperature = 0; // жадно
engine.add_agent(agent);
AgentContext ctx;
ctx.tensors["input.embedding"] = emb;
std::string err;
CHECK(engine.run(ctx, err), "run: %s", err.c_str());
CHECK(ctx.num("output.tokens") >= 1 && ctx.num("output.tokens") <= 3,
"сгенерировано токенов: %d", (int)ctx.num("output.tokens"));
CHECK(agent->history().size() >= (size_t)ctx.num("output.tokens"), "история агента растёт");
printf(" сгенерировано токенов: %d, история: %zu\n",
(int)ctx.num("output.tokens"), agent->history().size());
}
// MoE-эксперты: форма, детерминизм, ручной контроль одного эксперта
static void test_moe() {
printf("[4] MoEAgent: top-k роутинг\n");
const int d = 16, ffn = 24, E = 4;
MoEParams mp;
mp.init(d, ffn, E, /*top_k=*/2, 31337);
MoEAgent moe("moe", mp, "in", "out");
AgentContext ctx;
Rng rng(5);
Tensor x(3, d);
for (size_t i = 0; i < x.n(); ++i) x.at((int)i) = rng.normal() * 0.5f;
ctx.tensors["in"] = x;
CHECK(moe.process(ctx), "process");
CHECK(ctx.tensors["out"].R() == 3 && ctx.tensors["out"].C() == d, "форма выхода");
// детерминизм
AgentContext ctx2; ctx2.tensors["in"] = x;
moe.process(ctx2);
bool same = true;
for (size_t i = 0; i < ctx2.tensors["out"].n(); ++i)
if (ctx.tensors["out"].at((int)i) != ctx2.tensors["out"].at((int)i)) { same = false; break; }
CHECK(same, "детерминированный выход");
// ручной контроль: gate делает эксперта 0 единственным (top_k=1)
MoEParams mp1;
mp1.init(d, ffn, E, 1, 31337);
for (int i = 0; i < d; ++i)
for (int e = 0; e < E; ++e)
mp1.gate(i, e) = (e == 0) ? 10.0f : -10.0f;
MoEAgent moe1("moe1", mp1, "in", "out");
Tensor x1(1, d);
for (int i = 0; i < d; ++i) x1.at(i) = 0.3f * (i + 1);
AgentContext c1; c1.tensors["in"] = x1;
moe1.process(c1);
// ожидаемое: silu(x·w1[0]) * (x·w3[0]) · w2[0]
std::vector<float> want(d, 0.f);
for (int j = 0; j < ffn; ++j) {
float s1 = 0, s3 = 0;
for (int i = 0; i < d; ++i) {
s1 += x1.at(i) * mp1.w1[0](i, j);
s3 += x1.at(i) * mp1.w3[0](i, j);
}
const float ha = s1 / (1.f + std::exp(-s1)) * s3;
for (int o = 0; o < d; ++o) want[o] += ha * mp1.w2[0](j, o);
}
float maxd = 0;
for (int o = 0; o < d; ++o)
maxd = std::max(maxd, std::fabs(c1.tensors["out"].at(o) - want[o]));
CHECK(maxd < 1e-3f, "ручная сверка эксперта (maxdiff=%.2e)", maxd);
printf(" top-1 эксперт: maxdiff=%.2e\n", maxd);
}
// (7) мультимодальные конвертеры
static void test_multimodal() {
printf("[5] multimodal: PPM/WAV/вектор\n");
namespace fs = std::filesystem;
const std::string tmp = fs::temp_directory_path().string();
// PPM P6 8x6
{
std::ofstream f(tmp + "/xt_test.ppm", std::ios::binary);
f << "P6\n8 6\n255\n";
for (int i = 0; i < 8 * 6 * 3; ++i) f.put((char)(uint8_t)(i * 7 % 256));
f.close();
mm::Image img; std::string err;
CHECK(mm::load_ppm(tmp + "/xt_test.ppm", img, err), "load_ppm: %s", err.c_str());
CHECK(img.w == 8 && img.h == 6 && img.c == 3, "ppm dims");
CHECK(std::fabs(img.px[0] - 0.0f) < 1e-6f, "px[0]=0");
CHECK(std::fabs(img.px[1] - 7.0f / 255.0f) < 1e-6f && std::fabs(img.px[3] - 21.0f / 255.0f) < 1e-6f, "px[1]=7/255, px[3]=21/255");
Tensor p = mm::image_to_patches(img, 2); // (6/2)*(8/2)=12 патчей, 2*2*3=12
CHECK(p.R() == 12 && p.C() == 12, "patches 12x12, got %dx%d", p.R(), p.C());
fs::remove(tmp + "/xt_test.ppm");
}
// WAV: синус 440 Гц, 8 кГц, 16 бит, 0.1 с
{
const int sr = 8000, n = 800;
std::vector<int16_t> pcm(n);
for (int i = 0; i < n; ++i)
pcm[i] = (int16_t)(20000 * std::sin(2 * 3.14159265 * 440 * i / sr));
std::ofstream f(tmp + "/xt_test.wav", std::ios::binary);
auto w16 = [&](uint16_t v){ f.put((char)(v & 0xFF)); f.put((char)(v >> 8)); };
auto w32 = [&](uint32_t v){ for (int k = 0; k < 4; ++k) f.put((char)((v >> (8*k)) & 0xFF)); };
f.write("RIFF", 4); w32(36 + n * 2); f.write("WAVE", 4);
f.write("fmt ", 4); w32(16); w16(1); w16(1); w32(sr); w32(sr * 2); w16(2); w16(16);
f.write("data", 4); w32(n * 2);
f.write((const char*)pcm.data(), n * 2);
f.close();
mm::Wav wav; std::string err;
CHECK(mm::load_wav(tmp + "/xt_test.wav", wav, err), "load_wav: %s", err.c_str());
CHECK(wav.sample_rate == sr && wav.channels == 1 && (int)wav.mono.size() == n, "wav dims");
float maxd = 0;
for (int i = 0; i < n; ++i)
maxd = std::max(maxd, std::fabs(wav.mono[i] - pcm[i] / 32768.0f));
CHECK(maxd < 1e-4f, "wav pcm точен (%.2e)", maxd);
Tensor mel = mm::wav_to_logmel(wav, 64, 32, 8);
const int frames = (n - 64) / 32 + 1;
CHECK(mel.R() == frames && mel.C() == 8, "logmel %dx8 (ожидалось %d)", mel.R(), frames);
bool finite = true;
for (size_t i = 0; i < mel.n(); ++i) if (!std::isfinite(mel.at((int)i))) { finite = false; break; }
CHECK(finite, "logmel конечен");
fs::remove(tmp + "/xt_test.wav");
}
// вектор + concat + проектор
{
std::vector<float> v = {1, 2, 3, 4, 5};
Tensor t = mm::vector_to_tensor(v.data(), 5);
float mean = 0;
for (int i = 0; i < 5; ++i) mean += t.at(i);
CHECK(std::fabs(mean) < 1e-5f, "нормировка: среднее ~ 0");
Tensor a(2, 3), b(1, 3);
a.at(0) = 1; b.at(0) = 9;
Tensor c = mm::concat_rows(a, b);
CHECK(c.R() == 3 && c.at(2 * 3) == 9.f, "concat_rows");
mm::Projector pr; pr.init(3, 5, 1);
Tensor y; pr.apply(c, y);
CHECK(y.R() == 3 && y.C() == 5, "projector");
}
}
int main() {
test_forward_embed();
test_engine_router();
test_neural_embed_generation();
test_moe();
test_multimodal();
if (g_fail) { printf("\nПРОВАЛЕНО: %d\n", g_fail); return 1; }
printf("\nВсе агентные проверки пройдены\n");
return 0;
}