diff options
| author | Onur Gündüz <ogunduz@gmail.com> | 2026-06-20 20:10:56 +0200 |
|---|---|---|
| committer | Onur Gündüz <ogunduz@gmail.com> | 2026-06-21 05:57:19 +0200 |
| commit | 6b969d25ce136eaf695222bd1a10bff1ecac0220 (patch) | |
| tree | c23afb50c28b9deaddae5c6526a74ee11cf2d865 /src/model.c | |
| parent | d4bdb8dae753462f621507d5fc3582e0e53da35c (diff) | |
| download | ffwd-6b969d25ce136eaf695222bd1a10bff1ecac0220.tar.gz ffwd-6b969d25ce136eaf695222bd1a10bff1ecac0220.zip | |
all: split Makefile and reorg library/tools
Diffstat (limited to '')
| -rw-r--r-- | libffwd/model.c (renamed from src/model.c) | 352 |
1 files changed, 88 insertions, 264 deletions
diff --git a/src/model.c b/libffwd/model.c index c39c526..faecfd4 100644 --- a/src/model.c +++ b/libffwd/model.c @@ -1,19 +1,12 @@ -#include "embed.h" +#include "ffwd.h" #include "model_internal.h" #include "config.h" -#include "kernels.h" +#include "dtype.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> -#include <math.h> -#include <limits.h> - -/* ======================================================================== - * Globals - * ======================================================================== */ - -int embed_verbose = 0; +#include <string.h> /* ======================================================================== * Model-directory probes @@ -81,12 +74,12 @@ int tensor_has_supported_shape(const safetensors_file_t *sf, * to F32 by the caller (BF16 lazily per matmul, F16 once at load). */ int sixteen_ok = bf16_ok && (t->dtype == DTYPE_BF16 || t->dtype == DTYPE_F16); if (t->dtype != DTYPE_F32 && !sixteen_ok) { - fprintf(stderr, "embed: unsupported dtype for %s: got %s, expected %s\n", name, + fprintf(stderr, "ffwd: unsupported dtype for %s: got %s, expected %s\n", name, dtype_name(t->dtype), bf16_ok ? "F32, BF16, or F16" : "F32"); return 0; } if (t->ndim != ndim) { - fprintf(stderr, "embed: bad rank for %s: got %d, expected %d\n", name, t->ndim, ndim); + fprintf(stderr, "ffwd: bad rank for %s: got %d, expected %d\n", name, t->ndim, ndim); return 0; } @@ -94,13 +87,13 @@ int tensor_has_supported_shape(const safetensors_file_t *sf, for (int i = 0; i < ndim; i++) { if (t->shape[i] != shape[i]) { fprintf(stderr, - "embed: bad shape for %s at dim %d: " + "ffwd: bad shape for %s at dim %d: " "got %lld, expected %lld\n", name, i, (long long)t->shape[i], (long long)shape[i]); return 0; } if (shape[i] < 0 || (uint64_t)shape[i] > SIZE_MAX / numel) { - fprintf(stderr, "embed: shape too large for %s\n", name); + fprintf(stderr, "ffwd: shape too large for %s\n", name); return 0; } numel *= (size_t)shape[i]; @@ -108,17 +101,17 @@ int tensor_has_supported_shape(const safetensors_file_t *sf, size_t elem_size = dtype_size(t->dtype); if (elem_size == 0) { - fprintf(stderr, "embed: unsupported dtype for %s: got %s\n", name, dtype_name(t->dtype)); + fprintf(stderr, "ffwd: unsupported dtype for %s: got %s\n", name, dtype_name(t->dtype)); return 0; } size_t bytes; if (mul_size(numel, elem_size, &bytes) != 0) { - fprintf(stderr, "embed: tensor data too large for %s\n", name); + fprintf(stderr, "ffwd: tensor data too large for %s\n", name); return 0; } if (t->data_size != bytes) { - fprintf(stderr, "embed: bad data size for %s: got %zu, expected %zu\n", name, t->data_size, + fprintf(stderr, "ffwd: bad data size for %s: got %zu, expected %zu\n", name, t->data_size, bytes); return 0; } @@ -126,14 +119,47 @@ int tensor_has_supported_shape(const safetensors_file_t *sf, size_t data_start = 8 + sf->header_size; if (data_start > sf->file_size || t->data_offset > sf->file_size - data_start || t->data_size > sf->file_size - data_start - t->data_offset) { - fprintf(stderr, "embed: tensor data out of bounds for %s\n", name); + fprintf(stderr, "ffwd: tensor data out of bounds for %s\n", name); return 0; } return 1; } -embed_weight_ref_t weight_ref_from_tensor(const safetensors_file_t *sf, const safetensor_t *t) { - embed_weight_ref_t ref = {DTYPE_UNKNOWN, NULL, 0}; +/* Widen a safetensors tensor to f32 (caller frees). libsafetensors is a pure + * reader now, so the dtype conversion lives here, next to its only callers. */ +static float *safetensors_get_f32(const safetensors_file_t *sf, const safetensor_t *t) { + int64_t n = safetensor_numel(t); + if (n <= 0) + return NULL; + float *out = malloc((size_t)n * sizeof(float)); + if (!out) + return NULL; + const void *data = safetensors_data(sf, t); + switch (t->dtype) { + case DTYPE_F32: + memcpy(out, data, (size_t)n * sizeof(float)); + break; + case DTYPE_BF16: { + const uint16_t *s = (const uint16_t *)data; + for (int64_t i = 0; i < n; i++) + out[i] = ffwd_bf16_to_f32(s[i]); + break; + } + case DTYPE_F16: { + const uint16_t *s = (const uint16_t *)data; + for (int64_t i = 0; i < n; i++) + out[i] = ffwd_f16_to_f32(s[i]); + break; + } + default: + free(out); + return NULL; + } + return out; +} + +ffwd_weight_ref_t weight_ref_from_tensor(const safetensors_file_t *sf, const safetensor_t *t) { + ffwd_weight_ref_t ref = {DTYPE_UNKNOWN, NULL, 0}; /* F32/BF16 are consumed directly by the forward pass, so the ref borrows the * mmap (zero copy; BF16 is widened lazily per matmul). F16 has neither a * fused kernel nor a zero-copy F32 view, so widen it once here into an owned @@ -152,13 +178,13 @@ embed_weight_ref_t weight_ref_from_tensor(const safetensors_file_t *sf, const sa return ref; } -static embed_weight_ref_t +static ffwd_weight_ref_t load_weight_direct(multi_safetensors_t *ms, const char *name, const int64_t *shape, int ndim) { - embed_weight_ref_t ref = {DTYPE_UNKNOWN, NULL, 0}; + ffwd_weight_ref_t ref = {DTYPE_UNKNOWN, NULL, 0}; safetensors_file_t *sf = NULL; const safetensor_t *t = multi_safetensors_find(ms, name, &sf); if (!t) { - fprintf(stderr, "embed: tensor not found: %s\n", name); + fprintf(stderr, "ffwd: tensor not found: %s\n", name); return ref; } if (!tensor_has_supported_shape(sf, t, name, shape, ndim, 1)) @@ -172,7 +198,7 @@ load_norm_f32(multi_safetensors_t *ms, const char *name, const int64_t *shape, i safetensors_file_t *sf = NULL; const safetensor_t *t = multi_safetensors_find(ms, name, &sf); if (!t) { - fprintf(stderr, "embed: tensor not found: %s\n", name); + fprintf(stderr, "ffwd: tensor not found: %s\n", name); return NULL; } if (!tensor_has_supported_shape(sf, t, name, shape, ndim, 1)) @@ -186,13 +212,13 @@ load_norm_f32(multi_safetensors_t *ms, const char *name, const int64_t *shape, i /* BERT-family weight loader. The tensor names differ entirely from the Qwen * block (encoder.layer.N.*, embeddings.*), so the family gets its own entry - * point. Reused embed_layer_t slots carry their BERT meaning: wo is the + * point. Reused ffwd_layer_t slots carry their BERT meaning: wo is the * attention output dense, input_norm/post_attn_norm are the two block LayerNorm - * weights, up_proj/down_proj are the two FFN matrices (see embed_internal.h). */ + * weights, up_proj/down_proj are the two FFN matrices (see internal.h). */ static int -load_bert_weights(embed_model_t *model, multi_safetensors_t *ms, int layer_start, int layer_end) { - const embed_config_t *cfg = &model->config; - embed_weights_t *w = &model->weights; +load_bert_weights(ffwd_model_t *model, multi_safetensors_t *ms, int layer_start, int layer_end) { + const ffwd_config_t *cfg = &model->config; + ffwd_weights_t *w = &model->weights; char name[256]; /* sentence-transformers checkpoints store encoder tensors unprefixed; raw @@ -205,7 +231,7 @@ load_bert_weights(embed_model_t *model, multi_safetensors_t *ms, int layer_start else if (multi_safetensors_find(ms, "roberta.embeddings.word_embeddings.weight", NULL)) p = "roberta."; else { - fprintf(stderr, "embed_model_load: BERT-family word embeddings not found\n"); + fprintf(stderr, "ffwd_model_load: BERT-family word embeddings not found\n"); return -1; } @@ -223,20 +249,20 @@ load_bert_weights(embed_model_t *model, multi_safetensors_t *ms, int layer_start w->token_type_embeddings = load_norm_f32(ms, name, type_shape, 2); const int64_t ln_shape[1] = {hidden}; snprintf(name, sizeof(name), "%sembeddings.LayerNorm.weight", p); - w->embed_ln_w = load_norm_f32(ms, name, ln_shape, 1); + w->ffwd_ln_w = load_norm_f32(ms, name, ln_shape, 1); snprintf(name, sizeof(name), "%sembeddings.LayerNorm.bias", p); - w->embed_ln_b = load_norm_f32(ms, name, ln_shape, 1); + w->ffwd_ln_b = load_norm_f32(ms, name, ln_shape, 1); if (!w->embed_tokens.data || !w->position_embeddings || !w->token_type_embeddings || - !w->embed_ln_w || !w->embed_ln_b) + !w->ffwd_ln_w || !w->ffwd_ln_b) return -1; } - w->layers = (embed_layer_t *)calloc(cfg->n_layers, sizeof(embed_layer_t)); + w->layers = (ffwd_layer_t *)calloc(cfg->n_layers, sizeof(ffwd_layer_t)); if (!w->layers) return -1; for (int i = layer_start; i < layer_end; i++) { - embed_layer_t *l = &w->layers[i]; + ffwd_layer_t *l = &w->layers[i]; #define BERT_W(field, suffix, d0, d1) \ do { \ @@ -279,31 +305,31 @@ load_bert_weights(embed_model_t *model, multi_safetensors_t *ms, int layer_start return 0; } -embed_model_t * +ffwd_model_t * model_load_range_ex(const char *model_dir, int layer_start, int layer_end, int allow_late) { if (!allow_late && model_dir_has_late_projection(model_dir)) { - fprintf(stderr, "embed_model_load: late-interaction models require " + fprintf(stderr, "ffwd_model_load: late-interaction models require " "token-level MaxSim support and are not valid pooled " "embedding models yet\n"); return NULL; } - embed_model_t *model = (embed_model_t *)calloc(1, sizeof(embed_model_t)); + ffwd_model_t *model = (ffwd_model_t *)calloc(1, sizeof(ffwd_model_t)); if (!model) return NULL; /* Parse config.json */ - if (embed_config_parse(&model->config, model_dir) != 0) { + if (ffwd_config_parse(&model->config, model_dir) != 0) { free(model); return NULL; } - const embed_config_t *cfg = &model->config; + const ffwd_config_t *cfg = &model->config; if (layer_end == -1) layer_end = cfg->n_layers; if (layer_start < 0 || layer_start >= layer_end || layer_end > cfg->n_layers) { fprintf(stderr, - "embed_model_load: invalid layer range [%d, %d) " + "ffwd_model_load: invalid layer range [%d, %d) " "for %d-layer model\n", layer_start, layer_end, cfg->n_layers); free(model); @@ -311,42 +337,39 @@ model_load_range_ex(const char *model_dir, int layer_start, int layer_end, int a } model->layer_start = layer_start; model->layer_end = layer_end; - model->attention = cfg->attention_mode == EMBED_ATTENTION_CAUSAL - ? embed_causal_gqa_attention_packed_with_scratch - : embed_bidirectional_gqa_attention_packed_with_scratch; /* Open safetensors (handles single file or multi-shard) */ multi_safetensors_t *ms = multi_safetensors_open(model_dir); if (!ms) { - fprintf(stderr, "embed_model_load: failed to open safetensors in %s\n", model_dir); + fprintf(stderr, "ffwd_model_load: failed to open safetensors in %s\n", model_dir); free(model); return NULL; } model->safetensors = ms; - if (cfg->family == EMBED_FAMILY_BERT) { + if (cfg->family == FFWD_FAMILY_BERT) { if (load_bert_weights(model, ms, layer_start, layer_end) != 0) goto fail; - if (embed_verbose >= 1) - fprintf(stderr, "embed_model_load: BERT layers [%d, %d) loaded (%d-dim)\n", layer_start, + if (ffwd_verbose >= 1) + fprintf(stderr, "ffwd_model_load: BERT layers [%d, %d) loaded (%d-dim)\n", layer_start, layer_end, cfg->hidden_size); return model; } const char *weight_prefix = multi_safetensors_weight_prefix(ms, "embed_tokens.weight"); if (!weight_prefix) { - fprintf(stderr, "embed_model_load: neither embed_tokens.weight nor " + fprintf(stderr, "ffwd_model_load: neither embed_tokens.weight nor " "model.embed_tokens.weight was found\n"); goto fail; } - if (embed_verbose >= 1) - fprintf(stderr, "embed_model_load: loading weights from %s\n", model_dir); + if (ffwd_verbose >= 1) + fprintf(stderr, "ffwd_model_load: loading weights from %s\n", model_dir); char name[256]; /* Only the first stage needs token embeddings. */ - embed_weights_t *w = &model->weights; + ffwd_weights_t *w = &model->weights; if (layer_start == 0) { const int64_t embed_shape[2] = {cfg->vocab_size, cfg->hidden_size}; snprintf(name, sizeof(name), "%sembed_tokens.weight", weight_prefix); @@ -356,13 +379,13 @@ model_load_range_ex(const char *model_dir, int layer_start, int layer_end, int a } /* Allocate layer array */ - w->layers = (embed_layer_t *)calloc(cfg->n_layers, sizeof(embed_layer_t)); + w->layers = (ffwd_layer_t *)calloc(cfg->n_layers, sizeof(ffwd_layer_t)); if (!w->layers) goto fail; /* Per-layer weights */ for (int i = layer_start; i < layer_end; i++) { - embed_layer_t *l = &w->layers[i]; + ffwd_layer_t *l = &w->layers[i]; #define LOAD_NORM(field, fmt, d0) \ do { \ @@ -406,7 +429,7 @@ model_load_range_ex(const char *model_dir, int layer_start, int layer_end, int a #undef LOAD2 #undef LOAD_NORM - if (embed_verbose >= 2) + if (ffwd_verbose >= 2) fprintf(stderr, " layer %d loaded\n", i); } @@ -419,38 +442,38 @@ model_load_range_ex(const char *model_dir, int layer_start, int layer_end, int a goto fail; } - if (embed_verbose >= 1) + if (ffwd_verbose >= 1) fprintf(stderr, - "embed_model_load: layers [%d, %d) loaded " + "ffwd_model_load: layers [%d, %d) loaded " "(%d-dim embeddings)\n", layer_start, layer_end, cfg->hidden_size); return model; fail: - embed_model_free(model); + ffwd_model_free(model); return NULL; } -embed_model_t *embed_model_load(const char *model_dir) { +ffwd_model_t *ffwd_model_load(const char *model_dir) { return model_load_range_ex(model_dir, 0, -1, 0); } /* Release a weight ref's backing store. Only F16-widened refs own their buffer; * borrowed F32/BF16 views into the mmap are a no-op (see weight_ref_from_tensor). */ -static void free_weight_ref(embed_weight_ref_t *w) { +static void free_weight_ref(ffwd_weight_ref_t *w) { if (w->owned) free((void *)w->data); w->data = NULL; w->owned = 0; } -void embed_model_free(embed_model_t *model) { +void ffwd_model_free(ffwd_model_t *model) { if (!model) return; if (model->weights.layers) { for (int i = 0; i < model->config.n_layers; i++) { - embed_layer_t *l = &model->weights.layers[i]; + ffwd_layer_t *l = &model->weights.layers[i]; free_weight_ref(&l->wq); free_weight_ref(&l->wk); free_weight_ref(&l->wv); @@ -476,213 +499,14 @@ void embed_model_free(embed_model_t *model) { free((void *)model->weights.norm); free((void *)model->weights.position_embeddings); free((void *)model->weights.token_type_embeddings); - free((void *)model->weights.embed_ln_w); - free((void *)model->weights.embed_ln_b); + free((void *)model->weights.ffwd_ln_w); + free((void *)model->weights.ffwd_ln_b); if (model->safetensors) multi_safetensors_close((multi_safetensors_t *)model->safetensors); free(model->weights.layers); free(model); } -embed_workspace_t *embed_workspace_new(const embed_model_t *model) { - if (!model) - return NULL; - embed_workspace_t *ws = (embed_workspace_t *)calloc(1, sizeof(embed_workspace_t)); - if (!ws) - return NULL; - ws->model = model; - return ws; -} - -void embed_workspace_free(embed_workspace_t *ws) { - if (!ws) - return; - free(ws->x); - free(ws->x_norm); - free(ws->q); - free(ws->k); - free(ws->v); - free(ws->attn_out); - free(ws->proj_out); - free(ws->ffn_gate); - free(ws->ffn_up); - free(ws->attn_scores); - free(ws->offsets); - free(ws->rope_cos); - free(ws->rope_sin); - free(ws->bf16_widen); - free(ws); -} - -const embed_config_t *embed_model_config(const embed_model_t *model) { +const ffwd_config_t *ffwd_model_config(const ffwd_model_t *model) { return model ? &model->config : NULL; } - -/* ======================================================================== - * Workspace buffer growth - * - * Lazy per-call growth of the forward-pass scratch. Lives here, beside the - * workspace lifecycle and embed_workspace_nbytes below: nbytes reproduces these - * allocation sizes, so the allocator and the accountant stay in one file. - * ======================================================================== */ - -int ensure_buffers(embed_workspace_t *ws, const embed_config_t *c, int seq) { - if (seq <= ws->buf_seq_cap) - return 0; - - int cap; - if (grow_cap(ws->buf_seq_cap, seq, &cap) != 0) - return -1; - -#define R(ptr, n) \ - do { \ - if (realloc_floats_2d(&(ptr), cap, (n)) != 0) \ - return -1; \ - } while (0) - - R(ws->x, c->hidden_size); - R(ws->x_norm, c->hidden_size); - R(ws->q, c->q_dim); - R(ws->k, c->kv_dim); - R(ws->v, c->kv_dim); - R(ws->attn_out, c->q_dim); - R(ws->proj_out, c->hidden_size); - R(ws->ffn_gate, c->intermediate_size); - R(ws->ffn_up, c->intermediate_size); - -#undef R - - ws->buf_seq_cap = cap; - return 0; -} - -void ensure_attention_scores(embed_workspace_t *ws, const int *offsets, int batch) { - size_t bytes = embed_bidirectional_gqa_attention_packed_scratch_bytes(offsets, batch); - if (bytes <= ws->attn_scores_bytes) - return; - - void *p = realloc(ws->attn_scores, bytes); - if (!p) - return; - ws->attn_scores = (float *)p; - ws->attn_scores_bytes = bytes; -} - -int ensure_rope_cache(embed_workspace_t *ws, const embed_config_t *cfg, int n_pos) { - if (n_pos <= ws->rope_cache_cap) - return 0; - - int cap = ws->rope_cache_cap > 0 ? ws->rope_cache_cap : 512; - while (cap < n_pos) { - if (cap > INT_MAX / 2) - return -1; - cap *= 2; - } - - int head_dim = cfg->head_dim; - int half = head_dim / 2; - float theta = cfg->rope_theta; - - size_t count; - if (mul_size((size_t)cap, (size_t)head_dim, &count) != 0) - return -1; - if (realloc_floats(&ws->rope_cos, count) != 0) - return -1; - if (realloc_floats(&ws->rope_sin, count) != 0) - return -1; - - for (int pos = ws->rope_cache_cap; pos < cap; pos++) { - float fp = (float)pos; - float *c = ws->rope_cos + (size_t)pos * head_dim; - float *s = ws->rope_sin + (size_t)pos * head_dim; - for (int d = 0; d < half; d++) { - float inv = 1.0f / powf(theta, (float)(2 * d) / (float)head_dim); - float angle = fp * inv; - float cv = cosf(angle), sv = sinf(angle); - c[d] = cv; - c[half + d] = cv; - s[d] = sv; - s[half + d] = sv; - } - } - - ws->rope_cache_cap = cap; - return 0; -} - -int ensure_offsets(embed_workspace_t *ws, int batch) { - if (!ws || batch <= 0 || batch == INT_MAX) - return -1; - - int needed = batch + 1; - if (needed <= ws->offsets_cap) - return 0; - - if (realloc_ints(&ws->offsets, (size_t)needed) != 0) - return -1; - ws->offsets_cap = needed; - return 0; -} - -size_t embed_workspace_nbytes(const embed_workspace_t *ws) { - if (!ws) - return 0; - - size_t total = sizeof(*ws); - const embed_model_t *model = ws->model; - if (!model) - return total; - - const embed_config_t *c = &model->config; - size_t row_floats = 0; - const int dims[] = { - c->hidden_size, /* x */ - c->hidden_size, /* x_norm */ - c->q_dim, /* q */ - c->kv_dim, /* k */ - c->kv_dim, /* v */ - c->q_dim, /* attn_out */ - c->hidden_size, /* proj_out */ - c->intermediate_size, /* ffn_gate */ - c->intermediate_size, /* ffn_up */ - }; - - for (size_t i = 0; i < sizeof(dims) / sizeof(dims[0]); i++) { - if (dims[i] < 0 || add_size(row_floats, (size_t)dims[i], &row_floats) != 0) - return SIZE_MAX; - } - - size_t buf_floats = 0; - if (ws->buf_seq_cap > 0 && mul_size((size_t)ws->buf_seq_cap, row_floats, &buf_floats) != 0) - return SIZE_MAX; - - size_t rope_floats = 0; - if (ws->rope_cache_cap > 0) { - size_t rope_rows = 0; - if (mul_size((size_t)ws->rope_cache_cap, (size_t)c->head_dim, &rope_rows) != 0 || - mul_size(rope_rows, 2, &rope_floats) != 0) - return SIZE_MAX; - } - - size_t all_floats = 0, bytes = 0; - if (add_size(buf_floats, rope_floats, &all_floats) != 0 || - mul_size(all_floats, sizeof(float), &bytes) != 0 || add_size(total, bytes, &total) != 0) - return SIZE_MAX; - - size_t offset_bytes = 0; - if (ws->offsets_cap > 0 && mul_size((size_t)ws->offsets_cap, sizeof(int), &offset_bytes) != 0) - return SIZE_MAX; - if (add_size(total, offset_bytes, &total) != 0) - return SIZE_MAX; - if (add_size(total, ws->attn_scores_bytes, &total) != 0) - return SIZE_MAX; - - size_t widen_bytes = 0; - if (ws->bf16_widen_count > 0 && - mul_size(ws->bf16_widen_count, sizeof(float), &widen_bytes) != 0) - return SIZE_MAX; - if (add_size(total, widen_bytes, &total) != 0) - return SIZE_MAX; - - return total; -} |
