Build one src_entry for a token: dense float32 reference if in nomic vocab, * sparse inline representation otherwise. Collisions in the sparse hash are * merged and zeros filtered so the final representation is exactly the same * mathematical vector that the old dense path produced. */
| 1088 | * merged and zeros filtered so the final representation is exactly the same |
| 1089 | * mathematical vector that the old dense path produced. */ |
| 1090 | static void build_src_entry(const char *token, cbm_sem_src_entry_t *out) { |
| 1091 | memset(out, 0, sizeof(*out)); |
| 1092 | if (!token) { |
| 1093 | out->is_sparse = SKIP_ONE; |
| 1094 | out->nnz = 0; |
| 1095 | return; |
| 1096 | } |
| 1097 | /* Dense path: direct int8 pointer into pretrained blob (zero-copy). */ |
| 1098 | const char *idx_str = cbm_ht_get(g_pretrained_map, token); |
| 1099 | if (idx_str) { |
| 1100 | char *end = NULL; |
| 1101 | long idx = strtol(idx_str, &end, BASE_DECIMAL); |
| 1102 | if (end != idx_str && idx >= 0 && idx < PRETRAINED_TOKEN_COUNT) { |
| 1103 | out->is_sparse = 0; |
| 1104 | out->dense_int8 = pretrained_vec_at((int)idx); |
| 1105 | return; |
| 1106 | } |
| 1107 | } |
| 1108 | /* Sparse path: compute 8 hash positions with collision merging. */ |
| 1109 | out->is_sparse = SKIP_ONE; |
| 1110 | uint16_t tmp_idx[CBM_SEM_SPARSE_NNZE]; |
| 1111 | float tmp_val[CBM_SEM_SPARSE_NNZE]; |
| 1112 | int count = 0; |
| 1113 | uint64_t seed = XXH3_64bits(token, strlen(token)); |
| 1114 | for (int i = 0; i < CBM_SEM_SPARSE_NNZE; i++) { |
| 1115 | uint64_t h = XXH3_64bits_withSeed(&i, sizeof(i), seed + RI_SEED_BASE); |
| 1116 | int pos = (int)(h % CBM_SEM_DIM); |
| 1117 | float sign = (h & SKIP_ONE) ? CBM_SEM_UNIT_POS : -CBM_SEM_UNIT_POS; |
| 1118 | /* Merge collisions */ |
| 1119 | int found = CBM_NOT_FOUND; |
| 1120 | for (int j = 0; j < count; j++) { |
| 1121 | if (tmp_idx[j] == (uint16_t)pos) { |
| 1122 | found = j; |
| 1123 | break; |
| 1124 | } |
| 1125 | } |
| 1126 | if (found >= 0) { |
| 1127 | tmp_val[found] += sign; |
| 1128 | } else { |
| 1129 | tmp_idx[count] = (uint16_t)pos; |
| 1130 | tmp_val[count] = sign; |
| 1131 | count++; |
| 1132 | } |
| 1133 | } |
| 1134 | /* Filter zeros */ |
| 1135 | int nnz = 0; |
| 1136 | for (int j = 0; j < count; j++) { |
| 1137 | if (tmp_val[j] != 0.0F) { |
| 1138 | out->indices[nnz] = tmp_idx[j]; |
| 1139 | out->values[nnz] = tmp_val[j]; |
| 1140 | nnz++; |
| 1141 | } |
| 1142 | } |
| 1143 | out->nnz = (uint8_t)nnz; |
| 1144 | } |
| 1145 | |
| 1146 | static void src_build_worker(int worker_id, void *ctx_ptr) { |
| 1147 | (void)worker_id; |
no test coverage detected