Parametros seguem o bloco do editor (origin), nao a instancia remontada
O editor esquece o cache das arvores quando o usuario edita algo e monta outra instancia para o mesmo bloco da tela. Como os pesos da tensor eram achados pela instancia, cada remontagem comecava com pesos novos: no treino da GAN a perda voltava ao formato do inicio de tempos em tempos. Cada bloco da tela ganha um uid e as instancias levam esse uid em TinyBlocks_Block.origin. tt_param acha o parametro pela origem (sem origem, pela propria instancia) e a instancia nova herda os pesos; a velha, ao morrer, nao leva os da nova. As medias moveis do batch norm passam a ser parametros sem gradiente, para irem junto no "salve os parametros". Testes: test-tensor ganha a heranca pela origem; os donos de mentira dos testes viram blocos zerados (o param_key le owner->origin).
This commit is contained in:
1 parent
422c3fb6cb
commit
a26d329521
12 files changed
+68
-22
No files matched your search
@@ -3,7 +3,7 @@
|
||||
D = {
|
||||
# -- tb_block.h
|
||||
"TinyBlocks_BlockVTable": "Operações polimórficas de um bloco: `eval`, `destroy` (libera o interno, não o ponteiro), `to_string` e `clone`. Ver [polimorfismo.md](polimorfismo.md#2-vtable-de-bloco).",
|
||||
"TinyBlocks_Block": "Base de todo bloco: `kind`, `vtable`, `id`, `name`, `type`, `inputs`/`input_count`, `outputs`/`output_count`, `parent`, `userdata`, `dirty`, `in_eval`. Ver [tipos.md](tipos.md).",
|
||||
"TinyBlocks_Block": "Base de todo bloco: `kind`, `vtable`, `id`, `origin`, `name`, `type`, `inputs`/`input_count`, `outputs`/`output_count`, `parent`, `userdata`, `dirty`, `in_eval`. Ver [tipos.md](tipos.md).",
|
||||
"tb_block_connect": "Liga a entrada `input_idx` de `target` à saída `output_idx` de `source` e marca `target` como sujo. Falso se algum índice for inválido.",
|
||||
"tb_block_disconnect": "Desliga a entrada (volta a usar o valor padrão) e marca o bloco como sujo.",
|
||||
"tb_block_set_default": "Troca o valor padrão da entrada (usado quando não há conexão). Clona o valor.",
|
||||
|
||||
+11
-6
@@ -91,16 +91,21 @@ JSON, então só acontece se alguém puser um valor de bloco numa lista.)
|
||||
| `tinyblocks-libman` | 128 libraries no catálogo. |
|
||||
| Servidor MCP | 16 conexões HTTP simultâneas. |
|
||||
|
||||
### Parâmetros de uma camada dependem de onde o bloco próprio foi chamado
|
||||
### Parâmetros de uma camada seguem o bloco do editor
|
||||
|
||||
O editor monta a árvore de blocos de cada comando uma vez por (aba, bloco,
|
||||
profundidade de chamada de Meus Blocos) e reaproveita (`get_rt`). Como os
|
||||
parâmetros da `tinyblocks-tensor` pertencem à instância do bloco
|
||||
parâmetros da `tinyblocks-tensor` pertenciam à instância do bloco
|
||||
(`tt_param(owner, ...)`), um bloco próprio "gerador" chamado do script
|
||||
(profundidade 1) e de dentro de outro bloco próprio (profundidade 2) tem
|
||||
**dois conjuntos de pesos**: o segundo nunca é treinado. No exemplo da GAN
|
||||
o gerador é chamado sempre do laço principal. Solução possível: a chave do
|
||||
parâmetro ser o bloco do editor (e não a instância do runtime).
|
||||
(profundidade 1) e de dentro de outro bloco próprio (profundidade 2) tinha
|
||||
**dois conjuntos de pesos**: o segundo nunca era treinado.
|
||||
|
||||
Corrigido: cada bloco da tela ganha um `uid`, que o editor põe no campo
|
||||
`origin` das instâncias do runtime; o parâmetro é achado pela origem e a
|
||||
instância remontada herda os pesos. As médias móveis do batch norm passaram
|
||||
a ser parâmetros sem gradiente, para irem junto no "salve os parâmetros".
|
||||
O que ainda depende da instância é o estado que não passa por `tt_param`
|
||||
(ex.: buffers de outras libraries).
|
||||
|
||||
### Campo de texto de um bloco corta em 63 caracteres
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ um campo `TinyBlocks_Block base` - herança em C via primeiro membro.
|
||||
|
||||
| Declaração | Descrição |
|
||||
|---|---|
|
||||
| tipo `struct TinyBlocks_Block` | Base de todo bloco: `kind`, `vtable`, `id`, `name`, `type`, `inputs`/`input_count`, `outputs`/`output_count`, `parent`, `userdata`, `dirty`, `in_eval`. Ver [tipos.md](tipos.md). |
|
||||
| tipo `struct TinyBlocks_Block` | Base de todo bloco: `kind`, `vtable`, `id`, `origin`, `name`, `type`, `inputs`/`input_count`, `outputs`/`output_count`, `parent`, `userdata`, `dirty`, `in_eval`. Ver [tipos.md](tipos.md). |
|
||||
|
||||
### Ciclo de vida
|
||||
|
||||
@@ -185,7 +185,7 @@ Forward declarations, enums e tipos primitivos compartilhados por todo o runtime
|
||||
| Declaração | Descrição |
|
||||
|---|---|
|
||||
| tipo `struct TinyBlocks` | O runtime (definido em `tinyblocks.h`). |
|
||||
| tipo `struct TinyBlocks_Block` | Base de todo bloco: `kind`, `vtable`, `id`, `name`, `type`, `inputs`/`input_count`, `outputs`/`output_count`, `parent`, `userdata`, `dirty`, `in_eval`. Ver [tipos.md](tipos.md). |
|
||||
| tipo `struct TinyBlocks_Block` | Base de todo bloco: `kind`, `vtable`, `id`, `origin`, `name`, `type`, `inputs`/`input_count`, `outputs`/`output_count`, `parent`, `userdata`, `dirty`, `in_eval`. Ver [tipos.md](tipos.md). |
|
||||
| tipo `struct TinyBlocks_TypeBlock` | Tipo de bloco (a "classe"): nome, slots, `eval_fn`, hooks de instância, `on_draw`, forma, rótulo, fluxo, evento, traços. Ver [libraries.md](libraries.md). |
|
||||
| tipo `struct TinyBlocks_LibraryBlock` | Library: blocos contidos, hooks `on_load`/`on_unload`, `lib_userdata` e categoria. |
|
||||
| tipo `struct TinyBlocks_TextBlock` | Literal de texto (`value` no heap). |
|
||||
|
||||
@@ -18,6 +18,7 @@ Campos comuns (`TinyBlocks_Block`, `tb_block.h`):
|
||||
|---|---|
|
||||
| `kind`, `vtable` | Tag do struct concreto e tabela de operações. |
|
||||
| `id` | Único no runtime (`tb_rt_find_block`). |
|
||||
| `origin` | De onde o bloco veio, estável entre remontagens (o editor põe o id do bloco na tela). 0 = nenhuma. A `tinyblocks-tensor` usa isso como chave dos parâmetros, para uma instância nova herdar os pesos. |
|
||||
| `name` | Rótulo opcional (heap). |
|
||||
| `type` | O `TypeBlock` da instância (NULL nos primitivos). |
|
||||
| `inputs[input_count]` | Conexões de entrada (`TinyBlocks_Connection`). |
|
||||
|
||||
@@ -29,6 +29,9 @@ struct TinyBlocks_Block {
|
||||
const TinyBlocks_BlockVTable* vtable;
|
||||
|
||||
uint64_t id; /* ID único gerado pelo runtime */
|
||||
uint64_t origin; /* de onde veio, estável entre *
|
||||
* remontagens (o editor põe o id *
|
||||
* do bloco na tela); 0 = nenhuma */
|
||||
char* name; /* rótulo opcional (heap-owned) */
|
||||
|
||||
TinyBlocks_TypeBlock* type; /* tipo/classe deste bloco; NULL *
|
||||
|
||||
@@ -137,16 +137,16 @@ static void eval_batchnorm(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
if (x->nd < 2) A->set_error("batch norm precisa de [lote, canais, ...]");
|
||||
else {
|
||||
int C = x->shape[1];
|
||||
Layer* L = self->userdata;
|
||||
if (!L->buf[0] || (int)L->buf[0]->n != C) { /* medias moveis (nao treinam) */
|
||||
A->release(L->buf[0]); A->release(L->buf[1]);
|
||||
L->buf[0] = A->alloc(1, &C);
|
||||
L->buf[1] = A->alloc(1, &C);
|
||||
for (int i = 0; L->buf[1] && i < C; i++) L->buf[1]->d[i] = 1;
|
||||
}
|
||||
TbTensor* g = P(self, 0, 1, &C, TB_INIT_ONES, 1);
|
||||
TbTensor* b = P(self, 1, 1, &C, TB_INIT_ZEROS, 0);
|
||||
if (g && b && L->buf[0] && L->buf[1]) r = ai_batchnorm(x, g, b, L->buf[0], L->buf[1], g_ai_train, 0.1f);
|
||||
/* medias moveis: parametros sem gradiente (os otimizadores pulam),
|
||||
para irem junto no "salve os parametros" e sobreviverem quando o
|
||||
editor remonta o bloco */
|
||||
TbTensor* mean = P(self, 2, 1, &C, TB_INIT_ZEROS, 0);
|
||||
TbTensor* var = P(self, 3, 1, &C, TB_INIT_ONES, 1);
|
||||
if (mean) mean->req = false;
|
||||
if (var) var->req = false;
|
||||
if (g && b && mean && var) r = ai_batchnorm(x, g, b, mean, var, g_ai_train, 0.1f);
|
||||
}
|
||||
rel(&x, 1); done(self, rt, r);
|
||||
}
|
||||
|
||||
@@ -539,6 +539,7 @@ typedef struct {
|
||||
typedef struct {
|
||||
bool used;
|
||||
bool dragging;
|
||||
uint64_t uid; /* identidade do bloco (vai no origin das instâncias) */
|
||||
TinyBlocks_TypeBlock* type;
|
||||
char type_name[64];
|
||||
float x, y; /* posição (só para o topo de uma pilha) */
|
||||
|
||||
@@ -377,11 +377,18 @@ void blk_release(Tab* T, int i) {
|
||||
T->free_ids[T->free_n++] = i;
|
||||
}
|
||||
|
||||
/* Identidade de cada bloco que nasce na tela. Vai no "origin" das
|
||||
instancias do runtime: quando o cache das arvores e esvaziado (uma edicao,
|
||||
um clique) a instancia nova herda o estado preso a ela, como os
|
||||
parametros de uma camada da tinyblocks-tensor. */
|
||||
static uint64_t s_blk_uid;
|
||||
|
||||
static int blk_alloc(Tab* T) {
|
||||
if (T->free_n > 0) {
|
||||
int i = T->free_ids[--T->free_n];
|
||||
blk_slot_clear(T, i);
|
||||
T->ws[i].used = true;
|
||||
T->ws[i].uid = ++s_blk_uid;
|
||||
return i;
|
||||
}
|
||||
if (T->ws_n >= MAX_WS) return -1;
|
||||
@@ -389,6 +396,7 @@ static int blk_alloc(Tab* T) {
|
||||
if (!blk_reserve(T, i)) return -1;
|
||||
blk_slot_clear(T, i);
|
||||
T->ws[i].used = true;
|
||||
T->ws[i].uid = ++s_blk_uid;
|
||||
return i;
|
||||
}
|
||||
|
||||
@@ -1291,6 +1299,7 @@ TinyBlocks_Block* build_rt(Ed* ed, Tab* T, int bi) {
|
||||
if (ed->run_n >= MAX_RUN_BLOCKS) { run_abort(ed, "limite de blocos em execução atingido"); return NULL; }
|
||||
TinyBlocks_Block* r = tb_block_create(ed->rt, t);
|
||||
if (!r) return NULL;
|
||||
r->origin = b->uid;
|
||||
run_track(ed, r);
|
||||
if (T == ed->live_tab) b->live_rt = r;
|
||||
|
||||
@@ -3060,6 +3069,7 @@ static void bp_tab_load(Ed* ed, const TbBpTab* B, Tab* T) {
|
||||
if (!blk_reserve(T, i)) break;
|
||||
EdBlock* b = &T->ws[i];
|
||||
b->used = true;
|
||||
b->uid = ++s_blk_uid;
|
||||
snprintf(b->type_name, sizeof(b->type_name), "%s", o->type);
|
||||
b->type = b->type_name[0] ? tb_type_block_find(ed->rt, b->type_name) : NULL;
|
||||
b->x = o->x; b->y = o->y;
|
||||
|
||||
@@ -393,7 +393,14 @@ bool tt_backward(TbTensor* root) {
|
||||
}
|
||||
|
||||
/* == Parametros ======================================================= */
|
||||
typedef struct { TinyBlocks_Block* owner; int slot; TbTensor* t; char group[32]; } Param;
|
||||
/* Um parametro e achado pela origem do bloco dono (owner->origin, estavel
|
||||
quando o editor remonta a arvore: a instancia nova herda os pesos) ou,
|
||||
sem origem, pela propria instancia. */
|
||||
typedef struct { TinyBlocks_Block* owner; uint64_t key; int slot; TbTensor* t; char group[32]; } Param;
|
||||
|
||||
static uint64_t param_key(const TinyBlocks_Block* owner) {
|
||||
return owner && owner->origin ? owner->origin : (uint64_t)(uintptr_t)owner;
|
||||
}
|
||||
static char s_group[32]; /* grupo dos parametros que nascerem agora */
|
||||
static Param* s_params;
|
||||
static int s_param_n, s_param_cap;
|
||||
@@ -414,8 +421,10 @@ static void param_fill(TbTensor* t, int init, float scale) {
|
||||
}
|
||||
|
||||
TbTensor* tt_param(TinyBlocks_Block* owner, int slot, int nd, const int* shape, int init, float scale) {
|
||||
uint64_t key = param_key(owner);
|
||||
for (int i = 0; i < s_param_n; i++)
|
||||
if (s_params[i].owner == owner && s_params[i].slot == slot) {
|
||||
if (s_params[i].key == key && s_params[i].slot == slot) {
|
||||
s_params[i].owner = owner; /* instancia remontada: herda */
|
||||
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];
|
||||
@@ -439,7 +448,7 @@ TbTensor* tt_param(TinyBlocks_Block* owner, int slot, int nd, const int* shape,
|
||||
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, "" };
|
||||
s_params[s_param_n] = (Param){ owner, key, slot, t, "" };
|
||||
snprintf(s_params[s_param_n].group, sizeof(s_params[s_param_n].group), "%s", s_group);
|
||||
s_param_n++;
|
||||
return t;
|
||||
|
||||
@@ -17,6 +17,7 @@ TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt,
|
||||
b->kind = kind;
|
||||
b->vtable = vtable;
|
||||
b->id = tb_rt_next_id(rt);
|
||||
b->origin = 0;
|
||||
b->input_count = input_count;
|
||||
b->output_count = output_count;
|
||||
b->dirty = true;
|
||||
|
||||
+2
-1
@@ -111,7 +111,8 @@ int main(void) {
|
||||
tb_library_register(rt, tb_ai_get_library());
|
||||
CHECK(ai_begin(rt), "a IA acha a tabela da tinyblocks-tensor pelo runtime");
|
||||
tt_seed(3);
|
||||
OWNER = (TinyBlocks_Block*)(uintptr_t)0x2000;
|
||||
static TinyBlocks_Block owner_blk; /* zerado: so a identidade */
|
||||
OWNER = &owner_blk;
|
||||
|
||||
/* -- ativacoes, softmax, perdas --------------------------------------- */
|
||||
{
|
||||
|
||||
+16
-1
@@ -166,9 +166,24 @@ int main(void) {
|
||||
tt_release(ix); tt_release(x[0]); tt_release(x[1]);
|
||||
}
|
||||
|
||||
/* -- parametros pela origem: a instancia remontada herda os pesos ------ */
|
||||
{
|
||||
static TinyBlocks_Block a, b2;
|
||||
a.origin = b2.origin = 777;
|
||||
TbTensor* pa = tt_param(&a, 0, 1, (int[]){ 3 }, TB_INIT_NORMAL, 1.0f);
|
||||
pa->d[0] = 42;
|
||||
TbTensor* pb = tt_param(&b2, 0, 1, (int[]){ 3 }, TB_INIT_NORMAL, 1.0f);
|
||||
CHECK(pa == pb && pb->d[0] == 42, "bloco remontado (mesma origem) herda os parâmetros");
|
||||
tt_params_release(&a); /* a velha morre: o parametro fica */
|
||||
CHECK(tt_param_count() >= 1 && tt_param(&b2, 0, 1, (int[]){ 3 }, TB_INIT_ZEROS, 0)->d[0] == 42,
|
||||
"a instância velha morrer não leva os parâmetros da nova");
|
||||
tt_params_release(&b2);
|
||||
}
|
||||
|
||||
/* -- parametros e arquivo --------------------------------------------- */
|
||||
{
|
||||
TinyBlocks_Block* owner = (TinyBlocks_Block*)(uintptr_t)0x1000; /* so a identidade */
|
||||
static TinyBlocks_Block owner_blk; /* zerado: so a identidade */
|
||||
TinyBlocks_Block* owner = &owner_blk;
|
||||
tt_set_param_group("g");
|
||||
TbTensor* p = tt_param(owner, 0, 2, (int[]){ 2, 2 }, TB_INIT_ONES, 2.0f);
|
||||
TbTensor* p2 = tt_param(owner, 0, 2, (int[]){ 2, 2 }, TB_INIT_ZEROS, 0);
|
||||
|
||||
Reference in new issue
Block a user