diff options
| author | Onur Gündüz <ogunduz@gmail.com> | 2026-06-17 00:42:10 +0200 |
|---|---|---|
| committer | Onur Gündüz <ogunduz@gmail.com> | 2026-06-17 00:42:10 +0200 |
| commit | 48d6191f4701fe7d059f1a298907beeba7e680bc (patch) | |
| tree | 4a1409db3b98577ab48d165392c5d106397e96a9 | |
| parent | ecc202ac078d5cb5c61d60268fce5ac46bac1e87 (diff) | |
| download | ffwd-48d6191f4701fe7d059f1a298907beeba7e680bc.tar.gz ffwd-48d6191f4701fe7d059f1a298907beeba7e680bc.zip | |
api: guard cosine similarity denominator against overflow
| -rw-r--r-- | src/vec.c | 17 | ||||
| -rw-r--r-- | tests/test_workspace.c | 19 |
2 files changed, 30 insertions, 6 deletions
@@ -35,12 +35,19 @@ float embed_cosine_similarity(const float *a, const float *b, int dim) { 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]; + float av = a[i]; + float bv = b[i]; + dot += av * bv; + norm_a_sq += av * av; + norm_b_sq += bv * bv; } - if (!(norm_a_sq > 0.0f) || !(norm_b_sq > 0.0f) || !isfinite(norm_a_sq) || !isfinite(norm_b_sq)) + if (!(norm_a_sq > 0.0f) || !(norm_b_sq > 0.0f) || !isfinite(norm_a_sq) || + !isfinite(norm_b_sq) || !isfinite(dot)) return 0.0f; - return dot / sqrtf(norm_a_sq * norm_b_sq); + + double denom = sqrt((double)norm_a_sq) * sqrt((double)norm_b_sq); + if (!(denom > 0.0) || !isfinite(denom)) + return 0.0f; + return (float)((double)dot / denom); } diff --git a/tests/test_workspace.c b/tests/test_workspace.c index 64b7404..026a4f1 100644 --- a/tests/test_workspace.c +++ b/tests/test_workspace.c @@ -43,6 +43,23 @@ static int check_alloc_helpers(void) { return 0; } +static int check_vector_helpers(void) { + float a[1] = {1.0e19f}; + float b[1] = {1.0e19f}; + float cos = embed_cosine_similarity(a, b, 1); + if (fabsf(cos - 1.0f) > 1e-5f) { + fprintf(stderr, "large finite cosine failed: got %.9g\n", cos); + return -1; + } + + float z[2] = {0.0f, 0.0f}; + if (embed_l2_normalize(z, 2) == 0 || embed_cosine_similarity(z, a, 1) != 0.0f) { + fprintf(stderr, "zero-vector helpers accepted invalid input\n"); + return -1; + } + return 0; +} + /* The allocating and pooling API variants must agree with the *_into * results validated in main. reference is the batched row for ids0. */ static int check_alloc_and_pooling_variants(const embed_model_t *model, @@ -180,7 +197,7 @@ done: } int main(int argc, char **argv) { - if (check_alloc_helpers() != 0) + if (check_alloc_helpers() != 0 || check_vector_helpers() != 0) return 1; char fixture_dir[1024]; |
