tinyblocks-tensor: tensores com gradiente automatico como blocos
Tensores de float (ate 6 eixos) viajam como bloco-handle; cada bloco produtor e dono de um handle e troca o tensor a cada avaliacao. Contas com broadcasting, matmul em lote (GEMM com AVX2 escolhido em execucao e pool de threads), forma, fatias, juncao, indices, reducoes, imagem, bytes de arquivo e .tbt. Autograd por grafo com contagem de referencias; parametros por dono e por grupo, salvar/carregar. Outras libraries usam a tabela TbTensorApi do lib_userdata, sem linkar. test-tensor confere cada gradiente por diferenca finita. O "escreva" passa a usar as classes de valor (tensor aparecia como "resultado"). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3dd132d12d
commit
520cb10f08
11 files changed
+2586
-25
No files matched your search
@@ -0,0 +1,31 @@
|
||||
# Makefile da library tensor (categoria "Tensores")
|
||||
# Constroi build/libtinyblocks-tensor.a e build/libtinyblocks-tensor.so
|
||||
CC := gcc
|
||||
BUILD := build
|
||||
|
||||
CFLAGS := -std=c11 -O3 -ffp-contract=fast -Wall -Wextra -pedantic -fvisibility=hidden \
|
||||
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
|
||||
|
||||
SRCS := src/tensor.c src/ops.c src/blocks.c
|
||||
OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS))
|
||||
HDRS := include/tb_tensor.h src/tensor_internal.h
|
||||
LIB_A := $(BUILD)/libtinyblocks-tensor.a
|
||||
LIB_SO := $(BUILD)/libtinyblocks-tensor.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,172 @@
|
||||
/*
|
||||
* TinyBlocks - tb_tensor.h
|
||||
* Library tinyblocks-tensor: tensores de float (ate 6 eixos) com gradiente
|
||||
* automatico (autograd), como valores de bloco. Registra a categoria
|
||||
* "Tensores".
|
||||
*
|
||||
* Um tensor viaja entre blocos como um BLOCO-HANDLE (TB_VALUE_BLOCK): uma
|
||||
* instancia do tipo escondido "Tensor._Valor" cujo userdata aponta para o
|
||||
* TbTensor. Cada bloco que produz tensor e dono de UM handle (guardado no
|
||||
* comeco do userdata dele, TbProducer) e troca o tensor do handle a cada
|
||||
* avaliacao. Assim um laco nao cria um handle por volta, e
|
||||
* mude [h] para (relu de (h))
|
||||
* funciona: o bloco le o tensor atual e poe o novo no lugar.
|
||||
*
|
||||
* O tensor tem contagem de referencias (TinyBlocks_Object): o grafo do
|
||||
* autograd segura os tensores de que o backward precisa. Um tensor criado
|
||||
* por uma operacao lembra a operacao (TbNode) se alguma entrada pede
|
||||
* gradiente; "calcule os gradientes de (perda)" percorre o grafo de tras
|
||||
* para a frente e acumula em `g`.
|
||||
*
|
||||
* Outras libraries (ex.: tinyblocks-ai) NAO linkam com esta: pegam a tabela
|
||||
* TbTensorApi que ela publica no lib_userdata da library
|
||||
* (tb_tensor_api(rt)), para haver uma copia so do estado mesmo com as
|
||||
* libraries carregadas de jeitos diferentes (.so ou estatica).
|
||||
*/
|
||||
#ifndef TINYBLOCKS_TENSOR_H
|
||||
#define TINYBLOCKS_TENSOR_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
#define TB_TENSOR_MAX_DIMS 6
|
||||
#define TB_TENSOR_MAX_IN 4
|
||||
#define TB_TENSOR_LIB "tinyblocks-tensor"
|
||||
#define TB_TENSOR_API_VERSION 1
|
||||
|
||||
typedef struct TbTensor TbTensor;
|
||||
|
||||
/* Backward de uma operacao: le out->g e SOMA nos `g` das entradas que pedem
|
||||
gradiente (api->grad(in) garante o buffer). */
|
||||
typedef void (*TbBackwardFn)(TbTensor* out);
|
||||
|
||||
/* Como o tensor foi feito (backward == NULL: folha) */
|
||||
typedef struct TbNode {
|
||||
TbBackwardFn backward;
|
||||
TbTensor* in[TB_TENSOR_MAX_IN]; /* retidos enquanto o no existir */
|
||||
int n_in;
|
||||
void* ctx; /* dados guardados para o backward */
|
||||
void (*ctx_free)(void* ctx);
|
||||
int ik[6]; /* parametros pequenos da operacao */
|
||||
float fk[4];
|
||||
} TbNode;
|
||||
|
||||
struct TbTensor {
|
||||
TinyBlocks_Object obj; /* contagem de referencias (1o campo) */
|
||||
int nd; /* eixos (0 = escalar) */
|
||||
int shape[TB_TENSOR_MAX_DIMS];
|
||||
size_t n; /* elementos */
|
||||
float* d; /* dados, linha a linha (C order) */
|
||||
float* g; /* gradiente (NULL ate ser preciso) */
|
||||
bool req; /* participa do gradiente */
|
||||
bool param; /* parametro treinavel */
|
||||
TbNode node;
|
||||
uint32_t visit; /* marca do backward (ordem topologica) */
|
||||
void* opt; /* estado do otimizador (ex.: Adam) */
|
||||
void (*opt_free)(void* opt);
|
||||
};
|
||||
|
||||
/* Comeco do userdata de todo tipo que produz tensor (desta library ou de
|
||||
outra): o handle de que o bloco e dono. Zerado no nascimento. */
|
||||
typedef struct TbProducer {
|
||||
TinyBlocks_Block* handle;
|
||||
} TbProducer;
|
||||
|
||||
/* Inicializacao de parametros */
|
||||
enum { TB_INIT_ZEROS = 0, TB_INIT_ONES, TB_INIT_NORMAL, TB_INIT_UNIFORM };
|
||||
|
||||
/* Trabalho paralelo: fn(ctx, de, ate) para fatias de [0, n) */
|
||||
typedef void (*TbParallelFn)(void* ctx, int from, int to);
|
||||
|
||||
typedef struct TbTensorApi {
|
||||
int version; /* TB_TENSOR_API_VERSION */
|
||||
|
||||
/* -- Tensores ------------------------------------------------------- */
|
||||
TbTensor* (*alloc)(int nd, const int* shape); /* zerado, ref = 1 */
|
||||
TbTensor* (*alloc_like)(const TbTensor* t);
|
||||
void (*retain)(TbTensor* t);
|
||||
void (*release)(TbTensor* t); /* aceita NULL */
|
||||
float* (*grad)(TbTensor* t); /* garante t->g (zerado) */
|
||||
TbTensor* (*scalar)(float v);
|
||||
|
||||
/* -- Blocos --------------------------------------------------------- */
|
||||
/* Entrada i como tensor: handle, numero (escalar) ou lista. Ref NOVA
|
||||
(solte com release) ou NULL; NULL deixa o erro em last_error. */
|
||||
TbTensor* (*arg)(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i);
|
||||
/* Saida 0 do bloco = o handle dele com t (toma a referencia). O userdata
|
||||
do tipo comeca com TbProducer. */
|
||||
void (*put)(TinyBlocks_Block* self, TinyBlocks* rt, TbTensor* t);
|
||||
/* Chame no instance_deinit de um tipo produtor */
|
||||
void (*producer_free)(TinyBlocks_Block* self, TinyBlocks* rt);
|
||||
/* Tensor de um valor (handle) sem copiar; NULL se nao for tensor */
|
||||
TbTensor* (*of_value)(TinyBlocks_Value v);
|
||||
const char* (*last_error)(void);
|
||||
void (*set_error)(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
|
||||
|
||||
/* -- Autograd ------------------------------------------------------- */
|
||||
/* Liga out ao grafo se o gradiente estiver ligado e alguma entrada pedir
|
||||
gradiente; senao solta ctx (ctx_free) e nao guarda nada. */
|
||||
void (*link)(TbTensor* out, TbBackwardFn bw, TbTensor* const* in, int n,
|
||||
void* ctx, void (*ctx_free)(void* ctx));
|
||||
bool (*grad_enabled)(void);
|
||||
void (*set_grad_enabled)(bool on);
|
||||
|
||||
/* -- Parametros (registro global, na ordem de criacao) -------------- */
|
||||
/* Parametro do bloco `owner` (criado uma vez por instancia: chame de novo
|
||||
com o mesmo `slot` e recebe o mesmo). Ref EMPRESTADA. */
|
||||
TbTensor* (*param)(TinyBlocks_Block* owner, int slot, int nd, const int* shape,
|
||||
int init, float scale);
|
||||
void (*params_release)(TinyBlocks_Block* owner);
|
||||
int (*param_count)(void);
|
||||
TbTensor* (*param_at)(int i);
|
||||
/* Grupo do parametro i (o "use o grupo de parametros" ativo quando ele
|
||||
nasceu; "" = sem grupo). Otimizadores agem por grupo. */
|
||||
const char* (*param_group)(int i);
|
||||
|
||||
/* -- Operacoes com gradiente (ref nova ou NULL + last_error) --------- */
|
||||
TbTensor* (*add)(TbTensor* a, TbTensor* b); /* broadcasting */
|
||||
TbTensor* (*sub)(TbTensor* a, TbTensor* b);
|
||||
TbTensor* (*mul)(TbTensor* a, TbTensor* b);
|
||||
TbTensor* (*div)(TbTensor* a, TbTensor* b);
|
||||
TbTensor* (*scale)(TbTensor* a, float k);
|
||||
TbTensor* (*matmul)(TbTensor* a, TbTensor* b); /* [...,m,k] @ [...,k,n] */
|
||||
TbTensor* (*reshape)(TbTensor* a, int nd, const int* shape);
|
||||
TbTensor* (*transpose)(TbTensor* a, int ax1, int ax2);
|
||||
TbTensor* (*slice)(TbTensor* a, int axis, int from, int to); /* [from, to), 0-based */
|
||||
TbTensor* (*concat)(TbTensor* a, TbTensor* b, int axis);
|
||||
TbTensor* (*sum)(TbTensor* a, int axis, bool keep); /* axis < 0 = tudo */
|
||||
TbTensor* (*mean)(TbTensor* a, int axis, bool keep);
|
||||
|
||||
/* -- Utilidades ----------------------------------------------------- */
|
||||
/* C[m,n] = alpha * op(A)[m,k] op(B)[k,n] + beta * C (row-major) */
|
||||
void (*gemm)(bool ta, bool tb, int m, int n, int k, float alpha,
|
||||
const float* A, int lda, const float* B, int ldb,
|
||||
float beta, float* C, int ldc);
|
||||
void (*parallel_for)(int n, TbParallelFn fn, void* ctx);
|
||||
float (*randn)(void); /* normal(0, 1) */
|
||||
float (*randu)(void); /* [0, 1) */
|
||||
int (*shape_text)(const TbTensor* t, char* out, size_t cap); /* "[3, 32, 32]" */
|
||||
} TbTensorApi;
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_tensor_get_library(void);
|
||||
|
||||
/* A tabela publicada pela library carregada neste runtime (NULL se a
|
||||
tinyblocks-tensor nao estiver registrada). Sem linkar: so procura a
|
||||
library pelo nome e le o lib_userdata. */
|
||||
static inline const TbTensorApi* tb_tensor_api(TinyBlocks* rt) {
|
||||
TinyBlocks_LibraryBlock* lib = tb_rt_find_library(rt, TB_TENSOR_LIB);
|
||||
const TbTensorApi* api = lib ? (const TbTensorApi*)lib->lib_userdata : NULL;
|
||||
return api && api->version == TB_TENSOR_API_VERSION ? api : NULL;
|
||||
}
|
||||
|
||||
/* Elementos de uma forma */
|
||||
static inline size_t tb_tensor_numel(int nd, const int* shape) {
|
||||
size_t n = 1;
|
||||
for (int i = 0; i < nd; i++) n *= (size_t)shape[i];
|
||||
return n;
|
||||
}
|
||||
|
||||
#endif /* TINYBLOCKS_TENSOR_H */
|
||||
@@ -0,0 +1,15 @@
|
||||
# Metadados da library tensor. Lido pela UI/build sem recompilar o .so.
|
||||
[library]
|
||||
name = "tinyblocks-tensor"
|
||||
version = "1.0.0"
|
||||
category = "Tensores"
|
||||
description = "Tensores de float com gradiente automatico: contas, formas, fatias, reducoes, arquivos e imagens"
|
||||
color = [89, 107, 242, 255]
|
||||
dark = [61, 77, 199, 255]
|
||||
|
||||
[build]
|
||||
sources = ["src/tensor.c", "src/ops.c", "src/blocks.c"]
|
||||
includes = ["include"]
|
||||
shared = "build/libtinyblocks-tensor.so"
|
||||
static = "build/libtinyblocks-tensor.a"
|
||||
depends = []
|
||||
@@ -0,0 +1,819 @@
|
||||
/*
|
||||
* TinyBlocks - blocks.c
|
||||
* Blocos da tinyblocks-tensor (categoria "Tensores"), o bloco-handle que
|
||||
* leva o tensor de bloco em bloco e a tabela TbTensorApi publicada no
|
||||
* lib_userdata da library.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <ctype.h>
|
||||
#include <math.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
#include <tinyblocks/tb_json_block.h>
|
||||
#include <tinyblocks/tb_image.h>
|
||||
#include "tensor_internal.h"
|
||||
|
||||
/* == O bloco-handle =================================================== */
|
||||
typedef struct { TbTensor* t; TinyBlocks_Block* owner; } HandleData;
|
||||
|
||||
static TinyBlocks_TypeBlock* s_t_handle;
|
||||
|
||||
static void handle_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
HandleData* h = self->userdata;
|
||||
if (!h) return;
|
||||
tt_release(h->t);
|
||||
h->t = NULL;
|
||||
/* o dono pode ser destruido depois do handle (fase 1 do deinit): esquece */
|
||||
if (h->owner && h->owner->userdata) {
|
||||
TbProducer* p = h->owner->userdata;
|
||||
if (p->handle == self) p->handle = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
static size_t handle_text(TinyBlocks_Block* self, char* out, size_t cap) {
|
||||
HandleData* h = self->userdata;
|
||||
if (!h || !h->t) return (size_t)snprintf(out, cap, "tensor vazio");
|
||||
const TbTensor* t = h->t;
|
||||
if (t->nd == 0) return (size_t)snprintf(out, cap, "tensor %g", t->d[0]);
|
||||
char sh[96];
|
||||
tt_shape_text(t, sh, sizeof(sh));
|
||||
char buf[256];
|
||||
int n = snprintf(buf, sizeof(buf), "tensor %s", sh);
|
||||
if (t->n <= 6) {
|
||||
n += snprintf(buf + n, sizeof(buf) - (size_t)n, " (");
|
||||
for (size_t i = 0; i < t->n; i++)
|
||||
n += snprintf(buf + n, sizeof(buf) - (size_t)n, "%s%g", i ? ", " : "", t->d[i]);
|
||||
snprintf(buf + n, sizeof(buf) - (size_t)n, ")");
|
||||
}
|
||||
return (size_t)snprintf(out, cap, "%s", buf);
|
||||
}
|
||||
|
||||
static TbTensor* of_value(TinyBlocks_Value v) {
|
||||
if (v.kind != TB_VALUE_BLOCK || !v.as.block || v.as.block->type != s_t_handle) return NULL;
|
||||
HandleData* h = v.as.block->userdata;
|
||||
return h ? h->t : NULL;
|
||||
}
|
||||
|
||||
void tt_put(TinyBlocks_Block* self, TinyBlocks* rt, TbTensor* t) {
|
||||
TbProducer* p = self->userdata;
|
||||
if (!t) return;
|
||||
if (!p) { tt_release(t); return; }
|
||||
if (!p->handle) {
|
||||
p->handle = tb_block_create(rt, s_t_handle);
|
||||
if (!p->handle) { tt_release(t); return; }
|
||||
((HandleData*)p->handle->userdata)->owner = self;
|
||||
}
|
||||
HandleData* h = p->handle->userdata;
|
||||
tt_release(h->t);
|
||||
h->t = t;
|
||||
tb_block_set_output(self, 0, tb_value_block(p->handle));
|
||||
}
|
||||
|
||||
void tt_producer_free(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbProducer* p = self->userdata;
|
||||
if (p && p->handle) {
|
||||
TinyBlocks_Block* h = p->handle;
|
||||
p->handle = NULL;
|
||||
((HandleData*)h->userdata)->owner = NULL;
|
||||
tb_block_destroy(h, rt);
|
||||
}
|
||||
}
|
||||
|
||||
static void producer_deinit(TinyBlocks_Block* self, TinyBlocks* rt) { tt_producer_free(self, rt); }
|
||||
|
||||
/* == Valores -> tensor ================================================ */
|
||||
/* Forma escrita: "3,32,32", "3x32x32", "[3, 32, 32]" ou um numero */
|
||||
static int parse_shape(const char* s, int* shape) {
|
||||
int nd = 0;
|
||||
while (*s) {
|
||||
while (*s && !isdigit((unsigned char)*s) && *s != '-') s++;
|
||||
if (!*s) break;
|
||||
if (nd >= TB_TENSOR_MAX_DIMS) return -1;
|
||||
char* e;
|
||||
long v = strtol(s, &e, 10);
|
||||
if (e == s) { s++; continue; }
|
||||
shape[nd++] = (int)v;
|
||||
s = e;
|
||||
}
|
||||
return nd;
|
||||
}
|
||||
|
||||
static bool shape_arg(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i, int* nd, int* shape) {
|
||||
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
|
||||
TbTensor* t = of_value(v);
|
||||
if (t) { /* forma tirada de um tensor */
|
||||
*nd = t->nd;
|
||||
for (int k = 0; k < t->nd; k++) shape[k] = t->shape[k];
|
||||
return true;
|
||||
}
|
||||
*nd = parse_shape(tb_block_input_text(self, rt, i), shape);
|
||||
if (*nd < 0) { tinyblocks_set_error(rt, "forma com eixos demais (máximo %d)", TB_TENSOR_MAX_DIMS); return false; }
|
||||
for (int k = 0; k < *nd; k++)
|
||||
if (shape[k] < 0 && shape[k] != -1) { tinyblocks_set_error(rt, "forma com tamanho negativo"); return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Lista JSON retangular -> tensor */
|
||||
static bool list_shape(const TinyBlocks_JsonValue* j, int depth, int* nd, int* shape) {
|
||||
if (tb_json_kind(j) != TB_JSON_ARRAY) { *nd = depth; return true; }
|
||||
if (depth >= TB_TENSOR_MAX_DIMS) return false;
|
||||
uint32_t n = tb_json_array_length(j);
|
||||
shape[depth] = (int)n;
|
||||
if (!n) { *nd = depth + 1; return true; }
|
||||
TinyBlocks_JsonValue* first = tb_json_array_get(j, 0);
|
||||
bool ok = list_shape(first, depth + 1, nd, shape);
|
||||
tb_json_release(first);
|
||||
return ok;
|
||||
}
|
||||
|
||||
static bool list_fill(const TinyBlocks_JsonValue* j, int depth, int nd, const int* shape, float** w) {
|
||||
if (depth == nd) {
|
||||
const char* s = tb_json_as_string(j);
|
||||
*(*w)++ = s ? (float)strtod(s, NULL) : (float)tb_json_as_number(j, 0);
|
||||
return true;
|
||||
}
|
||||
if (tb_json_kind(j) != TB_JSON_ARRAY || (int)tb_json_array_length(j) != shape[depth]) return false;
|
||||
for (int i = 0; i < shape[depth]; i++) {
|
||||
TinyBlocks_JsonValue* c = tb_json_array_get(j, (uint32_t)i);
|
||||
bool ok = list_fill(c, depth + 1, nd, shape, w);
|
||||
tb_json_release(c);
|
||||
if (!ok) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static TbTensor* from_json(const TinyBlocks_JsonValue* j) {
|
||||
int nd = 0, shape[TB_TENSOR_MAX_DIMS];
|
||||
if (!list_shape(j, 0, &nd, shape)) { tt_set_error("lista com níveis demais para um tensor"); return NULL; }
|
||||
TbTensor* t = tt_alloc(nd, shape);
|
||||
if (!t) return NULL;
|
||||
float* w = t->d;
|
||||
if (!list_fill(j, 0, nd, shape, &w)) { tt_release(t); tt_set_error("a lista não é retangular (sublistas de tamanhos diferentes)"); return NULL; }
|
||||
return t;
|
||||
}
|
||||
|
||||
static TbTensor* from_image(const TinyBlocks_Image* img) {
|
||||
int w = tb_image_width(img), h = tb_image_height(img);
|
||||
TbTensor* t = tt_alloc(3, (int[]){ 3, h, w });
|
||||
if (!t) return NULL;
|
||||
for (int y = 0; y < h; y++)
|
||||
for (int x = 0; x < w; x++) {
|
||||
uint8_t r, g, b, a;
|
||||
tb_image_get_pixel(img, x, y, &r, &g, &b, &a);
|
||||
size_t o = (size_t)y * w + x;
|
||||
t->d[o] = r / 255.f; t->d[(size_t)w * h + o] = g / 255.f; t->d[2 * (size_t)w * h + o] = b / 255.f;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/* "1, 2, 3" (vetor) ou "1, 2; 3, 4" (matriz: linhas separadas por ';') */
|
||||
static TbTensor* from_matrix_text(const char* s) {
|
||||
int rows = 0, cols = -1, cur = 0, cap = 64, n = 0;
|
||||
float* v = malloc((size_t)cap * sizeof(float));
|
||||
if (!v) { tt_set_error("sem memória"); return NULL; }
|
||||
const char* p = s;
|
||||
bool any_semicolon = strchr(s, ';') != NULL;
|
||||
for (;;) {
|
||||
while (*p == ' ' || *p == '\t' || *p == ',') p++;
|
||||
if (*p == ';' || !*p) {
|
||||
if (cur > 0 || *p == ';') {
|
||||
if (cols >= 0 && cur != cols) { free(v); tt_set_error("as linhas da matriz têm tamanhos diferentes (%d e %d)", cols, cur); return NULL; }
|
||||
cols = cur; cur = 0; rows++;
|
||||
}
|
||||
if (!*p) break;
|
||||
p++;
|
||||
continue;
|
||||
}
|
||||
char* e;
|
||||
double x = strtod(p, &e);
|
||||
if (e == p) { free(v); tt_set_error("'%s' não é um número nem uma lista de números", s); return NULL; }
|
||||
if (n == cap) { cap *= 2; float* nv = realloc(v, (size_t)cap * sizeof(float)); if (!nv) { free(v); return NULL; } v = nv; }
|
||||
v[n++] = (float)x; cur++;
|
||||
p = e;
|
||||
}
|
||||
TbTensor* t = any_semicolon ? tt_alloc(2, (int[]){ rows, cols < 0 ? 0 : cols }) : tt_alloc(1, &n);
|
||||
if (t) memcpy(t->d, v, (size_t)n * sizeof(float));
|
||||
free(v);
|
||||
return t;
|
||||
}
|
||||
|
||||
TbTensor* tt_from_value(TinyBlocks_Value v) {
|
||||
TbTensor* t = of_value(v);
|
||||
if (t) { tt_retain(t); return t; }
|
||||
double d;
|
||||
switch (v.kind) {
|
||||
case TB_VALUE_INTEGER: return tt_scalar((float)v.as.integer);
|
||||
case TB_VALUE_REAL: return tt_scalar((float)v.as.real);
|
||||
case TB_VALUE_JSON: if (tb_json_kind(v.as.json) == TB_JSON_ARRAY) return from_json(v.as.json);
|
||||
if (tb_value_to_number(v, &d)) return tt_scalar((float)d);
|
||||
break;
|
||||
case TB_VALUE_IMAGE: return v.as.image ? from_image(v.as.image) : NULL;
|
||||
case TB_VALUE_TEXT: {
|
||||
const char* s = v.as.text ? v.as.text : "";
|
||||
while (isspace((unsigned char)*s)) s++;
|
||||
if (*s == '[') {
|
||||
TinyBlocks_JsonValue* j = tb_json_parse(s, NULL, 0);
|
||||
if (j) { TbTensor* r = from_json(j); tb_json_release(j); return r; }
|
||||
}
|
||||
if (tb_text_to_number(s, &d)) return tt_scalar((float)d);
|
||||
return from_matrix_text(s);
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
tt_set_error("esperava um tensor e veio %s", tb_value_type_name(v));
|
||||
return NULL;
|
||||
}
|
||||
|
||||
TbTensor* tt_arg(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
return tt_from_value(tb_block_get_input(self, rt, i));
|
||||
}
|
||||
|
||||
/* == Ajudas dos blocos ================================================ */
|
||||
#define FAIL(rt) tinyblocks_set_error((rt), "%s", tt_last_error())
|
||||
|
||||
static void done(TinyBlocks_Block* self, TinyBlocks* rt, TbTensor* r) {
|
||||
if (r) tt_put(self, rt, r);
|
||||
else FAIL(rt);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* Le n entradas como tensores; false (com o erro levantado) se alguma falhar */
|
||||
static bool args(TinyBlocks_Block* self, TinyBlocks* rt, int n, TbTensor** t) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
t[i] = tt_arg(self, rt, (uint32_t)i);
|
||||
if (!t[i]) {
|
||||
for (int k = 0; k < i; k++) tt_release(t[k]);
|
||||
FAIL(rt);
|
||||
self->dirty = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void release_all(TbTensor** t, int n) { for (int i = 0; i < n; i++) tt_release(t[i]); }
|
||||
|
||||
static int axis_in(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
|
||||
return (int)tb_block_input_integer(self, rt, i, 1) - 1; /* eixos 1..n para quem usa */
|
||||
}
|
||||
|
||||
/* == Criacao ========================================================== */
|
||||
static void eval_zeros(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int nd, s[TB_TENSOR_MAX_DIMS];
|
||||
if (!shape_arg(self, rt, 0, &nd, s)) { self->dirty = false; return; }
|
||||
done(self, rt, tt_alloc(nd, s));
|
||||
}
|
||||
|
||||
static void eval_full(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
float v = (float)tb_block_input_number(self, rt, 0, 0);
|
||||
int nd, s[TB_TENSOR_MAX_DIMS];
|
||||
if (!shape_arg(self, rt, 1, &nd, s)) { self->dirty = false; return; }
|
||||
TbTensor* t = tt_alloc(nd, s);
|
||||
if (t) for (size_t i = 0; i < t->n; i++) t->d[i] = v;
|
||||
done(self, rt, t);
|
||||
}
|
||||
|
||||
static void eval_randn(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int nd, s[TB_TENSOR_MAX_DIMS];
|
||||
if (!shape_arg(self, rt, 0, &nd, s)) { self->dirty = false; return; }
|
||||
TbTensor* t = tt_alloc(nd, s);
|
||||
if (t) for (size_t i = 0; i < t->n; i++) t->d[i] = tt_randn();
|
||||
done(self, rt, t);
|
||||
}
|
||||
|
||||
static void eval_rand(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
float lo = (float)tb_block_input_number(self, rt, 0, 0), hi = (float)tb_block_input_number(self, rt, 1, 1);
|
||||
int nd, s[TB_TENSOR_MAX_DIMS];
|
||||
if (!shape_arg(self, rt, 2, &nd, s)) { self->dirty = false; return; }
|
||||
TbTensor* t = tt_alloc(nd, s);
|
||||
if (t) for (size_t i = 0; i < t->n; i++) t->d[i] = lo + (hi - lo) * tt_randu();
|
||||
done(self, rt, t);
|
||||
}
|
||||
|
||||
static void eval_range(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
double a = tb_block_input_number(self, rt, 0, 1), b = tb_block_input_number(self, rt, 1, 10);
|
||||
int n = b >= a ? (int)floor(b - a) + 1 : 0;
|
||||
TbTensor* t = tt_alloc(1, &n);
|
||||
if (t) for (int i = 0; i < n; i++) t->d[i] = (float)(a + i);
|
||||
done(self, rt, t);
|
||||
}
|
||||
|
||||
static void eval_from(TinyBlocks_Block* self, TinyBlocks* rt) { /* lista, imagem, numero */
|
||||
TbTensor* t = tt_arg(self, rt, 0);
|
||||
if (t && of_value(tb_block_get_input(self, rt, 0)) == t) { /* ja era tensor: copia */
|
||||
TbTensor* c = tt_detach(t);
|
||||
tt_release(t);
|
||||
t = c;
|
||||
}
|
||||
done(self, rt, t);
|
||||
}
|
||||
|
||||
static void eval_from_bytes(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
const char* path = tb_block_input_text(self, rt, 0);
|
||||
long off = (long)tb_block_input_number(self, rt, 1, 0);
|
||||
int nd, s[TB_TENSOR_MAX_DIMS];
|
||||
if (!shape_arg(self, rt, 2, &nd, s)) { self->dirty = false; return; }
|
||||
FILE* f = fopen(path, "rb");
|
||||
if (!f) { tinyblocks_set_error(rt, "não abriu '%s'", path); self->dirty = false; return; }
|
||||
TbTensor* t = tt_alloc(nd, s);
|
||||
if (t) {
|
||||
unsigned char* buf = malloc(t->n ? t->n : 1);
|
||||
size_t got = 0;
|
||||
if (buf && fseek(f, off, SEEK_SET) == 0) got = fread(buf, 1, t->n, f);
|
||||
if (!buf || got != t->n) {
|
||||
tt_release(t); t = NULL;
|
||||
tt_set_error("'%s' não tem %zu bytes a partir de %ld (leu %zu)", path, tb_tensor_numel(nd, s), off, got);
|
||||
} else for (size_t i = 0; i < t->n; i++) t->d[i] = (float)buf[i];
|
||||
free(buf);
|
||||
}
|
||||
fclose(f);
|
||||
done(self, rt, t);
|
||||
}
|
||||
|
||||
static void eval_load(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
int n = 0;
|
||||
TbTensor** ts = tt_load(tb_block_input_text(self, rt, 0), &n);
|
||||
TbTensor* t = NULL;
|
||||
if (ts && n > 0) { t = ts[0]; for (int i = 1; i < n; i++) tt_release(ts[i]); }
|
||||
else if (ts) tt_set_error("o arquivo não tem nenhum tensor");
|
||||
free(ts);
|
||||
done(self, rt, t);
|
||||
}
|
||||
|
||||
static void eval_save(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
if (!tt_save(tb_block_input_text(self, rt, 1), &t, 1)) FAIL(rt);
|
||||
tt_release(t);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_seed(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
tt_seed((uint32_t)tb_block_input_integer(self, rt, 0, 1));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_perm(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
done(self, rt, tt_permutation((int)tb_block_input_integer(self, rt, 0, 10)));
|
||||
}
|
||||
|
||||
/* == Informacao ======================================================= */
|
||||
static void eval_shape(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
char buf[128]; size_t n = 0;
|
||||
buf[0] = 0;
|
||||
for (int i = 0; i < t->nd; i++) n += (size_t)snprintf(buf + n, sizeof(buf) - n, "%s%d", i ? "," : "", t->shape[i]);
|
||||
tb_block_set_output(self, 0, tb_value_text(buf));
|
||||
tt_release(t);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_dim(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
int ax = axis_in(self, rt, 1);
|
||||
tb_block_set_output(self, 0, tb_value_integer(ax >= 0 && ax < t->nd ? t->shape[ax] : 0));
|
||||
tt_release(t);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_numel(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
tb_block_set_output(self, 0, tb_value_integer((int64_t)t->n));
|
||||
tt_release(t);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_item(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
int64_t i = tb_block_input_integer(self, rt, 1, 1);
|
||||
if (i < 1 || (size_t)i > t->n) tinyblocks_set_error(rt, "elemento %lld não existe (há %zu)", (long long)i, t->n);
|
||||
else tb_block_set_output(self, 0, tb_value_number(t->d[i - 1]));
|
||||
tt_release(t);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static TinyBlocks_JsonValue* to_json(const float** p, int depth, const TbTensor* t) {
|
||||
if (depth == t->nd) return tb_json_number(*(*p)++);
|
||||
TinyBlocks_JsonValue* arr = tb_json_array();
|
||||
for (int i = 0; arr && i < t->shape[depth]; i++) {
|
||||
TinyBlocks_JsonValue* c = to_json(p, depth + 1, t);
|
||||
if (c) { tb_json_array_push(arr, c); tb_json_release(c); }
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
static void eval_to_list(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
if (t->n > 1000000) tinyblocks_set_error(rt, "tensor grande demais para virar lista (%zu números)", t->n);
|
||||
else {
|
||||
const float* p = t->d;
|
||||
TinyBlocks_JsonValue* j = to_json(&p, 0, t);
|
||||
tb_block_set_output(self, 0, tb_value_json(j));
|
||||
tb_json_release(j);
|
||||
}
|
||||
tt_release(t);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* [H,W], [1|3,H,W] ou um lote [B,C,H,W] (vira uma grade). Os valores de lo
|
||||
a hi viram 0..255. */
|
||||
static void eval_to_image(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
float lo = (float)tb_block_input_number(self, rt, 1, 0), hi = (float)tb_block_input_number(self, rt, 2, 1);
|
||||
int B = 1, C = 1, H, W;
|
||||
if (t->nd == 2) { H = t->shape[0]; W = t->shape[1]; }
|
||||
else if (t->nd == 3) { C = t->shape[0]; H = t->shape[1]; W = t->shape[2]; }
|
||||
else if (t->nd == 4) { B = t->shape[0]; C = t->shape[1]; H = t->shape[2]; W = t->shape[3]; }
|
||||
else { tinyblocks_set_error(rt, "imagem precisa de um tensor [A,L], [C,A,L] ou [lote,C,A,L]"); tt_release(t); self->dirty = false; return; }
|
||||
if (C != 1 && C != 3) { tinyblocks_set_error(rt, "imagem com %d canais (use 1 ou 3)", C); tt_release(t); self->dirty = false; return; }
|
||||
int cols = (int)ceil(sqrt((double)B)), rows = (B + cols - 1) / cols, gap = B > 1 ? 1 : 0;
|
||||
int IW = cols * W + (cols - 1) * gap, IH = rows * H + (rows - 1) * gap;
|
||||
TinyBlocks_Image* img = tb_image_new(IW > 0 ? IW : 1, IH > 0 ? IH : 1, 4);
|
||||
float k = hi != lo ? 255.f / (hi - lo) : 255.f;
|
||||
for (int b = 0; img && b < B; b++) {
|
||||
int ox = (b % cols) * (W + gap), oy = (b / cols) * (H + gap);
|
||||
const float* base = t->d + (size_t)b * C * H * W;
|
||||
for (int y = 0; y < H; y++)
|
||||
for (int x = 0; x < W; x++) {
|
||||
float v[3];
|
||||
for (int c = 0; c < 3; c++) {
|
||||
float f = (base[(size_t)(C == 3 ? c : 0) * H * W + (size_t)y * W + x] - lo) * k;
|
||||
v[c] = f < 0 ? 0 : f > 255 ? 255 : f;
|
||||
}
|
||||
tb_image_set_pixel(img, ox + x, oy + y, (uint8_t)(v[0] + .5f), (uint8_t)(v[1] + .5f), (uint8_t)(v[2] + .5f), 255);
|
||||
}
|
||||
}
|
||||
if (img) { tb_block_set_output(self, 0, tb_value_image(img)); tb_image_release(img); }
|
||||
tt_release(t);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* == Contas =========================================================== */
|
||||
#define BIN(name, op) \
|
||||
static void name(TinyBlocks_Block* self, TinyBlocks* rt) { \
|
||||
TbTensor* t[2]; \
|
||||
if (!args(self, rt, 2, t)) return; \
|
||||
TbTensor* r = tt_binary(t[0], t[1], op); \
|
||||
release_all(t, 2); done(self, rt, r); }
|
||||
BIN(eval_add, TT_ADD)
|
||||
BIN(eval_sub, TT_SUB)
|
||||
BIN(eval_mul, TT_MUL)
|
||||
BIN(eval_div, TT_DIV)
|
||||
|
||||
static void eval_matmul(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t[2];
|
||||
if (!args(self, rt, 2, t)) return;
|
||||
TbTensor* r = tt_matmul(t[0], t[1]);
|
||||
release_all(t, 2); done(self, rt, r);
|
||||
}
|
||||
|
||||
static void eval_powk(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
TbTensor* r = tt_powk(t, (float)tb_block_input_number(self, rt, 1, 2));
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
#define UNARY(name, op) \
|
||||
static void name(TinyBlocks_Block* self, TinyBlocks* rt) { \
|
||||
TbTensor* t; \
|
||||
if (!args(self, rt, 1, &t)) return; \
|
||||
TbTensor* r = tt_unary(t, op); \
|
||||
tt_release(t); done(self, rt, r); }
|
||||
UNARY(eval_exp, TT_EXP)
|
||||
UNARY(eval_log, TT_LOG)
|
||||
UNARY(eval_sqrt, TT_SQRT)
|
||||
UNARY(eval_abs, TT_ABS)
|
||||
|
||||
/* == Forma ============================================================ */
|
||||
static void eval_reshape(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
int nd, s[TB_TENSOR_MAX_DIMS];
|
||||
TbTensor* r = NULL;
|
||||
if (shape_arg(self, rt, 1, &nd, s)) { r = tt_reshape(t, nd, s); if (!r) FAIL(rt); }
|
||||
tt_release(t);
|
||||
if (r) tt_put(self, rt, r);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_transpose(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
TbTensor* r = tt_transpose(t, axis_in(self, rt, 1), axis_in(self, rt, 2));
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
static void eval_flatten(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
TbTensor* r = tt_flatten(t);
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
static void eval_slice(TinyBlocks_Block* self, TinyBlocks* rt) { /* posições 1..n, inclusive */
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
int ax = axis_in(self, rt, 1);
|
||||
int from = (int)tb_block_input_integer(self, rt, 2, 1), to = (int)tb_block_input_integer(self, rt, 3, 1);
|
||||
TbTensor* r = tt_slice(t, ax, from - 1, to);
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
static void eval_rows(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
int from = (int)tb_block_input_integer(self, rt, 1, 1), to = (int)tb_block_input_integer(self, rt, 2, 1);
|
||||
TbTensor* r = tt_slice(t, 0, from - 1, to);
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
static void eval_gather(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t[2];
|
||||
if (!args(self, rt, 2, t)) return;
|
||||
TbTensor* r = tt_gather(t[0], t[1]);
|
||||
release_all(t, 2); done(self, rt, r);
|
||||
}
|
||||
|
||||
/* "concatene": um lado que nao e tensor (um 0 de variavel nova) e vazio */
|
||||
static void eval_concat(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TinyBlocks_Value va = tb_block_get_input(self, rt, 0), vb = tb_block_get_input(self, rt, 1);
|
||||
TbTensor* a = of_value(va); TbTensor* b = of_value(vb);
|
||||
int ax = axis_in(self, rt, 2);
|
||||
TbTensor* r = NULL;
|
||||
if (a && b) r = tt_concat(a, b, ax);
|
||||
else if (a || b) r = tt_detach(a ? a : b);
|
||||
else tt_set_error("concatene precisa de pelo menos um tensor");
|
||||
done(self, rt, r);
|
||||
}
|
||||
|
||||
static void eval_flip(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
TbTensor* r = tt_flip(t, axis_in(self, rt, 1));
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
static void eval_where(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
TbTensor* r = tt_where_eq(t, (float)tb_block_input_number(self, rt, 1, 0));
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
/* == Reducoes ========================================================= */
|
||||
#define REDUCE_ALL(name, fn) \
|
||||
static void name(TinyBlocks_Block* self, TinyBlocks* rt) { \
|
||||
TbTensor* t; \
|
||||
if (!args(self, rt, 1, &t)) return; \
|
||||
TbTensor* r = fn(t, -1, false); \
|
||||
tt_release(t); done(self, rt, r); }
|
||||
#define REDUCE_AXIS(name, fn) \
|
||||
static void name(TinyBlocks_Block* self, TinyBlocks* rt) { \
|
||||
TbTensor* t; \
|
||||
if (!args(self, rt, 1, &t)) return; \
|
||||
int ax = axis_in(self, rt, 1); \
|
||||
TbTensor* r = ax < 0 ? (tt_set_error("eixo %d não existe", ax + 1), NULL) : fn(t, ax, false); \
|
||||
tt_release(t); done(self, rt, r); }
|
||||
REDUCE_ALL(eval_sum, tt_sum)
|
||||
REDUCE_ALL(eval_mean, tt_mean)
|
||||
REDUCE_AXIS(eval_sum_axis, tt_sum)
|
||||
REDUCE_AXIS(eval_mean_axis, tt_mean)
|
||||
REDUCE_AXIS(eval_max_axis, tt_max)
|
||||
|
||||
static void eval_argmax(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
TbTensor* r = tt_argmax(t, axis_in(self, rt, 1));
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
/* == Gradiente e parametros =========================================== */
|
||||
static void eval_backward(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
if (!tt_backward(t)) FAIL(rt);
|
||||
tt_release(t);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_grad(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
TbTensor* r = tt_alloc_like(t);
|
||||
if (r && t->g) memcpy(r->d, t->g, t->n * sizeof(float));
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
static void eval_detach(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
TbTensor* t;
|
||||
if (!args(self, rt, 1, &t)) return;
|
||||
TbTensor* r = tt_detach(t);
|
||||
tt_release(t); done(self, rt, r);
|
||||
}
|
||||
|
||||
static void eval_group(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
tt_set_param_group(tb_block_input_text(self, rt, 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_zero_grad(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
tt_params_zero_grad(tb_block_input_text(self, rt, 0));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_param_count(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
(void)rt;
|
||||
tb_block_set_output(self, 0, tb_value_integer((int64_t)tt_params_numel()));
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_params_save(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
if (!tt_params_save(tb_block_input_text(self, rt, 0))) FAIL(rt);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
static void eval_params_load(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
if (!tt_params_load(tb_block_input_text(self, rt, 0))) FAIL(rt);
|
||||
self->dirty = false;
|
||||
}
|
||||
|
||||
/* == A tabela para outras libraries ================================== */
|
||||
static void api_put(TinyBlocks_Block* self, TinyBlocks* rt, TbTensor* t) { tt_put(self, rt, t); }
|
||||
static TbTensor* api_reshape(TbTensor* a, int nd, const int* s) { return tt_reshape(a, nd, s); }
|
||||
|
||||
static const TbTensorApi s_api = {
|
||||
.version = TB_TENSOR_API_VERSION,
|
||||
.alloc = tt_alloc,
|
||||
.alloc_like = tt_alloc_like,
|
||||
.retain = tt_retain,
|
||||
.release = tt_release,
|
||||
.grad = tt_grad,
|
||||
.scalar = tt_scalar,
|
||||
.arg = tt_arg,
|
||||
.put = api_put,
|
||||
.producer_free = tt_producer_free,
|
||||
.of_value = of_value,
|
||||
.last_error = tt_last_error,
|
||||
.set_error = tt_set_error,
|
||||
.link = tt_link,
|
||||
.grad_enabled = tt_grad_enabled,
|
||||
.set_grad_enabled = tt_set_grad_enabled,
|
||||
.param = tt_param,
|
||||
.params_release = tt_params_release,
|
||||
.param_count = tt_param_count,
|
||||
.param_at = tt_param_at,
|
||||
.param_group = tt_param_group,
|
||||
.add = tt_add, .sub = tt_sub, .mul = tt_mul, .div = tt_div,
|
||||
.scale = tt_scale,
|
||||
.matmul = tt_matmul,
|
||||
.reshape = api_reshape,
|
||||
.transpose = tt_transpose,
|
||||
.slice = tt_slice,
|
||||
.concat = tt_concat,
|
||||
.sum = tt_sum,
|
||||
.mean = tt_mean,
|
||||
.gemm = tt_gemm,
|
||||
.parallel_for = tt_parallel_for,
|
||||
.randn = tt_randn,
|
||||
.randu = tt_randu,
|
||||
.shape_text = tt_shape_text,
|
||||
};
|
||||
|
||||
/* == Registro ========================================================= */
|
||||
typedef struct {
|
||||
const char* name;
|
||||
const char* label;
|
||||
const char* defs;
|
||||
int nin;
|
||||
TinyBlocks_ValueKind in[5];
|
||||
int out; /* 0 = comando, 1 = tensor, 2 = numero, 3 = texto, 4 = lista, 5 = imagem */
|
||||
void (*fn)(TinyBlocks_Block*, TinyBlocks*);
|
||||
const char* fname; /* funcao C (tooltip do editor: abre o codigo) */
|
||||
const char* doc;
|
||||
} Spec;
|
||||
|
||||
#define N TB_VALUE_NONE
|
||||
#define R TB_VALUE_REAL
|
||||
#define I TB_VALUE_INTEGER
|
||||
#define T TB_VALUE_TEXT
|
||||
|
||||
static const Spec s_specs[] = {
|
||||
/* criacao */
|
||||
{ "Tensor.Zeros", "tensor de zeros com forma %1", "2,3", 1, {T}, 1, eval_zeros, "eval_zeros", "Tensor cheio de zeros" },
|
||||
{ "Tensor.Full", "tensor cheio de %1 com forma %2", "1|2,3", 2, {R,T}, 1, eval_full, "eval_full", "Tensor com o mesmo número em tudo" },
|
||||
{ "Tensor.Randn", "tensor aleatório normal com forma %1", "2,3", 1, {T}, 1, eval_randn, "eval_randn", "Números da normal (média 0, desvio 1)" },
|
||||
{ "Tensor.Rand", "tensor aleatório entre %1 e %2 com forma %3", "0|1|2,3", 3, {R,R,T}, 1, eval_rand, "eval_rand", "Números uniformes no intervalo" },
|
||||
{ "Tensor.Range", "tensor de %1 até %2", "1|10", 2, {R,R}, 1, eval_range, "eval_range", "Números de a até b, de 1 em 1" },
|
||||
{ "Tensor.From", "tensor de %1", "1, 2; 3, 4", 1, {N}, 1, eval_from, "eval_from", "Tensor de \"1, 2; 3, 4\" (linhas separadas por ;), de uma lista, de uma imagem ([3,A,L], 0..1) ou de um número" },
|
||||
{ "Tensor.Bytes", "tensor dos bytes de %1 a partir de %2 com forma %3", "dados.bin|0|10", 3, {T,I,T}, 1, eval_from_bytes, "eval_from_bytes", "Lê bytes de um arquivo (0..255 cada)" },
|
||||
{ "Tensor.Load", "tensor do arquivo %1", "tensor.tbt", 1, {T}, 1, eval_load, "eval_load", "Lê um tensor gravado (.tbt)" },
|
||||
{ "Tensor.Save", "salve o tensor %1 em %2", "|tensor.tbt", 2, {N,T}, 0, eval_save, "eval_save", "Grava o tensor (.tbt)" },
|
||||
{ "Tensor.Seed", "semente aleatória %1", "1", 1, {I}, 0, eval_seed, "eval_seed", "Fixa os números aleatórios (repetível)" },
|
||||
{ "Tensor.Perm", "permutação de 1 até %1", "10", 1, {I}, 1, eval_perm, "eval_perm", "Os números de 1 a n embaralhados" },
|
||||
/* informacao */
|
||||
{ "Tensor.Shape", "forma de %1", "", 1, {N}, 3, eval_shape, "eval_shape", "Forma do tensor em texto (\"3,32,32\")" },
|
||||
{ "Tensor.Dim", "tamanho do eixo %2 de %1", "|1", 2, {N,I}, 2, eval_dim, "eval_dim", "Tamanho de um eixo (1 = o primeiro)" },
|
||||
{ "Tensor.Numel", "número de elementos de %1", "", 1, {N}, 2, eval_numel, "eval_numel", "Quantos números o tensor tem" },
|
||||
{ "Tensor.Item", "elemento %2 de %1", "|1", 2, {N,I}, 2, eval_item, "eval_item", "Um número do tensor (posição 1..n, linha a linha)" },
|
||||
{ "Tensor.ToList", "lista do tensor %1", "", 1, {N}, 4, eval_to_list, "eval_to_list", "O tensor como lista (de listas)" },
|
||||
{ "Tensor.ToImage", "imagem do tensor %1 de %2 a %3", "|0|1", 3, {N,R,R}, 5, eval_to_image, "eval_to_image", "Imagem de [A,L], [C,A,L] ou de um lote (grade); lo..hi vira 0..255" },
|
||||
/* contas */
|
||||
{ "Tensor.Add", "%1 mais %2", "", 2, {N,N}, 1, eval_add, "eval_add", "Soma elemento a elemento (com broadcasting)" },
|
||||
{ "Tensor.Sub", "%1 menos %2", "", 2, {N,N}, 1, eval_sub, "eval_sub", "Subtração elemento a elemento" },
|
||||
{ "Tensor.Mul", "%1 vezes %2", "", 2, {N,N}, 1, eval_mul, "eval_mul", "Produto elemento a elemento" },
|
||||
{ "Tensor.Div", "%1 dividido por %2", "", 2, {N,N}, 1, eval_div, "eval_div", "Divisão elemento a elemento" },
|
||||
{ "Tensor.MatMul", "produto de matrizes %1 e %2", "", 2, {N,N}, 1, eval_matmul, "eval_matmul", "Produto de matrizes [..,m,k] e [..,k,n]" },
|
||||
{ "Tensor.Pow", "%1 elevado a %2 elemento a elemento", "|2", 2, {N,R}, 1, eval_powk, "eval_powk", "Cada elemento elevado a p" },
|
||||
{ "Tensor.Exp", "exp do tensor %1", "", 1, {N}, 1, eval_exp, "eval_exp", "e elevado a cada elemento" },
|
||||
{ "Tensor.Log", "log do tensor %1", "", 1, {N}, 1, eval_log, "eval_log", "Logaritmo natural de cada elemento" },
|
||||
{ "Tensor.Sqrt", "raiz do tensor %1", "", 1, {N}, 1, eval_sqrt, "eval_sqrt", "Raiz quadrada de cada elemento" },
|
||||
{ "Tensor.Abs", "módulo do tensor %1", "", 1, {N}, 1, eval_abs, "eval_abs", "Valor absoluto de cada elemento" },
|
||||
/* forma */
|
||||
{ "Tensor.Reshape", "%1 com forma %2", "|-1", 2, {N,T}, 1, eval_reshape, "eval_reshape", "Mesmos números em outra forma (um eixo pode ser -1)" },
|
||||
{ "Tensor.Transpose","%1 trocando os eixos %2 e %3", "|1|2", 3, {N,I,I}, 1, eval_transpose, "eval_transpose", "Troca dois eixos" },
|
||||
{ "Tensor.Flatten", "achate %1", "", 1, {N}, 1, eval_flatten, "eval_flatten", "[lote, ...] vira [lote, resto]" },
|
||||
{ "Tensor.Slice", "fatia de %1 no eixo %2 de %3 até %4", "|1|1|2", 4, {N,I,I,I}, 1, eval_slice, "eval_slice", "Pedaço de um eixo (posições 1..n, inclusive)" },
|
||||
{ "Tensor.Rows", "linhas %2 até %3 de %1", "|1|10", 3, {N,I,I}, 1, eval_rows, "eval_rows", "Pedaço do primeiro eixo (inclusive)" },
|
||||
{ "Tensor.Gather", "linhas %2 de %1", "", 2, {N,N}, 1, eval_gather, "eval_gather", "As linhas cujas posições (1..n) estão no tensor de índices" },
|
||||
{ "Tensor.Concat", "concatene %1 e %2 no eixo %3", "||1", 3, {N,N,I}, 1, eval_concat, "eval_concat", "Junta dois tensores ao longo de um eixo" },
|
||||
{ "Tensor.Flip", "espelhe %1 no eixo %2", "|1", 2, {N,I}, 1, eval_flip, "eval_flip", "Inverte a ordem ao longo de um eixo" },
|
||||
{ "Tensor.Where", "posições onde %1 vale %2", "|0", 2, {N,R}, 1, eval_where, "eval_where", "Posições (1..n) dos elementos iguais ao número" },
|
||||
/* reducoes */
|
||||
{ "Tensor.Sum", "soma de %1", "", 1, {N}, 1, eval_sum, "eval_sum", "Soma de todos os elementos" },
|
||||
{ "Tensor.Mean", "média de %1", "", 1, {N}, 1, eval_mean, "eval_mean", "Média de todos os elementos" },
|
||||
{ "Tensor.SumAxis", "soma de %1 no eixo %2", "|1", 2, {N,I}, 1, eval_sum_axis, "eval_sum_axis", "Soma ao longo de um eixo" },
|
||||
{ "Tensor.MeanAxis","média de %1 no eixo %2", "|1", 2, {N,I}, 1, eval_mean_axis, "eval_mean_axis", "Média ao longo de um eixo" },
|
||||
{ "Tensor.MaxAxis", "máximo de %1 no eixo %2", "|1", 2, {N,I}, 1, eval_max_axis, "eval_max_axis", "Maior valor ao longo de um eixo" },
|
||||
{ "Tensor.ArgMax", "posição do máximo de %1 no eixo %2", "|1", 2, {N,I}, 1, eval_argmax, "eval_argmax", "Posição (1..n) do maior valor ao longo de um eixo" },
|
||||
/* gradiente */
|
||||
{ "Tensor.Backward","calcule os gradientes de %1", "", 1, {N}, 0, eval_backward, "eval_backward", "Backward: deriva o tensor (a perda) em relação aos parâmetros" },
|
||||
{ "Tensor.Grad", "gradiente de %1", "", 1, {N}, 1, eval_grad, "eval_grad", "O gradiente acumulado do tensor" },
|
||||
{ "Tensor.Detach", "%1 solto do grafo", "", 1, {N}, 1, eval_detach, "eval_detach", "Cópia que não leva gradiente para trás" },
|
||||
{ "Tensor.Group", "use o grupo de parâmetros %1", "modelo", 1, {T}, 0, eval_group, "eval_group", "Parâmetros criados daqui em diante entram neste grupo" },
|
||||
{ "Tensor.ZeroGrad","zere os gradientes do grupo %1", "", 1, {T}, 0, eval_zero_grad, "eval_zero_grad", "Zera os gradientes (grupo vazio = todos)" },
|
||||
{ "Tensor.Params", "número de parâmetros", "", 0, {N}, 2, eval_param_count, "eval_param_count", "Quantos números treináveis existem" },
|
||||
{ "Tensor.ParamsSave","salve os parâmetros em %1", "modelo.tbt", 1, {T}, 0, eval_params_save, "eval_params_save", "Grava todos os parâmetros, na ordem em que nasceram" },
|
||||
{ "Tensor.ParamsLoad","carregue os parâmetros de %1", "modelo.tbt", 1, {T}, 0, eval_params_load, "eval_params_load", "Lê os parâmetros (vale também para camadas que ainda vão nascer)" },
|
||||
};
|
||||
|
||||
#undef N
|
||||
#undef R
|
||||
#undef I
|
||||
#undef T
|
||||
|
||||
static bool tensor_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
static const TinyBlocks_Category cat = { "Tensores", {0.35f, 0.42f, 0.95f, 1.f}, {0.24f, 0.30f, 0.78f, 1.f} };
|
||||
tb_library_set_category(lib, &cat);
|
||||
lib->lib_userdata = (void*)&s_api;
|
||||
tt_pool_start();
|
||||
|
||||
s_t_handle = tb_type_block_create(rt, "Tensor._Valor", NULL, 0, NULL, 0, NULL);
|
||||
if (!s_t_handle) return false;
|
||||
tb_type_block_set_flags(s_t_handle, TB_TYPE_HIDDEN);
|
||||
tb_type_block_set_instance_hooks(s_t_handle, sizeof(HandleData), NULL, handle_deinit);
|
||||
tb_type_block_set_value_text(s_t_handle, handle_text);
|
||||
if (!tb_library_add(lib, &s_t_handle->base)) return false;
|
||||
|
||||
static const char* outs[] = { NULL, "tensor", "valor", "texto", "lista", "imagem" };
|
||||
static const TinyBlocks_ValueKind out_kind[] = { TB_VALUE_NONE, TB_VALUE_BLOCK, TB_VALUE_NONE, TB_VALUE_TEXT, TB_VALUE_JSON, TB_VALUE_IMAGE };
|
||||
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];
|
||||
static const char* names[] = { "a", "b", "c", "d", "e" };
|
||||
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);
|
||||
if (sp->out == 1) tb_type_block_set_instance_hooks(t, sizeof(TbProducer), NULL, producer_deinit);
|
||||
tb_meta_declare(sp->name, sp->fname, __FILE__, sp->doc);
|
||||
if (!tb_library_add(lib, &t->base)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void tensor_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
|
||||
(void)rt;
|
||||
lib->lib_userdata = NULL;
|
||||
tt_params_reset();
|
||||
tt_pool_stop();
|
||||
}
|
||||
|
||||
TINYBLOCKS_DEFINE_LIBRARY(tensor, "tinyblocks-tensor", "1.0.0", tensor_init, tensor_deinit)
|
||||
|
||||
const TinyBlocks_LibraryDescriptor* tb_tensor_get_library(void) {
|
||||
return &_tb_lib_desc_tensor;
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
/*
|
||||
* TinyBlocks - ops.c
|
||||
* Operacoes da tinyblocks-tensor. Cada uma devolve um tensor novo (ref = 1)
|
||||
* ou NULL com o erro em tt_last_error, e liga o resultado ao grafo
|
||||
* (tt_link) com a funcao de backward dela. O backward SOMA nos gradientes
|
||||
* das entradas que pedem gradiente.
|
||||
*/
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "tensor_internal.h"
|
||||
|
||||
/* == Ajudas =========================================================== */
|
||||
static TbTensor* IN(TbTensor* out, int i) { return out->node.in[i]; }
|
||||
static float* G(TbTensor* t) { return t && t->req ? tt_grad(t) : NULL; }
|
||||
|
||||
static int norm_axis(const TbTensor* a, int axis) {
|
||||
if (axis < 0) axis += a->nd;
|
||||
if (axis < 0 || axis >= a->nd) { tt_set_error("eixo %d não existe num tensor de %d eixos", axis + 1, a->nd); return -1; }
|
||||
return axis;
|
||||
}
|
||||
|
||||
/* Tamanhos de antes, do proprio e de depois do eixo */
|
||||
static void split_axis(const TbTensor* a, int axis, size_t* outer, int* len, size_t* inner) {
|
||||
*outer = 1; *inner = 1;
|
||||
for (int i = 0; i < axis; i++) *outer *= (size_t)a->shape[i];
|
||||
for (int i = axis + 1; i < a->nd; i++) *inner *= (size_t)a->shape[i];
|
||||
*len = a->shape[axis];
|
||||
}
|
||||
|
||||
/* == Broadcasting (regras do NumPy) =================================== */
|
||||
typedef struct {
|
||||
int nd;
|
||||
int shape[TB_TENSOR_MAX_DIMS];
|
||||
size_t n;
|
||||
long sa[TB_TENSOR_MAX_DIMS], sb[TB_TENSOR_MAX_DIMS];
|
||||
bool same; /* mesma forma: indices iguais */
|
||||
} Bcast;
|
||||
|
||||
static void strides_for(const TbTensor* t, int nd, long* s, const int* oshape) {
|
||||
long st = 1;
|
||||
for (int i = nd - 1; i >= 0; i--) {
|
||||
int ti = i - (nd - t->nd);
|
||||
if (ti < 0) { s[i] = 0; continue; }
|
||||
s[i] = (t->shape[ti] == 1 && oshape[i] != 1) ? 0 : st;
|
||||
st *= t->shape[ti];
|
||||
}
|
||||
}
|
||||
|
||||
static bool bcast(const TbTensor* a, const TbTensor* b, Bcast* bc) {
|
||||
bc->nd = a->nd > b->nd ? a->nd : b->nd;
|
||||
for (int i = 0; i < bc->nd; i++) {
|
||||
int ia = i - (bc->nd - a->nd), ib = i - (bc->nd - b->nd);
|
||||
int da = ia >= 0 ? a->shape[ia] : 1, db = ib >= 0 ? b->shape[ib] : 1;
|
||||
if (da != db && da != 1 && db != 1) {
|
||||
char sa[64], sb[64];
|
||||
tt_shape_text(a, sa, sizeof(sa)); tt_shape_text(b, sb, sizeof(sb));
|
||||
tt_set_error("formas %s e %s não combinam (eixo %d)", sa, sb, i + 1);
|
||||
return false;
|
||||
}
|
||||
bc->shape[i] = da > db ? da : db;
|
||||
}
|
||||
bc->n = tb_tensor_numel(bc->nd, bc->shape);
|
||||
strides_for(a, bc->nd, bc->sa, bc->shape);
|
||||
strides_for(b, bc->nd, bc->sb, bc->shape);
|
||||
bc->same = a->n == bc->n && b->n == bc->n;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Percorre a saida com os deslocamentos de a e de b */
|
||||
#define BCAST_LOOP(bc, ...) \
|
||||
do { \
|
||||
int idx_[TB_TENSOR_MAX_DIMS] = {0}; \
|
||||
long oa = 0, ob = 0; \
|
||||
for (size_t i = 0; i < (bc).n; i++) { \
|
||||
__VA_ARGS__; \
|
||||
for (int d_ = (bc).nd - 1; d_ >= 0; d_--) { \
|
||||
oa += (bc).sa[d_]; ob += (bc).sb[d_]; \
|
||||
if (++idx_[d_] < (bc).shape[d_]) break; \
|
||||
oa -= (bc).sa[d_] * (bc).shape[d_]; \
|
||||
ob -= (bc).sb[d_] * (bc).shape[d_]; \
|
||||
idx_[d_] = 0; \
|
||||
} \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
static void binary_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0); TbTensor* b = IN(out, 1);
|
||||
float* ga = G(a); float* gb = G(b);
|
||||
const float* g = out->g;
|
||||
int op = out->node.ik[0];
|
||||
Bcast bc;
|
||||
bcast(a, b, &bc);
|
||||
if (bc.same) {
|
||||
for (size_t i = 0; i < bc.n; i++) {
|
||||
float x = a->d[i], y = b->d[i], gi = g[i];
|
||||
switch (op) {
|
||||
case TT_ADD: if (ga) ga[i] += gi; if (gb) gb[i] += gi; break;
|
||||
case TT_SUB: if (ga) ga[i] += gi; if (gb) gb[i] -= gi; break;
|
||||
case TT_MUL: if (ga) ga[i] += gi * y; if (gb) gb[i] += gi * x; break;
|
||||
default: if (ga) ga[i] += gi / y; if (gb) gb[i] -= gi * x / (y * y); break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
BCAST_LOOP(bc, {
|
||||
float x = a->d[oa], y = b->d[ob], gi = g[i];
|
||||
switch (op) {
|
||||
case TT_ADD: if (ga) ga[oa] += gi; if (gb) gb[ob] += gi; break;
|
||||
case TT_SUB: if (ga) ga[oa] += gi; if (gb) gb[ob] -= gi; break;
|
||||
case TT_MUL: if (ga) ga[oa] += gi * y; if (gb) gb[ob] += gi * x; break;
|
||||
default: if (ga) ga[oa] += gi / y; if (gb) gb[ob] -= gi * x / (y * y); break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
TbTensor* tt_binary(TbTensor* a, TbTensor* b, int op) {
|
||||
Bcast bc;
|
||||
if (!bcast(a, b, &bc)) return NULL;
|
||||
TbTensor* o = tt_alloc(bc.nd, bc.shape);
|
||||
if (!o) return NULL;
|
||||
float* r = o->d;
|
||||
if (bc.same) {
|
||||
const float* x = a->d; const float* y = b->d;
|
||||
switch (op) {
|
||||
case TT_ADD: for (size_t i = 0; i < bc.n; i++) r[i] = x[i] + y[i]; break;
|
||||
case TT_SUB: for (size_t i = 0; i < bc.n; i++) r[i] = x[i] - y[i]; break;
|
||||
case TT_MUL: for (size_t i = 0; i < bc.n; i++) r[i] = x[i] * y[i]; break;
|
||||
default: for (size_t i = 0; i < bc.n; i++) r[i] = x[i] / y[i]; break;
|
||||
}
|
||||
} else {
|
||||
BCAST_LOOP(bc, {
|
||||
float x = a->d[oa], y = b->d[ob];
|
||||
r[i] = op == TT_ADD ? x + y : op == TT_SUB ? x - y : op == TT_MUL ? x * y : x / y;
|
||||
});
|
||||
}
|
||||
TbTensor* in[2] = { a, b };
|
||||
tt_link(o, binary_backward, in, 2, NULL, NULL);
|
||||
o->node.ik[0] = op;
|
||||
return o;
|
||||
}
|
||||
|
||||
TbTensor* tt_add(TbTensor* a, TbTensor* b) { return tt_binary(a, b, TT_ADD); }
|
||||
TbTensor* tt_sub(TbTensor* a, TbTensor* b) { return tt_binary(a, b, TT_SUB); }
|
||||
TbTensor* tt_mul(TbTensor* a, TbTensor* b) { return tt_binary(a, b, TT_MUL); }
|
||||
TbTensor* tt_div(TbTensor* a, TbTensor* b) { return tt_binary(a, b, TT_DIV); }
|
||||
|
||||
/* == Escala, potencia e funcoes de um argumento ======================= */
|
||||
static void scale_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a); float k = out->node.fk[0];
|
||||
for (size_t i = 0; i < a->n; i++) ga[i] += out->g[i] * k;
|
||||
}
|
||||
|
||||
TbTensor* tt_scale(TbTensor* a, float k) {
|
||||
TbTensor* o = tt_alloc_like(a);
|
||||
if (!o) return NULL;
|
||||
for (size_t i = 0; i < a->n; i++) o->d[i] = a->d[i] * k;
|
||||
tt_link(o, scale_backward, &a, 1, NULL, NULL);
|
||||
o->node.fk[0] = k;
|
||||
return o;
|
||||
}
|
||||
|
||||
static void powk_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a); float p = out->node.fk[0];
|
||||
for (size_t i = 0; i < a->n; i++) ga[i] += out->g[i] * p * powf(a->d[i], p - 1);
|
||||
}
|
||||
|
||||
TbTensor* tt_powk(TbTensor* a, float p) {
|
||||
TbTensor* o = tt_alloc_like(a);
|
||||
if (!o) return NULL;
|
||||
for (size_t i = 0; i < a->n; i++) o->d[i] = powf(a->d[i], p);
|
||||
tt_link(o, powk_backward, &a, 1, NULL, NULL);
|
||||
o->node.fk[0] = p;
|
||||
return o;
|
||||
}
|
||||
|
||||
static void unary_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a);
|
||||
for (size_t i = 0; i < a->n; i++) {
|
||||
float x = a->d[i], y = out->d[i], d;
|
||||
switch (out->node.ik[0]) {
|
||||
case TT_EXP: d = y; break;
|
||||
case TT_LOG: d = 1.0f / x; break;
|
||||
case TT_SQRT: d = y > 0 ? 0.5f / y : 0; break;
|
||||
default: d = x > 0 ? 1.f : x < 0 ? -1.f : 0.f; break;
|
||||
}
|
||||
ga[i] += out->g[i] * d;
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* tt_unary(TbTensor* a, int op) {
|
||||
TbTensor* o = tt_alloc_like(a);
|
||||
if (!o) return NULL;
|
||||
for (size_t i = 0; i < a->n; i++) {
|
||||
float x = a->d[i];
|
||||
o->d[i] = op == TT_EXP ? expf(x) : op == TT_LOG ? logf(x) : op == TT_SQRT ? sqrtf(x) : fabsf(x);
|
||||
}
|
||||
tt_link(o, unary_backward, &a, 1, NULL, NULL);
|
||||
o->node.ik[0] = op;
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Produto de matrizes ==============================================
|
||||
* a [..., m, k] @ b [..., k, n]. Os eixos de lote tem de ser iguais, ou b
|
||||
* ter so 2 eixos (pesos compartilhados: vira um GEMM so), ou a ter so 2. */
|
||||
typedef struct { int batch, m, n, k; bool b_shared, a_shared; } MatShape;
|
||||
|
||||
static bool mat_shape(const TbTensor* a, const TbTensor* b, MatShape* s, int* nd, int* shape) {
|
||||
if (a->nd < 2 || b->nd < 2) { tt_set_error("produto de matrizes precisa de tensores com 2 eixos ou mais"); return false; }
|
||||
s->m = a->shape[a->nd - 2]; s->k = a->shape[a->nd - 1];
|
||||
s->n = b->shape[b->nd - 1];
|
||||
if (b->shape[b->nd - 2] != s->k) {
|
||||
char sa[64], sb[64]; tt_shape_text(a, sa, sizeof(sa)); tt_shape_text(b, sb, sizeof(sb));
|
||||
tt_set_error("produto %s @ %s: as colunas da primeira (%d) têm de ser as linhas da segunda (%d)",
|
||||
sa, sb, s->k, b->shape[b->nd - 2]);
|
||||
return false;
|
||||
}
|
||||
s->b_shared = b->nd == 2;
|
||||
s->a_shared = !s->b_shared && a->nd == 2;
|
||||
const TbTensor* big = s->a_shared ? b : a;
|
||||
if (!s->b_shared && !s->a_shared) {
|
||||
bool ok = a->nd == b->nd;
|
||||
for (int i = 0; ok && i < a->nd - 2; i++) ok = a->shape[i] == b->shape[i];
|
||||
if (!ok) { tt_set_error("produto de matrizes: os eixos de lote têm de ser iguais"); return false; }
|
||||
}
|
||||
s->batch = 1;
|
||||
for (int i = 0; i < big->nd - 2; i++) s->batch *= big->shape[i];
|
||||
*nd = big->nd;
|
||||
for (int i = 0; i < big->nd - 2; i++) shape[i] = big->shape[i];
|
||||
shape[*nd - 2] = s->m; shape[*nd - 1] = s->n;
|
||||
if (s->b_shared) { s->m *= s->batch; s->batch = 1; } /* um GEMM so */
|
||||
return true;
|
||||
}
|
||||
|
||||
static void matmul_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0); TbTensor* b = IN(out, 1);
|
||||
MatShape s; int nd, shape[TB_TENSOR_MAX_DIMS];
|
||||
mat_shape(a, b, &s, &nd, shape);
|
||||
float* ga = G(a); float* gb = G(b);
|
||||
size_t as = s.a_shared ? 0 : (size_t)s.m * s.k, bs = s.b_shared ? 0 : (size_t)s.k * s.n, os = (size_t)s.m * s.n;
|
||||
for (int t = 0; t < s.batch; t++) {
|
||||
const float* g = out->g + t * os;
|
||||
if (ga) tt_gemm(false, true, s.m, s.k, s.n, 1.f, g, s.n, b->d + t * bs, s.n, 1.f, ga + t * as, s.k);
|
||||
if (gb) tt_gemm(true, false, s.k, s.n, s.m, 1.f, a->d + t * as, s.k, g, s.n, 1.f, gb + t * bs, s.n);
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* tt_matmul(TbTensor* a, TbTensor* b) {
|
||||
MatShape s; int nd, shape[TB_TENSOR_MAX_DIMS];
|
||||
if (!mat_shape(a, b, &s, &nd, shape)) return NULL;
|
||||
TbTensor* o = tt_alloc(nd, shape);
|
||||
if (!o) return NULL;
|
||||
size_t as = s.a_shared ? 0 : (size_t)s.m * s.k, bs = s.b_shared ? 0 : (size_t)s.k * s.n, os = (size_t)s.m * s.n;
|
||||
for (int t = 0; t < s.batch; t++)
|
||||
tt_gemm(false, false, s.m, s.n, s.k, 1.f, a->d + t * as, s.k, b->d + t * bs, s.n, 0.f, o->d + t * os, s.n);
|
||||
TbTensor* in[2] = { a, b };
|
||||
tt_link(o, matmul_backward, in, 2, NULL, NULL);
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Forma ============================================================ */
|
||||
static void same_n_backward(TbTensor* out) { /* reshape / flatten */
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a);
|
||||
for (size_t i = 0; i < a->n; i++) ga[i] += out->g[i];
|
||||
}
|
||||
|
||||
TbTensor* tt_reshape(TbTensor* a, int nd, const int* shape) {
|
||||
int s[TB_TENSOR_MAX_DIMS], free_ax = -1;
|
||||
size_t known = 1;
|
||||
if (nd < 0 || nd > TB_TENSOR_MAX_DIMS) { tt_set_error("forma com %d eixos", nd); return NULL; }
|
||||
for (int i = 0; i < nd; i++) {
|
||||
s[i] = shape[i];
|
||||
if (s[i] == -1) {
|
||||
if (free_ax >= 0) { tt_set_error("só um eixo pode ser -1 na forma"); return NULL; }
|
||||
free_ax = i;
|
||||
} else known *= (size_t)s[i];
|
||||
}
|
||||
if (free_ax >= 0) {
|
||||
if (!known || a->n % known) { tt_set_error("não dá para deduzir o eixo -1 (%zu números)", a->n); return NULL; }
|
||||
s[free_ax] = (int)(a->n / known);
|
||||
known *= (size_t)s[free_ax];
|
||||
}
|
||||
if (known != a->n) {
|
||||
char sa[64]; tt_shape_text(a, sa, sizeof(sa));
|
||||
tt_set_error("a forma nova tem %zu números e o tensor %s tem %zu", known, sa, a->n);
|
||||
return NULL;
|
||||
}
|
||||
TbTensor* o = tt_alloc(nd, s);
|
||||
if (!o) return NULL;
|
||||
memcpy(o->d, a->d, a->n * sizeof(float));
|
||||
tt_link(o, same_n_backward, &a, 1, NULL, NULL);
|
||||
return o;
|
||||
}
|
||||
|
||||
TbTensor* tt_flatten(TbTensor* a) {
|
||||
if (a->nd < 2) return tt_reshape(a, 1, (int[]){ (int)a->n });
|
||||
int s[2] = { a->shape[0], -1 };
|
||||
return tt_reshape(a, 2, s);
|
||||
}
|
||||
|
||||
/* Copia (ou soma, acc) a com os eixos ax1 e ax2 trocados em dst */
|
||||
static void swap_copy(const float* src, float* dst, int nd, const int* shape, int ax1, int ax2, bool acc) {
|
||||
long st[TB_TENSOR_MAX_DIMS] = {0}, s = 1;
|
||||
for (int i = nd - 1; i >= 0; i--) { st[i] = s; s *= shape[i]; }
|
||||
int oshape[TB_TENSOR_MAX_DIMS]; long ost[TB_TENSOR_MAX_DIMS];
|
||||
for (int i = 0; i < nd; i++) { oshape[i] = shape[i]; ost[i] = st[i]; }
|
||||
oshape[ax1] = shape[ax2]; oshape[ax2] = shape[ax1];
|
||||
ost[ax1] = st[ax2]; ost[ax2] = st[ax1]; /* passo na origem para cada eixo da saida */
|
||||
size_t n = tb_tensor_numel(nd, shape);
|
||||
int idx[TB_TENSOR_MAX_DIMS] = {0};
|
||||
long off = 0;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (acc) dst[i] += src[off]; else dst[i] = src[off];
|
||||
for (int d = nd - 1; d >= 0; d--) {
|
||||
off += ost[d];
|
||||
if (++idx[d] < oshape[d]) break;
|
||||
off -= ost[d] * oshape[d];
|
||||
idx[d] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void transpose_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a);
|
||||
swap_copy(out->g, ga, out->nd, out->shape, out->node.ik[0], out->node.ik[1], true);
|
||||
}
|
||||
|
||||
TbTensor* tt_transpose(TbTensor* a, int ax1, int ax2) {
|
||||
if ((ax1 = norm_axis(a, ax1)) < 0 || (ax2 = norm_axis(a, ax2)) < 0) return NULL;
|
||||
int s[TB_TENSOR_MAX_DIMS];
|
||||
for (int i = 0; i < a->nd; i++) s[i] = a->shape[i];
|
||||
s[ax1] = a->shape[ax2]; s[ax2] = a->shape[ax1];
|
||||
TbTensor* o = tt_alloc(a->nd, s);
|
||||
if (!o) return NULL;
|
||||
swap_copy(a->d, o->d, a->nd, a->shape, ax1, ax2, false);
|
||||
tt_link(o, transpose_backward, &a, 1, NULL, NULL);
|
||||
o->node.ik[0] = ax1; o->node.ik[1] = ax2;
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Fatias e junção ================================================== */
|
||||
static void slice_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a);
|
||||
int axis = out->node.ik[0], from = out->node.ik[1];
|
||||
size_t outer, inner; int len;
|
||||
split_axis(a, axis, &outer, &len, &inner);
|
||||
int olen = out->shape[axis];
|
||||
for (size_t o = 0; o < outer; o++)
|
||||
for (int k = 0; k < olen; k++) {
|
||||
float* dst = ga + (o * len + from + k) * inner;
|
||||
const float* src = out->g + (o * olen + k) * inner;
|
||||
for (size_t i = 0; i < inner; i++) dst[i] += src[i];
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* tt_slice(TbTensor* a, int axis, int from, int to) {
|
||||
if ((axis = norm_axis(a, axis)) < 0) return NULL;
|
||||
int len = a->shape[axis];
|
||||
if (from < 0) from = 0;
|
||||
if (to > len) to = len;
|
||||
if (from >= to) { tt_set_error("fatia vazia (de %d até %d num eixo de %d)", from + 1, to, len); return NULL; }
|
||||
int s[TB_TENSOR_MAX_DIMS];
|
||||
for (int i = 0; i < a->nd; i++) s[i] = a->shape[i];
|
||||
s[axis] = to - from;
|
||||
TbTensor* o = tt_alloc(a->nd, s);
|
||||
if (!o) return NULL;
|
||||
size_t outer, inner; int l;
|
||||
split_axis(a, axis, &outer, &l, &inner);
|
||||
for (size_t k = 0; k < outer; k++)
|
||||
memcpy(o->d + k * (size_t)(to - from) * inner, a->d + (k * len + from) * inner,
|
||||
(size_t)(to - from) * inner * sizeof(float));
|
||||
tt_link(o, slice_backward, &a, 1, NULL, NULL);
|
||||
o->node.ik[0] = axis; o->node.ik[1] = from;
|
||||
return o;
|
||||
}
|
||||
|
||||
static void concat_backward(TbTensor* out) {
|
||||
int axis = out->node.ik[0];
|
||||
size_t outer, inner; int len;
|
||||
split_axis(out, axis, &outer, &len, &inner);
|
||||
int off = 0;
|
||||
for (int w = 0; w < 2; w++) {
|
||||
TbTensor* t = IN(out, w);
|
||||
float* gt = G(t);
|
||||
int tl = t->shape[axis];
|
||||
if (gt)
|
||||
for (size_t o = 0; o < outer; o++) {
|
||||
const float* src = out->g + (o * len + off) * inner;
|
||||
float* dst = gt + o * tl * inner;
|
||||
for (size_t i = 0; i < (size_t)tl * inner; i++) dst[i] += src[i];
|
||||
}
|
||||
off += tl;
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* tt_concat(TbTensor* a, TbTensor* b, int axis) {
|
||||
if ((axis = norm_axis(a, axis)) < 0) return NULL;
|
||||
bool ok = a->nd == b->nd;
|
||||
for (int i = 0; ok && i < a->nd; i++) ok = i == axis || a->shape[i] == b->shape[i];
|
||||
if (!ok) {
|
||||
char sa[64], sb[64]; tt_shape_text(a, sa, sizeof(sa)); tt_shape_text(b, sb, sizeof(sb));
|
||||
tt_set_error("não dá para juntar %s e %s no eixo %d (os outros eixos têm de ser iguais)", sa, sb, axis + 1);
|
||||
return NULL;
|
||||
}
|
||||
int s[TB_TENSOR_MAX_DIMS];
|
||||
for (int i = 0; i < a->nd; i++) s[i] = a->shape[i];
|
||||
s[axis] = a->shape[axis] + b->shape[axis];
|
||||
TbTensor* o = tt_alloc(a->nd, s);
|
||||
if (!o) return NULL;
|
||||
size_t outer, inner; int len;
|
||||
split_axis(o, axis, &outer, &len, &inner);
|
||||
size_t na = (size_t)a->shape[axis] * inner, nb = (size_t)b->shape[axis] * inner;
|
||||
for (size_t k = 0; k < outer; k++) {
|
||||
memcpy(o->d + k * (na + nb), a->d + k * na, na * sizeof(float));
|
||||
memcpy(o->d + k * (na + nb) + na, b->d + k * nb, nb * sizeof(float));
|
||||
}
|
||||
TbTensor* in[2] = { a, b };
|
||||
tt_link(o, concat_backward, in, 2, NULL, NULL);
|
||||
o->node.ik[0] = axis;
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Reducoes ========================================================= */
|
||||
static void reduce_shape(const TbTensor* a, int axis, bool keep, int* nd, int* s) {
|
||||
if (axis < 0) { /* tudo */
|
||||
*nd = keep ? a->nd : 0;
|
||||
for (int i = 0; i < *nd; i++) s[i] = 1;
|
||||
return;
|
||||
}
|
||||
*nd = 0;
|
||||
for (int i = 0; i < a->nd; i++) {
|
||||
if (i == axis) { if (keep) s[(*nd)++] = 1; }
|
||||
else s[(*nd)++] = a->shape[i];
|
||||
}
|
||||
}
|
||||
|
||||
static void sum_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a);
|
||||
int axis = out->node.ik[0];
|
||||
float k = out->node.fk[0]; /* 1 (soma) ou 1/len (media) */
|
||||
if (axis < 0) { for (size_t i = 0; i < a->n; i++) ga[i] += out->g[0] * k; return; }
|
||||
size_t outer, inner; int len;
|
||||
split_axis(a, axis, &outer, &len, &inner);
|
||||
for (size_t o = 0; o < outer; o++)
|
||||
for (int l = 0; l < len; l++)
|
||||
for (size_t i = 0; i < inner; i++)
|
||||
ga[(o * len + l) * inner + i] += out->g[o * inner + i] * k;
|
||||
}
|
||||
|
||||
static TbTensor* reduce_sum(TbTensor* a, int axis, bool keep, bool mean) {
|
||||
if (axis < 0) axis = -1; /* negativo = tudo */
|
||||
else if ((axis = norm_axis(a, axis)) < 0) return NULL;
|
||||
int nd, s[TB_TENSOR_MAX_DIMS] = {0};
|
||||
reduce_shape(a, axis, keep, &nd, s);
|
||||
TbTensor* o = tt_alloc(nd, s);
|
||||
if (!o) return NULL;
|
||||
float k;
|
||||
if (axis < 0) {
|
||||
double acc = 0;
|
||||
for (size_t i = 0; i < a->n; i++) acc += a->d[i];
|
||||
k = mean && a->n ? 1.0f / (float)a->n : 1.0f;
|
||||
o->d[0] = (float)(acc * k);
|
||||
} else {
|
||||
size_t outer, inner; int len;
|
||||
split_axis(a, axis, &outer, &len, &inner);
|
||||
k = mean && len ? 1.0f / (float)len : 1.0f;
|
||||
for (size_t q = 0; q < outer; q++)
|
||||
for (int l = 0; l < len; l++)
|
||||
for (size_t i = 0; i < inner; i++)
|
||||
o->d[q * inner + i] += a->d[(q * len + l) * inner + i];
|
||||
if (k != 1.0f) for (size_t i = 0; i < o->n; i++) o->d[i] *= k;
|
||||
}
|
||||
tt_link(o, sum_backward, &a, 1, NULL, NULL);
|
||||
o->node.ik[0] = axis; o->node.fk[0] = k;
|
||||
return o;
|
||||
}
|
||||
|
||||
TbTensor* tt_sum(TbTensor* a, int axis, bool keep) { return reduce_sum(a, axis, keep, false); }
|
||||
TbTensor* tt_mean(TbTensor* a, int axis, bool keep) { return reduce_sum(a, axis, keep, true); }
|
||||
|
||||
static void max_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a);
|
||||
const int* arg = out->node.ctx;
|
||||
for (size_t i = 0; i < out->n; i++) ga[arg[i]] += out->g[i];
|
||||
}
|
||||
|
||||
TbTensor* tt_max(TbTensor* a, int axis, bool keep) {
|
||||
if ((axis = norm_axis(a, axis)) < 0) return NULL;
|
||||
int nd, s[TB_TENSOR_MAX_DIMS] = {0};
|
||||
reduce_shape(a, axis, keep, &nd, s);
|
||||
TbTensor* o = tt_alloc(nd, s);
|
||||
if (!o) return NULL;
|
||||
int* arg = malloc(o->n * sizeof(int) + 1);
|
||||
size_t outer, inner; int len;
|
||||
split_axis(a, axis, &outer, &len, &inner);
|
||||
for (size_t q = 0; q < outer; q++)
|
||||
for (size_t i = 0; i < inner; i++) {
|
||||
size_t best = q * len * inner + i;
|
||||
for (int l = 1; l < len; l++) {
|
||||
size_t at = (q * len + l) * inner + i;
|
||||
if (a->d[at] > a->d[best]) best = at;
|
||||
}
|
||||
o->d[q * inner + i] = a->d[best];
|
||||
if (arg) arg[q * inner + i] = (int)best;
|
||||
}
|
||||
tt_link(o, max_backward, &a, 1, arg, free);
|
||||
return o;
|
||||
}
|
||||
|
||||
TbTensor* tt_argmax(TbTensor* a, int axis) {
|
||||
if ((axis = norm_axis(a, axis)) < 0) return NULL;
|
||||
int nd, s[TB_TENSOR_MAX_DIMS] = {0};
|
||||
reduce_shape(a, axis, false, &nd, s);
|
||||
TbTensor* o = tt_alloc(nd, s);
|
||||
if (!o) return NULL;
|
||||
size_t outer, inner; int len;
|
||||
split_axis(a, axis, &outer, &len, &inner);
|
||||
for (size_t q = 0; q < outer; q++)
|
||||
for (size_t i = 0; i < inner; i++) {
|
||||
int best = 0;
|
||||
for (int l = 1; l < len; l++)
|
||||
if (a->d[(q * len + l) * inner + i] > a->d[(q * len + best) * inner + i]) best = l;
|
||||
o->d[q * inner + i] = (float)(best + 1);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/* == Indices ========================================================== */
|
||||
typedef struct { int n; int rows[]; } Rows;
|
||||
|
||||
static void gather_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a);
|
||||
const Rows* r = out->node.ctx;
|
||||
size_t row = a->shape[0] ? a->n / (size_t)a->shape[0] : 0;
|
||||
for (int k = 0; k < r->n; k++) {
|
||||
float* dst = ga + (size_t)r->rows[k] * row;
|
||||
const float* src = out->g + (size_t)k * row;
|
||||
for (size_t i = 0; i < row; i++) dst[i] += src[i];
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* tt_gather(TbTensor* a, TbTensor* idx) {
|
||||
if (a->nd < 1) { tt_set_error("\"linhas de\" precisa de um tensor com eixos"); return NULL; }
|
||||
int N = a->shape[0];
|
||||
Rows* r = malloc(sizeof(Rows) + idx->n * sizeof(int));
|
||||
if (!r) { tt_set_error("sem memória"); return NULL; }
|
||||
r->n = (int)idx->n;
|
||||
for (size_t k = 0; k < idx->n; k++) {
|
||||
int p = (int)lroundf(idx->d[k]);
|
||||
if (p < 1 || p > N) { free(r); tt_set_error("linha %d não existe (há %d)", p, N); return NULL; }
|
||||
r->rows[k] = p - 1;
|
||||
}
|
||||
int s[TB_TENSOR_MAX_DIMS];
|
||||
s[0] = r->n;
|
||||
for (int i = 1; i < a->nd; i++) s[i] = a->shape[i];
|
||||
TbTensor* o = tt_alloc(a->nd, s);
|
||||
if (!o) { free(r); return NULL; }
|
||||
size_t row = N ? a->n / (size_t)N : 0;
|
||||
for (int k = 0; k < r->n; k++) memcpy(o->d + (size_t)k * row, a->d + (size_t)r->rows[k] * row, row * sizeof(float));
|
||||
tt_link(o, gather_backward, &a, 1, r, free);
|
||||
return o;
|
||||
}
|
||||
|
||||
TbTensor* tt_where_eq(TbTensor* a, float v) {
|
||||
size_t k = 0;
|
||||
for (size_t i = 0; i < a->n; i++) if (a->d[i] == v) k++;
|
||||
TbTensor* o = tt_alloc(1, (int[]){ (int)k });
|
||||
if (!o) return NULL;
|
||||
k = 0;
|
||||
for (size_t i = 0; i < a->n; i++) if (a->d[i] == v) o->d[k++] = (float)(i + 1);
|
||||
return o;
|
||||
}
|
||||
|
||||
static void flip_backward(TbTensor* out) {
|
||||
TbTensor* a = IN(out, 0);
|
||||
float* ga = G(a);
|
||||
size_t outer, inner; int len;
|
||||
split_axis(a, out->node.ik[0], &outer, &len, &inner);
|
||||
for (size_t q = 0; q < outer; q++)
|
||||
for (int l = 0; l < len; l++)
|
||||
for (size_t i = 0; i < inner; i++)
|
||||
ga[(q * len + l) * inner + i] += out->g[(q * len + (len - 1 - l)) * inner + i];
|
||||
}
|
||||
|
||||
TbTensor* tt_flip(TbTensor* a, int axis) {
|
||||
if ((axis = norm_axis(a, axis)) < 0) return NULL;
|
||||
TbTensor* o = tt_alloc_like(a);
|
||||
if (!o) return NULL;
|
||||
size_t outer, inner; int len;
|
||||
split_axis(a, axis, &outer, &len, &inner);
|
||||
for (size_t q = 0; q < outer; q++)
|
||||
for (int l = 0; l < len; l++)
|
||||
memcpy(o->d + (q * len + l) * inner, a->d + (q * len + (len - 1 - l)) * inner, inner * sizeof(float));
|
||||
tt_link(o, flip_backward, &a, 1, NULL, NULL);
|
||||
o->node.ik[0] = axis;
|
||||
return o;
|
||||
}
|
||||
|
||||
TbTensor* tt_detach(TbTensor* a) {
|
||||
TbTensor* o = tt_alloc_like(a);
|
||||
if (o) memcpy(o->d, a->d, a->n * sizeof(float));
|
||||
return o;
|
||||
}
|
||||
|
||||
TbTensor* tt_permutation(int n) {
|
||||
if (n < 0) { tt_set_error("permutação de %d", n); return NULL; }
|
||||
TbTensor* o = tt_alloc(1, &n);
|
||||
if (!o) return NULL;
|
||||
for (int i = 0; i < n; i++) o->d[i] = (float)(i + 1);
|
||||
for (int i = n - 1; i > 0; i--) {
|
||||
int j = (int)(tt_randu() * (float)(i + 1));
|
||||
if (j > i) j = i;
|
||||
float t = o->d[i]; o->d[i] = o->d[j]; o->d[j] = t;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
/*
|
||||
* TinyBlocks - tensor.c
|
||||
* Nucleo da tinyblocks-tensor: o objeto tensor, erros, numeros aleatorios,
|
||||
* o pool de threads, o GEMM, o autograd, o registro de parametros e os
|
||||
* blocos-handle que levam o tensor de bloco em bloco.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <math.h>
|
||||
#include <pthread.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "tensor_internal.h"
|
||||
|
||||
/* == Erros ============================================================ */
|
||||
static char s_err[256];
|
||||
|
||||
const char* tt_last_error(void) { return s_err; }
|
||||
|
||||
void tt_set_error(const char* fmt, ...) {
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(s_err, sizeof(s_err), fmt, ap);
|
||||
va_end(ap);
|
||||
}
|
||||
|
||||
/* == Objeto tensor ==================================================== */
|
||||
static void node_clear(TbNode* nd) {
|
||||
for (int i = 0; i < nd->n_in; i++) tt_release(nd->in[i]);
|
||||
if (nd->ctx && nd->ctx_free) nd->ctx_free(nd->ctx);
|
||||
memset(nd, 0, sizeof(*nd));
|
||||
}
|
||||
|
||||
static void tensor_destroy(TinyBlocks_Object* o) {
|
||||
TbTensor* t = (TbTensor*)o;
|
||||
node_clear(&t->node);
|
||||
if (t->opt && t->opt_free) t->opt_free(t->opt);
|
||||
free(t->d);
|
||||
free(t->g);
|
||||
free(t);
|
||||
}
|
||||
|
||||
static const TinyBlocks_ObjectClass s_tensor_class = { "tensor", tensor_destroy };
|
||||
|
||||
TbTensor* tt_alloc(int nd, const int* shape) {
|
||||
if (nd < 0 || nd > TB_TENSOR_MAX_DIMS) { tt_set_error("tensor com %d eixos (o máximo é %d)", nd, TB_TENSOR_MAX_DIMS); return NULL; }
|
||||
for (int i = 0; i < nd; i++)
|
||||
if (shape[i] < 0) { tt_set_error("eixo %d com tamanho negativo (%d)", i + 1, shape[i]); return NULL; }
|
||||
size_t n = tb_tensor_numel(nd, shape);
|
||||
if (n > (size_t)1 << 31) { tt_set_error("tensor grande demais (%zu elementos)", n); return NULL; }
|
||||
TbTensor* t = calloc(1, sizeof(TbTensor));
|
||||
if (!t) { tt_set_error("sem memória"); return NULL; }
|
||||
t->d = calloc(n ? n : 1, sizeof(float));
|
||||
if (!t->d) { free(t); tt_set_error("sem memória para %zu números", n); return NULL; }
|
||||
tb_object_init(&t->obj, &s_tensor_class);
|
||||
t->nd = nd;
|
||||
for (int i = 0; i < nd; i++) t->shape[i] = shape[i];
|
||||
t->n = n;
|
||||
return t;
|
||||
}
|
||||
|
||||
TbTensor* tt_alloc_like(const TbTensor* a) { return tt_alloc(a->nd, a->shape); }
|
||||
|
||||
TbTensor* tt_scalar(float v) {
|
||||
TbTensor* t = tt_alloc(0, NULL);
|
||||
if (t) t->d[0] = v;
|
||||
return t;
|
||||
}
|
||||
|
||||
void tt_retain(TbTensor* t) { tb_object_retain(t); }
|
||||
void tt_release(TbTensor* t) { tb_object_release(t); }
|
||||
|
||||
float* tt_grad(TbTensor* t) {
|
||||
if (!t->g) t->g = calloc(t->n ? t->n : 1, sizeof(float));
|
||||
return t->g;
|
||||
}
|
||||
|
||||
int tt_shape_text(const TbTensor* t, char* out, size_t cap) {
|
||||
size_t len = 0;
|
||||
int w = snprintf(out, cap, "[");
|
||||
len += w > 0 ? (size_t)w : 0;
|
||||
for (int i = 0; i < t->nd; i++) {
|
||||
w = snprintf(len < cap ? out + len : NULL, len < cap ? cap - len : 0, "%s%d", i ? ", " : "", t->shape[i]);
|
||||
len += w > 0 ? (size_t)w : 0;
|
||||
}
|
||||
w = snprintf(len < cap ? out + len : NULL, len < cap ? cap - len : 0, "]");
|
||||
len += w > 0 ? (size_t)w : 0;
|
||||
return (int)len;
|
||||
}
|
||||
|
||||
/* == Numeros aleatorios (xoshiro128+, semente fixavel) ================ */
|
||||
static uint32_t s_rng[4] = { 0x9E3779B9u, 0x243F6A88u, 0xB7E15162u, 0x8AED2A6Bu };
|
||||
static bool s_rng_seeded;
|
||||
|
||||
static inline uint32_t rotl(uint32_t x, int k) { return (x << k) | (x >> (32 - k)); }
|
||||
|
||||
static uint32_t rng_next(void) {
|
||||
if (!s_rng_seeded) tt_seed((uint32_t)time(NULL) ^ (uint32_t)getpid());
|
||||
uint32_t r = s_rng[0] + s_rng[3], t = s_rng[1] << 9;
|
||||
s_rng[2] ^= s_rng[0]; s_rng[3] ^= s_rng[1]; s_rng[1] ^= s_rng[2]; s_rng[0] ^= s_rng[3];
|
||||
s_rng[2] ^= t; s_rng[3] = rotl(s_rng[3], 11);
|
||||
return r;
|
||||
}
|
||||
|
||||
void tt_seed(uint32_t seed) {
|
||||
uint64_t z = seed + 0x9E3779B97F4A7C15ull;
|
||||
for (int i = 0; i < 4; i++) { /* splitmix64 */
|
||||
z += 0x9E3779B97F4A7C15ull;
|
||||
uint64_t x = z;
|
||||
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
|
||||
x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
|
||||
s_rng[i] = (uint32_t)(x ^ (x >> 31)) | 1u;
|
||||
}
|
||||
s_rng_seeded = true;
|
||||
}
|
||||
|
||||
float tt_randu(void) { return (float)(rng_next() >> 8) * (1.0f / 16777216.0f); }
|
||||
|
||||
float tt_randn(void) {
|
||||
static bool has;
|
||||
static float spare;
|
||||
if (has) { has = false; return spare; }
|
||||
float u, v, s;
|
||||
do { u = tt_randu() * 2 - 1; v = tt_randu() * 2 - 1; s = u * u + v * v; } while (s >= 1 || s == 0);
|
||||
float m = sqrtf(-2.0f * logf(s) / s);
|
||||
spare = v * m; has = true;
|
||||
return u * m;
|
||||
}
|
||||
|
||||
/* == Pool de threads ================================================== */
|
||||
#define POOL_MAX 32
|
||||
static struct {
|
||||
pthread_t th[POOL_MAX];
|
||||
int n; /* trabalhadores (sem contar quem chama) */
|
||||
pthread_mutex_t mu;
|
||||
pthread_cond_t go, done;
|
||||
unsigned gen; /* muda a cada trabalho novo */
|
||||
int pending; /* trabalhadores ainda ocupados */
|
||||
bool quit;
|
||||
TbParallelFn fn;
|
||||
void* ctx;
|
||||
int total, chunks;
|
||||
int next; /* proxima fatia a pegar */
|
||||
} P;
|
||||
static _Thread_local bool t_in_pool; /* trabalho aninhado roda direto */
|
||||
|
||||
static void run_chunks(void) {
|
||||
for (;;) {
|
||||
pthread_mutex_lock(&P.mu);
|
||||
int c = P.next < P.chunks ? P.next++ : -1;
|
||||
pthread_mutex_unlock(&P.mu);
|
||||
if (c < 0) return;
|
||||
int from = (int)((long long)P.total * c / P.chunks);
|
||||
int to = (int)((long long)P.total * (c + 1) / P.chunks);
|
||||
if (from < to) P.fn(P.ctx, from, to);
|
||||
}
|
||||
}
|
||||
|
||||
static void* worker(void* arg) {
|
||||
(void)arg;
|
||||
t_in_pool = true;
|
||||
unsigned seen = 0;
|
||||
pthread_mutex_lock(&P.mu);
|
||||
for (;;) {
|
||||
while (!P.quit && P.gen == seen) pthread_cond_wait(&P.go, &P.mu);
|
||||
if (P.quit) break;
|
||||
seen = P.gen;
|
||||
pthread_mutex_unlock(&P.mu);
|
||||
run_chunks();
|
||||
pthread_mutex_lock(&P.mu);
|
||||
if (--P.pending == 0) pthread_cond_signal(&P.done);
|
||||
}
|
||||
pthread_mutex_unlock(&P.mu);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void tt_pool_start(void) {
|
||||
if (P.n) return;
|
||||
long cpus = sysconf(_SC_NPROCESSORS_ONLN);
|
||||
int n = cpus > 1 ? (int)cpus - 1 : 0;
|
||||
if (n > POOL_MAX) n = POOL_MAX;
|
||||
pthread_mutex_init(&P.mu, NULL);
|
||||
pthread_cond_init(&P.go, NULL);
|
||||
pthread_cond_init(&P.done, NULL);
|
||||
P.quit = false;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (pthread_create(&P.th[i], NULL, worker, NULL) != 0) break;
|
||||
P.n++;
|
||||
}
|
||||
}
|
||||
|
||||
void tt_pool_stop(void) {
|
||||
if (!P.n) return;
|
||||
pthread_mutex_lock(&P.mu);
|
||||
P.quit = true;
|
||||
pthread_cond_broadcast(&P.go);
|
||||
pthread_mutex_unlock(&P.mu);
|
||||
for (int i = 0; i < P.n; i++) pthread_join(P.th[i], NULL);
|
||||
P.n = 0;
|
||||
pthread_cond_destroy(&P.go);
|
||||
pthread_cond_destroy(&P.done);
|
||||
pthread_mutex_destroy(&P.mu);
|
||||
}
|
||||
|
||||
int tt_pool_size(void) { return P.n + 1; }
|
||||
|
||||
void tt_parallel_for(int n, TbParallelFn fn, void* ctx) {
|
||||
if (n <= 0) return;
|
||||
if (n == 1 || !P.n || t_in_pool) { fn(ctx, 0, n); return; }
|
||||
pthread_mutex_lock(&P.mu);
|
||||
P.fn = fn; P.ctx = ctx; P.total = n;
|
||||
P.chunks = n < (P.n + 1) * 4 ? n : (P.n + 1) * 4;
|
||||
P.next = 0;
|
||||
P.pending = P.n;
|
||||
P.gen++;
|
||||
pthread_cond_broadcast(&P.go);
|
||||
pthread_mutex_unlock(&P.mu);
|
||||
t_in_pool = true;
|
||||
run_chunks();
|
||||
t_in_pool = false;
|
||||
pthread_mutex_lock(&P.mu);
|
||||
while (P.pending > 0) pthread_cond_wait(&P.done, &P.mu);
|
||||
pthread_mutex_unlock(&P.mu);
|
||||
}
|
||||
|
||||
/* == GEMM ============================================================= */
|
||||
/* Nucleo: C[m,n] += A[m,k] B[k,n], tudo contiguo e row-major. Quatro
|
||||
linhas de C por vez reaproveitam cada linha de B; o laco de dentro
|
||||
vetoriza (AVX2/FMA escolhido em execucao, SSE2 nos outros). */
|
||||
__attribute__((target_clones("arch=haswell", "default")))
|
||||
static void kernel(int m, int n, int k, const float* A, int lda, const float* B, int ldb, float* C, int ldc) {
|
||||
enum { KB = 256, NB = 512 };
|
||||
for (int j0 = 0; j0 < n; j0 += NB) {
|
||||
int nj = n - j0 < NB ? n - j0 : NB;
|
||||
for (int p0 = 0; p0 < k; p0 += KB) {
|
||||
int np = k - p0 < KB ? k - p0 : KB;
|
||||
int i = 0;
|
||||
for (; i + 4 <= m; i += 4) {
|
||||
float* c0 = C + (size_t)i * ldc + j0;
|
||||
float* c1 = c0 + ldc;
|
||||
float* c2 = c1 + ldc;
|
||||
float* c3 = c2 + ldc;
|
||||
const float* a0 = A + (size_t)i * lda + p0;
|
||||
for (int p = 0; p < np; p++) {
|
||||
float x0 = a0[p], x1 = a0[lda + p], x2 = a0[2 * lda + p], x3 = a0[3 * lda + p];
|
||||
const float* b = B + (size_t)(p0 + p) * ldb + j0;
|
||||
for (int j = 0; j < nj; j++) {
|
||||
float bj = b[j];
|
||||
c0[j] += x0 * bj; c1[j] += x1 * bj; c2[j] += x2 * bj; c3[j] += x3 * bj;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (; i < m; i++) {
|
||||
float* c = C + (size_t)i * ldc + j0;
|
||||
const float* a = A + (size_t)i * lda + p0;
|
||||
for (int p = 0; p < np; p++) {
|
||||
float x = a[p];
|
||||
const float* b = B + (size_t)(p0 + p) * ldb + j0;
|
||||
for (int j = 0; j < nj; j++) c[j] += x * b[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
typedef struct {
|
||||
int m, n, k; float alpha;
|
||||
const float* A; int lda; const float* B; int ldb; float* C; int ldc;
|
||||
} GemmJob;
|
||||
|
||||
/* Fatias de 4 linhas (o nucleo trabalha de 4 em 4) */
|
||||
static void gemm_rows(void* ctx, int from, int to) {
|
||||
GemmJob* g = ctx;
|
||||
from *= 4; to *= 4;
|
||||
if (to > g->m) to = g->m;
|
||||
if (from >= to) return;
|
||||
kernel(to - from, g->n, g->k, g->A + (size_t)from * g->lda, g->lda, g->B, g->ldb,
|
||||
g->C + (size_t)from * g->ldc, g->ldc);
|
||||
}
|
||||
|
||||
void tt_gemm(bool ta, bool tb, int m, int n, int k, float alpha,
|
||||
const float* A, int lda, const float* B, int ldb,
|
||||
float beta, float* C, int ldc) {
|
||||
if (m <= 0 || n <= 0) return;
|
||||
for (int i = 0; i < m; i++) {
|
||||
float* c = C + (size_t)i * ldc;
|
||||
if (beta == 0.0f) memset(c, 0, (size_t)n * sizeof(float));
|
||||
else if (beta != 1.0f) for (int j = 0; j < n; j++) c[j] *= beta;
|
||||
}
|
||||
if (k <= 0 || alpha == 0.0f) return;
|
||||
/* operandos transpostos ou com alpha viram copias contiguas */
|
||||
float* At = NULL; float* Bt = NULL;
|
||||
if (ta || alpha != 1.0f) {
|
||||
At = malloc((size_t)m * k * sizeof(float));
|
||||
if (!At) return;
|
||||
for (int i = 0; i < m; i++)
|
||||
for (int p = 0; p < k; p++)
|
||||
At[(size_t)i * k + p] = alpha * (ta ? A[(size_t)p * lda + i] : A[(size_t)i * lda + p]);
|
||||
A = At; lda = k;
|
||||
}
|
||||
if (tb) {
|
||||
Bt = malloc((size_t)k * n * sizeof(float));
|
||||
if (!Bt) { free(At); return; }
|
||||
for (int p = 0; p < k; p++)
|
||||
for (int j = 0; j < n; j++) Bt[(size_t)p * n + j] = B[(size_t)j * ldb + p];
|
||||
B = Bt; ldb = n;
|
||||
}
|
||||
GemmJob g = { m, n, k, 1.0f, A, lda, B, ldb, C, ldc };
|
||||
double work = (double)m * n * k;
|
||||
int groups = (m + 3) / 4;
|
||||
if (work > 2e5 && groups >= 2) tt_parallel_for(groups, gemm_rows, &g);
|
||||
else gemm_rows(&g, 0, groups);
|
||||
free(At); free(Bt);
|
||||
}
|
||||
|
||||
/* == Autograd ========================================================= */
|
||||
static bool s_grad_on = true;
|
||||
|
||||
bool tt_grad_enabled(void) { return s_grad_on; }
|
||||
void tt_set_grad_enabled(bool on) { s_grad_on = on; }
|
||||
|
||||
void tt_link(TbTensor* out, TbBackwardFn bw, TbTensor* const* in, int n, void* ctx, void (*ctx_free)(void*)) {
|
||||
bool need = false;
|
||||
if (s_grad_on) for (int i = 0; i < n; i++) if (in[i] && in[i]->req) need = true;
|
||||
if (!need || !out) {
|
||||
if (ctx && ctx_free) ctx_free(ctx);
|
||||
return;
|
||||
}
|
||||
node_clear(&out->node);
|
||||
out->req = true;
|
||||
out->node.backward = bw;
|
||||
out->node.n_in = n;
|
||||
for (int i = 0; i < n; i++) { out->node.in[i] = in[i]; if (in[i]) tt_retain(in[i]); }
|
||||
out->node.ctx = ctx;
|
||||
out->node.ctx_free = ctx_free;
|
||||
}
|
||||
|
||||
/* Ordem topologica (pos-ordem) a partir da raiz, sem recursao */
|
||||
static uint32_t s_visit = 1;
|
||||
|
||||
static TbTensor** topo(TbTensor* root, int* count) {
|
||||
int cap = 256, n = 0, sp = 0, scap = 256;
|
||||
TbTensor** order = malloc((size_t)cap * sizeof(*order));
|
||||
struct { TbTensor* t; int next; }* st = malloc((size_t)scap * sizeof(*st));
|
||||
if (!order || !st) { free(order); free(st); *count = 0; return NULL; }
|
||||
uint32_t mark = ++s_visit;
|
||||
root->visit = mark;
|
||||
st[sp].t = root; st[sp].next = 0; sp++;
|
||||
while (sp > 0) {
|
||||
TbTensor* t = st[sp - 1].t;
|
||||
if (st[sp - 1].next < t->node.n_in) {
|
||||
TbTensor* c = t->node.in[st[sp - 1].next++];
|
||||
if (c && c->req && c->visit != mark) {
|
||||
c->visit = mark;
|
||||
if (sp == scap) { scap *= 2; void* p = realloc(st, (size_t)scap * sizeof(*st)); if (!p) break; st = p; }
|
||||
st[sp].t = c; st[sp].next = 0; sp++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
sp--;
|
||||
if (n == cap) { cap *= 2; void* p = realloc(order, (size_t)cap * sizeof(*order)); if (!p) break; order = p; }
|
||||
order[n++] = t;
|
||||
}
|
||||
free(st);
|
||||
*count = n;
|
||||
return order;
|
||||
}
|
||||
|
||||
bool tt_backward(TbTensor* root) {
|
||||
if (!root->req) { tt_set_error("a perda não depende de nenhum parâmetro (nada a derivar)"); return false; }
|
||||
int n = 0;
|
||||
TbTensor** order = topo(root, &n);
|
||||
if (!order) { tt_set_error("sem memória no backward"); return false; }
|
||||
/* os intermediarios comecam do zero; os parametros acumulam */
|
||||
for (int i = 0; i < n; i++)
|
||||
if (order[i]->node.backward && order[i]->g) memset(order[i]->g, 0, order[i]->n * sizeof(float));
|
||||
float* g = tt_grad(root);
|
||||
if (!g) { free(order); return false; }
|
||||
for (size_t i = 0; i < root->n; i++) g[i] += 1.0f;
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
TbTensor* t = order[i];
|
||||
if (t->node.backward && t->g) t->node.backward(t);
|
||||
}
|
||||
free(order);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* == Parametros ======================================================= */
|
||||
typedef struct { TinyBlocks_Block* owner; int slot; TbTensor* t; char group[32]; } Param;
|
||||
static char s_group[32]; /* grupo dos parametros que nascerem agora */
|
||||
static Param* s_params;
|
||||
static int s_param_n, s_param_cap;
|
||||
|
||||
/* Dados carregados de arquivo esperando o parametro nascer (pela ordem) */
|
||||
static TbTensor** s_pending;
|
||||
static int s_pending_n;
|
||||
|
||||
static void param_fill(TbTensor* t, int init, float scale) {
|
||||
for (size_t i = 0; i < t->n; i++) {
|
||||
switch (init) {
|
||||
case TB_INIT_ONES: t->d[i] = scale; break;
|
||||
case TB_INIT_NORMAL: t->d[i] = tt_randn() * scale; break;
|
||||
case TB_INIT_UNIFORM: t->d[i] = (tt_randu() * 2 - 1) * scale; break;
|
||||
default: t->d[i] = 0; break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TbTensor* tt_param(TinyBlocks_Block* owner, int slot, int nd, const int* shape, int init, float scale) {
|
||||
for (int i = 0; i < s_param_n; i++)
|
||||
if (s_params[i].owner == owner && s_params[i].slot == slot) {
|
||||
TbTensor* t = s_params[i].t;
|
||||
bool same = t->nd == nd;
|
||||
for (int k = 0; same && k < nd; k++) same = t->shape[k] == shape[k];
|
||||
if (same) return t;
|
||||
tt_set_error("a forma da entrada mudou depois que a camada criou os parâmetros");
|
||||
return NULL;
|
||||
}
|
||||
TbTensor* t = tt_alloc(nd, shape);
|
||||
if (!t) return NULL;
|
||||
t->req = t->param = true;
|
||||
param_fill(t, init, scale);
|
||||
int idx = s_param_n;
|
||||
if (idx < s_pending_n && s_pending[idx] && s_pending[idx]->n == t->n) {
|
||||
memcpy(t->d, s_pending[idx]->d, t->n * sizeof(float)); /* carregado antes */
|
||||
tt_release(s_pending[idx]);
|
||||
s_pending[idx] = NULL;
|
||||
}
|
||||
if (s_param_n == s_param_cap) {
|
||||
int nc = s_param_cap ? s_param_cap * 2 : 64;
|
||||
Param* p = realloc(s_params, (size_t)nc * sizeof(*p));
|
||||
if (!p) { tt_release(t); tt_set_error("sem memória"); return NULL; }
|
||||
s_params = p; s_param_cap = nc;
|
||||
}
|
||||
s_params[s_param_n] = (Param){ owner, slot, t, "" };
|
||||
snprintf(s_params[s_param_n].group, sizeof(s_params[s_param_n].group), "%s", s_group);
|
||||
s_param_n++;
|
||||
return t;
|
||||
}
|
||||
|
||||
void tt_params_release(TinyBlocks_Block* owner) {
|
||||
int k = 0;
|
||||
for (int i = 0; i < s_param_n; i++) {
|
||||
if (s_params[i].owner == owner) { tt_release(s_params[i].t); continue; }
|
||||
s_params[k++] = s_params[i];
|
||||
}
|
||||
s_param_n = k;
|
||||
}
|
||||
|
||||
int tt_param_count(void) { return s_param_n; }
|
||||
TbTensor* tt_param_at(int i) { return i >= 0 && i < s_param_n ? s_params[i].t : NULL; }
|
||||
|
||||
const char* tt_param_group(int i) { return i >= 0 && i < s_param_n ? s_params[i].group : ""; }
|
||||
|
||||
void tt_set_param_group(const char* name) { snprintf(s_group, sizeof(s_group), "%s", name ? name : ""); }
|
||||
|
||||
void tt_params_zero_grad(const char* group) {
|
||||
for (int i = 0; i < s_param_n; i++) {
|
||||
if (group && group[0] && strcmp(group, s_params[i].group) != 0) continue;
|
||||
if (s_params[i].t->g) memset(s_params[i].t->g, 0, s_params[i].t->n * sizeof(float));
|
||||
}
|
||||
}
|
||||
|
||||
size_t tt_params_numel(void) {
|
||||
size_t n = 0;
|
||||
for (int i = 0; i < s_param_n; i++) n += s_params[i].t->n;
|
||||
return n;
|
||||
}
|
||||
|
||||
/* == Arquivo .tbt =====================================================
|
||||
* "TBT1", numero de tensores (u32) e, para cada um: eixos (u32), forma
|
||||
* (u32 cada) e os floats. Um tensor = 1; parametros = varios. */
|
||||
static bool write_tensor(FILE* f, const TbTensor* t) {
|
||||
uint32_t nd = (uint32_t)t->nd;
|
||||
if (fwrite(&nd, 4, 1, f) != 1) return false;
|
||||
for (int i = 0; i < t->nd; i++) { uint32_t s = (uint32_t)t->shape[i]; if (fwrite(&s, 4, 1, f) != 1) return false; }
|
||||
return fwrite(t->d, sizeof(float), t->n, f) == t->n;
|
||||
}
|
||||
|
||||
static TbTensor* read_tensor(FILE* f) {
|
||||
uint32_t nd;
|
||||
if (fread(&nd, 4, 1, f) != 1 || nd > TB_TENSOR_MAX_DIMS) return NULL;
|
||||
int shape[TB_TENSOR_MAX_DIMS];
|
||||
for (uint32_t i = 0; i < nd; i++) { uint32_t s; if (fread(&s, 4, 1, f) != 1) return NULL; shape[i] = (int)s; }
|
||||
TbTensor* t = tt_alloc((int)nd, shape);
|
||||
if (!t) return NULL;
|
||||
if (fread(t->d, sizeof(float), t->n, f) != t->n) { tt_release(t); return NULL; }
|
||||
return t;
|
||||
}
|
||||
|
||||
bool tt_save(const char* path, TbTensor* const* ts, int n) {
|
||||
tt_mkdirs_for(path);
|
||||
FILE* f = fopen(path, "wb");
|
||||
if (!f) { tt_set_error("não abriu '%s' para gravar", path); return false; }
|
||||
uint32_t cnt = (uint32_t)n;
|
||||
bool ok = fwrite("TBT1", 4, 1, f) == 1 && fwrite(&cnt, 4, 1, f) == 1;
|
||||
for (int i = 0; ok && i < n; i++) ok = write_tensor(f, ts[i]);
|
||||
ok = fclose(f) == 0 && ok;
|
||||
if (!ok) tt_set_error("falha ao gravar '%s'", path);
|
||||
return ok;
|
||||
}
|
||||
|
||||
TbTensor** tt_load(const char* path, int* n) {
|
||||
*n = 0;
|
||||
FILE* f = fopen(path, "rb");
|
||||
if (!f) { tt_set_error("não abriu '%s'", path); return NULL; }
|
||||
char magic[4]; uint32_t cnt = 0;
|
||||
if (fread(magic, 4, 1, f) != 1 || memcmp(magic, "TBT1", 4) != 0 || fread(&cnt, 4, 1, f) != 1 || cnt > 1u << 20) {
|
||||
fclose(f); tt_set_error("'%s' não é um arquivo de tensores (.tbt)", path); return NULL;
|
||||
}
|
||||
TbTensor** ts = calloc(cnt ? cnt : 1, sizeof(*ts));
|
||||
for (uint32_t i = 0; ts && i < cnt; i++) {
|
||||
ts[i] = read_tensor(f);
|
||||
if (!ts[i]) {
|
||||
for (uint32_t k = 0; k < i; k++) tt_release(ts[k]);
|
||||
free(ts); fclose(f);
|
||||
tt_set_error("'%s' está cortado ou corrompido", path);
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
*n = (int)cnt;
|
||||
return ts;
|
||||
}
|
||||
|
||||
bool tt_params_save(const char* path) {
|
||||
TbTensor** ts = malloc((size_t)(s_param_n ? s_param_n : 1) * sizeof(*ts));
|
||||
if (!ts) return false;
|
||||
for (int i = 0; i < s_param_n; i++) ts[i] = s_params[i].t;
|
||||
bool ok = tt_save(path, ts, s_param_n);
|
||||
free(ts);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* Copia para os parametros que ja existem e guarda o resto para quando as
|
||||
camadas os criarem (na mesma ordem). */
|
||||
bool tt_params_load(const char* path) {
|
||||
int n = 0;
|
||||
TbTensor** ts = tt_load(path, &n);
|
||||
if (!ts) return false;
|
||||
for (int i = 0; i < s_pending_n; i++) tt_release(s_pending[i]);
|
||||
free(s_pending);
|
||||
s_pending = NULL; s_pending_n = 0;
|
||||
for (int i = 0; i < n && i < s_param_n; i++) {
|
||||
TbTensor* p = s_params[i].t;
|
||||
if (p->n != ts[i]->n) {
|
||||
tt_set_error("parâmetro %d: o arquivo tem %zu números e a camada %zu", i + 1, ts[i]->n, p->n);
|
||||
for (int k = 0; k < n; k++) tt_release(ts[k]);
|
||||
free(ts);
|
||||
return false;
|
||||
}
|
||||
memcpy(p->d, ts[i]->d, p->n * sizeof(float));
|
||||
}
|
||||
for (int i = 0; i < n && i < s_param_n; i++) { tt_release(ts[i]); ts[i] = NULL; }
|
||||
s_pending = ts; s_pending_n = n;
|
||||
return true;
|
||||
}
|
||||
|
||||
void tt_params_reset(void) {
|
||||
for (int i = 0; i < s_param_n; i++) tt_release(s_params[i].t);
|
||||
free(s_params);
|
||||
s_params = NULL; s_param_n = s_param_cap = 0;
|
||||
for (int i = 0; i < s_pending_n; i++) tt_release(s_pending[i]);
|
||||
free(s_pending);
|
||||
s_pending = NULL; s_pending_n = 0;
|
||||
}
|
||||
|
||||
/* == Pastas =========================================================== */
|
||||
#include <sys/stat.h>
|
||||
void tt_mkdirs_for(const char* path) {
|
||||
char buf[1024];
|
||||
snprintf(buf, sizeof(buf), "%s", path);
|
||||
for (char* p = buf + 1; *p; p++) {
|
||||
if (*p != '/') continue;
|
||||
*p = 0;
|
||||
mkdir(buf, 0755);
|
||||
*p = '/';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* TinyBlocks - tensor_internal.h
|
||||
* Funcoes internas da tinyblocks-tensor, divididas entre tensor.c (nucleo),
|
||||
* ops.c (operacoes com gradiente) e blocks.c (blocos e a tabela TbTensorApi).
|
||||
*/
|
||||
#ifndef TB_TENSOR_INTERNAL_H
|
||||
#define TB_TENSOR_INTERNAL_H
|
||||
|
||||
#include "tb_tensor.h"
|
||||
|
||||
/* -- Nucleo (tensor.c) -- */
|
||||
const char* tt_last_error(void);
|
||||
void tt_set_error(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
|
||||
TbTensor* tt_alloc(int nd, const int* shape);
|
||||
TbTensor* tt_alloc_like(const TbTensor* a);
|
||||
TbTensor* tt_scalar(float v);
|
||||
void tt_retain(TbTensor* t);
|
||||
void tt_release(TbTensor* t);
|
||||
float* tt_grad(TbTensor* t);
|
||||
int tt_shape_text(const TbTensor* t, char* out, size_t cap);
|
||||
void tt_seed(uint32_t seed);
|
||||
float tt_randu(void);
|
||||
float tt_randn(void);
|
||||
void tt_pool_start(void);
|
||||
void tt_pool_stop(void);
|
||||
int tt_pool_size(void);
|
||||
void tt_parallel_for(int n, TbParallelFn fn, void* ctx);
|
||||
void tt_gemm(bool ta, bool tb, int m, int n, int k, float alpha,
|
||||
const float* A, int lda, const float* B, int ldb,
|
||||
float beta, float* C, int ldc);
|
||||
bool tt_grad_enabled(void);
|
||||
void tt_set_grad_enabled(bool on);
|
||||
void tt_link(TbTensor* out, TbBackwardFn bw, TbTensor* const* in, int n,
|
||||
void* ctx, void (*ctx_free)(void*));
|
||||
bool tt_backward(TbTensor* root);
|
||||
TbTensor* tt_param(TinyBlocks_Block* owner, int slot, int nd, const int* shape, int init, float scale);
|
||||
void tt_params_release(TinyBlocks_Block* owner);
|
||||
int tt_param_count(void);
|
||||
TbTensor* tt_param_at(int i);
|
||||
const char* tt_param_group(int i);
|
||||
void tt_set_param_group(const char* name);
|
||||
void tt_params_zero_grad(const char* group); /* NULL ou "" = todos */
|
||||
size_t tt_params_numel(void);
|
||||
bool tt_params_save(const char* path);
|
||||
bool tt_params_load(const char* path);
|
||||
void tt_params_reset(void);
|
||||
bool tt_save(const char* path, TbTensor* const* ts, int n);
|
||||
TbTensor** tt_load(const char* path, int* n);
|
||||
void tt_mkdirs_for(const char* path);
|
||||
|
||||
/* -- Operacoes (ops.c): ref nova ou NULL + erro -- */
|
||||
enum { TT_ADD, TT_SUB, TT_MUL, TT_DIV };
|
||||
enum { TT_EXP, TT_LOG, TT_SQRT, TT_ABS };
|
||||
TbTensor* tt_binary(TbTensor* a, TbTensor* b, int op);
|
||||
TbTensor* tt_add(TbTensor* a, TbTensor* b);
|
||||
TbTensor* tt_sub(TbTensor* a, TbTensor* b);
|
||||
TbTensor* tt_mul(TbTensor* a, TbTensor* b);
|
||||
TbTensor* tt_div(TbTensor* a, TbTensor* b);
|
||||
TbTensor* tt_scale(TbTensor* a, float k);
|
||||
TbTensor* tt_powk(TbTensor* a, float p);
|
||||
TbTensor* tt_unary(TbTensor* a, int op);
|
||||
TbTensor* tt_matmul(TbTensor* a, TbTensor* b);
|
||||
TbTensor* tt_reshape(TbTensor* a, int nd, const int* shape);
|
||||
TbTensor* tt_transpose(TbTensor* a, int ax1, int ax2);
|
||||
TbTensor* tt_slice(TbTensor* a, int axis, int from, int to);
|
||||
TbTensor* tt_concat(TbTensor* a, TbTensor* b, int axis);
|
||||
TbTensor* tt_sum(TbTensor* a, int axis, bool keep);
|
||||
TbTensor* tt_mean(TbTensor* a, int axis, bool keep);
|
||||
TbTensor* tt_max(TbTensor* a, int axis, bool keep);
|
||||
TbTensor* tt_argmax(TbTensor* a, int axis); /* posições 1..n, sem gradiente */
|
||||
TbTensor* tt_gather(TbTensor* a, TbTensor* idx); /* linhas idx (1..N) do eixo 0 */
|
||||
TbTensor* tt_where_eq(TbTensor* a, float v); /* posições (1..n) onde a == v */
|
||||
TbTensor* tt_flip(TbTensor* a, int axis);
|
||||
TbTensor* tt_detach(TbTensor* a); /* cópia fora do grafo */
|
||||
TbTensor* tt_flatten(TbTensor* a); /* [B, resto] */
|
||||
TbTensor* tt_permutation(int n); /* 1..n embaralhados */
|
||||
|
||||
#endif /* TB_TENSOR_INTERNAL_H */
|
||||
Reference in new issue
Block a user