GigaAM-v4-c / src /ga_encoder.c
eschmidbauer's picture
streaming runtime and conversion pipeline for GigaAM-v4
5b65ff7
Raw History Blame Contribute Delete
28.7 kB
#include "ga_encoder.h"
#include "ga_kernels.h"
#include "ga_math.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GA_NORM_EPS 1e-6f
#define GA_ROPE_BASE 10000.0f
#define GA_LAYER_BLEND 0.25f
#define GA_MIN_GROUP 8 /* smallest int8 scale group the activation scratch is sized for */
static const int32_t *config_list(ga_weights *w, const char *name, int expected)
{
int count;
const int32_t *values = ga_weights_i32(w, name, &count);
if (values && count != expected) {
ga_weights_fail(w, "%s: expected %d values", name, expected);
return NULL;
}
return values;
}
/* int8 weights the backend cannot multiply directly, widened to f32 at load. */
static const float *dequantize(ga_weights *w, const ga_lin *lin)
{
float *wide = ga_weights_alloc(w, (size_t)lin->out * lin->in * sizeof(float));
int groups = lin->in / lin->group;
if (!wide || !lin->wscale)
return NULL;
for (int r = 0; r < lin->out; r++)
for (int c = 0; c < lin->in; c++)
wide[(size_t)r * lin->in + c] = (float)lin->wq[(size_t)r * lin->in + c] *
lin->wscale[(size_t)r * groups + c / lin->group];
return wide;
}
/* Scales of an int8 linear: [out] (one group per row) or [out, in / group]. */
static void load_scales(ga_lin *lin, ga_weights *w, const char *name)
{
const ga_entry *e = ga_weights_find(w, name);
int groups = e && e->ndim == 2 ? (int)e->dims[1] : 1;
if (!e || (int)e->dims[0] != lin->out || groups < 1 || lin->in % groups) {
ga_weights_fail(w, "bad %s", name);
return;
}
lin->group = lin->in / groups;
if (lin->in > GA_I8_MAX_K) {
ga_weights_fail(w, "%s: int8 rows longer than %d", name, GA_I8_MAX_K);
return;
}
if (lin->group < GA_MIN_GROUP) {
ga_weights_fail(w, "%s: int8 group %d < %d", name, lin->group, GA_MIN_GROUP);
return;
}
lin->wscale = ga_weights_flat(w, (size_t)lin->out * groups, "%s", name);
}
/* Weights in the int8 kernel's layout: as stored, or packed in pairs for i8mm. */
static const int8_t *kernel_weights(ga_weights *w, const ga_lin *lin)
{
int8_t *packed;
if (!lin->wq || !ga_kernel_i8_pairs(lin->group))
return lin->wq;
packed = ga_weights_alloc(w, (size_t)(lin->out + 1) / 2 * 2 * lin->in);
if (packed)
ga_kernel_i8_pack_weights(lin->wq, lin->out, lin->in, packed);
return packed;
}
/* Scales in the int8 kernel's layout. */
static const float *kernel_scales(ga_weights *w, const ga_lin *lin)
{
int groups = lin->in / lin->group;
float *out = ga_weights_alloc(w, (size_t)(lin->out + 3) / 4 * 4 * groups * sizeof(float));
if (out && lin->wscale)
ga_kernel_i8_interleave_scales(lin->wscale, lin->out, groups, out);
return out;
}
/* Weights as stored (int8, f16 or f32), in the form the backend multiplies best. */
static ga_lin load_linear(ga_weights *w, int out, int in, int stack, int layer,
const char *name)
{
ga_lin lin;
memset(&lin, 0, sizeof(lin));
lin.in = in;
lin.out = out;
lin.b = ga_weights_mat(w, out, 0, "encoders.%d.layers.%d.%s.bias", stack, layer, name);
lin.wq = ga_weights_mat_i8(w, out, in, "encoders.%d.layers.%d.%s.weight", stack, layer,
name);
if (lin.wq) {
char scales[128];
snprintf(scales, sizeof(scales), "encoders.%d.layers.%d.%s.wscale", stack, layer, name);
load_scales(&lin, w, scales);
if (!ga_math_reads_i8()) {
lin.w = dequantize(w, &lin);
lin.wq = NULL;
} else {
lin.wscale = kernel_scales(w, &lin);
lin.wq = kernel_weights(w, &lin);
}
return lin;
}
lin.wh = ga_math_reads_f16()
? ga_weights_mat_f16(w, out, in, "encoders.%d.layers.%d.%s.weight", stack,
layer, name)
: NULL;
if (!lin.wh)
lin.w = ga_weights_mat(w, out, in, "encoders.%d.layers.%d.%s.weight", stack, layer,
name);
return lin;
}
static void load_conv_module(ga_layer *l, ga_weights *w, int dim, int s, int i)
{
char name[128];
const ga_entry *e;
const float *raw;
float *weight;
snprintf(name, sizeof(name), "encoders.%d.layers.%d.conv_module.depthwise_conv.weight", s,
i);
e = ga_weights_find(w, name);
if (!e)
return;
if (e->ndim != 2 || (int)e->dims[0] != dim || !(e->dims[1] & 1u)) {
ga_weights_fail(w, "bad %s", name);
return;
}
l->kernel = (int)e->dims[1];
raw = ga_weights_mat(w, dim, l->kernel, "%s", name);
weight = ga_weights_alloc(w, (size_t)dim * l->kernel * sizeof(float));
if (!raw || !weight)
return;
for (int c = 0; c < dim; c++)
for (int k = 0; k < l->kernel; k++)
weight[(size_t)k * dim + c] = raw[(size_t)c * l->kernel + k];
l->dw_weight = weight;
l->dw_bias = ga_weights_mat(w, dim, 0,
"encoders.%d.layers.%d.conv_module.depthwise_conv.bias", s, i);
l->mean_weight = ga_weights_mat(
w, dim, 0, "encoders.%d.layers.%d.conv_module.weighted_mean.weights", s, i);
l->conv_in = load_linear(w, 2 * dim, dim, s, i, "conv_module.in_proj");
l->conv_out = load_linear(w, dim, dim, s, i, "conv_module.out_proj");
l->ff2_in = load_linear(w, l->ff1_in.out, dim, s, i, "feed_forward2.in_proj");
l->ff2_out = load_linear(w, dim, l->ff1_in.out, s, i, "feed_forward2.out_proj");
}
static void load_layer(ga_layer *l, ga_weights *w, const ga_stack *st, int s, int i)
{
char name[128];
const ga_entry *e;
int dim = st->dim, hidden;
snprintf(name, sizeof(name), "encoders.%d.layers.%d.feed_forward1.in_proj.weight", s, i);
e = ga_weights_find(w, name);
if (!e || e->ndim != 2) {
ga_weights_fail(w, "missing tensor %s", name);
return;
}
hidden = (int)e->dims[0];
l->ff1_in = load_linear(w, hidden, dim, s, i, "feed_forward1.in_proj");
l->ff1_out = load_linear(w, dim, hidden, s, i, "feed_forward1.out_proj");
l->qk = load_linear(w, 2 * st->heads * st->qdim, dim, s, i, "self_attn.qk_in_proj");
l->vg = load_linear(w, 3 * st->heads * st->vdim, dim, s, i, "self_attn.vg_in_proj");
l->attn_out = load_linear(w, dim, st->heads * st->vdim, s, i, "self_attn.out_proj");
l->in_norm =
ga_weights_mat(w, dim, 0, "encoders.%d.layers.%d.self_attn.in_norm.weight", s, i);
l->norm = ga_weights_mat(w, dim, 0, "encoders.%d.layers.%d.norm.weight", s, i);
load_conv_module(l, w, dim, s, i);
}
static void load_stack(ga_stack *st, ga_weights *w, int s, int feat)
{
char name[64];
const ga_entry *e;
const float *scale;
float *transposed;
snprintf(name, sizeof(name), "encoders.%d.proj.weight", s);
e = ga_weights_find(w, name);
if (!e || e->ndim != 2 || (int)e->dims[1] != st->ds * feat) {
ga_weights_fail(w, "bad %s", name);
return;
}
st->dim = (int)e->dims[0];
st->in_dim = (int)e->dims[1];
st->proj = ga_weights_mat(w, st->dim, st->in_dim, "%s", name);
st->residual_scales =
ga_weights_mat(w, st->n_layers + 1, 0, "encoders.%d.residual_scales", s);
scale = ga_weights_mat(w, 1, 0, "encoders.%d.input_scale", s);
st->layers = ga_weights_alloc(w, (size_t)st->n_layers * sizeof(ga_layer));
transposed = ga_weights_alloc(w, (size_t)st->dim * st->in_dim * sizeof(float));
if (ga_weights_failed(w))
return;
for (int r = 0; r < st->dim; r++)
for (int c = 0; c < st->in_dim; c++)
transposed[(size_t)c * st->dim + r] = st->proj[(size_t)r * st->in_dim + c];
st->proj_t = transposed;
st->input_scale = scale[0];
for (int i = 0; i < st->n_layers && !ga_weights_failed(w); i++)
load_layer(&st->layers[i], w, st, s, i);
}
int ga_encoder_init(ga_encoder *e, ga_weights *w, int feat)
{
int count;
const int32_t *ds = ga_weights_i32(w, "config.downsampling", &count);
const int32_t *layers = config_list(w, "config.num_layers", count);
const int32_t *heads = config_list(w, "config.num_heads", count);
const int32_t *qdim = config_list(w, "config.query_head_dim", count);
const int32_t *vdim = config_list(w, "config.value_head_dim", count);
const float *scale = ga_weights_mat(w, 1, 0, "out_norm.scale");
const float *eps = ga_weights_mat(w, 1, 0, "out_norm.eps_sq");
memset(e, 0, sizeof(*e));
if (ga_weights_failed(w))
return -1;
e->feat = feat;
e->n_stacks = count;
e->out_scale = scale[0];
e->out_eps_sq = eps[0];
e->stacks = ga_weights_alloc(w, (size_t)count * sizeof(ga_stack));
if (!e->stacks)
return -1;
for (int s = 0; s < count && !ga_weights_failed(w); s++) {
ga_stack *st = &e->stacks[s];
st->ds = ds[s];
st->n_layers = layers[s];
st->heads = heads[s];
st->qdim = qdim[s];
st->vdim = vdim[s];
if (st->ds < 1 || st->n_layers < 1 || st->heads < 1 || st->qdim < 2 || (st->qdim & 1)) {
ga_weights_fail(w, "bad stack %d config", s);
break;
}
load_stack(st, w, s, feat);
}
return ga_weights_failed(w) ? -1 : 0;
}
static size_t max_size(size_t a, size_t b)
{
return a > b ? a : b;
}
void ga_encoder_state_reset(const ga_encoder *e, ga_encoder_state *s)
{
for (int i = 0; i < e->n_stacks; i++)
s->n_past[i] = 0;
}
void ga_encoder_state_free(const ga_encoder *e, ga_encoder_state *s)
{
if (s->layers)
for (int i = 0; i < e->n_stacks; i++) {
for (int j = 0; s->layers[i] && j < e->stacks[i].n_layers; j++) {
free(s->layers[i][j].keys);
free(s->layers[i][j].values);
free(s->layers[i][j].conv);
}
free(s->layers[i]);
}
free(s->layers);
free(s->n_past);
memset(s, 0, sizeof(*s));
}
int ga_encoder_state_init(const ga_encoder *e, ga_encoder_state *s, int chunk, int left)
{
memset(s, 0, sizeof(*s));
s->chunk = chunk;
s->left = left;
s->n_past = calloc((size_t)e->n_stacks, sizeof(int));
s->layers = calloc((size_t)e->n_stacks, sizeof(ga_layer_state *));
if (!s->n_past || !s->layers) {
ga_encoder_state_free(e, s);
return -1;
}
for (int i = 0; i < e->n_stacks; i++) {
const ga_stack *st = &e->stacks[i];
size_t rows = (size_t)(left + chunk) / st->ds;
size_t q = (size_t)st->heads * st->qdim, v = (size_t)st->heads * st->vdim;
if (chunk % st->ds || left % st->ds) {
ga_encoder_state_free(e, s);
return -1;
}
s->layers[i] = calloc((size_t)st->n_layers, sizeof(ga_layer_state));
if (!s->layers[i]) {
ga_encoder_state_free(e, s);
return -1;
}
for (int j = 0; j < st->n_layers; j++) {
ga_layer_state *ls = &s->layers[i][j];
ls->keys = calloc(rows * q, sizeof(float));
ls->values = calloc(rows * v, sizeof(float));
ls->conv = st->layers[j].kernel ? calloc(rows * st->dim, sizeof(float)) : NULL;
if (!ls->keys || !ls->values || (st->layers[j].kernel && !ls->conv)) {
ga_encoder_state_free(e, s);
return -1;
}
}
}
return 0;
}
void ga_encoder_work_free(ga_encoder_work *w)
{
free(w->rope_cos);
free(w->rope_sin);
free(w->shapes);
free(w->x);
free(w->bypass);
free(w->orig);
free(w->wide);
free(w->tmp);
free(w->query);
free(w->keys);
free(w->scores);
free(w->attn);
free(w->gate);
free(w->mean);
free(w->xq);
free(w->xq_scale);
memset(w, 0, sizeof(*w));
}
static int init_rope(const ga_encoder *e, ga_encoder_work *w)
{
int positions = w->left + w->chunk, half = 0;
for (int i = 0; i < e->n_stacks; i++)
if (e->stacks[i].qdim / 2 > half)
half = e->stacks[i].qdim / 2;
w->rope_stride = positions * half;
w->rope_cos = malloc((size_t)e->n_stacks * w->rope_stride * sizeof(float));
w->rope_sin = malloc((size_t)e->n_stacks * w->rope_stride * sizeof(float));
if (!w->rope_cos || !w->rope_sin)
return -1;
for (int i = 0; i < e->n_stacks; i++) {
int qdim = e->stacks[i].qdim;
for (int p = 0; p < positions; p++)
for (int k = 0; k < qdim / 2; k++) {
float freq = 1.0f / powf(GA_ROPE_BASE, (float)(2 * k) / (float)qdim);
float angle = (float)p * freq;
size_t at = (size_t)i * w->rope_stride + (size_t)p * (qdim / 2) + k;
w->rope_cos[at] = cosf(angle);
w->rope_sin[at] = sinf(angle);
}
}
return 0;
}
int ga_encoder_work_init(const ga_encoder *e, ga_encoder_work *w, int chunk, int left,
int batch)
{
size_t dim = 0, wide = 0, hq = 0, hv = 0, hist = 0, heads = 0, in_max = 0;
size_t rows = (size_t)batch * chunk;
memset(w, 0, sizeof(*w));
w->chunk = chunk;
w->left = left;
w->batch = batch;
if (batch < 1 || init_rope(e, w) != 0) {
ga_encoder_work_free(w);
return -1;
}
for (int i = 0; i < e->n_stacks; i++) {
const ga_stack *st = &e->stacks[i];
size_t q = (size_t)st->heads * st->qdim, v = (size_t)st->heads * st->vdim;
dim = max_size(dim, (size_t)st->dim);
hq = max_size(hq, q);
hv = max_size(hv, v);
hist = max_size(hist, (size_t)(left + chunk) / st->ds);
heads = max_size(heads, (size_t)st->heads);
wide = max_size(wide, max_size(2 * q, 3 * v));
for (int j = 0; j < st->n_layers; j++)
wide = max_size(wide, max_size((size_t)st->layers[j].ff1_in.out, 2 * (size_t)st->dim));
in_max = max_size(in_max, max_size(dim, max_size(hv, wide)));
}
w->shapes = malloc((size_t)batch * sizeof(ga_step_shape));
w->x = malloc(rows * dim * sizeof(float));
w->bypass = malloc(rows * dim * sizeof(float));
w->orig = malloc(rows * dim * sizeof(float));
w->tmp = malloc(rows * dim * sizeof(float));
w->mean = malloc(rows * dim * sizeof(float));
w->wide = malloc(rows * wide * sizeof(float));
w->query = malloc(rows * hq * sizeof(float));
w->keys = malloc((size_t)batch * hist * hq * sizeof(float));
w->scores = malloc((size_t)batch * heads * chunk * hist * sizeof(float));
w->attn = malloc(rows * hv * sizeof(float));
w->gate = malloc(rows * max_size(hv, dim) * sizeof(float));
w->xq = malloc((rows + 1) * in_max);
w->xq_scale = malloc(rows * (in_max / GA_MIN_GROUP + 1) * sizeof(float));
w->keys_stride = hist * hq;
w->scores_stride = (size_t)chunk * hist;
if (!w->shapes || !w->x || !w->bypass || !w->orig || !w->tmp || !w->mean || !w->wide ||
!w->query || !w->keys || !w->scores || !w->attn || !w->gate || !w->xq ||
!w->xq_scale) {
ga_encoder_work_free(w);
return -1;
}
return 0;
}
/* First cached row a query may see: at most `keep` rows back. */
static int first_visible(const ga_step_shape *g, int query)
{
int first = query + g->past - g->keep;
return first < 0 ? 0 : first;
}
static void add_rows(float *x, const float *y, size_t n)
{
for (size_t i = 0; i < n; i++)
x[i] += y[i];
}
static void apply_linear(const ga_lin *lin, const float *x, int rows, float *y,
ga_encoder_work *w)
{
if (lin->wq)
ga_linear_i8(x, rows, lin->in, lin->wq, lin->wscale, lin->group, lin->b, lin->out, y,
w->xq, w->xq_scale, w->pool);
else if (lin->wh)
ga_linear_f16(x, rows, lin->in, lin->wh, lin->b, lin->out, y, w->pool);
else
ga_linear(x, rows, lin->in, lin->w, lin->b, lin->out, y, w->pool);
}
static void rotate(const float *in, float *out, int heads, int qdim, const float *cos,
const float *sin)
{
for (int h = 0; h < heads; h++)
for (int k = 0; k < qdim / 2; k++) {
float a = in[h * qdim + 2 * k], b = in[h * qdim + 2 * k + 1];
out[h * qdim + 2 * k] = a * cos[k] - b * sin[k];
out[h * qdim + 2 * k + 1] = a * sin[k] + b * cos[k];
}
}
/* Softmax over the visible key range of each query row; zero elsewhere. */
static void masked_softmax(float *scores, int keys, const ga_step_shape *g)
{
int last = g->past + g->valid;
for (int t = 0; t < g->frames; t++) {
float *row = scores + (size_t)t * keys;
int first = first_visible(g, t);
float peak, sum = 0.0f;
if (first >= last) {
for (int i = 0; i < keys; i++)
row[i] = 1.0f / (float)keys;
continue;
}
peak = row[first];
for (int i = first + 1; i < last; i++)
if (row[i] > peak)
peak = row[i];
for (int i = 0; i < first; i++)
row[i] = 0.0f;
for (int i = first; i < last; i++) {
row[i] = expf(row[i] - peak);
sum += row[i];
}
for (int i = first; i < last; i++)
row[i] /= sum;
for (int i = last; i < keys; i++)
row[i] = 0.0f;
}
}
/* Drop the oldest rows so at most `keep` remain. */
static void trim_history(float *rows, size_t width, const ga_step_shape *g)
{
int total = g->past + g->frames;
if (total > g->keep)
memmove(rows, rows + (size_t)(total - g->keep) * width,
(size_t)g->keep * width * sizeof(float));
}
/* Mean of the visible convolution inputs per query row, scaled per channel. */
static void context_mean(const ga_layer *l, const float *history, int dim, float *mean,
const ga_step_shape *g)
{
int last = g->past + g->valid;
for (int t = 0; t < g->frames; t++) {
float *out = mean + (size_t)t * dim;
int first = first_visible(g, t);
int count = last - first;
float scale = 1.0f / (float)(count > 1 ? count : 1);
memset(out, 0, (size_t)dim * sizeof(float));
for (int i = first; i < last; i++)
add_rows(out, history + (size_t)i * dim, (size_t)dim);
for (int c = 0; c < dim; c++)
out[c] *= scale * l->mean_weight[c];
}
}
/* Depthwise conv: full causal past, future taps stop at the chunk edge. */
static void depthwise(const ga_layer *l, const float *history, int dim, float *out,
const ga_step_shape *g)
{
int radius = l->kernel / 2;
for (int t = 0; t < g->frames; t++) {
float *dst = out + (size_t)t * dim;
memcpy(dst, l->dw_bias, (size_t)dim * sizeof(float));
for (int k = 0; k < l->kernel; k++) {
int row = g->past + t + k - radius;
const float *src, *weight;
if (row < 0 || t + k - radius >= g->frames)
continue;
src = history + (size_t)row * dim;
weight = l->dw_weight + (size_t)k * dim;
for (int c = 0; c < dim; c++)
dst[c] += weight[c] * src[c];
}
}
}
/* One layer of one stack for every stream of a step; rows of stream b start at b * frames. */
typedef struct layer_ctx {
const ga_stack *st;
const ga_layer *l;
ga_encoder_state *const *states;
ga_encoder_work *w;
int stack, layer, count, frames;
} layer_ctx;
static ga_layer_state *layer_state(const layer_ctx *c, int b)
{
return &c->states[b]->layers[c->stack][c->layer];
}
typedef void (*unit_fn)(const layer_ctx *c, int unit);
typedef struct unit_task {
const layer_ctx *ctx;
unit_fn fn;
int units;
} unit_task;
static void units_part(void *arg, int part, int parts)
{
const unit_task *t = arg;
for (int u = t->units * part / parts; u < t->units * (part + 1) / parts; u++)
t->fn(t->ctx, u);
}
/* fn(c, u) for every u in [0, units), spread over the pool. */
static void run_units(const layer_ctx *c, int units, unit_fn fn)
{
unit_task t = {c, fn, units};
ga_pool_run(c->w->pool, units_part, &t);
}
static void feed_forward(const ga_lin *in, const ga_lin *out, float *x, int rows,
ga_encoder_work *w)
{
apply_linear(in, x, rows, w->wide, w);
ga_silu(w->wide, (size_t)rows * in->out, w->pool);
apply_linear(out, w->wide, rows, w->tmp, w);
add_rows(x, w->tmp, (size_t)rows * out->out);
}
/* Stream b: cache its new keys, rotate its queries and all its visible keys. */
static void stream_keys(const layer_ctx *c, int b)
{
const ga_stack *st = c->st;
const ga_step_shape *g = &c->w->shapes[b];
ga_layer_state *ls = layer_state(c, b);
int hq = st->heads * st->qdim, half = st->qdim / 2;
float *keys = c->w->keys + (size_t)b * c->w->keys_stride;
for (int t = 0; t < g->frames; t++) {
size_t row = (size_t)b * g->frames + t;
const float *qk = c->w->wide + row * 2 * hq;
int pos = g->past + t;
memcpy(ls->keys + (size_t)pos * hq, qk + hq, (size_t)hq * sizeof(float));
rotate(qk, c->w->query + row * hq, st->heads, st->qdim, g->cos + (size_t)pos * half,
g->sin + (size_t)pos * half);
}
for (int i = 0; i < g->past + g->frames; i++)
rotate(ls->keys + (size_t)i * hq, keys + (size_t)i * hq, st->heads, st->qdim,
g->cos + (size_t)i * half, g->sin + (size_t)i * half);
}
/* Stream b: gate its new values into the cache, keep the output gate. */
static void stream_values(const layer_ctx *c, int b)
{
const ga_step_shape *g = &c->w->shapes[b];
ga_layer_state *ls = layer_state(c, b);
int hv = c->st->heads * c->st->vdim;
for (int t = 0; t < g->frames; t++) {
size_t row = (size_t)b * g->frames + t;
float *vg = c->w->wide + row * 3 * hv;
float *value = ls->values + (size_t)(g->past + t) * hv;
ga_sigmoid(vg + hv, (size_t)2 * hv, NULL);
for (int i = 0; i < hv; i++)
value[i] = vg[i] * vg[hv + i];
memcpy(c->w->gate + row * hv, vg + 2 * hv, (size_t)hv * sizeof(float));
}
}
/* Unit = (stream, head): scores, softmax and weighted values, each with its own scores. */
static void stream_head(const layer_ctx *c, int unit)
{
const ga_stack *st = c->st;
int b = unit / st->heads, h = unit % st->heads;
const ga_step_shape *g = &c->w->shapes[b];
int hq = st->heads * st->qdim, hv = st->heads * st->vdim, keys = g->past + g->frames;
size_t row = (size_t)b * g->frames;
float *scores = c->w->scores + (size_t)unit * c->w->scores_stride;
float scale = 1.0f / sqrtf((float)st->qdim);
ga_gemm_nt(g->frames, keys, st->qdim, scale, c->w->query + row * hq + h * st->qdim, hq,
c->w->keys + (size_t)b * c->w->keys_stride + h * st->qdim, hq, 0.0f, scores,
keys, NULL);
masked_softmax(scores, keys, g);
ga_gemm_nn(g->frames, st->vdim, keys, 1.0f, scores, keys,
layer_state(c, b)->values + h * st->vdim, hv, 0.0f,
c->w->attn + row * hv + h * st->vdim, hv);
}
static void attention(const layer_ctx *c, float *x)
{
const ga_stack *st = c->st;
const ga_layer *l = c->l;
ga_encoder_work *w = c->w;
int rows = c->count * c->frames, hq = st->heads * st->qdim, hv = st->heads * st->vdim;
ga_rms_norm(w->orig, rows, st->dim, l->in_norm, GA_NORM_EPS, w->tmp);
apply_linear(&l->qk, w->tmp, rows, w->wide, w);
run_units(c, c->count, stream_keys);
apply_linear(&l->vg, x, rows, w->wide, w);
run_units(c, c->count, stream_values);
run_units(c, c->count * st->heads, stream_head);
for (size_t i = 0; i < (size_t)rows * hv; i++)
w->attn[i] *= w->gate[i];
apply_linear(&l->attn_out, w->attn, rows, w->tmp, w);
add_rows(x, w->tmp, (size_t)rows * st->dim);
for (int b = 0; b < c->count; b++) {
trim_history(layer_state(c, b)->keys, (size_t)hq, &w->shapes[b]);
trim_history(layer_state(c, b)->values, (size_t)hv, &w->shapes[b]);
}
}
/* Stream b: cache its convolution inputs, split the gate, context mean and depthwise. */
static void stream_conv(const layer_ctx *c, int b)
{
const ga_step_shape *g = &c->w->shapes[b];
ga_layer_state *ls = layer_state(c, b);
int dim = c->st->dim;
size_t row = (size_t)b * g->frames;
float *fresh = ls->conv + (size_t)g->past * dim;
for (int t = 0; t < g->frames; t++) {
const float *in = c->w->wide + (row + t) * 2 * dim;
float *dst = fresh + (size_t)t * dim;
if (t < g->valid)
memcpy(dst, in, (size_t)dim * sizeof(float));
else
memset(dst, 0, (size_t)dim * sizeof(float));
memcpy(c->w->gate + (row + t) * dim, in + dim, (size_t)dim * sizeof(float));
}
context_mean(c->l, ls->conv, dim, c->w->mean + row * dim, g);
depthwise(c->l, ls->conv, dim, c->w->tmp + row * dim, g);
}
static void convolution(const layer_ctx *c, float *x)
{
const ga_layer *l = c->l;
ga_encoder_work *w = c->w;
int rows = c->count * c->frames, dim = c->st->dim;
size_t total = (size_t)rows * dim;
apply_linear(&l->conv_in, x, rows, w->wide, w);
run_units(c, c->count, stream_conv);
ga_sigmoid(w->gate, total, w->pool);
for (size_t i = 0; i < total; i++)
w->tmp[i] = (w->tmp[i] + w->mean[i]) * w->gate[i];
ga_silu(w->tmp, total, w->pool);
apply_linear(&l->conv_out, w->tmp, rows, w->mean, w);
add_rows(x, w->mean, total);
for (int b = 0; b < c->count; b++)
trim_history(layer_state(c, b)->conv, (size_t)dim, &w->shapes[b]);
}
static void layer_step(const layer_ctx *c, float *x)
{
const ga_layer *l = c->l;
ga_encoder_work *w = c->w;
int rows = c->count * c->frames;
size_t total = (size_t)rows * c->st->dim;
memcpy(w->orig, x, total * sizeof(float));
feed_forward(&l->ff1_in, &l->ff1_out, x, rows, w);
attention(c, x);
if (l->kernel) {
convolution(c, x);
feed_forward(&l->ff2_in, &l->ff2_out, x, rows, w);
}
for (size_t i = 0; i < total; i++)
x[i] = w->orig[i] + GA_LAYER_BLEND * (x[i] - w->orig[i]);
ga_rms_norm(x, rows, c->st->dim, l->norm, GA_NORM_EPS, x);
}
static void stack_step(const ga_encoder *e, ga_encoder_state *const *states, int count,
ga_encoder_work *w, int index, float *io, const int *n_valid)
{
const ga_stack *st = &e->stacks[index];
layer_ctx c;
int frames = w->chunk / st->ds, rows = count * frames;
size_t total = (size_t)rows * st->dim;
for (int b = 0; b < count; b++) {
ga_step_shape *g = &w->shapes[b];
g->frames = frames;
g->valid = (n_valid[b] + st->ds - 1) / st->ds;
g->past = states[b]->n_past[index];
g->keep = w->left / st->ds;
g->cos = w->rope_cos + (size_t)index * w->rope_stride;
g->sin = w->rope_sin + (size_t)index * w->rope_stride;
if (st->ds > 1 && n_valid[b] < w->chunk)
memset(io + ((size_t)b * w->chunk + n_valid[b]) * e->feat, 0,
(size_t)(w->chunk - n_valid[b]) * e->feat * sizeof(float));
}
ga_linear(io, rows, st->in_dim, st->proj, NULL, st->dim, w->x, w->pool);
for (size_t i = 0; i < total; i++) {
w->bypass[i] = st->residual_scales[0] * w->x[i];
w->x[i] *= st->input_scale;
}
c.st = st;
c.states = states;
c.w = w;
c.stack = index;
c.count = count;
c.frames = frames;
for (int i = 0; i < st->n_layers; i++) {
float scale = st->residual_scales[i + 1];
c.l = &st->layers[i];
c.layer = i;
layer_step(&c, w->x);
for (size_t j = 0; j < total; j++)
w->bypass[j] += scale * w->x[j];
}
ga_gemm_nt(rows, st->in_dim, st->dim, 1.0f, w->bypass, st->dim, st->proj_t, st->dim,
1.0f, io, st->in_dim, w->pool);
for (int b = 0; b < count; b++) {
const ga_step_shape *g = &w->shapes[b];
states[b]->n_past[index] = g->past + g->frames > g->keep ? g->keep : g->past + g->frames;
}
}
void ga_encoder_step(const ga_encoder *e, ga_encoder_state *const *states, int count,
ga_encoder_work *w, float *x, const int *n_valid)
{
for (int i = 0; i < e->n_stacks; i++)
stack_step(e, states, count, w, i, x, n_valid);
for (int t = 0; t < count * w->chunk; t++) {
float *row = x + (size_t)t * e->feat;
float sum = 0.0f, scale;
for (int i = 0; i < e->feat; i++)
sum += row[i] * row[i];
scale = e->out_scale / sqrtf(sum / (float)e->feat + e->out_eps_sq);
for (int i = 0; i < e->feat; i++)
row[i] *= scale;
}
}