/* * 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 #include #include #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; }