From 10bf114474d5b79193159e5c865734362cf7abfb Mon Sep 17 00:00:00 2001 From: Onur Gündüz Date: Sat, 30 May 2026 10:36:10 +0200 Subject: api: add opt-in l2 normalization helper --- pplx_embed.c | 34 +++++++++++++++++++++++++++++++--- pplx_embed.h | 9 +++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/pplx_embed.c b/pplx_embed.c index 9c02fa9..ba77676 100644 --- a/pplx_embed.c +++ b/pplx_embed.c @@ -1070,12 +1070,40 @@ float *pplx_model_embed(const pplx_model_t *model, pplx_workspace_t *ws, } /* ======================================================================== - * Cosine similarity + * Vector helpers * ======================================================================== */ +int pplx_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 pplx_cosine_similarity(const float *a, const float *b, int dim) { + if (!a || !b || dim <= 0) return 0.0f; + float dot = 0.0f; - for (int i = 0; i < dim; i++) dot += a[i] * b[i]; - return dot; + 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); } diff --git a/pplx_embed.h b/pplx_embed.h index 276c67f..0816e20 100644 --- a/pplx_embed.h +++ b/pplx_embed.h @@ -164,8 +164,17 @@ int pplx_model_embed_spans(const pplx_model_t *model, pplx_workspace_t *ws, const pplx_span_t *spans, int n_spans, float *out_embeddings); +/* + * L2-normalize vec[dim] in place. + * + * Returns 0 on success. Returns -1 for invalid arguments or a zero-length + * vector, which cannot be normalized. + */ +int pplx_l2_normalize(float *vec, int dim); + /* * Cosine similarity between two vectors. + * Returns 0 for invalid arguments or if either vector has zero length. */ float pplx_cosine_similarity(const float *a, const float *b, int dim); -- cgit v1.3.1