nx_cosine_similarity.nx
buildroot/runtime/nx_cosine_similarity.nx
about
nx_cosine_similarity.nx -- signed Q10 cosine between two vectors.
Universal vector-space similarity. Same primitive over any nx_int
feature vectors of equal length: image-feature embeddings (for the
"AI grows by ingesting image" textual-inversion roadmap), audio
MFCC frames, token frequency histograms, latent embeddings,
document term vectors, code AST-bag features.
Math:
cos(theta) = dot(a, b) / (||a|| * ||b||)
dot(a, b) = sum a[i] * b[i]
||a|| = sqrt(dot(a, a))
All math nx_int. Newton-Raphson integer sqrt (O(log n) iterations,
no f64). Output signed Q10 in [-Q, +Q]:
+Q = parallel (same direction)
0 = orthogonal
-Q = anti-parallel (opposite direction)
Sealed-enum bands (substrate dual-reading cardinal):
NX_COSINE_BAND_ANTIPARALLEL cos <= -921 (essentially -1)
NX_COSINE_BAND_OPPOSED cos < -307
NX_COSINE_BAND_ORTHOGONAL -307 <= cos <= +307
NX_COSINE_BAND_ALIGNED cos > +307
NX_COSINE_BAND_PARALLEL cos >= +921
USE CASES (image-gen + general):
- concept-embedding lookup: incoming "new outfit" image -> feature
vector -> nearest concept in nishi-library concept store.
- prompt similarity over learned embeddings (next layer above
string-similarity).
- clustering: pairwise cosine grid + hierarchical merge.
- recommendation: user-liked-image features cosine-compared
against gallery features.
EDGE CASES:
- empty vectors (n == 0) -> return 0 (orthogonal-by-vacuum)
- zero vector (norm == 0) -> return 0 (cosine undefined)
- length mismatch -> NX_COSINE_LENGTH_MISMATCH sentinel
dependencies 2 imports · 4 importers
imports: nx_syscalls.nxnx_tier.nx
imported by: nx_concept_embedding.nxnx_cosine_similarity_test.nxnx_recall_rerank.nxnx_render_target_match.nx
structs
| none |
consts
| 66 | const NX_COSINE_Q: nx_int = 1024 |
| 67 | const NX_COSINE_LENGTH_MISMATCH: nx_int = -2147483647 // sentinel |
| 70 | const NX_COSINE_BAND_ANTIPARALLEL: nx_int = 0 |
| 71 | const NX_COSINE_BAND_OPPOSED: nx_int = 1 |
| 72 | const NX_COSINE_BAND_ORTHOGONAL: nx_int = 2 |
| 73 | const NX_COSINE_BAND_ALIGNED: nx_int = 3 |
| 74 | const NX_COSINE_BAND_PARALLEL: nx_int = 4 |
| 75 | const NX_COSINE_N_BANDS: nx_int = 5 |
functions
| 82 | func _cosine_isqrt(n: nx_int) -> nx_int called by 1: nx_cosine_similarity |
| 96 | func _cosine_dot(a: *nx_int, b: *nx_int, n: nx_int) -> nx_int called by 1: nx_cosine_similarity |
| 112 | func nx_cosine_similarity(a: *nx_int, n_a: nx_int, b: *nx_int, n_b: nx_int) -> nx_int |
| 142 | func nx_cosine_classify(cos_q10: nx_int) -> nx_int called by 1: main |
| 150 | func nx_cosine_band_is_valid(band: nx_int) -> nx_int called by 1: main |
| 161 | func nx_cosine_distance(a: *nx_int, n_a: nx_int, b: *nx_int, n_b: nx_int) -> nx_int |