Files
tinyblocks/libraries/tinyblocks-ai/src/ai_bpe.c
T
mguinhosandClaude Opus 5.5 05fdb094ed 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>
2026-10-23 23:12:32 -03:00

158 lines
5.9 KiB
C

/*
* 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();
}