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).
688 lines
32 KiB
C
688 lines
32 KiB
C
/*
|
|
* TinyBlocks - ai_blocks.c
|
|
* Blocos da tinyblocks-ai (categoria "IA"): camadas, ativacoes, perdas,
|
|
* otimizadores, algoritmo genetico, amostragem e o tokenizador BPE.
|
|
*
|
|
* Camadas com parametros: os parametros sao da INSTANCIA do bloco (A->param
|
|
* com o bloco como dono) e nascem na primeira avaliacao, com a forma da
|
|
* entrada. LSTM, atencao e SwiGLU sao montadas com as operacoes da
|
|
* tinyblocks-tensor (matmul, fatia, transposicao...), entao o gradiente
|
|
* delas sai do proprio grafo.
|
|
*/
|
|
#define _POSIX_C_SOURCE 200809L
|
|
#include <math.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#include "ai_internal.h"
|
|
|
|
/* userdata de toda camada: o handle (TbProducer) e buffers que nao treinam */
|
|
typedef struct { TbProducer p; TbTensor* buf[2]; } Layer;
|
|
|
|
static void layer_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
const TbTensorApi* api = tb_tensor_api(rt);
|
|
Layer* L = self->userdata;
|
|
if (!api || !L) return;
|
|
api->producer_free(self, rt);
|
|
api->params_release(self);
|
|
for (int i = 0; i < 2; i++) { api->release(L->buf[i]); L->buf[i] = NULL; }
|
|
}
|
|
|
|
/* == Ajudas =========================================================== */
|
|
#define FAIL(rt) tinyblocks_set_error((rt), "%s", A->last_error())
|
|
|
|
static void done(TinyBlocks_Block* self, TinyBlocks* rt, TbTensor* r) {
|
|
if (r) A->put(self, rt, r);
|
|
else FAIL(rt);
|
|
self->dirty = false;
|
|
}
|
|
|
|
static bool args(TinyBlocks_Block* self, TinyBlocks* rt, int n, TbTensor** t) {
|
|
if (!ai_begin(rt)) { self->dirty = false; return false; }
|
|
for (int i = 0; i < n; i++) {
|
|
t[i] = A->arg(self, rt, (uint32_t)i);
|
|
if (!t[i]) {
|
|
for (int k = 0; k < i; k++) A->release(t[k]);
|
|
FAIL(rt);
|
|
self->dirty = false;
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static void rel(TbTensor** t, int n) { for (int i = 0; i < n; i++) A->release(t[i]); }
|
|
|
|
static int in_int(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i, int def) {
|
|
return (int)tb_block_input_integer(self, rt, i, def);
|
|
}
|
|
|
|
/* Parametro `slot` deste bloco (emprestado) */
|
|
static TbTensor* P(TinyBlocks_Block* self, int slot, int nd, const int* shape, int init, float scale) {
|
|
return A->param(self, slot, nd, shape, init, scale);
|
|
}
|
|
|
|
/* Solta os temporarios de uma composicao (NULL-safe) */
|
|
#define DROP(...) do { TbTensor* d_[] = { __VA_ARGS__ }; for (size_t i_ = 0; i_ < sizeof(d_) / sizeof(d_[0]); i_++) A->release(d_[i_]); } while (0)
|
|
|
|
/* == Camadas ========================================================== */
|
|
static TbTensor* linear(TinyBlocks_Block* self, int slot, TbTensor* x, int out, bool bias) {
|
|
if (x->nd < 1) { A->set_error("camada linear precisa de um tensor com eixos"); return NULL; }
|
|
int in = x->shape[x->nd - 1];
|
|
TbTensor* W = P(self, slot, 2, (int[]){ in, out }, TB_INIT_UNIFORM, 1.f / sqrtf((float)in));
|
|
if (!W) return NULL;
|
|
TbTensor* y;
|
|
if (x->nd == 1) { /* vetor: vira [1, in] */
|
|
TbTensor* x2 = A->reshape(x, 2, (int[]){ 1, in });
|
|
y = x2 ? A->matmul(x2, W) : NULL;
|
|
A->release(x2);
|
|
} else y = A->matmul(x, W);
|
|
if (!y || !bias) return y;
|
|
TbTensor* b = P(self, slot + 1, 1, &out, TB_INIT_ZEROS, 0);
|
|
TbTensor* r = b ? A->add(y, b) : NULL;
|
|
A->release(y);
|
|
return r;
|
|
}
|
|
|
|
static void eval_linear(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
TbTensor* r = linear(self, 0, x, in_int(self, rt, 1, 10), true);
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
static void eval_conv(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
int O = in_int(self, rt, 1, 16), k = in_int(self, rt, 2, 3), s = in_int(self, rt, 3, 1), p = in_int(self, rt, 4, 1);
|
|
TbTensor* r = NULL;
|
|
if (x->nd != 4) A->set_error("convolução precisa de [lote, canais, altura, largura]");
|
|
else {
|
|
int C = x->shape[1];
|
|
TbTensor* W = P(self, 0, 4, (int[]){ O, C, k, k }, TB_INIT_UNIFORM, 1.f / sqrtf((float)(C * k * k)));
|
|
TbTensor* b = P(self, 1, 1, &O, TB_INIT_ZEROS, 0);
|
|
if (W && b) r = ai_conv2d(x, W, b, s, p);
|
|
}
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
static void eval_conv_t(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
int O = in_int(self, rt, 1, 16), k = in_int(self, rt, 2, 4), s = in_int(self, rt, 3, 2), p = in_int(self, rt, 4, 1);
|
|
TbTensor* r = NULL;
|
|
if (x->nd != 4) A->set_error("convolução transposta precisa de [lote, canais, altura, largura]");
|
|
else {
|
|
int C = x->shape[1];
|
|
TbTensor* W = P(self, 0, 4, (int[]){ C, O, k, k }, TB_INIT_UNIFORM, 1.f / sqrtf((float)(O * k * k)));
|
|
TbTensor* b = P(self, 1, 1, &O, TB_INIT_ZEROS, 0);
|
|
if (W && b) r = ai_conv_t2d(x, W, b, s, p);
|
|
}
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
static void eval_pool(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
int k = in_int(self, rt, 1, 2);
|
|
TbTensor* r = ai_maxpool(x, k, k);
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
static void eval_batchnorm(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
TbTensor* r = NULL;
|
|
if (x->nd < 2) A->set_error("batch norm precisa de [lote, canais, ...]");
|
|
else {
|
|
int C = x->shape[1];
|
|
TbTensor* g = P(self, 0, 1, &C, TB_INIT_ONES, 1);
|
|
TbTensor* b = P(self, 1, 1, &C, TB_INIT_ZEROS, 0);
|
|
/* medias moveis: parametros sem gradiente (os otimizadores pulam),
|
|
para irem junto no "salve os parametros" e sobreviverem quando o
|
|
editor remonta o bloco */
|
|
TbTensor* mean = P(self, 2, 1, &C, TB_INIT_ZEROS, 0);
|
|
TbTensor* var = P(self, 3, 1, &C, TB_INIT_ONES, 1);
|
|
if (mean) mean->req = false;
|
|
if (var) var->req = false;
|
|
if (g && b && mean && var) r = ai_batchnorm(x, g, b, mean, var, g_ai_train, 0.1f);
|
|
}
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
static void norm_any(TinyBlocks_Block* self, TinyBlocks* rt, bool rms) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
int D = x->nd ? x->shape[x->nd - 1] : 1;
|
|
TbTensor* g = P(self, 0, 1, &D, TB_INIT_ONES, 1);
|
|
TbTensor* b = rms ? NULL : P(self, 1, 1, &D, TB_INIT_ZEROS, 0);
|
|
TbTensor* r = g && (rms || b) ? ai_layernorm(x, g, b, rms) : NULL;
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
static void eval_layernorm(TinyBlocks_Block* self, TinyBlocks* rt) { norm_any(self, rt, false); }
|
|
static void eval_rmsnorm(TinyBlocks_Block* self, TinyBlocks* rt) { norm_any(self, rt, true); }
|
|
|
|
static void eval_embedding(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
int V = in_int(self, rt, 1, 256), D = in_int(self, rt, 2, 64);
|
|
TbTensor* W = P(self, 0, 2, (int[]){ V, D }, TB_INIT_NORMAL, 0.1f);
|
|
TbTensor* r = W ? ai_embedding(x, W) : NULL;
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
static void eval_dropout(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
TbTensor* r = ai_dropout(x, (float)tb_block_input_number(self, rt, 1, 0.1));
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
/* LSTM: x [B,T,F] -> [B,T,H]. Portas i, f, g, o em z = x_t Wx + h Wh + b */
|
|
static TbTensor* lstm(TinyBlocks_Block* self, TbTensor* x, int H) {
|
|
if (x->nd != 3) { A->set_error("LSTM precisa de [lote, tempo, características]"); return NULL; }
|
|
int B = x->shape[0], T = x->shape[1], F = x->shape[2];
|
|
float bound = 1.f / sqrtf((float)H);
|
|
TbTensor* Wx = P(self, 0, 2, (int[]){ F, 4 * H }, TB_INIT_UNIFORM, bound);
|
|
TbTensor* Wh = P(self, 1, 2, (int[]){ H, 4 * H }, TB_INIT_UNIFORM, bound);
|
|
TbTensor* bb = P(self, 2, 1, (int[]){ 4 * H }, TB_INIT_ZEROS, 0);
|
|
if (!Wx || !Wh || !bb) return NULL;
|
|
TbTensor* h = A->alloc(2, (int[]){ B, H });
|
|
TbTensor* c = A->alloc(2, (int[]){ B, H });
|
|
TbTensor* out = NULL;
|
|
for (int t = 0; t < T && h && c; t++) {
|
|
TbTensor* xs = A->slice(x, 1, t, t + 1);
|
|
TbTensor* xt = xs ? A->reshape(xs, 2, (int[]){ B, F }) : NULL;
|
|
TbTensor* a1 = xt ? A->matmul(xt, Wx) : NULL;
|
|
TbTensor* a2 = A->matmul(h, Wh);
|
|
TbTensor* s1 = a1 && a2 ? A->add(a1, a2) : NULL;
|
|
TbTensor* z = s1 ? A->add(s1, bb) : NULL;
|
|
TbTensor* zi = z ? A->slice(z, 1, 0, H) : NULL;
|
|
TbTensor* zf = z ? A->slice(z, 1, H, 2 * H) : NULL;
|
|
TbTensor* zg = z ? A->slice(z, 1, 2 * H, 3 * H) : NULL;
|
|
TbTensor* zo = z ? A->slice(z, 1, 3 * H, 4 * H) : NULL;
|
|
TbTensor* gi = zi ? ai_act(zi, AI_SIGMOID, 0) : NULL;
|
|
TbTensor* gf = zf ? ai_act(zf, AI_SIGMOID, 0) : NULL;
|
|
TbTensor* gg = zg ? ai_act(zg, AI_TANH, 0) : NULL;
|
|
TbTensor* go = zo ? ai_act(zo, AI_SIGMOID, 0) : NULL;
|
|
TbTensor* fc = gf ? A->mul(gf, c) : NULL;
|
|
TbTensor* ig = gi && gg ? A->mul(gi, gg) : NULL;
|
|
TbTensor* c2 = fc && ig ? A->add(fc, ig) : NULL;
|
|
TbTensor* tc = c2 ? ai_act(c2, AI_TANH, 0) : NULL;
|
|
TbTensor* h2 = go && tc ? A->mul(go, tc) : NULL;
|
|
TbTensor* hs = h2 ? A->reshape(h2, 3, (int[]){ B, 1, H }) : NULL;
|
|
TbTensor* o2 = hs ? (out ? A->concat(out, hs, 1) : (A->retain(hs), hs)) : NULL;
|
|
DROP(xs, xt, a1, a2, s1, z, zi, zf, zg, zo, gi, gf, gg, go, fc, ig, tc, hs, out, h, c);
|
|
out = o2; h = h2; c = c2;
|
|
if (!out) break;
|
|
}
|
|
if (!out) DROP(h, c);
|
|
else DROP(h, c);
|
|
return out;
|
|
}
|
|
|
|
static void eval_lstm(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
TbTensor* r = lstm(self, x, in_int(self, rt, 1, 32));
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
/* Atencao multi-cabeca: x [B,T,D] -> [B,T,D] */
|
|
static TbTensor* heads_split(TbTensor* t, int B, int T, int h, int dh) { /* [B,T,D] -> [B,h,T,dh] */
|
|
TbTensor* r = A->reshape(t, 4, (int[]){ B, T, h, dh });
|
|
TbTensor* s = r ? A->transpose(r, 1, 2) : NULL;
|
|
A->release(r);
|
|
return s;
|
|
}
|
|
|
|
static TbTensor* attention(TinyBlocks_Block* self, TbTensor* x, int heads, bool causal) {
|
|
if (x->nd != 3) { A->set_error("atenção precisa de [lote, tempo, dimensão]"); return NULL; }
|
|
int B = x->shape[0], T = x->shape[1], D = x->shape[2];
|
|
if (heads < 1 || D % heads) { A->set_error("a dimensão %d não divide por %d cabeças", D, heads); return NULL; }
|
|
int dh = D / heads;
|
|
TbTensor* q = linear(self, 0, x, D, false);
|
|
TbTensor* k = q ? linear(self, 2, x, D, false) : NULL;
|
|
TbTensor* v = k ? linear(self, 4, x, D, false) : NULL;
|
|
TbTensor* qh = v ? heads_split(q, B, T, heads, dh) : NULL;
|
|
TbTensor* kh = qh ? heads_split(k, B, T, heads, dh) : NULL;
|
|
TbTensor* vh = kh ? heads_split(v, B, T, heads, dh) : NULL;
|
|
TbTensor* kt = vh ? A->transpose(kh, 2, 3) : NULL;
|
|
TbTensor* sc = kt ? A->matmul(qh, kt) : NULL;
|
|
TbTensor* ss = sc ? A->scale(sc, 1.f / sqrtf((float)dh)) : NULL;
|
|
TbTensor* p = ss ? ai_softmax(ss, causal) : NULL;
|
|
TbTensor* oh = p ? A->matmul(p, vh) : NULL;
|
|
TbTensor* ot = oh ? A->transpose(oh, 1, 2) : NULL;
|
|
TbTensor* om = ot ? A->reshape(ot, 3, (int[]){ B, T, D }) : NULL;
|
|
TbTensor* r = om ? linear(self, 6, om, D, false) : NULL;
|
|
DROP(q, k, v, qh, kh, vh, kt, sc, ss, p, oh, ot, om);
|
|
return r;
|
|
}
|
|
|
|
static void eval_attention(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
TbTensor* r = attention(self, x, in_int(self, rt, 1, 4), tb_block_input_truthy(self, rt, 2));
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
/* SwiGLU: (SiLU(x W1) * (x W2)) W3, saida com a dimensao da entrada */
|
|
static void eval_swiglu(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
int Hd = in_int(self, rt, 1, 64), D = x->nd ? x->shape[x->nd - 1] : 1;
|
|
TbTensor* a = linear(self, 0, x, Hd, false);
|
|
TbTensor* b = a ? linear(self, 2, x, Hd, false) : NULL;
|
|
TbTensor* s = b ? ai_act(a, AI_SILU, 0) : NULL;
|
|
TbTensor* m = s ? A->mul(s, b) : NULL;
|
|
TbTensor* r = m ? linear(self, 4, m, D, false) : NULL;
|
|
DROP(a, b, s, m);
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
/* == Ativacoes ======================================================== */
|
|
#define ACT(name, kind) \
|
|
static void name(TinyBlocks_Block* self, TinyBlocks* rt) { \
|
|
TbTensor* x; \
|
|
if (!args(self, rt, 1, &x)) return; \
|
|
TbTensor* r = ai_act(x, kind, 0); \
|
|
rel(&x, 1); done(self, rt, r); }
|
|
ACT(eval_relu, AI_RELU)
|
|
ACT(eval_tanh, AI_TANH)
|
|
ACT(eval_sigmoid, AI_SIGMOID)
|
|
ACT(eval_gelu, AI_GELU)
|
|
ACT(eval_silu, AI_SILU)
|
|
|
|
static void eval_leaky(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
TbTensor* r = ai_act(x, AI_LEAKY, (float)tb_block_input_number(self, rt, 1, 0.2));
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
static void eval_softmax(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
TbTensor* r = ai_softmax(x, false);
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
/* == Perdas e medidas ================================================= */
|
|
#define LOSS(name, fn) \
|
|
static void name(TinyBlocks_Block* self, TinyBlocks* rt) { \
|
|
TbTensor* t[2]; \
|
|
if (!args(self, rt, 2, t)) return; \
|
|
TbTensor* r = fn(t[0], t[1]); \
|
|
rel(t, 2); done(self, rt, r); }
|
|
LOSS(eval_ce, ai_cross_entropy)
|
|
LOSS(eval_bce, ai_bce_logits)
|
|
LOSS(eval_mse, ai_mse)
|
|
|
|
static void eval_accuracy(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* t[2];
|
|
if (!args(self, rt, 2, t)) return;
|
|
int C = t[0]->nd ? t[0]->shape[t[0]->nd - 1] : 1;
|
|
size_t rows = C ? t[0]->n / (size_t)C : 0, hit = 0;
|
|
if (rows != t[1]->n) tinyblocks_set_error(rt, "acertos: %zu linhas e %zu classes", rows, t[1]->n);
|
|
else {
|
|
for (size_t r = 0; r < rows; r++) {
|
|
const float* v = t[0]->d + r * C;
|
|
int best = 0;
|
|
for (int j = 1; j < C; j++) if (v[j] > v[best]) best = j;
|
|
if (best + 1 == (int)lroundf(t[1]->d[r])) hit++;
|
|
}
|
|
tb_block_set_output(self, 0, tb_value_real(rows ? (double)hit / rows : 0));
|
|
}
|
|
rel(t, 2);
|
|
self->dirty = false;
|
|
}
|
|
|
|
/* == Treino =========================================================== */
|
|
static void eval_train_mode(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
if (ai_begin(rt)) { g_ai_train = true; A->set_grad_enabled(true); }
|
|
self->dirty = false;
|
|
}
|
|
|
|
static void eval_eval_mode(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
if (ai_begin(rt)) { g_ai_train = false; A->set_grad_enabled(false); }
|
|
self->dirty = false;
|
|
}
|
|
|
|
typedef struct { float* m; float* v; long t; } AdamState;
|
|
static void adam_free(void* p) { AdamState* s = p; free(s->m); free(s->v); free(s); }
|
|
|
|
static bool in_group(int i, const char* group) {
|
|
return !group[0] || strcmp(A->param_group(i), group) == 0;
|
|
}
|
|
|
|
static void eval_adam(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
if (!ai_begin(rt)) { self->dirty = false; return; }
|
|
const char* group = tb_block_input_text(self, rt, 0);
|
|
float lr = (float)tb_block_input_number(self, rt, 1, 0.001);
|
|
float b1 = (float)tb_block_input_number(self, rt, 2, 0.9), b2 = (float)tb_block_input_number(self, rt, 3, 0.999);
|
|
int n = 0;
|
|
for (int i = 0; i < A->param_count(); i++) {
|
|
TbTensor* p = A->param_at(i);
|
|
if (!in_group(i, group) || !p->g) continue;
|
|
AdamState* s = p->opt;
|
|
if (!s) {
|
|
s = calloc(1, sizeof(AdamState));
|
|
if (s) { s->m = calloc(p->n, sizeof(float)); s->v = calloc(p->n, sizeof(float)); }
|
|
if (!s || !s->m || !s->v) { if (s) adam_free(s); tinyblocks_set_error(rt, "sem memória"); break; }
|
|
p->opt = s; p->opt_free = adam_free;
|
|
}
|
|
s->t++;
|
|
float c1 = 1.f - powf(b1, (float)s->t), c2 = 1.f - powf(b2, (float)s->t);
|
|
for (size_t k = 0; k < p->n; k++) {
|
|
float g = p->g[k];
|
|
s->m[k] = b1 * s->m[k] + (1 - b1) * g;
|
|
s->v[k] = b2 * s->v[k] + (1 - b2) * g * g;
|
|
p->d[k] -= lr * (s->m[k] / c1) / (sqrtf(s->v[k] / c2) + 1e-8f);
|
|
}
|
|
n++;
|
|
}
|
|
if (!n && !tinyblocks_last_error(rt)[0])
|
|
tinyblocks_set_error(rt, "Adam: nenhum parâmetro com gradiente no grupo '%s' (faltou calcular os gradientes?)", group);
|
|
self->dirty = false;
|
|
}
|
|
|
|
static void sgd_free(void* p) { free(p); }
|
|
|
|
static void eval_sgd(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
if (!ai_begin(rt)) { self->dirty = false; return; }
|
|
const char* group = tb_block_input_text(self, rt, 0);
|
|
float lr = (float)tb_block_input_number(self, rt, 1, 0.01), mom = (float)tb_block_input_number(self, rt, 2, 0);
|
|
for (int i = 0; i < A->param_count(); i++) {
|
|
TbTensor* p = A->param_at(i);
|
|
if (!in_group(i, group) || !p->g) continue;
|
|
float* vel = p->opt;
|
|
if (mom > 0 && !vel) { vel = calloc(p->n, sizeof(float)); p->opt = vel; p->opt_free = sgd_free; }
|
|
for (size_t k = 0; k < p->n; k++) {
|
|
float step = p->g[k];
|
|
if (vel) { vel[k] = mom * vel[k] + step; step = vel[k]; }
|
|
p->d[k] -= lr * step;
|
|
}
|
|
}
|
|
self->dirty = false;
|
|
}
|
|
|
|
/* Espelha cada imagem do lote [B,C,H,W] com 50% de chance (sem gradiente) */
|
|
static void eval_rand_flip(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
TbTensor* r = NULL;
|
|
if (x->nd != 4) A->set_error("espelhe aleatoriamente precisa de [lote, canais, altura, largura]");
|
|
else if ((r = A->alloc_like(x))) {
|
|
int B = x->shape[0], W = x->shape[3];
|
|
size_t img = x->n / (size_t)(B ? B : 1), rows = img / (size_t)(W ? W : 1);
|
|
for (int b = 0; b < B; b++) {
|
|
bool f = A->randu() < 0.5f;
|
|
for (size_t y = 0; y < rows; y++) {
|
|
const float* s = x->d + b * img + y * W;
|
|
float* d = r->d + b * img + y * W;
|
|
for (int i = 0; i < W; i++) d[i] = f ? s[W - 1 - i] : s[i];
|
|
}
|
|
}
|
|
}
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
static void eval_onehot(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
int C = in_int(self, rt, 1, 10);
|
|
TbTensor* r = A->alloc(2, (int[]){ (int)x->n, C });
|
|
for (size_t i = 0; r && i < x->n; i++) {
|
|
int k = (int)lroundf(x->d[i]);
|
|
if (k >= 1 && k <= C) r->d[i * C + k - 1] = 1;
|
|
}
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
/* Amostra um simbolo (1..V) de cada linha de logits [.., V] */
|
|
static void eval_sample(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
float temp = (float)tb_block_input_number(self, rt, 1, 1.0);
|
|
int topk = in_int(self, rt, 2, 0);
|
|
int V = x->nd ? x->shape[x->nd - 1] : 1;
|
|
size_t rows = V ? x->n / (size_t)V : 0;
|
|
TbTensor* r = A->alloc(1, (int[]){ (int)rows });
|
|
float* p = malloc((size_t)V * sizeof(float));
|
|
for (size_t q = 0; r && p && q < rows; q++) {
|
|
const float* v = x->d + q * V;
|
|
float cut = -INFINITY;
|
|
if (topk > 0 && topk < V) { /* o k-esimo maior */
|
|
for (int j = 0; j < V; j++) p[j] = v[j];
|
|
for (int a = 0; a < topk; a++) {
|
|
int best = a;
|
|
for (int j = a + 1; j < V; j++) if (p[j] > p[best]) best = j;
|
|
float t = p[a]; p[a] = p[best]; p[best] = t;
|
|
}
|
|
cut = p[topk - 1];
|
|
}
|
|
int pick = 0;
|
|
if (temp <= 0) {
|
|
for (int j = 1; j < V; j++) if (v[j] > v[pick]) pick = j;
|
|
} else {
|
|
float mx = -INFINITY;
|
|
for (int j = 0; j < V; j++) if (v[j] >= cut && v[j] > mx) mx = v[j];
|
|
double s = 0;
|
|
for (int j = 0; j < V; j++) { p[j] = v[j] >= cut ? expf((v[j] - mx) / temp) : 0; s += p[j]; }
|
|
double u = A->randu() * s, acc = 0;
|
|
for (int j = 0; j < V; j++) { acc += p[j]; if (u < acc) { pick = j; break; } pick = j; }
|
|
}
|
|
r->d[q] = (float)(pick + 1);
|
|
}
|
|
free(p);
|
|
rel(&x, 1); done(self, rt, r);
|
|
}
|
|
|
|
/* == Algoritmo genetico ============================================== */
|
|
static void eval_ga_pop(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
if (!ai_begin(rt)) { self->dirty = false; return; }
|
|
int Pn = in_int(self, rt, 0, 20), Gn = in_int(self, rt, 1, 5);
|
|
TbTensor* r = A->alloc(2, (int[]){ Pn, Gn });
|
|
for (size_t i = 0; r && i < r->n; i++) r->d[i] = A->randu() * 2 - 1;
|
|
done(self, rt, r);
|
|
}
|
|
|
|
/* Torneio de 3: o de maior nota entre tres sorteados */
|
|
static int tournament(const TbTensor* fit) {
|
|
int n = (int)fit->n, best = (int)(A->randu() * n);
|
|
for (int k = 0; k < 2; k++) {
|
|
int c = (int)(A->randu() * n);
|
|
if (c >= n) c = n - 1;
|
|
if (fit->d[c] > fit->d[best]) best = c;
|
|
}
|
|
return best < n ? best : n - 1;
|
|
}
|
|
|
|
/* Elitismo (o melhor passa igual), cruzamento uniforme, mutacao normal */
|
|
static void eval_ga_next(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* t[2];
|
|
if (!args(self, rt, 2, t)) return;
|
|
float mut = (float)tb_block_input_number(self, rt, 2, 0.1);
|
|
TbTensor* pop = t[0]; TbTensor* fit = t[1];
|
|
TbTensor* r = NULL;
|
|
if (pop->nd != 2 || (int)fit->n != pop->shape[0]) A->set_error("nova geração: a população é [indivíduos, genes] e as notas uma por indivíduo");
|
|
else if ((r = A->alloc_like(pop))) {
|
|
int Pn = pop->shape[0], Gn = pop->shape[1], elite = 0;
|
|
for (int i = 1; i < Pn; i++) if (fit->d[i] > fit->d[elite]) elite = i;
|
|
memcpy(r->d, pop->d + (size_t)elite * Gn, (size_t)Gn * sizeof(float));
|
|
for (int i = 1; i < Pn; i++) {
|
|
const float* a = pop->d + (size_t)tournament(fit) * Gn;
|
|
const float* b = pop->d + (size_t)tournament(fit) * Gn;
|
|
float* c = r->d + (size_t)i * Gn;
|
|
for (int g = 0; g < Gn; g++) c[g] = (A->randu() < 0.5f ? a[g] : b[g]) + mut * A->randn();
|
|
}
|
|
}
|
|
rel(t, 2); done(self, rt, r);
|
|
}
|
|
|
|
static void eval_ga_best(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* t[2];
|
|
if (!args(self, rt, 2, t)) return;
|
|
TbTensor* r = NULL;
|
|
if (t[0]->nd != 2 || (int)t[1]->n != t[0]->shape[0]) A->set_error("melhor: a população é [indivíduos, genes] e as notas uma por indivíduo");
|
|
else {
|
|
int best = 0, Gn = t[0]->shape[1];
|
|
for (size_t i = 1; i < t[1]->n; i++) if (t[1]->d[i] > t[1]->d[best]) best = (int)i;
|
|
if ((r = A->alloc(1, &Gn))) memcpy(r->d, t[0]->d + (size_t)best * Gn, (size_t)Gn * sizeof(float));
|
|
}
|
|
rel(t, 2); done(self, rt, r);
|
|
}
|
|
|
|
/* == BPE ============================================================== */
|
|
static void eval_bpe_train(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
if (ai_begin(rt) && !ai_bpe_train(tb_block_input_text(self, rt, 0), in_int(self, rt, 1, 100))) FAIL(rt);
|
|
self->dirty = false;
|
|
}
|
|
|
|
static void eval_bpe_encode(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
if (!ai_begin(rt)) { self->dirty = false; return; }
|
|
int n = 0;
|
|
int* ids = ai_bpe_encode(tb_block_input_text(self, rt, 0), &n);
|
|
TbTensor* r = ids ? A->alloc(1, &n) : NULL;
|
|
for (int i = 0; r && i < n; i++) r->d[i] = (float)ids[i];
|
|
free(ids);
|
|
done(self, rt, r);
|
|
}
|
|
|
|
static void eval_bpe_decode(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
TbTensor* x;
|
|
if (!args(self, rt, 1, &x)) return;
|
|
int* ids = malloc(x->n * sizeof(int) + 1);
|
|
for (size_t i = 0; ids && i < x->n; i++) ids[i] = (int)lroundf(x->d[i]);
|
|
char* s = ids ? ai_bpe_decode(ids, (int)x->n) : NULL;
|
|
tb_block_set_output(self, 0, tb_value_text(s ? s : ""));
|
|
free(s); free(ids);
|
|
rel(&x, 1);
|
|
self->dirty = false;
|
|
}
|
|
|
|
static void eval_bpe_vocab(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
(void)rt;
|
|
tb_block_set_output(self, 0, tb_value_integer(ai_bpe_vocab()));
|
|
self->dirty = false;
|
|
}
|
|
|
|
static void eval_bpe_save(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
if (ai_begin(rt) && !ai_bpe_save(tb_block_input_text(self, rt, 0))) FAIL(rt);
|
|
self->dirty = false;
|
|
}
|
|
|
|
static void eval_bpe_load(TinyBlocks_Block* self, TinyBlocks* rt) {
|
|
if (ai_begin(rt) && !ai_bpe_load(tb_block_input_text(self, rt, 0))) FAIL(rt);
|
|
self->dirty = false;
|
|
}
|
|
|
|
/* == Registro ========================================================= */
|
|
typedef struct {
|
|
const char* name;
|
|
const char* label;
|
|
const char* defs;
|
|
int nin;
|
|
TinyBlocks_ValueKind in[5];
|
|
uint32_t bool_in; /* bits: entradas hexagonais */
|
|
int out; /* 0 comando, 1 tensor, 2 numero, 3 texto */
|
|
void (*fn)(TinyBlocks_Block*, TinyBlocks*);
|
|
const char* fname;
|
|
const char* doc;
|
|
} Spec;
|
|
|
|
#define N TB_VALUE_NONE
|
|
#define R TB_VALUE_REAL
|
|
#define I TB_VALUE_INTEGER
|
|
#define T TB_VALUE_TEXT
|
|
#define S(fn) fn, #fn
|
|
|
|
static const Spec s_specs[] = {
|
|
/* camadas */
|
|
{ "AI.Linear", "camada linear de %1 com %2 saídas", "|10", 2, {N,I}, 0, 1, S(eval_linear), "x W + b (W [entradas, saídas]); os pesos nascem na primeira vez" },
|
|
{ "AI.Conv", "convolução de %1 com %2 filtros de tamanho %3 passo %4 margem %5", "|16|3|1|1", 5, {N,I,I,I,I}, 0, 1, S(eval_conv), "Convolução 2D de [lote, canais, A, L]" },
|
|
{ "AI.ConvT", "convolução transposta de %1 com %2 filtros de tamanho %3 passo %4 margem %5", "|16|4|2|1", 5, {N,I,I,I,I}, 0, 1, S(eval_conv_t), "Convolução transposta (aumenta a imagem): A' = (A-1) passo - 2 margem + filtro" },
|
|
{ "AI.MaxPool", "max pool de %1 com janela %2", "|2", 2, {N,I}, 0, 1, S(eval_pool), "Maior valor de cada janela (passo = janela)" },
|
|
{ "AI.BatchNorm", "batch norm de %1", "", 1, {N}, 0, 1, S(eval_batchnorm), "Normaliza cada canal pelo lote (médias móveis no modo de avaliação)" },
|
|
{ "AI.LayerNorm", "layer norm de %1", "", 1, {N}, 0, 1, S(eval_layernorm), "Normaliza o último eixo (ganho e deslocamento treináveis)" },
|
|
{ "AI.RMSNorm", "RMSNorm de %1", "", 1, {N}, 0, 1, S(eval_rmsnorm), "Divide o último eixo pela raiz da média dos quadrados (ganho treinável)" },
|
|
{ "AI.Embedding", "embedding de %1 com %2 símbolos e %3 dimensões", "|256|64", 3, {N,I,I}, 0, 1, S(eval_embedding), "Cada símbolo (1..V) vira um vetor treinável" },
|
|
{ "AI.Dropout", "dropout de %1 com chance %2", "|0.1", 2, {N,R}, 0, 1, S(eval_dropout), "Zera números ao acaso no modo de treino" },
|
|
{ "AI.LSTM", "LSTM de %1 com %2 unidades", "|32", 2, {N,I}, 0, 1, S(eval_lstm), "Rede recorrente: [lote, tempo, F] vira [lote, tempo, unidades]" },
|
|
{ "AI.Attention", "atenção de %1 com %2 cabeças causal %3", "|4|", 3, {N,I,I}, 4, 1, S(eval_attention), "Autoatenção multi-cabeça de [lote, tempo, dimensão]; causal = cada posição só vê as anteriores" },
|
|
{ "AI.SwiGLU", "SwiGLU de %1 com %2 ocultas", "|64", 2, {N,I}, 0, 1, S(eval_swiglu), "Camada de alimentação do transformer: (SiLU(x W1) * x W2) W3" },
|
|
/* ativacoes */
|
|
{ "AI.ReLU", "relu de %1", "", 1, {N}, 0, 1, S(eval_relu), "max(x, 0)" },
|
|
{ "AI.Leaky", "leaky relu de %1 com inclinação %2", "|0.2", 2, {N,R}, 0, 1, S(eval_leaky), "x se positivo, senão inclinação vezes x" },
|
|
{ "AI.Tanh", "tanh de %1", "", 1, {N}, 0, 1, S(eval_tanh), "Tangente hiperbólica (-1 a 1)" },
|
|
{ "AI.Sigmoid", "sigmoide de %1", "", 1, {N}, 0, 1, S(eval_sigmoid), "1 / (1 + e^-x) (0 a 1)" },
|
|
{ "AI.GELU", "GELU de %1", "", 1, {N}, 0, 1, S(eval_gelu), "Ativação dos transformers (aproximação por tanh)" },
|
|
{ "AI.SiLU", "SiLU de %1", "", 1, {N}, 0, 1, S(eval_silu), "x vezes sigmoide de x" },
|
|
{ "AI.Softmax", "softmax de %1", "", 1, {N}, 0, 1, S(eval_softmax), "Probabilidades no último eixo" },
|
|
/* perdas */
|
|
{ "AI.CrossEntropy", "entropia cruzada de %1 com as classes %2", "", 2, {N,N}, 0, 1, S(eval_ce), "Perda de classificação: logits [.., C] e classes 1..C" },
|
|
{ "AI.BCE", "BCE de %1 com alvo %2", "|1", 2, {N,N}, 0, 1, S(eval_bce), "Entropia cruzada binária com logits (alvo 0 ou 1)" },
|
|
{ "AI.MSE", "erro quadrático entre %1 e %2", "", 2, {N,N}, 0, 1, S(eval_mse), "Média de (a - b)^2" },
|
|
{ "AI.Accuracy", "acertos de %1 com as classes %2", "", 2, {N,N}, 0, 2, S(eval_accuracy), "Fração (0 a 1) das linhas cujo maior logit é a classe certa" },
|
|
/* treino */
|
|
{ "AI.TrainMode", "modo de treino", "", 0, {N}, 0, 0, S(eval_train_mode), "Dropout ligado, batch norm pelo lote, gradiente ligado" },
|
|
{ "AI.EvalMode", "modo de avaliação", "", 0, {N}, 0, 0, S(eval_eval_mode), "Dropout desligado, batch norm pelas médias, sem gradiente" },
|
|
{ "AI.Adam", "passo do Adam no grupo %1 com taxa %2 beta1 %3 beta2 %4", "modelo|0.001|0.9|0.999", 4, {T,R,R,R}, 0, 0, S(eval_adam), "Atualiza os parâmetros do grupo (vazio = todos) pelo gradiente" },
|
|
{ "AI.SGD", "passo do SGD no grupo %1 com taxa %2 e momento %3", "modelo|0.01|0.9", 3, {T,R,R}, 0, 0, S(eval_sgd), "Descida do gradiente (com momento)" },
|
|
{ "AI.RandFlip", "espelhe aleatoriamente %1", "", 1, {N}, 0, 1, S(eval_rand_flip), "Espelha cada imagem do lote com 50% de chance (aumento de dados)" },
|
|
{ "AI.OneHot", "um-quente de %1 com %2 classes", "|10", 2, {N,I}, 0, 1, S(eval_onehot), "Classes 1..C viram linhas [0 .. 1 .. 0]" },
|
|
{ "AI.Sample", "amostre de %1 com temperatura %2 e top %3", "|1|0", 3, {N,R,I}, 0, 1, S(eval_sample), "Sorteia um símbolo (1..V) de cada linha de logits; top 0 = todos, temperatura 0 = o maior" },
|
|
/* algoritmo genetico */
|
|
{ "AI.GaPop", "população de %1 indivíduos com %2 genes", "20|5", 2, {I,I}, 0, 1, S(eval_ga_pop), "Indivíduos [n, genes] com genes entre -1 e 1" },
|
|
{ "AI.GaNext", "nova geração de %1 com notas %2 e mutação %3", "||0.1", 3, {N,N,R}, 0, 1, S(eval_ga_next), "Elitismo, torneio, cruzamento uniforme e mutação normal (maior nota = melhor)" },
|
|
{ "AI.GaBest", "melhor de %1 com notas %2", "", 2, {N,N}, 0, 1, S(eval_ga_best), "Os genes do indivíduo de maior nota" },
|
|
/* BPE */
|
|
{ "AI.BpeTrain", "treine o BPE em %1 com %2 fusões", "|100", 2, {T,I}, 0, 0, S(eval_bpe_train), "Aprende o tokenizador: 256 bytes + uma fusão do par mais frequente por vez" },
|
|
{ "AI.BpeEncode", "tokens de %1", "", 1, {T}, 0, 1, S(eval_bpe_encode), "Texto vira símbolos (1..V)" },
|
|
{ "AI.BpeDecode", "texto dos tokens %1", "", 1, {N}, 0, 3, S(eval_bpe_decode), "Símbolos voltam a ser texto" },
|
|
{ "AI.BpeVocab", "tamanho do vocabulário", "", 0, {N}, 0, 2, S(eval_bpe_vocab), "256 + número de fusões" },
|
|
{ "AI.BpeSave", "salve o BPE em %1", "bpe.txt", 1, {T}, 0, 0, S(eval_bpe_save), "Grava as fusões" },
|
|
{ "AI.BpeLoad", "carregue o BPE de %1", "bpe.txt", 1, {T}, 0, 0, S(eval_bpe_load), "Lê as fusões" },
|
|
};
|
|
|
|
#undef N
|
|
#undef R
|
|
#undef I
|
|
#undef T
|
|
|
|
static bool ai_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
|
static const TinyBlocks_Category cat = { "IA", {0.93f, 0.36f, 0.62f, 1.f}, {0.76f, 0.24f, 0.48f, 1.f} };
|
|
tb_library_set_category(lib, &cat);
|
|
static const char* names[] = { "a", "b", "c", "d", "e" };
|
|
static const char* outs[] = { NULL, "tensor", "valor", "texto" };
|
|
static const TinyBlocks_ValueKind out_kind[] = { TB_VALUE_NONE, TB_VALUE_BLOCK, TB_VALUE_NONE, TB_VALUE_TEXT };
|
|
for (size_t i = 0; i < sizeof(s_specs) / sizeof(s_specs[0]); i++) {
|
|
const Spec* sp = &s_specs[i];
|
|
TinyBlocks_SlotDesc in[5], out[1];
|
|
for (int k = 0; k < sp->nin; k++) in[k] = (TinyBlocks_SlotDesc){ names[k], sp->in[k] };
|
|
out[0] = (TinyBlocks_SlotDesc){ outs[sp->out], out_kind[sp->out] };
|
|
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, sp->name, sp->nin ? in : NULL, (uint32_t)sp->nin,
|
|
sp->out ? out : NULL, sp->out ? 1u : 0u, sp->fn);
|
|
if (!t) return false;
|
|
tb_type_block_set_label(t, sp->label, sp->defs);
|
|
for (int k = 0; k < sp->nin; k++)
|
|
if (sp->bool_in & (1u << k)) tb_type_block_set_input_flags(t, (uint32_t)k, TB_SLOT_BOOLEAN);
|
|
if (sp->out == 1) tb_type_block_set_instance_hooks(t, sizeof(Layer), NULL, layer_deinit);
|
|
tb_meta_declare(sp->name, sp->fname, __FILE__, sp->doc);
|
|
if (!tb_library_add(lib, &t->base)) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
static void ai_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
|
(void)rt; (void)lib;
|
|
ai_bpe_reset();
|
|
}
|
|
|
|
TINYBLOCKS_DEFINE_LIBRARY(ai, "tinyblocks-ai", "1.0.0", ai_init, ai_deinit)
|
|
|
|
const TinyBlocks_LibraryDescriptor* tb_ai_get_library(void) {
|
|
return &_tb_lib_desc_ai;
|
|
}
|