tinyblocks-ai: redes neurais em blocos sobre a tinyblocks-tensor
Camadas com os parametros na instancia do bloco (nascem na primeira avaliacao, no grupo ativo): linear, convolucao e convolucao transposta (im2col + GEMM, lote dividido entre threads), max pool, batch norm, layer norm, RMSNorm, embedding, dropout, LSTM, atencao multi-cabeca (causal ou nao) e SwiGLU. Ativacoes relu, leaky relu, tanh, sigmoide, GELU, SiLU, softmax; perdas entropia cruzada, BCE com logits e erro quadratico; Adam e SGD por grupo; algoritmo genetico; tokenizador BPE por bytes; amostragem com temperatura e top-k. Usa so a tabela TbTensorApi (sem linkar com a tensor). test-ai confere o gradiente de cada operacao e camada (pesos inclusive) por diferenca finita, um treino com Adam, o BPE ida e volta e o algoritmo genetico. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
520cb10f08
commit
05fdb094ed
11 files changed
+1947
-2
No files matched your search
@@ -0,0 +1,33 @@
|
||||
# Makefile da library ai (categoria "IA")
|
||||
# Constroi build/libtinyblocks-ai.a e build/libtinyblocks-ai.so.
|
||||
# So inclui o header da tinyblocks-tensor: as chamadas passam pela tabela
|
||||
# TbTensorApi que ela publica (nada a linkar).
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -O3 -ffp-contract=fast -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude -I../tinyblocks-tensor/include
|
||||
|
||||
SRCS := src/ai_ops.c src/ai_conv.c src/ai_bpe.c src/ai_blocks.c
|
||||
OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS))
|
||||
HDRS := include/tb_ai.h src/ai_internal.h ../tinyblocks-tensor/include/tb_tensor.h
|
||||
LIB_A := $(BUILD)/libtinyblocks-ai.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-ai.so
|
||||
|
||||
.PHONY: all static shared clean
|
||||
all: static shared
|
||||
static: $(LIB_A)
|
||||
shared: $(LIB_SO)
|
||||
|
||||
$(BUILD)/%.o: src/%.c $(HDRS)
|
||||
@mkdir -p $(BUILD)
|
||||
$(CC) $(CFLAGS) -fPIC -c $< -o $@
|
||||
|
||||
$(LIB_A): $(OBJS)
|
||||
ar rcs $@ $^
|
||||
|
||||
$(LIB_SO): $(OBJS)
|
||||
$(CC) -shared -o $@ $^ -lm -lpthread
|
||||
|
||||
clean:
|
||||
$(RM) -r $(BUILD)
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* TinyBlocks - tb_ai.h
|
||||
* Library tinyblocks-ai: redes neurais em blocos, sobre a tinyblocks-tensor.
|
||||
* Registra a categoria "IA".
|
||||
*
|
||||
* camadas linear, convolucao, convolucao transposta, max pool,
|
||||
* batch norm, layer norm, RMSNorm, embedding, dropout, LSTM,
|
||||
* atencao multi-cabeca (com mascara causal), SwiGLU
|
||||
* ativacoes relu, leaky relu, tanh, sigmoide, GELU, SiLU, softmax
|
||||
* perdas entropia cruzada, BCE com logits, erro quadratico medio
|
||||
* otimizacao Adam e SGD (com momento) por grupo de parametros
|
||||
* evolucao algoritmo genetico (populacao, nova geracao, melhor)
|
||||
* texto tokenizador BPE (bytes + fusoes), amostragem de tokens
|
||||
*
|
||||
* Cada camada guarda os parametros na instancia do bloco: eles nascem na
|
||||
* primeira avaliacao, com a forma tirada da entrada (como as camadas
|
||||
* "lazy" do PyTorch), e entram no grupo de parametros ativo (bloco "use o
|
||||
* grupo de parametros" da tinyblocks-tensor).
|
||||
*
|
||||
* Nao linka com a tinyblocks-tensor: usa a tabela TbTensorApi que ela
|
||||
* publica (tb_tensor_api), achada a cada avaliacao.
|
||||
*/
|
||||
#ifndef TINYBLOCKS_AI_H
|
||||
#define TINYBLOCKS_AI_H
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_ai_get_library(void);
|
||||
|
||||
#endif /* TINYBLOCKS_AI_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library ai. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-ai"
|
||||
version = "1.0.0"
|
||||
category = "IA"
|
||||
description = "Redes neurais: camadas (linear, convolucao, LSTM, atencao...), ativacoes, perdas, Adam/SGD, algoritmo genetico e BPE"
|
||||
color = [237, 92, 158, 255]
|
||||
dark = [194, 61, 122, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/ai_ops.c", "src/ai_conv.c", "src/ai_bpe.c", "src/ai_blocks.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-ai.so"
|
||||
static = "build/libtinyblocks-ai.a"
|
||||
depends = ["tensor"]
|
||||
@@ -0,0 +1,687 @@
|
||||
/*
|
||||
* 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];
|
||||
Layer* L = self->userdata;
|
||||
if (!L->buf[0] || (int)L->buf[0]->n != C) { /* medias moveis (nao treinam) */
|
||||
A->release(L->buf[0]); A->release(L->buf[1]);
|
||||
L->buf[0] = A->alloc(1, &C);
|
||||
L->buf[1] = A->alloc(1, &C);
|
||||
for (int i = 0; L->buf[1] && i < C; i++) L->buf[1]->d[i] = 1;
|
||||
}
|
||||
TbTensor* g = P(self, 0, 1, &C, TB_INIT_ONES, 1);
|
||||
TbTensor* b = P(self, 1, 1, &C, TB_INIT_ZEROS, 0);
|
||||
if (g && b && L->buf[0] && L->buf[1]) r = ai_batchnorm(x, g, b, L->buf[0], L->buf[1], 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 %3 x %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 %3 x %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;
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* TinyBlocks - ai_bpe.c
|
||||
* Tokenizador BPE (byte pair encoding) por bytes: o vocabulario comeca com
|
||||
* os 256 bytes e cada fusao junta o par vizinho mais frequente num simbolo
|
||||
* novo (256, 257, ...). Codificar aplica as fusoes na ordem em que foram
|
||||
* aprendidas. Para quem usa os blocos, os simbolos vao de 1 a V.
|
||||
*
|
||||
* Um tokenizador por processo (o dos blocos "treine o BPE", "tokens de"...).
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ai_internal.h"
|
||||
|
||||
typedef struct { int a, b; } Merge;
|
||||
|
||||
static Merge* s_merges;
|
||||
static int s_merge_n;
|
||||
static char** s_tok; /* bytes de cada simbolo (para decodificar) */
|
||||
static int* s_tok_len;
|
||||
|
||||
void ai_bpe_reset(void) {
|
||||
for (int i = 0; i < 256 + s_merge_n && s_tok; i++) free(s_tok[i]);
|
||||
free(s_tok); free(s_tok_len); free(s_merges);
|
||||
s_tok = NULL; s_tok_len = NULL; s_merges = NULL; s_merge_n = 0;
|
||||
}
|
||||
|
||||
int ai_bpe_vocab(void) { return 256 + s_merge_n; }
|
||||
|
||||
/* Monta a tabela de bytes de cada simbolo a partir das fusoes */
|
||||
static bool build_tokens(void) {
|
||||
int V = 256 + s_merge_n;
|
||||
s_tok = calloc((size_t)V, sizeof(char*));
|
||||
s_tok_len = calloc((size_t)V, sizeof(int));
|
||||
if (!s_tok || !s_tok_len) return false;
|
||||
for (int i = 0; i < 256; i++) { s_tok[i] = malloc(1); s_tok[i][0] = (char)i; s_tok_len[i] = 1; }
|
||||
for (int m = 0; m < s_merge_n; m++) {
|
||||
int a = s_merges[m].a, b = s_merges[m].b, id = 256 + m;
|
||||
s_tok_len[id] = s_tok_len[a] + s_tok_len[b];
|
||||
s_tok[id] = malloc((size_t)s_tok_len[id]);
|
||||
if (!s_tok[id]) return false;
|
||||
memcpy(s_tok[id], s_tok[a], (size_t)s_tok_len[a]);
|
||||
memcpy(s_tok[id] + s_tok_len[a], s_tok[b], (size_t)s_tok_len[b]);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Troca toda ocorrencia do par (a, b) por id; devolve o tamanho novo */
|
||||
static int apply_merge(int* seq, int n, int a, int b, int id) {
|
||||
int w = 0;
|
||||
for (int r = 0; r < n; r++) {
|
||||
if (r + 1 < n && seq[r] == a && seq[r + 1] == b) { seq[w++] = id; r++; }
|
||||
else seq[w++] = seq[r];
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
/* Tabela de contagem de pares (enderecamento aberto) */
|
||||
typedef struct { uint64_t key; int count; } Slot;
|
||||
|
||||
static uint64_t pair_key(int a, int b) { return ((uint64_t)(uint32_t)a << 32) | (uint32_t)b; }
|
||||
|
||||
bool ai_bpe_train(const char* text, int merges) {
|
||||
ai_bpe_reset();
|
||||
int n = (int)strlen(text);
|
||||
int* seq = malloc((size_t)(n ? n : 1) * sizeof(int));
|
||||
s_merges = malloc((size_t)(merges > 0 ? merges : 1) * sizeof(Merge));
|
||||
if (!seq || !s_merges) { free(seq); A->set_error("sem memória"); return false; }
|
||||
for (int i = 0; i < n; i++) seq[i] = (unsigned char)text[i];
|
||||
size_t cap = 1;
|
||||
while (cap < (size_t)n * 2 + 16) cap <<= 1;
|
||||
Slot* tab = malloc(cap * sizeof(Slot));
|
||||
if (!tab) { free(seq); A->set_error("sem memória"); return false; }
|
||||
for (int m = 0; m < merges && n > 1; m++) {
|
||||
memset(tab, 0, cap * sizeof(Slot));
|
||||
uint64_t best = 0; int best_n = 1; /* so funde par que repete */
|
||||
for (int i = 0; i + 1 < n; i++) {
|
||||
uint64_t k = pair_key(seq[i], seq[i + 1]) + 1;
|
||||
size_t h = (size_t)((k * 0x9E3779B97F4A7C15ull) >> 20) & (cap - 1);
|
||||
while (tab[h].key && tab[h].key != k) h = (h + 1) & (cap - 1);
|
||||
tab[h].key = k;
|
||||
if (++tab[h].count > best_n || (tab[h].count == best_n && best && k < best)) {
|
||||
if (tab[h].count > best_n) best_n = tab[h].count;
|
||||
best = k;
|
||||
}
|
||||
}
|
||||
if (!best) break;
|
||||
best -= 1;
|
||||
int a = (int)(best >> 32), b = (int)(best & 0xffffffffu);
|
||||
s_merges[s_merge_n++] = (Merge){ a, b };
|
||||
n = apply_merge(seq, n, a, b, 256 + m);
|
||||
}
|
||||
free(tab);
|
||||
free(seq);
|
||||
return build_tokens();
|
||||
}
|
||||
|
||||
int* ai_bpe_encode(const char* text, int* out_n) {
|
||||
int n = (int)strlen(text);
|
||||
int* seq = malloc((size_t)(n ? n : 1) * sizeof(int));
|
||||
if (!seq) { *out_n = 0; return NULL; }
|
||||
for (int i = 0; i < n; i++) seq[i] = (unsigned char)text[i];
|
||||
for (int m = 0; m < s_merge_n && n > 1; m++) n = apply_merge(seq, n, s_merges[m].a, s_merges[m].b, 256 + m);
|
||||
for (int i = 0; i < n; i++) seq[i] += 1; /* 1..V para os blocos */
|
||||
*out_n = n;
|
||||
return seq;
|
||||
}
|
||||
|
||||
char* ai_bpe_decode(const int* ids, int n) {
|
||||
if (!s_tok && !build_tokens()) return NULL;
|
||||
int V = ai_bpe_vocab();
|
||||
size_t len = 0;
|
||||
for (int i = 0; i < n; i++) { int t = ids[i] - 1; if (t >= 0 && t < V) len += (size_t)s_tok_len[t]; }
|
||||
char* out = malloc(len + 1);
|
||||
if (!out) return NULL;
|
||||
size_t w = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
int t = ids[i] - 1;
|
||||
if (t < 0 || t >= V) continue;
|
||||
memcpy(out + w, s_tok[t], (size_t)s_tok_len[t]);
|
||||
w += (size_t)s_tok_len[t];
|
||||
}
|
||||
out[w] = 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Arquivo de texto: "TBBPE1", numero de fusoes e um par "a b" por linha */
|
||||
bool ai_bpe_save(const char* path) {
|
||||
FILE* f = fopen(path, "w");
|
||||
if (!f) { A->set_error("não abriu '%s' para gravar", path); return false; }
|
||||
fprintf(f, "TBBPE1\n%d\n", s_merge_n);
|
||||
for (int m = 0; m < s_merge_n; m++) fprintf(f, "%d %d\n", s_merges[m].a, s_merges[m].b);
|
||||
return fclose(f) == 0;
|
||||
}
|
||||
|
||||
bool ai_bpe_load(const char* path) {
|
||||
FILE* f = fopen(path, "r");
|
||||
if (!f) { A->set_error("não abriu '%s'", path); return false; }
|
||||
char magic[16] = "";
|
||||
int n = 0;
|
||||
if (fscanf(f, "%15s %d", magic, &n) != 2 || strcmp(magic, "TBBPE1") != 0 || n < 0 || n > 1 << 20) {
|
||||
fclose(f); A->set_error("'%s' não é um tokenizador BPE", path); return false;
|
||||
}
|
||||
ai_bpe_reset();
|
||||
s_merges = malloc((size_t)(n ? n : 1) * sizeof(Merge));
|
||||
if (!s_merges) { fclose(f); return false; }
|
||||
for (int m = 0; m < n; m++) {
|
||||
int a, b;
|
||||
if (fscanf(f, "%d %d", &a, &b) != 2 || a < 0 || b < 0 || a >= 256 + m || b >= 256 + m) {
|
||||
fclose(f); ai_bpe_reset(); A->set_error("'%s' está corrompido (fusão %d)", path, m + 1); return false;
|
||||
}
|
||||
s_merges[s_merge_n++] = (Merge){ a, b };
|
||||
}
|
||||
fclose(f);
|
||||
return build_tokens();
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
/*
|
||||
* TinyBlocks - ai_conv.c
|
||||
* Convolucao 2D, convolucao transposta e max pool, com gradiente.
|
||||
*
|
||||
* As duas convolucoes usam im2col: cada janela k x k da imagem vira uma
|
||||
* coluna, e a conta inteira vira um produto de matrizes (o GEMM da
|
||||
* tinyblocks-tensor). O lote e dividido entre as threads (uma imagem por
|
||||
* vez em cada fatia); o gradiente dos pesos e somado por fatia e juntado
|
||||
* no fim, com uma trava.
|
||||
*
|
||||
* conv2d: x [B,C,H,W], W [O,C,k,k], b [O] -> [B,O,Ho,Wo]
|
||||
* Ho = (H + 2p - k) / s + 1
|
||||
* conv_t2d: x [B,C,H,W], W [C,O,k,k], b [O] -> [B,O,Ho,Wo]
|
||||
* Ho = (H - 1) s - 2p + k (o adjunto da conv)
|
||||
*/
|
||||
#include <math.h>
|
||||
#include <pthread.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ai_internal.h"
|
||||
|
||||
static TbTensor* IN(TbTensor* out, int i) { return out->node.in[i]; }
|
||||
static float* G(TbTensor* t) { return t && t->req ? A->grad(t) : NULL; }
|
||||
|
||||
/* img [Cc, Hi, Wi] -> col [Cc*k*k, Ho*Wo] (janelas com passo s e margem p) */
|
||||
static void im2col(const float* img, int Cc, int Hi, int Wi, int k, int s, int p, int Ho, int Wo, float* col) {
|
||||
for (int c = 0; c < Cc; c++)
|
||||
for (int ky = 0; ky < k; ky++)
|
||||
for (int kx = 0; kx < k; kx++) {
|
||||
float* row = col + ((size_t)(c * k + ky) * k + kx) * Ho * Wo;
|
||||
for (int oy = 0; oy < Ho; oy++) {
|
||||
int iy = oy * s - p + ky;
|
||||
float* r = row + (size_t)oy * Wo;
|
||||
if (iy < 0 || iy >= Hi) { memset(r, 0, (size_t)Wo * sizeof(float)); continue; }
|
||||
const float* src = img + ((size_t)c * Hi + iy) * Wi;
|
||||
for (int ox = 0; ox < Wo; ox++) {
|
||||
int ix = ox * s - p + kx;
|
||||
r[ox] = ix >= 0 && ix < Wi ? src[ix] : 0.f;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* O caminho de volta: soma col nas posicoes da imagem */
|
||||
static void col2im(const float* col, int Cc, int Hi, int Wi, int k, int s, int p, int Ho, int Wo, float* img) {
|
||||
for (int c = 0; c < Cc; c++)
|
||||
for (int ky = 0; ky < k; ky++)
|
||||
for (int kx = 0; kx < k; kx++) {
|
||||
const float* row = col + ((size_t)(c * k + ky) * k + kx) * Ho * Wo;
|
||||
for (int oy = 0; oy < Ho; oy++) {
|
||||
int iy = oy * s - p + ky;
|
||||
if (iy < 0 || iy >= Hi) continue;
|
||||
float* dst = img + ((size_t)c * Hi + iy) * Wi;
|
||||
const float* r = row + (size_t)oy * Wo;
|
||||
for (int ox = 0; ox < Wo; ox++) {
|
||||
int ix = ox * s - p + kx;
|
||||
if (ix >= 0 && ix < Wi) dst[ix] += r[ox];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
bool transpose;
|
||||
int B, C, H, W, O, k, s, p, Ho, Wo;
|
||||
const float *x, *w, *bias;
|
||||
float* out;
|
||||
/* backward */
|
||||
const float* gout;
|
||||
float *gx, *gw, *gb;
|
||||
pthread_mutex_t mu;
|
||||
} Conv;
|
||||
|
||||
/* Uma fatia do lote, para a frente */
|
||||
static void conv_fwd(void* ctx, int from, int to) {
|
||||
Conv* c = ctx;
|
||||
int CKK = c->C * c->k * c->k, OKK = c->O * c->k * c->k;
|
||||
size_t in_sz = (size_t)c->C * c->H * c->W, out_sz = (size_t)c->O * c->Ho * c->Wo;
|
||||
size_t col_n = c->transpose ? (size_t)OKK * c->H * c->W : (size_t)CKK * c->Ho * c->Wo;
|
||||
float* col = malloc(col_n * sizeof(float));
|
||||
if (!col) return;
|
||||
for (int b = from; b < to; b++) {
|
||||
const float* xb = c->x + b * in_sz;
|
||||
float* ob = c->out + b * out_sz;
|
||||
if (!c->transpose) {
|
||||
im2col(xb, c->C, c->H, c->W, c->k, c->s, c->p, c->Ho, c->Wo, col);
|
||||
A->gemm(false, false, c->O, c->Ho * c->Wo, CKK, 1.f, c->w, CKK, col, c->Ho * c->Wo, 0.f, ob, c->Ho * c->Wo);
|
||||
} else {
|
||||
/* W [C, O*k*k]: col = W^T x_b, depois espalha na imagem de saida */
|
||||
A->gemm(true, false, OKK, c->H * c->W, c->C, 1.f, c->w, OKK, xb, c->H * c->W, 0.f, col, c->H * c->W);
|
||||
memset(ob, 0, out_sz * sizeof(float));
|
||||
col2im(col, c->O, c->Ho, c->Wo, c->k, c->s, c->p, c->H, c->W, ob);
|
||||
}
|
||||
if (c->bias)
|
||||
for (int o = 0; o < c->O; o++) {
|
||||
float bv = c->bias[o];
|
||||
float* r = ob + (size_t)o * c->Ho * c->Wo;
|
||||
for (int i = 0; i < c->Ho * c->Wo; i++) r[i] += bv;
|
||||
}
|
||||
}
|
||||
free(col);
|
||||
}
|
||||
|
||||
/* Uma fatia do lote, para tras: gx direto; gw e gb somados na fatia */
|
||||
static void conv_bwd(void* ctx, int from, int to) {
|
||||
Conv* c = ctx;
|
||||
int CKK = c->C * c->k * c->k, OKK = c->O * c->k * c->k;
|
||||
size_t in_sz = (size_t)c->C * c->H * c->W, out_sz = (size_t)c->O * c->Ho * c->Wo;
|
||||
size_t col_n = c->transpose ? (size_t)OKK * c->H * c->W : (size_t)CKK * c->Ho * c->Wo;
|
||||
size_t wn = (size_t)c->O * CKK;
|
||||
float* col = malloc(col_n * sizeof(float));
|
||||
float* dcol = malloc(col_n * sizeof(float));
|
||||
float* lw = c->gw ? calloc(wn, sizeof(float)) : NULL;
|
||||
float* lb = c->gb ? calloc((size_t)c->O, sizeof(float)) : NULL;
|
||||
if (!col || !dcol || (c->gw && !lw) || (c->gb && !lb)) { free(col); free(dcol); free(lw); free(lb); return; }
|
||||
for (int b = from; b < to; b++) {
|
||||
const float* xb = c->x + b * in_sz;
|
||||
const float* gb = c->gout + b * out_sz;
|
||||
if (lb)
|
||||
for (int o = 0; o < c->O; o++) {
|
||||
const float* r = gb + (size_t)o * c->Ho * c->Wo;
|
||||
double s = 0;
|
||||
for (int i = 0; i < c->Ho * c->Wo; i++) s += r[i];
|
||||
lb[o] += (float)s;
|
||||
}
|
||||
if (!c->transpose) {
|
||||
int HW = c->Ho * c->Wo;
|
||||
if (lw) {
|
||||
im2col(xb, c->C, c->H, c->W, c->k, c->s, c->p, c->Ho, c->Wo, col);
|
||||
A->gemm(false, true, c->O, CKK, HW, 1.f, gb, HW, col, HW, 1.f, lw, CKK);
|
||||
}
|
||||
if (c->gx) {
|
||||
A->gemm(true, false, CKK, HW, c->O, 1.f, c->w, CKK, gb, HW, 0.f, dcol, HW);
|
||||
col2im(dcol, c->C, c->H, c->W, c->k, c->s, c->p, c->Ho, c->Wo, c->gx + b * in_sz);
|
||||
}
|
||||
} else {
|
||||
int HW = c->H * c->W;
|
||||
im2col(gb, c->O, c->Ho, c->Wo, c->k, c->s, c->p, c->H, c->W, dcol); /* [OKK, HW] */
|
||||
if (c->gx)
|
||||
A->gemm(false, false, c->C, HW, OKK, 1.f, c->w, OKK, dcol, HW, 1.f, c->gx + b * in_sz, HW);
|
||||
if (lw)
|
||||
A->gemm(false, true, c->C, OKK, HW, 1.f, xb, HW, dcol, HW, 1.f, lw, OKK);
|
||||
}
|
||||
}
|
||||
pthread_mutex_lock(&c->mu);
|
||||
if (lw) for (size_t i = 0; i < wn; i++) c->gw[i] += lw[i];
|
||||
if (lb) for (int o = 0; o < c->O; o++) c->gb[o] += lb[o];
|
||||
pthread_mutex_unlock(&c->mu);
|
||||
free(col); free(dcol); free(lw); free(lb);
|
||||
}
|
||||
|
||||
static void conv_backward(TbTensor* out) {
|
||||
TbTensor* x = IN(out, 0); TbTensor* w = IN(out, 1); TbTensor* b = out->node.n_in > 2 ? IN(out, 2) : NULL;
|
||||
Conv c;
|
||||
memset(&c, 0, sizeof(c));
|
||||
c.transpose = out->node.ik[0];
|
||||
c.B = x->shape[0]; c.C = x->shape[1]; c.H = x->shape[2]; c.W = x->shape[3];
|
||||
c.O = out->shape[1]; c.Ho = out->shape[2]; c.Wo = out->shape[3];
|
||||
c.k = out->node.ik[1]; c.s = out->node.ik[2]; c.p = out->node.ik[3];
|
||||
c.x = x->d; c.w = w->d;
|
||||
c.gout = out->g;
|
||||
c.gx = G(x); c.gw = G(w); c.gb = G(b);
|
||||
pthread_mutex_init(&c.mu, NULL);
|
||||
A->parallel_for(c.B, conv_bwd, &c);
|
||||
pthread_mutex_destroy(&c.mu);
|
||||
}
|
||||
|
||||
static TbTensor* conv_any(TbTensor* x, TbTensor* w, TbTensor* b, int stride, int pad, bool transpose) {
|
||||
const char* nome = transpose ? "convolução transposta" : "convolução";
|
||||
if (x->nd != 4) { A->set_error("%s precisa de uma entrada [lote, canais, altura, largura]", nome); return NULL; }
|
||||
if (w->nd != 4 || w->shape[2] != w->shape[3]) { A->set_error("%s: pesos com forma inválida", nome); return NULL; }
|
||||
if (stride < 1) stride = 1;
|
||||
if (pad < 0) pad = 0;
|
||||
Conv c;
|
||||
memset(&c, 0, sizeof(c));
|
||||
c.transpose = transpose;
|
||||
c.B = x->shape[0]; c.C = x->shape[1]; c.H = x->shape[2]; c.W = x->shape[3];
|
||||
c.k = w->shape[2]; c.s = stride; c.p = pad;
|
||||
int win = transpose ? w->shape[0] : w->shape[1];
|
||||
if (win != c.C) { A->set_error("%s: a entrada tem %d canais e os pesos esperam %d", nome, c.C, win); return NULL; }
|
||||
c.O = transpose ? w->shape[1] : w->shape[0];
|
||||
if (transpose) { c.Ho = (c.H - 1) * stride - 2 * pad + c.k; c.Wo = (c.W - 1) * stride - 2 * pad + c.k; }
|
||||
else { c.Ho = (c.H + 2 * pad - c.k) / stride + 1; c.Wo = (c.W + 2 * pad - c.k) / stride + 1; }
|
||||
if (c.Ho < 1 || c.Wo < 1) { A->set_error("%s: a imagem %dx%d é pequena para o filtro %d", nome, c.H, c.W, c.k); return NULL; }
|
||||
TbTensor* o = A->alloc(4, (int[]){ c.B, c.O, c.Ho, c.Wo });
|
||||
if (!o) return NULL;
|
||||
c.x = x->d; c.w = w->d; c.bias = b ? b->d : NULL; c.out = o->d;
|
||||
A->parallel_for(c.B, conv_fwd, &c);
|
||||
TbTensor* in[3] = { x, w, b };
|
||||
A->link(o, conv_backward, in, b ? 3 : 2, NULL, NULL);
|
||||
o->node.ik[0] = transpose; o->node.ik[1] = c.k; o->node.ik[2] = stride; o->node.ik[3] = pad;
|
||||
return o;
|
||||
}
|
||||
|
||||
TbTensor* ai_conv2d(TbTensor* x, TbTensor* W, TbTensor* b, int stride, int pad) { return conv_any(x, W, b, stride, pad, false); }
|
||||
TbTensor* ai_conv_t2d(TbTensor* x, TbTensor* W, TbTensor* b, int stride, int pad) { return conv_any(x, W, b, stride, pad, true); }
|
||||
|
||||
/* == Max pool ========================================================= */
|
||||
static void pool_backward(TbTensor* out) {
|
||||
TbTensor* x = IN(out, 0);
|
||||
float* gx = G(x);
|
||||
const int* arg = out->node.ctx;
|
||||
for (size_t i = 0; i < out->n; i++) gx[arg[i]] += out->g[i];
|
||||
}
|
||||
|
||||
TbTensor* ai_maxpool(TbTensor* x, int k, int stride) {
|
||||
if (x->nd != 4) { A->set_error("max pool precisa de [lote, canais, altura, largura]"); return NULL; }
|
||||
if (k < 1) k = 2;
|
||||
if (stride < 1) stride = k;
|
||||
int B = x->shape[0], C = x->shape[1], H = x->shape[2], W = x->shape[3];
|
||||
int Ho = (H - k) / stride + 1, Wo = (W - k) / stride + 1;
|
||||
if (Ho < 1 || Wo < 1) { A->set_error("max pool %d numa imagem %dx%d", k, H, W); return NULL; }
|
||||
TbTensor* o = A->alloc(4, (int[]){ B, C, Ho, Wo });
|
||||
int* arg = malloc(o ? o->n * sizeof(int) + 1 : 1);
|
||||
if (!o || !arg) { A->release(o); free(arg); A->set_error("sem memória"); return NULL; }
|
||||
size_t q = 0;
|
||||
for (int bc = 0; bc < B * C; bc++) {
|
||||
const float* img = x->d + (size_t)bc * H * W;
|
||||
for (int oy = 0; oy < Ho; oy++)
|
||||
for (int ox = 0; ox < Wo; ox++, q++) {
|
||||
int best = (oy * stride) * W + ox * stride;
|
||||
for (int ky = 0; ky < k; ky++)
|
||||
for (int kx = 0; kx < k; kx++) {
|
||||
int at = (oy * stride + ky) * W + ox * stride + kx;
|
||||
if (img[at] > img[best]) best = at;
|
||||
}
|
||||
o->d[q] = img[best];
|
||||
arg[q] = (int)((size_t)bc * H * W + best);
|
||||
}
|
||||
}
|
||||
A->link(o, pool_backward, &x, 1, arg, free);
|
||||
return o;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* TinyBlocks - ai_internal.h
|
||||
* Funcoes internas da tinyblocks-ai: operacoes com gradiente (ai_ops.c,
|
||||
* ai_conv.c), blocos (ai_blocks.c), tokenizador BPE (ai_bpe.c).
|
||||
* Tudo passa pela tabela da tinyblocks-tensor em `A`.
|
||||
*/
|
||||
#ifndef TB_AI_INTERNAL_H
|
||||
#define TB_AI_INTERNAL_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include "tb_tensor.h"
|
||||
#include "tb_ai.h"
|
||||
|
||||
/* A tabela da tinyblocks-tensor (posta por ai_begin a cada avaliacao) */
|
||||
extern const TbTensorApi* A;
|
||||
bool ai_begin(TinyBlocks* rt); /* false = tensor ausente (erro levantado) */
|
||||
|
||||
/* Modo de treino: dropout ativo e batch norm com as medias do lote */
|
||||
extern bool g_ai_train;
|
||||
|
||||
/* -- Ativacoes ---------------------------------------------------------- */
|
||||
enum { AI_RELU, AI_LEAKY, AI_TANH, AI_SIGMOID, AI_GELU, AI_SILU };
|
||||
TbTensor* ai_act(TbTensor* x, int kind, float alpha);
|
||||
TbTensor* ai_softmax(TbTensor* x, bool causal); /* ultimo eixo */
|
||||
|
||||
/* -- Perdas (escalares, media) ------------------------------------------ */
|
||||
TbTensor* ai_cross_entropy(TbTensor* logits, TbTensor* classes); /* classes 1..C */
|
||||
TbTensor* ai_bce_logits(TbTensor* x, TbTensor* target);
|
||||
TbTensor* ai_mse(TbTensor* a, TbTensor* b);
|
||||
|
||||
/* -- Normalizacao e regularizacao ---------------------------------------- */
|
||||
TbTensor* ai_batchnorm(TbTensor* x, TbTensor* gamma, TbTensor* beta,
|
||||
TbTensor* run_mean, TbTensor* run_var, bool train, float momentum);
|
||||
TbTensor* ai_layernorm(TbTensor* x, TbTensor* gamma, TbTensor* beta, bool rms); /* beta NULL no RMS */
|
||||
TbTensor* ai_dropout(TbTensor* x, float p);
|
||||
TbTensor* ai_embedding(TbTensor* idx, TbTensor* W); /* idx 1..V */
|
||||
|
||||
/* -- Convolucao (ai_conv.c) ---------------------------------------------- */
|
||||
TbTensor* ai_conv2d(TbTensor* x, TbTensor* W, TbTensor* b, int stride, int pad);
|
||||
TbTensor* ai_conv_t2d(TbTensor* x, TbTensor* W, TbTensor* b, int stride, int pad);
|
||||
TbTensor* ai_maxpool(TbTensor* x, int k, int stride);
|
||||
|
||||
/* -- BPE (ai_bpe.c) ----------------------------------------------------- */
|
||||
bool ai_bpe_train(const char* text, int merges);
|
||||
int ai_bpe_vocab(void);
|
||||
int* ai_bpe_encode(const char* text, int* n); /* ids 1..V, malloc */
|
||||
char* ai_bpe_decode(const int* ids, int n); /* malloc */
|
||||
bool ai_bpe_save(const char* path);
|
||||
bool ai_bpe_load(const char* path);
|
||||
void ai_bpe_reset(void);
|
||||
|
||||
#endif /* TB_AI_INTERNAL_H */
|
||||
@@ -0,0 +1,395 @@
|
||||
/*
|
||||
* TinyBlocks - ai_ops.c
|
||||
* Operacoes da tinyblocks-ai com gradiente: ativacoes, softmax, perdas,
|
||||
* normalizacoes, dropout e embedding. Cada uma aloca a saida pela tabela
|
||||
* da tinyblocks-tensor e se liga ao grafo (A->link) com o seu backward.
|
||||
*/
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ai_internal.h"
|
||||
|
||||
const TbTensorApi* A;
|
||||
bool g_ai_train = true;
|
||||
|
||||
bool ai_begin(TinyBlocks* rt) {
|
||||
A = tb_tensor_api(rt);
|
||||
if (!A) tinyblocks_set_error(rt, "a IA precisa da library tinyblocks-tensor carregada");
|
||||
return A != NULL;
|
||||
}
|
||||
|
||||
static TbTensor* IN(TbTensor* out, int i) { return out->node.in[i]; }
|
||||
static float* G(TbTensor* t) { return t && t->req ? A->grad(t) : NULL; }
|
||||
|
||||
/* Linhas e tamanho do ultimo eixo */
|
||||
static void rows_cols(const TbTensor* x, size_t* rows, int* cols) {
|
||||
*cols = x->nd ? x->shape[x->nd - 1] : 1;
|
||||
*rows = *cols ? x->n / (size_t)*cols : 0;
|
||||
}
|
||||
|
||||
/* == Ativacoes ======================================================== */
|
||||
static const float GELU_C = 0.7978845608f; /* sqrt(2/pi) */
|
||||
|
||||
static void act_backward(TbTensor* out) {
|
||||
TbTensor* x = IN(out, 0);
|
||||
float* gx = G(x);
|
||||
int kind = out->node.ik[0];
|
||||
float a = out->node.fk[0];
|
||||
for (size_t i = 0; i < x->n; i++) {
|
||||
float v = x->d[i], y = out->d[i], d;
|
||||
switch (kind) {
|
||||
case AI_RELU: d = v > 0 ? 1.f : 0.f; break;
|
||||
case AI_LEAKY: d = v > 0 ? 1.f : a; break;
|
||||
case AI_TANH: d = 1.f - y * y; break;
|
||||
case AI_SIGMOID: d = y * (1.f - y); break;
|
||||
case AI_GELU: {
|
||||
float u = GELU_C * (v + 0.044715f * v * v * v), t = tanhf(u);
|
||||
d = 0.5f * (1.f + t) + 0.5f * v * (1.f - t * t) * GELU_C * (1.f + 3.f * 0.044715f * v * v);
|
||||
break;
|
||||
}
|
||||
default: { /* SiLU */
|
||||
float s = 1.f / (1.f + expf(-v));
|
||||
d = s + v * s * (1.f - s);
|
||||
break;
|
||||
}
|
||||
}
|
||||
gx[i] += out->g[i] * d;
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* ai_act(TbTensor* x, int kind, float alpha) {
|
||||
TbTensor* o = A->alloc_like(x);
|
||||
if (!o) return NULL;
|
||||
for (size_t i = 0; i < x->n; i++) {
|
||||
float v = x->d[i];
|
||||
switch (kind) {
|
||||
case AI_RELU: o->d[i] = v > 0 ? v : 0; break;
|
||||
case AI_LEAKY: o->d[i] = v > 0 ? v : alpha * v; break;
|
||||
case AI_TANH: o->d[i] = tanhf(v); break;
|
||||
case AI_SIGMOID: o->d[i] = 1.f / (1.f + expf(-v)); break;
|
||||
case AI_GELU: o->d[i] = 0.5f * v * (1.f + tanhf(GELU_C * (v + 0.044715f * v * v * v))); break;
|
||||
default: o->d[i] = v / (1.f + expf(-v)); break;
|
||||
}
|
||||
}
|
||||
A->link(o, act_backward, &x, 1, NULL, NULL);
|
||||
o->node.ik[0] = kind;
|
||||
o->node.fk[0] = alpha;
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Softmax (ultimo eixo; causal: [.., T, T] so ve j <= i) ============ */
|
||||
static void softmax_backward(TbTensor* out) {
|
||||
TbTensor* x = IN(out, 0);
|
||||
float* gx = G(x);
|
||||
size_t rows; int C;
|
||||
rows_cols(out, &rows, &C);
|
||||
for (size_t r = 0; r < rows; r++) {
|
||||
const float* y = out->d + r * C;
|
||||
const float* g = out->g + r * C;
|
||||
double dot = 0;
|
||||
for (int c = 0; c < C; c++) dot += (double)g[c] * y[c];
|
||||
for (int c = 0; c < C; c++) gx[r * C + c] += y[c] * (g[c] - (float)dot);
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* ai_softmax(TbTensor* x, bool causal) {
|
||||
if (x->nd < 1) { A->set_error("softmax precisa de um tensor com eixos"); return NULL; }
|
||||
TbTensor* o = A->alloc_like(x);
|
||||
if (!o) return NULL;
|
||||
size_t rows; int C;
|
||||
rows_cols(x, &rows, &C);
|
||||
int T = causal && x->nd >= 2 ? x->shape[x->nd - 2] : 0;
|
||||
for (size_t r = 0; r < rows; r++) {
|
||||
const float* v = x->d + r * C;
|
||||
float* y = o->d + r * C;
|
||||
int lim = causal && T ? (int)(r % (size_t)T) + 1 : C; /* linha i ve as colunas 0..i */
|
||||
if (lim > C) lim = C;
|
||||
float mx = v[0];
|
||||
for (int c = 1; c < lim; c++) if (v[c] > mx) mx = v[c];
|
||||
double s = 0;
|
||||
for (int c = 0; c < lim; c++) { y[c] = expf(v[c] - mx); s += y[c]; }
|
||||
for (int c = 0; c < lim; c++) y[c] = (float)(y[c] / s);
|
||||
for (int c = lim; c < C; c++) y[c] = 0;
|
||||
}
|
||||
A->link(o, softmax_backward, &x, 1, NULL, NULL);
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Perdas =========================================================== */
|
||||
typedef struct { size_t rows; int C; float* p; int* cls; } CeCtx;
|
||||
|
||||
static void ce_free(void* p) { CeCtx* c = p; free(c->p); free(c->cls); free(c); }
|
||||
|
||||
static void ce_backward(TbTensor* out) {
|
||||
TbTensor* x = IN(out, 0);
|
||||
float* gx = G(x);
|
||||
CeCtx* c = out->node.ctx;
|
||||
float k = out->g[0] / (float)c->rows;
|
||||
for (size_t r = 0; r < c->rows; r++)
|
||||
for (int j = 0; j < c->C; j++)
|
||||
gx[r * c->C + j] += k * (c->p[r * c->C + j] - (j == c->cls[r] ? 1.f : 0.f));
|
||||
}
|
||||
|
||||
TbTensor* ai_cross_entropy(TbTensor* logits, TbTensor* classes) {
|
||||
size_t rows; int C;
|
||||
rows_cols(logits, &rows, &C);
|
||||
if (classes->n != rows) {
|
||||
A->set_error("entropia cruzada: %zu linhas de logits e %zu classes", rows, classes->n);
|
||||
return NULL;
|
||||
}
|
||||
CeCtx* c = calloc(1, sizeof(CeCtx));
|
||||
if (c) { c->p = malloc(logits->n * sizeof(float)); c->cls = malloc(rows * sizeof(int) + 1); }
|
||||
if (!c || !c->p || !c->cls) { if (c) ce_free(c); A->set_error("sem memória"); return NULL; }
|
||||
c->rows = rows; c->C = C;
|
||||
double loss = 0;
|
||||
for (size_t r = 0; r < rows; r++) {
|
||||
int k = (int)lroundf(classes->d[r]) - 1;
|
||||
if (k < 0 || k >= C) { ce_free(c); A->set_error("classe %d fora de 1..%d", k + 1, C); return NULL; }
|
||||
c->cls[r] = k;
|
||||
const float* v = logits->d + r * C;
|
||||
float mx = v[0];
|
||||
for (int j = 1; j < C; j++) if (v[j] > mx) mx = v[j];
|
||||
double s = 0;
|
||||
for (int j = 0; j < C; j++) s += exp(v[j] - mx);
|
||||
for (int j = 0; j < C; j++) c->p[r * C + j] = (float)(exp(v[j] - mx) / s);
|
||||
loss += -(v[k] - mx - log(s));
|
||||
}
|
||||
TbTensor* o = A->scalar((float)(rows ? loss / rows : 0));
|
||||
if (!o) { ce_free(c); return NULL; }
|
||||
A->link(o, ce_backward, &logits, 1, c, ce_free);
|
||||
return o;
|
||||
}
|
||||
|
||||
static void bce_backward(TbTensor* out) {
|
||||
TbTensor* x = IN(out, 0); TbTensor* t = IN(out, 1);
|
||||
float* gx = G(x);
|
||||
float k = out->g[0] / (float)x->n;
|
||||
for (size_t i = 0; i < x->n; i++) {
|
||||
float tv = t->n == 1 ? t->d[0] : t->d[i];
|
||||
gx[i] += k * (1.f / (1.f + expf(-x->d[i])) - tv);
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* ai_bce_logits(TbTensor* x, TbTensor* t) {
|
||||
if (t->n != 1 && t->n != x->n) { A->set_error("BCE: %zu logits e %zu alvos", x->n, t->n); return NULL; }
|
||||
double loss = 0;
|
||||
for (size_t i = 0; i < x->n; i++) {
|
||||
float v = x->d[i], tv = t->n == 1 ? t->d[0] : t->d[i];
|
||||
loss += (v > 0 ? v : 0) - v * tv + log1p(exp(-fabs(v)));
|
||||
}
|
||||
TbTensor* o = A->scalar((float)(x->n ? loss / x->n : 0));
|
||||
if (!o) return NULL;
|
||||
TbTensor* in[2] = { x, t };
|
||||
A->link(o, bce_backward, in, 2, NULL, NULL);
|
||||
return o;
|
||||
}
|
||||
|
||||
static void mse_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0); TbTensor* b = IN(out, 1);
|
||||
float* ga = G(a); float* gb = G(b);
|
||||
float k = 2.f * out->g[0] / (float)a->n;
|
||||
for (size_t i = 0; i < a->n; i++) {
|
||||
float d = a->d[i] - (b->n == 1 ? b->d[0] : b->d[i]);
|
||||
if (ga) ga[i] += k * d;
|
||||
if (gb) { if (b->n == 1) gb[0] -= k * d; else gb[i] -= k * d; }
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* ai_mse(TbTensor* a, TbTensor* b) {
|
||||
if (b->n != 1 && b->n != a->n) { A->set_error("erro quadrático: %zu e %zu números", a->n, b->n); return NULL; }
|
||||
double s = 0;
|
||||
for (size_t i = 0; i < a->n; i++) { double d = a->d[i] - (b->n == 1 ? b->d[0] : b->d[i]); s += d * d; }
|
||||
TbTensor* o = A->scalar((float)(a->n ? s / a->n : 0));
|
||||
if (!o) return NULL;
|
||||
TbTensor* in[2] = { a, b };
|
||||
A->link(o, mse_backward, in, 2, NULL, NULL);
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Batch norm (eixo 1 = canais; media no lote e no espaco) =========== */
|
||||
typedef struct { float* xhat; float* inv; bool train; } BnCtx;
|
||||
static void bn_free(void* p) { BnCtx* c = p; free(c->xhat); free(c->inv); free(c); }
|
||||
|
||||
static void bn_dims(const TbTensor* x, int* B, int* C, size_t* S) {
|
||||
*B = x->shape[0]; *C = x->nd > 1 ? x->shape[1] : 1;
|
||||
*S = 1;
|
||||
for (int i = 2; i < x->nd; i++) *S *= (size_t)x->shape[i];
|
||||
}
|
||||
|
||||
static void bn_backward(TbTensor* out) {
|
||||
TbTensor* x = IN(out, 0); TbTensor* gm = IN(out, 1); TbTensor* bt = IN(out, 2);
|
||||
float* gx = G(x); float* gg = G(gm); float* gb = G(bt);
|
||||
BnCtx* c = out->node.ctx;
|
||||
int B, C; size_t S;
|
||||
bn_dims(x, &B, &C, &S);
|
||||
double m = (double)B * S;
|
||||
for (int ch = 0; ch < C; ch++) {
|
||||
double sg = 0, sgx = 0;
|
||||
for (int b = 0; b < B; b++)
|
||||
for (size_t s = 0; s < S; s++) {
|
||||
size_t i = ((size_t)b * C + ch) * S + s;
|
||||
sg += out->g[i]; sgx += out->g[i] * c->xhat[i];
|
||||
}
|
||||
if (gg) gg[ch] += (float)sgx;
|
||||
if (gb) gb[ch] += (float)sg;
|
||||
if (!gx) continue;
|
||||
float g0 = gm->d[ch], inv = c->inv[ch];
|
||||
for (int b = 0; b < B; b++)
|
||||
for (size_t s = 0; s < S; s++) {
|
||||
size_t i = ((size_t)b * C + ch) * S + s;
|
||||
if (c->train)
|
||||
gx[i] += (float)(g0 * inv / m * (m * out->g[i] - sg - c->xhat[i] * sgx));
|
||||
else
|
||||
gx[i] += g0 * inv * out->g[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* ai_batchnorm(TbTensor* x, TbTensor* gamma, TbTensor* beta,
|
||||
TbTensor* run_mean, TbTensor* run_var, bool train, float momentum) {
|
||||
if (x->nd < 2) { A->set_error("batch norm precisa de [lote, canais, ...]"); return NULL; }
|
||||
int B, C; size_t S;
|
||||
bn_dims(x, &B, &C, &S);
|
||||
TbTensor* o = A->alloc_like(x);
|
||||
BnCtx* c = calloc(1, sizeof(BnCtx));
|
||||
if (c) { c->xhat = malloc(x->n * sizeof(float)); c->inv = malloc((size_t)C * sizeof(float)); }
|
||||
if (!o || !c || !c->xhat || !c->inv) { A->release(o); if (c) bn_free(c); A->set_error("sem memória"); return NULL; }
|
||||
c->train = train && B * S > 1;
|
||||
double m = (double)B * S;
|
||||
for (int ch = 0; ch < C; ch++) {
|
||||
double mean, var;
|
||||
if (c->train) {
|
||||
double s = 0, s2 = 0;
|
||||
for (int b = 0; b < B; b++)
|
||||
for (size_t q = 0; q < S; q++) { double v = x->d[((size_t)b * C + ch) * S + q]; s += v; s2 += v * v; }
|
||||
mean = s / m; var = s2 / m - mean * mean;
|
||||
if (var < 0) var = 0;
|
||||
run_mean->d[ch] = (1 - momentum) * run_mean->d[ch] + momentum * (float)mean;
|
||||
run_var->d[ch] = (1 - momentum) * run_var->d[ch] + momentum * (float)(var * m / (m > 1 ? m - 1 : 1));
|
||||
} else { mean = run_mean->d[ch]; var = run_var->d[ch]; }
|
||||
float inv = (float)(1.0 / sqrt(var + 1e-5));
|
||||
c->inv[ch] = inv;
|
||||
for (int b = 0; b < B; b++)
|
||||
for (size_t q = 0; q < S; q++) {
|
||||
size_t i = ((size_t)b * C + ch) * S + q;
|
||||
float xh = (float)(x->d[i] - mean) * inv;
|
||||
c->xhat[i] = xh;
|
||||
o->d[i] = gamma->d[ch] * xh + beta->d[ch];
|
||||
}
|
||||
}
|
||||
TbTensor* in[3] = { x, gamma, beta };
|
||||
A->link(o, bn_backward, in, 3, c, bn_free);
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Layer norm / RMSNorm (ultimo eixo) =============================== */
|
||||
typedef struct { float* xhat; float* inv; } LnCtx;
|
||||
static void ln_free(void* p) { LnCtx* c = p; free(c->xhat); free(c->inv); free(c); }
|
||||
|
||||
static void ln_backward(TbTensor* out) {
|
||||
TbTensor* x = IN(out, 0); TbTensor* gm = IN(out, 1); TbTensor* bt = out->node.n_in > 2 ? IN(out, 2) : NULL;
|
||||
float* gx = G(x); float* gg = G(gm); float* gb = G(bt);
|
||||
LnCtx* c = out->node.ctx;
|
||||
bool rms = out->node.ik[0];
|
||||
size_t rows; int D;
|
||||
rows_cols(x, &rows, &D);
|
||||
for (size_t r = 0; r < rows; r++) {
|
||||
const float* g = out->g + r * D;
|
||||
const float* xh = c->xhat + r * D;
|
||||
double s1 = 0, s2 = 0;
|
||||
for (int j = 0; j < D; j++) {
|
||||
float dxh = g[j] * gm->d[j];
|
||||
s1 += dxh; s2 += dxh * xh[j];
|
||||
if (gg) gg[j] += g[j] * xh[j];
|
||||
if (gb) gb[j] += g[j];
|
||||
}
|
||||
if (!gx) continue;
|
||||
float inv = c->inv[r];
|
||||
for (int j = 0; j < D; j++) {
|
||||
float dxh = g[j] * gm->d[j];
|
||||
gx[r * D + j] += rms ? inv * (dxh - xh[j] * (float)(s2 / D))
|
||||
: inv * (dxh - (float)(s1 / D) - xh[j] * (float)(s2 / D));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* ai_layernorm(TbTensor* x, TbTensor* gamma, TbTensor* beta, bool rms) {
|
||||
size_t rows; int D;
|
||||
rows_cols(x, &rows, &D);
|
||||
TbTensor* o = A->alloc_like(x);
|
||||
LnCtx* c = calloc(1, sizeof(LnCtx));
|
||||
if (c) { c->xhat = malloc(x->n * sizeof(float)); c->inv = malloc(rows * sizeof(float) + 1); }
|
||||
if (!o || !c || !c->xhat || !c->inv) { A->release(o); if (c) ln_free(c); A->set_error("sem memória"); return NULL; }
|
||||
for (size_t r = 0; r < rows; r++) {
|
||||
const float* v = x->d + r * D;
|
||||
double mean = 0, var = 0;
|
||||
if (!rms) { for (int j = 0; j < D; j++) mean += v[j]; mean /= D; }
|
||||
for (int j = 0; j < D; j++) { double d = v[j] - mean; var += d * d; }
|
||||
var /= D;
|
||||
float inv = (float)(1.0 / sqrt(var + 1e-5));
|
||||
c->inv[r] = inv;
|
||||
for (int j = 0; j < D; j++) {
|
||||
float xh = (float)(v[j] - mean) * inv;
|
||||
c->xhat[r * D + j] = xh;
|
||||
o->d[r * D + j] = gamma->d[j] * xh + (beta ? beta->d[j] : 0);
|
||||
}
|
||||
}
|
||||
TbTensor* in[3] = { x, gamma, beta };
|
||||
A->link(o, ln_backward, in, beta ? 3 : 2, c, ln_free);
|
||||
o->node.ik[0] = rms;
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Dropout ========================================================== */
|
||||
static void dropout_backward(TbTensor* out) {
|
||||
TbTensor* x = IN(out, 0);
|
||||
float* gx = G(x);
|
||||
const float* mask = out->node.ctx;
|
||||
for (size_t i = 0; i < x->n; i++) gx[i] += out->g[i] * mask[i];
|
||||
}
|
||||
|
||||
TbTensor* ai_dropout(TbTensor* x, float p) {
|
||||
if (!g_ai_train || p <= 0) return A->scale(x, 1.f);
|
||||
if (p >= 1) p = 0.999f;
|
||||
TbTensor* o = A->alloc_like(x);
|
||||
float* mask = malloc(x->n * sizeof(float) + 1);
|
||||
if (!o || !mask) { A->release(o); free(mask); A->set_error("sem memória"); return NULL; }
|
||||
float k = 1.f / (1.f - p);
|
||||
for (size_t i = 0; i < x->n; i++) { mask[i] = A->randu() < p ? 0.f : k; o->d[i] = x->d[i] * mask[i]; }
|
||||
A->link(o, dropout_backward, &x, 1, mask, free);
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Embedding ======================================================== */
|
||||
typedef struct { size_t n; int id[]; } Ids;
|
||||
|
||||
static void emb_backward(TbTensor* out) {
|
||||
TbTensor* W = IN(out, 0);
|
||||
float* gw = G(W);
|
||||
const Ids* c = out->node.ctx;
|
||||
int D = W->shape[1];
|
||||
for (size_t k = 0; k < c->n; k++)
|
||||
for (int j = 0; j < D; j++) gw[(size_t)c->id[k] * D + j] += out->g[k * D + j];
|
||||
}
|
||||
|
||||
TbTensor* ai_embedding(TbTensor* idx, TbTensor* W) {
|
||||
int V = W->shape[0], D = W->shape[1];
|
||||
if (idx->nd >= TB_TENSOR_MAX_DIMS) { A->set_error("índices com eixos demais"); return NULL; }
|
||||
Ids* c = malloc(sizeof(Ids) + idx->n * sizeof(int));
|
||||
if (!c) { A->set_error("sem memória"); return NULL; }
|
||||
c->n = idx->n;
|
||||
for (size_t k = 0; k < idx->n; k++) {
|
||||
int v = (int)lroundf(idx->d[k]);
|
||||
if (v < 1 || v > V) { free(c); A->set_error("símbolo %d fora de 1..%d", v, V); return NULL; }
|
||||
c->id[k] = v - 1;
|
||||
}
|
||||
int s[TB_TENSOR_MAX_DIMS];
|
||||
for (int i = 0; i < idx->nd; i++) s[i] = idx->shape[i];
|
||||
s[idx->nd] = D;
|
||||
TbTensor* o = A->alloc(idx->nd + 1, s);
|
||||
if (!o) { free(c); return NULL; }
|
||||
for (size_t k = 0; k < idx->n; k++) memcpy(o->d + k * D, W->d + (size_t)c->id[k] * D, (size_t)D * sizeof(float));
|
||||
A->link(o, emb_backward, &W, 1, c, free);
|
||||
return o;
|
||||
}
|
||||
Reference in new issue
Block a user