From cca81e59a9afeebe1237f713e919b5002df3d749 Mon Sep 17 00:00:00 2001 From: Onur Gündüz Date: Tue, 16 Jun 2026 17:11:55 +0200 Subject: cpu: extract alloc.{c,h} and vec.c from embed.c --- src/vec.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/vec.c (limited to 'src/vec.c') diff --git a/src/vec.c b/src/vec.c new file mode 100644 index 0000000..63bd4bc --- /dev/null +++ b/src/vec.c @@ -0,0 +1,46 @@ +#include "embed.h" + +#include + +/* ======================================================================== + * Vector helpers + * + * Standalone post-processing on embedding vectors: callers (CLI, server) use + * these to L2-normalize outputs and to score pooled embeddings with cosine + * similarity. They touch no model or tensor internals, only the public API. + * ======================================================================== */ + +int embed_l2_normalize(float *vec, int dim) { + if (!vec || dim <= 0) + return -1; + + float norm_sq = 0.0f; + for (int i = 0; i < dim; i++) + norm_sq += vec[i] * vec[i]; + + if (!(norm_sq > 0.0f) || !isfinite(norm_sq)) + return -1; + + float inv_norm = 1.0f / sqrtf(norm_sq); + for (int i = 0; i < dim; i++) + vec[i] *= inv_norm; + return 0; +} + +float embed_cosine_similarity(const float *a, const float *b, int dim) { + if (!a || !b || dim <= 0) + return 0.0f; + + float dot = 0.0f; + float norm_a_sq = 0.0f; + float norm_b_sq = 0.0f; + for (int i = 0; i < dim; i++) { + dot += a[i] * b[i]; + norm_a_sq += a[i] * a[i]; + norm_b_sq += b[i] * b[i]; + } + + if (!(norm_a_sq > 0.0f) || !(norm_b_sq > 0.0f) || !isfinite(norm_a_sq) || !isfinite(norm_b_sq)) + return 0.0f; + return dot / sqrtf(norm_a_sq * norm_b_sq); +} -- cgit v1.3.1