Files
mguinhos a26d329521 Parametros seguem o bloco do editor (origin), nao a instancia remontada
O editor esquece o cache das arvores quando o usuario edita algo e monta
outra instancia para o mesmo bloco da tela. Como os pesos da tensor eram
achados pela instancia, cada remontagem comecava com pesos novos: no treino
da GAN a perda voltava ao formato do inicio de tempos em tempos.

Cada bloco da tela ganha um uid e as instancias levam esse uid em
TinyBlocks_Block.origin. tt_param acha o parametro pela origem (sem origem,
pela propria instancia) e a instancia nova herda os pesos; a velha, ao
morrer, nao leva os da nova. As medias moveis do batch norm passam a ser
parametros sem gradiente, para irem junto no "salve os parametros".

Testes: test-tensor ganha a heranca pela origem; os donos de mentira dos
testes viram blocos zerados (o param_key le owner->origin).
2026-10-27 00:47:18 -03:00

238 lines
12 KiB
C

/*
* tensor_test.c - testa a tinyblocks-tensor: valores das operacoes, o
* gradiente de cada uma conferido por diferenca finita, parametros, arquivo
* .tbt e os blocos (handle, texto do valor, entradas).
*/
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include "../libraries/tinyblocks-tensor/src/tensor_internal.h"
static int fails = 0;
#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0)
static TbTensor* mk(int nd, const int* shape, const float* v) {
TbTensor* t = tt_alloc(nd, shape);
for (size_t i = 0; i < t->n; i++) t->d[i] = v ? v[i] : tt_randn();
return t;
}
static bool close_to(const TbTensor* t, const float* v, float tol) {
for (size_t i = 0; i < t->n; i++) if (fabsf(t->d[i] - v[i]) > tol) return false;
return true;
}
/* -- Gradiente por diferenca finita ---------------------------------------
* f(entradas) -> tensor; perda = soma(f * R) com R aleatorio fixo. */
typedef TbTensor* (*Fn)(TbTensor** in, void* ud);
static double loss_of(Fn f, TbTensor** in, void* ud, TbTensor* R) {
tt_set_grad_enabled(false);
TbTensor* y = f(in, ud);
double s = 0;
for (size_t i = 0; i < y->n; i++) s += (double)y->d[i] * R->d[i];
tt_release(y);
tt_set_grad_enabled(true);
return s;
}
static bool gradcheck(const char* name, Fn f, TbTensor** in, int n, void* ud) {
for (int i = 0; i < n; i++) { in[i]->req = true; free(in[i]->g); in[i]->g = NULL; }
TbTensor* y = f(in, ud);
if (!y) { printf(" %s: %s\n", name, tt_last_error()); return false; }
TbTensor* R = tt_alloc_like(y);
for (size_t i = 0; i < R->n; i++) R->d[i] = tt_randn();
TbTensor* p = tt_mul(y, R);
TbTensor* L = tt_sum(p, -1, false);
tt_backward(L);
double worst = 0;
for (int k = 0; k < n; k++) {
TbTensor* x = in[k];
size_t step = x->n > 24 ? x->n / 24 : 1;
for (size_t i = 0; i < x->n; i += step) {
float keep = x->d[i];
const float eps = 1e-2f;
x->d[i] = keep + eps; double lp = loss_of(f, in, ud, R);
x->d[i] = keep - eps; double lm = loss_of(f, in, ud, R);
x->d[i] = keep;
double num = (lp - lm) / (2 * eps), an = x->g ? x->g[i] : 0;
double err = fabs(num - an) / fmax(1.0, fabs(num) + fabs(an));
if (err > worst) worst = err;
}
}
tt_release(L); tt_release(p); tt_release(R); tt_release(y);
bool ok = worst < 3e-2;
if (!ok) printf(" %s: erro relativo %.4f\n", name, worst);
return ok;
}
static TbTensor* f_add(TbTensor** in, void* ud) { (void)ud; return tt_add(in[0], in[1]); }
static TbTensor* f_sub(TbTensor** in, void* ud) { (void)ud; return tt_sub(in[0], in[1]); }
static TbTensor* f_mul(TbTensor** in, void* ud) { (void)ud; return tt_mul(in[0], in[1]); }
static TbTensor* f_div(TbTensor** in, void* ud) { (void)ud; return tt_div(in[0], in[1]); }
static TbTensor* f_mm(TbTensor** in, void* ud) { (void)ud; return tt_matmul(in[0], in[1]); }
static TbTensor* f_scale(TbTensor** in, void* ud){ (void)ud; return tt_scale(in[0], -1.5f); }
static TbTensor* f_pow(TbTensor** in, void* ud) { (void)ud; return tt_powk(in[0], 3.0f); }
static TbTensor* f_exp(TbTensor** in, void* ud) { (void)ud; return tt_unary(in[0], TT_EXP); }
static TbTensor* f_tr(TbTensor** in, void* ud) { (void)ud; return tt_transpose(in[0], 0, 2); }
static TbTensor* f_rs(TbTensor** in, void* ud) { (void)ud; return tt_reshape(in[0], 2, (int[]){ -1, 4 }); }
static TbTensor* f_sl(TbTensor** in, void* ud) { (void)ud; return tt_slice(in[0], 1, 1, 3); }
static TbTensor* f_cat(TbTensor** in, void* ud) { (void)ud; return tt_concat(in[0], in[1], 1); }
static TbTensor* f_sum1(TbTensor** in, void* ud) { (void)ud; return tt_sum(in[0], 1, true); }
static TbTensor* f_mean(TbTensor** in, void* ud) { (void)ud; return tt_mean(in[0], -1, false); }
static TbTensor* f_max(TbTensor** in, void* ud) { (void)ud; return tt_max(in[0], 2, false); }
static TbTensor* f_flip(TbTensor** in, void* ud) { (void)ud; return tt_flip(in[0], 2); }
static TbTensor* f_gat(TbTensor** in, void* ud) { return tt_gather(in[0], (TbTensor*)ud); }
int main(void) {
tt_seed(7);
tt_pool_start();
/* -- valores ---------------------------------------------------------- */
TbTensor* a = mk(2, (int[]){ 2, 3 }, (float[]){ 1, 2, 3, 4, 5, 6 });
TbTensor* b = mk(1, (int[]){ 3 }, (float[]){ 10, 20, 30 });
TbTensor* s = tt_add(a, b);
CHECK(s && s->nd == 2 && close_to(s, (float[]){ 11, 22, 33, 14, 25, 36 }, 1e-5f), "broadcasting: [2,3] + [3]");
TbTensor* at = tt_transpose(a, 0, 1);
TbTensor* m = tt_matmul(a, at);
tt_release(at);
CHECK(m && m->shape[0] == 2 && m->shape[1] == 2 && close_to(m, (float[]){ 14, 32, 32, 77 }, 1e-4f), "matmul a @ aT");
TbTensor* sm = tt_sum(a, 1, false);
CHECK(sm && sm->nd == 1 && close_to(sm, (float[]){ 6, 15 }, 1e-5f), "soma no eixo 2");
TbTensor* am = tt_argmax(a, 0);
CHECK(am && close_to(am, (float[]){ 2, 2, 2 }, 0), "argmax 1-based");
TbTensor* idx = mk(1, (int[]){ 3 }, (float[]){ 2, 1, 2 });
TbTensor* ga = tt_gather(a, idx);
CHECK(ga && ga->shape[0] == 3 && close_to(ga, (float[]){ 4, 5, 6, 1, 2, 3, 4, 5, 6 }, 0), "linhas (gather) 1-based");
TbTensor* we = tt_where_eq(b, 20);
CHECK(we && we->n == 1 && we->d[0] == 2, "posições onde vale");
TbTensor* cat = tt_concat(a, a, 0);
CHECK(cat && cat->shape[0] == 4 && cat->d[9] == 4, "concatene no eixo 1");
TbTensor* bad = tt_matmul(a, a);
CHECK(!bad && strstr(tt_last_error(), "colunas"), "matmul com formas erradas explica o erro");
tt_release(s); tt_release(m); tt_release(sm); tt_release(am); tt_release(ga); tt_release(we); tt_release(cat);
/* GEMM grande (paralelo) contra a conta direta */
{
int M = 67, K = 129, Nn = 83;
TbTensor* A = mk(2, (int[]){ M, K }, NULL);
TbTensor* B = mk(2, (int[]){ K, Nn }, NULL);
TbTensor* C = tt_matmul(A, B);
double worst = 0;
for (int i = 0; i < M; i++)
for (int j = 0; j < Nn; j++) {
double ref = 0;
for (int p = 0; p < K; p++) ref += (double)A->d[i * K + p] * B->d[p * Nn + j];
worst = fmax(worst, fabs(ref - C->d[i * Nn + j]));
}
CHECK(worst < 1e-3, "GEMM paralelo bate com a conta direta");
tt_release(A); tt_release(B); tt_release(C);
}
/* -- gradientes ------------------------------------------------------- */
{
TbTensor* x[2];
x[0] = mk(2, (int[]){ 3, 4 }, NULL); x[1] = mk(1, (int[]){ 4 }, NULL);
CHECK(gradcheck("add", f_add, x, 2, NULL), "gradiente: soma com broadcasting");
CHECK(gradcheck("sub", f_sub, x, 2, NULL), "gradiente: subtração");
CHECK(gradcheck("mul", f_mul, x, 2, NULL), "gradiente: produto elemento a elemento");
for (size_t i = 0; i < x[1]->n; i++) x[1]->d[i] = 1.5f + tt_randu();
CHECK(gradcheck("div", f_div, x, 2, NULL), "gradiente: divisão");
tt_release(x[0]); tt_release(x[1]);
x[0] = mk(3, (int[]){ 2, 3, 4 }, NULL); x[1] = mk(2, (int[]){ 4, 5 }, NULL);
CHECK(gradcheck("matmul", f_mm, x, 2, NULL), "gradiente: matmul com pesos compartilhados");
tt_release(x[1]);
x[1] = mk(3, (int[]){ 2, 4, 3 }, NULL);
CHECK(gradcheck("bmm", f_mm, x, 2, NULL), "gradiente: matmul em lote");
CHECK(gradcheck("scale", f_scale, x, 1, NULL), "gradiente: escala");
CHECK(gradcheck("pow", f_pow, x, 1, NULL), "gradiente: potência");
CHECK(gradcheck("exp", f_exp, x, 1, NULL), "gradiente: exp");
CHECK(gradcheck("transpose", f_tr, x, 1, NULL), "gradiente: transposição");
CHECK(gradcheck("reshape", f_rs, x, 1, NULL), "gradiente: reshape com -1");
CHECK(gradcheck("slice", f_sl, x, 1, NULL), "gradiente: fatia");
TbTensor* y2[2] = { x[0], mk(3, (int[]){ 2, 2, 4 }, NULL) };
CHECK(gradcheck("concat", f_cat, y2, 2, NULL), "gradiente: concatene");
tt_release(y2[1]);
CHECK(gradcheck("sum", f_sum1, x, 1, NULL), "gradiente: soma num eixo");
CHECK(gradcheck("mean", f_mean, x, 1, NULL), "gradiente: média de tudo");
CHECK(gradcheck("max", f_max, x, 1, NULL), "gradiente: máximo num eixo");
CHECK(gradcheck("flip", f_flip, x, 1, NULL), "gradiente: espelhar");
TbTensor* ix = mk(1, (int[]){ 3 }, (float[]){ 2, 2, 1 });
CHECK(gradcheck("gather", f_gat, x, 1, ix), "gradiente: linhas (soma onde repete)");
tt_release(ix); tt_release(x[0]); tt_release(x[1]);
}
/* -- parametros pela origem: a instancia remontada herda os pesos ------ */
{
static TinyBlocks_Block a, b2;
a.origin = b2.origin = 777;
TbTensor* pa = tt_param(&a, 0, 1, (int[]){ 3 }, TB_INIT_NORMAL, 1.0f);
pa->d[0] = 42;
TbTensor* pb = tt_param(&b2, 0, 1, (int[]){ 3 }, TB_INIT_NORMAL, 1.0f);
CHECK(pa == pb && pb->d[0] == 42, "bloco remontado (mesma origem) herda os parâmetros");
tt_params_release(&a); /* a velha morre: o parametro fica */
CHECK(tt_param_count() >= 1 && tt_param(&b2, 0, 1, (int[]){ 3 }, TB_INIT_ZEROS, 0)->d[0] == 42,
"a instância velha morrer não leva os parâmetros da nova");
tt_params_release(&b2);
}
/* -- parametros e arquivo --------------------------------------------- */
{
static TinyBlocks_Block owner_blk; /* zerado: so a identidade */
TinyBlocks_Block* owner = &owner_blk;
tt_set_param_group("g");
TbTensor* p = tt_param(owner, 0, 2, (int[]){ 2, 2 }, TB_INIT_ONES, 2.0f);
TbTensor* p2 = tt_param(owner, 0, 2, (int[]){ 2, 2 }, TB_INIT_ZEROS, 0);
CHECK(p && p == p2 && p->d[3] == 2.0f && p->param && !strcmp(tt_param_group(0), "g"), "parâmetro nasce uma vez por (dono, posição)");
CHECK(tt_params_save("/tmp/tb_tensor_test.tbt"), "salva os parâmetros");
p->d[0] = 99;
CHECK(tt_params_load("/tmp/tb_tensor_test.tbt") && p->d[0] == 2.0f, "carrega por cima");
tt_params_release(owner);
CHECK(tt_param_count() == 0, "dono destruído solta os parâmetros");
tt_params_load("/tmp/tb_tensor_test.tbt"); /* antes da camada nascer */
TbTensor* p3 = tt_param(owner, 0, 2, (int[]){ 2, 2 }, TB_INIT_ZEROS, 0);
CHECK(p3 && p3->d[0] == 2.0f, "carregado antes: o parâmetro novo nasce com os dados do arquivo");
tt_params_release(owner);
tt_params_reset();
}
/* -- blocos ----------------------------------------------------------- */
{
TinyBlocks* rt = NULL;
tinyblocks_init(&rt, NULL);
tb_library_register(rt, tb_tensor_get_library());
const TbTensorApi* api = tb_tensor_api(rt);
CHECK(api && api->version == TB_TENSOR_API_VERSION, "a library publica a tabela TbTensorApi");
TinyBlocks_Block* z = tb_block_create(rt, tb_type_block_find(rt, "Tensor.Zeros"));
TinyBlocks_Value sh = tb_value_text("3,32,32");
tb_block_set_default(z, 0, sh);
tb_value_free(&sh);
tb_block_eval(z, rt);
char txt[64];
tb_value_to_text(z->outputs[0], txt, sizeof(txt));
CHECK(!strcmp(txt, "tensor [3, 32, 32]"), "o valor aparece como \"tensor [3, 32, 32]\"");
TinyBlocks_Value first = z->outputs[0];
tb_block_eval(z, rt);
CHECK(z->outputs[0].as.block == first.as.block, "o produtor reaproveita o mesmo handle");
TinyBlocks_Block* add = tb_block_create(rt, tb_type_block_find(rt, "Tensor.Add"));
tb_block_connect(add, 0, z, 0);
TinyBlocks_Value lst = tb_value_text("[1, 2]");
tb_block_set_default(add, 1, lst);
tb_value_free(&lst);
tb_block_eval(add, rt);
CHECK(tinyblocks_last_error(rt)[0] && strstr(tinyblocks_last_error(rt), "não combinam"), "formas incompatíveis viram erro do bloco");
tinyblocks_clear_error(rt);
tinyblocks_deinit(&rt);
}
tt_release(a); tt_release(b); tt_release(idx);
tt_pool_stop();
if (fails) printf("\n%d FALHA(S)\n", fails);
else printf("\nTUDO OK\n");
return fails != 0;
}