| 1 | /* |
| 2 | Copyright (C) 2025 Sutou Kouhei <[email protected]> |
| 3 | |
| 4 | This library is free software; you can redistribute it and/or |
| 5 | modify it under the terms of the GNU Lesser General Public |
| 6 | License as published by the Free Software Foundation; either |
| 7 | version 2.1 of the License, or (at your option) any later version. |
| 8 | |
| 9 | This library is distributed in the hope that it will be useful, |
| 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 12 | Lesser General Public License for more details. |
| 13 | |
| 14 | You should have received a copy of the GNU Lesser General Public |
| 15 | License along with this library; if not, write to the Free Software |
| 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
| 17 | */ |
| 18 | |
| 19 | #ifdef GRN_EMBEDDED |
| 20 | # define GRN_PLUGIN_FUNCTION_TAG language_model_knn |
| 21 | #endif |
| 22 | |
| 23 | #include <groonga.h> |
| 24 | #include <groonga/tokenizer.h> |
| 25 | |
| 26 | #include <faiss/Clustering.h> |
| 27 | #include <faiss/IndexFlat.h> |
| 28 | #include <faiss/VectorTransform.h> |
| 29 | |
| 30 | #define FAISS_VERSION_OR_LATER(major, minor, micro) \ |
| 31 | (FAISS_VERSION_MAJOR > (major) || \ |
| 32 | (FAISS_VERSION_MAJOR == (major) && FAISS_VERSION_MINOR > (minor)) || \ |
| 33 | (FAISS_VERSION_MAJOR == (major) && FAISS_VERSION_MINOR == (minor) && \ |
| 34 | FAISS_VERSION_MICRO >= (micro))) |
| 35 | |
| 36 | #if FAISS_VERSION_OR_LATER(1, 7, 3) |
| 37 | # define GRN_FAISS_HAVE_FLAT_CODES_DISTANCE_COMPUTER |
| 38 | #endif |
| 39 | |
| 40 | #if !FAISS_VERSION_OR_LATER(1, 7, 4) |
| 41 | namespace faiss { |
| 42 | using idx_t = Index::idx_t; |
| 43 | }; |
| 44 | #endif |
| 45 | |
| 46 | #if FAISS_VERSION_OR_LATER(1, 11, 0) |
| 47 | # define GRN_FAISS_HAVE_RABITQ |
| 48 | # define GRN_FAISS_HAVE_MAYBE_OWNED_VECTOR |
| 49 | # include <faiss/impl/RaBitQuantizer.h> |
| 50 | #endif |
| 51 | |
| 52 | #include <algorithm> |
| 53 | #include <cinttypes> |
| 54 | #include <cmath> |
| 55 | #include <optional> |
| 56 | #include <string> |
| 57 | #include <utility> |
| 58 | #include <vector> |
| 59 | |
| 60 | #ifndef _WIN32 |
| 61 | # include <unistd.h> |
| 62 | #endif |
| 63 | |
| 64 | /* IVF based approximate nearest neighbor search implementation. */ |
| 65 | |
| 66 | namespace { |
| 67 | const char *TAG = "[language-model][knn]"; |
| 68 | const int SEED = 29; |
| 69 | |
| 70 | enum class Quantizer { |
| 71 | NONE, |
| 72 | RABITQ, |
| 73 | }; |
| 74 | |
| 75 | struct Options { |
| 76 | /* Input */ |
| 77 | std::string model_name; |
| 78 | int32_t n_gpu_layers; |
| 79 | std::string centroid_column_name; |
| 80 | uint32_t n_clusters; |
| 81 | Quantizer quantizer; |
| 82 | std::string code_column_name; |
| 83 | std::string passage_prefix; |
| 84 | std::string query_prefix; |
| 85 | |
| 86 | /* Others are cached data for performance. */ |
| 87 | |
| 88 | grn_language_model *model; |
| 89 | grn_language_model_inferencer *inferencer; |
| 90 | uint32_t n_dimensions; |
| 91 | std::vector<float> centroids; |
| 92 | std::vector<grn_id> centroid_index_to_record_id; |
| 93 | faiss::IndexFlatIP centroid_searcher; |
| 94 | |
| 95 | /* For clustering */ |
| 96 | grn_obj *centroid_column; |
| 97 | |
| 98 | /* For quantization */ |
| 99 | grn_obj *code_column; |
| 100 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 101 | /* For RaBitQ */ |
| 102 | faiss::RandomRotationMatrix random_rotation_matrix; /* P in RaBitQ */ |
| 103 | faiss::RaBitQuantizer rabitq; |
| 104 | #endif |
| 105 | }; |
| 106 | |
| 107 | void |
| 108 | options_init(grn_ctx *ctx, Options *options) |
| 109 | { |
| 110 | new (&options->model_name) std::string; |
| 111 | options->n_gpu_layers = GRN_LANGUAGE_MODEL_LOADER_N_GPU_LAYERS_DEFAULT; |
| 112 | new (&options->centroid_column_name) std::string; |
| 113 | new (&options->code_column_name) std::string; |
| 114 | new (&options->passage_prefix) std::string; |
| 115 | new (&options->query_prefix) std::string; |
| 116 | options->n_clusters = 0; |
| 117 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 118 | options->quantizer = Quantizer::RABITQ; |
| 119 | #else |
| 120 | options->quantizer = Quantizer::NONE; |
| 121 | #endif |
| 122 | |
| 123 | options->model = nullptr; |
| 124 | options->inferencer = nullptr; |
| 125 | options->n_dimensions = 0; |
| 126 | new (&options->centroids) std::vector<float>; |
| 127 | new (&options->centroid_index_to_record_id) std::vector<grn_id>; |
| 128 | new (&options->centroid_searcher) faiss::IndexFlatIP; |
| 129 | |
| 130 | options->centroid_column = nullptr; |
| 131 | |
| 132 | options->code_column = nullptr; |
| 133 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 134 | new (&options->random_rotation_matrix) faiss::RandomRotationMatrix; |
| 135 | new (&options->rabitq) faiss::RaBitQuantizer; |
| 136 | #endif |
| 137 | } |
| 138 | |
| 139 | void |
| 140 | options_fin(grn_ctx *ctx, Options *options) |
| 141 | { |
| 142 | if (options->inferencer) { |
| 143 | grn_language_model_inferencer_close(ctx, options->inferencer); |
| 144 | } |
| 145 | if (options->model) { |
| 146 | grn_language_model_close(ctx, options->model); |
| 147 | } |
| 148 | options->model_name.~basic_string(); |
| 149 | |
| 150 | // This may not work when this options is closed by grn_fin() |
| 151 | // because centroid_column/code_column may be alread closed. |
| 152 | // if (options->centroid_column) { |
| 153 | // grn_obj_unref(ctx, options->centroid_column); |
| 154 | // } |
| 155 | // if (options->code_column) { |
| 156 | // grn_obj_unref(ctx, options->code_column); |
| 157 | // } |
| 158 | options->centroid_column_name.~basic_string(); |
| 159 | options->code_column_name.~basic_string(); |
| 160 | |
| 161 | options->passage_prefix.~basic_string(); |
| 162 | options->query_prefix.~basic_string(); |
| 163 | |
| 164 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 165 | options->rabitq.~RaBitQuantizer(); |
| 166 | options->random_rotation_matrix.~RandomRotationMatrix(); |
| 167 | #endif |
| 168 | |
| 169 | options->centroid_searcher.~IndexFlatIP(); |
| 170 | options->centroid_index_to_record_id.~vector(); |
| 171 | options->centroids.~vector(); |
| 172 | } |
| 173 | |
| 174 | const char *TOKENIZER_TAG = "[tokenizer][language-model]"; |
| 175 | struct Tokenizer { |
| 176 | grn_obj *lexicon; |
| 177 | grn_obj *source_table; |
| 178 | Options *options; |
| 179 | std::string_view query; |
| 180 | grn_obj embedding; |
| 181 | grn_obj transformed_embedding; |
| 182 | grn_obj code; |
| 183 | // We need to keep token data until the next next() is called. |
| 184 | uint32_t current_centroid_id; |
| 185 | }; |
| 186 | |
| 187 | Tokenizer * |
| 188 | tokenizer_open(grn_ctx *ctx, Options *options, std::string_view query) |
| 189 | { |
| 190 | auto tokenizer = |
| 191 | static_cast<Tokenizer *>(GRN_PLUGIN_CALLOC(ctx, sizeof(Tokenizer))); |
| 192 | if (!tokenizer) { |
| 193 | GRN_PLUGIN_ERROR(ctx, |
| 194 | GRN_NO_MEMORY_AVAILABLE, |
| 195 | "%s failed to allocate tokenizer", |
| 196 | TOKENIZER_TAG); |
| 197 | return nullptr; |
| 198 | } |
| 199 | |
| 200 | tokenizer->options = options; |
| 201 | tokenizer->query = query; |
| 202 | GRN_FLOAT32_INIT(&(tokenizer->embedding), GRN_OBJ_VECTOR); |
| 203 | GRN_FLOAT32_INIT(&(tokenizer->transformed_embedding), GRN_OBJ_VECTOR); |
| 204 | if (options->quantizer == Quantizer::NONE) { |
| 205 | GRN_SHORT_BINARY_INIT(&(tokenizer->code), GRN_OBJ_DO_SHALLOW_COPY); |
| 206 | } else { |
| 207 | GRN_SHORT_BINARY_INIT(&(tokenizer->code), 0); |
| 208 | } |
| 209 | |
| 210 | return tokenizer; |
| 211 | } |
| 212 | |
| 213 | void |
| 214 | tokenizer_close(grn_ctx *ctx, Tokenizer *tokenizer) |
| 215 | { |
| 216 | GRN_OBJ_FIN(ctx, &(tokenizer->embedding)); |
| 217 | GRN_OBJ_FIN(ctx, &(tokenizer->transformed_embedding)); |
| 218 | GRN_OBJ_FIN(ctx, &(tokenizer->code)); |
| 219 | GRN_PLUGIN_FREE(ctx, tokenizer); |
| 220 | } |
| 221 | |
| 222 | struct OpenOptionsData { |
| 223 | grn_obj *lexicon; |
| 224 | grn_obj *source_table; |
| 225 | }; |
| 226 | |
| 227 | void |
| 228 | close_options(grn_ctx *ctx, void *data) |
| 229 | { |
| 230 | Options *options = static_cast<Options *>(data); |
| 231 | options_fin(ctx, options); |
| 232 | GRN_PLUGIN_FREE(ctx, options); |
| 233 | } |
| 234 | |
| 235 | void * |
| 236 | open_options(grn_ctx *ctx, |
| 237 | grn_obj *tokenizer, |
| 238 | grn_obj *raw_options, |
| 239 | void *user_data) |
| 240 | { |
| 241 | auto data = static_cast<OpenOptionsData *>(user_data); |
| 242 | auto options = |
| 243 | static_cast<Options *>(GRN_PLUGIN_CALLOC(ctx, sizeof(Options))); |
| 244 | if (!options) { |
| 245 | GRN_PLUGIN_ERROR(ctx, |
| 246 | GRN_NO_MEMORY_AVAILABLE, |
| 247 | "%s failed to allocate memory for options", |
| 248 | TOKENIZER_TAG); |
| 249 | return nullptr; |
| 250 | } |
| 251 | |
| 252 | auto set_string = |
| 253 | [&](std::string &target, grn_obj *raw_options, unsigned int i) { |
| 254 | const char *raw_value = nullptr; |
| 255 | grn_id domain = GRN_ID_NIL; |
| 256 | auto length = grn_vector_get_element(ctx, |
| 257 | raw_options, |
| 258 | i, |
| 259 | &raw_value, |
| 260 | nullptr, |
| 261 | &domain); |
| 262 | if (grn_type_id_is_text_family(ctx, domain)) { |
| 263 | target = std::string(raw_value, length); |
| 264 | } |
| 265 | }; |
| 266 | |
| 267 | options_init(ctx, options); |
| 268 | GRN_OPTION_VALUES_EACH_BEGIN(ctx, raw_options, i, name, name_length) |
| 269 | { |
| 270 | std::string_view name_raw(name, name_length); |
| 271 | |
| 272 | if (name_raw == "model") { |
| 273 | set_string(options->model_name, raw_options, i); |
| 274 | } else if (name_raw == "n_gpu_layers") { |
| 275 | options->n_gpu_layers = |
| 276 | grn_vector_get_element_int32(ctx, |
| 277 | raw_options, |
| 278 | i, |
| 279 | options->n_gpu_layers); |
| 280 | } else if (name_raw == "n_clusters") { |
| 281 | options->n_clusters = |
| 282 | grn_vector_get_element_uint32(ctx, |
| 283 | raw_options, |
| 284 | i, |
| 285 | options->n_clusters); |
| 286 | } else if (name_raw == "centroid_column") { |
| 287 | set_string(options->centroid_column_name, raw_options, i); |
| 288 | } else if (name_raw == "quantizer") { |
| 289 | // TODO: RaBitQ and no quantization are only supported for now |
| 290 | } else if (name_raw == "code_column") { |
| 291 | set_string(options->code_column_name, raw_options, i); |
| 292 | } else if (name_raw == "passage_prefix") { |
| 293 | set_string(options->passage_prefix, raw_options, i); |
| 294 | } else if (name_raw == "query_prefix") { |
| 295 | set_string(options->query_prefix, raw_options, i); |
| 296 | } |
| 297 | } |
| 298 | GRN_OPTION_VALUES_EACH_END(); |
| 299 | |
| 300 | if (options->model_name.empty()) { |
| 301 | GRN_PLUGIN_ERROR(ctx, |
| 302 | GRN_INVALID_ARGUMENT, |
| 303 | "%s model isn't specified", |
| 304 | TOKENIZER_TAG); |
| 305 | close_options(ctx, options); |
| 306 | return nullptr; |
| 307 | } |
| 308 | |
| 309 | if (options->centroid_column_name.empty()) { |
| 310 | options->centroid_column = nullptr; |
| 311 | } else { |
| 312 | options->centroid_column = |
| 313 | grn_obj_column(ctx, |
| 314 | data->lexicon, |
| 315 | options->centroid_column_name.data(), |
| 316 | options->centroid_column_name.size()); |
| 317 | if (!options->centroid_column) { |
| 318 | char lexicon_name[GRN_TABLE_MAX_KEY_SIZE]; |
| 319 | int lexicon_name_size = |
| 320 | grn_obj_name(ctx, data->lexicon, lexicon_name, sizeof(lexicon_name)); |
| 321 | GRN_PLUGIN_ERROR(ctx, |
| 322 | GRN_INVALID_ARGUMENT, |
| 323 | "%s couldn't find centroid column: <%.*s.%s>", |
| 324 | TOKENIZER_TAG, |
| 325 | lexicon_name_size, |
| 326 | lexicon_name, |
| 327 | options->centroid_column_name.data()); |
| 328 | close_options(ctx, options); |
| 329 | return nullptr; |
| 330 | } |
| 331 | grn_id range = grn_obj_get_range(ctx, options->centroid_column); |
| 332 | bool is_vector = grn_obj_is_vector_column(ctx, options->centroid_column); |
| 333 | if (range != GRN_DB_FLOAT32 || !is_vector) { |
| 334 | char lexicon_name[GRN_TABLE_MAX_KEY_SIZE]; |
| 335 | int lexicon_name_size = |
| 336 | grn_obj_name(ctx, data->lexicon, lexicon_name, sizeof(lexicon_name)); |
| 337 | const char *column_type = nullptr; |
| 338 | if (is_vector) { |
| 339 | column_type = "VECTOR"; |
| 340 | } else if (grn_obj_is_index_column(ctx, options->centroid_column)) { |
| 341 | column_type = "INDEX"; |
| 342 | } else { |
| 343 | column_type = "SCALAR"; |
| 344 | } |
| 345 | GRN_PLUGIN_ERROR(ctx, |
| 346 | GRN_INVALID_ARGUMENT, |
| 347 | "%s centroid column must be Float32 vector: " |
| 348 | "<%.*s.%s>: <%s>: <%s>", |
| 349 | TOKENIZER_TAG, |
| 350 | lexicon_name_size, |
| 351 | lexicon_name, |
| 352 | options->centroid_column_name.data(), |
| 353 | grn_type_id_to_string_builtin(ctx, range), |
| 354 | column_type); |
| 355 | close_options(ctx, options); |
| 356 | return nullptr; |
| 357 | } |
| 358 | if (data->lexicon->header.domain != GRN_DB_UINT32) { |
| 359 | char lexicon_name[GRN_TABLE_MAX_KEY_SIZE]; |
| 360 | int lexicon_name_size = |
| 361 | grn_obj_name(ctx, data->lexicon, lexicon_name, sizeof(lexicon_name)); |
| 362 | char lexicon_type_name[GRN_TABLE_MAX_KEY_SIZE]; |
| 363 | int lexicon_type_name_size = |
| 364 | grn_table_get_key(ctx, |
| 365 | grn_ctx_db(ctx), |
| 366 | data->lexicon->header.domain, |
| 367 | lexicon_type_name, |
| 368 | sizeof(lexicon_type_name)); |
| 369 | GRN_PLUGIN_ERROR(ctx, |
| 370 | GRN_INVALID_ARGUMENT, |
| 371 | "%s lexicon key type must be UInt32 " |
| 372 | "with centroid column: <%.*s.%s>: <%.*s>", |
| 373 | TOKENIZER_TAG, |
| 374 | lexicon_name_size, |
| 375 | lexicon_name, |
| 376 | options->centroid_column_name.data(), |
| 377 | lexicon_type_name_size, |
| 378 | lexicon_type_name); |
| 379 | close_options(ctx, options); |
| 380 | return nullptr; |
| 381 | } |
| 382 | } |
| 383 | |
| 384 | if (options->code_column_name.empty()) { |
| 385 | GRN_PLUGIN_ERROR(ctx, |
| 386 | GRN_INVALID_ARGUMENT, |
| 387 | "%s code_column isn't specified", |
| 388 | TOKENIZER_TAG); |
| 389 | close_options(ctx, options); |
| 390 | return nullptr; |
| 391 | } |
| 392 | options->code_column = grn_obj_column(ctx, |
| 393 | data->source_table, |
| 394 | options->code_column_name.data(), |
| 395 | options->code_column_name.size()); |
| 396 | if (!options->code_column) { |
| 397 | GRN_PLUGIN_ERROR(ctx, |
| 398 | GRN_INVALID_ARGUMENT, |
| 399 | "%s couldn't find code column: <%s>", |
| 400 | TOKENIZER_TAG, |
| 401 | options->code_column_name.data()); |
| 402 | close_options(ctx, options); |
| 403 | return nullptr; |
| 404 | } |
| 405 | |
| 406 | grn_language_model_loader *loader = grn_language_model_loader_open(ctx); |
| 407 | grn_language_model_loader_set_model(ctx, |
| 408 | loader, |
| 409 | options->model_name.data(), |
| 410 | options->model_name.size()); |
| 411 | grn_language_model_loader_set_n_gpu_layers(ctx, |
| 412 | loader, |
| 413 | options->n_gpu_layers); |
| 414 | options->model = grn_language_model_loader_load(ctx, loader); |
| 415 | grn_language_model_loader_close(ctx, loader); |
| 416 | if (!options->model) { |
| 417 | std::string message(ctx->errbuf); |
| 418 | GRN_PLUGIN_ERROR(ctx, |
| 419 | GRN_INVALID_ARGUMENT, |
| 420 | "%s couldn't load model: <%s>: %s", |
| 421 | TOKENIZER_TAG, |
| 422 | options->model_name.data(), |
| 423 | message.data()); |
| 424 | close_options(ctx, options); |
| 425 | return nullptr; |
| 426 | } |
| 427 | |
| 428 | options->inferencer = |
| 429 | grn_language_model_open_inferencer(ctx, options->model); |
| 430 | if (!options->inferencer) { |
| 431 | std::string message(ctx->errbuf); |
| 432 | GRN_PLUGIN_ERROR(ctx, |
| 433 | GRN_INVALID_ARGUMENT, |
| 434 | "%s failed to create model inferencer: %s", |
| 435 | TOKENIZER_TAG, |
| 436 | message.data()); |
| 437 | close_options(ctx, options); |
| 438 | return nullptr; |
| 439 | } |
| 440 | if (!options->passage_prefix.empty()) { |
| 441 | grn_language_model_inferencer_set_input_column_value_prefix( |
| 442 | ctx, |
| 443 | options->inferencer, |
| 444 | options->passage_prefix.data(), |
| 445 | static_cast<int64_t>(options->passage_prefix.size())); |
| 446 | } |
| 447 | |
| 448 | options->n_dimensions = |
| 449 | grn_language_model_get_n_embedding_dimensions(ctx, options->model); |
| 450 | options->centroid_searcher.d = options->n_dimensions; |
| 451 | options->centroid_searcher.metric_type = |
| 452 | faiss::MetricType::METRIC_INNER_PRODUCT; |
| 453 | options->centroid_searcher.code_size = |
| 454 | sizeof(float) * options->n_dimensions; |
| 455 | options->n_clusters = grn_table_size(ctx, data->lexicon); |
| 456 | if (options->n_clusters > 0) { |
| 457 | options->centroids.resize(options->n_dimensions * options->n_clusters); |
| 458 | options->centroid_index_to_record_id.resize(options->n_clusters); |
| 459 | size_t i = 0; |
| 460 | if (options->centroid_column) { |
| 461 | grn_obj centroid; |
| 462 | GRN_FLOAT32_INIT(¢roid, GRN_OBJ_VECTOR | GRN_OBJ_DO_SHALLOW_COPY); |
| 463 | GRN_TABLE_EACH_BEGIN_FLAGS(ctx, |
| 464 | data->lexicon, |
| 465 | cursor, |
| 466 | id, |
| 467 | GRN_CURSOR_BY_ID) |
| 468 | { |
| 469 | // This is for avoiding needless copy but this is tricky... |
| 470 | GRN_TEXT_SET_REF(¢roid, |
| 471 | options->centroids.data() + |
| 472 | (options->n_dimensions * i), |
| 473 | 0); |
| 474 | // The above 0 length and this sets rest |
| 475 | // size. grn_obj_get_value() copies a column value without |
| 476 | // changing GRN_BULK_HEAD(¢roid) if ¢roid has enough |
| 477 | // rest size. |
| 478 | centroid.u.b.tail = |
| 479 | centroid.u.b.head + (sizeof(float) * options->n_dimensions); |
| 480 | grn_obj_get_value(ctx, options->centroid_column, id, ¢roid); |
| 481 | options->centroid_index_to_record_id[i] = id; |
| 482 | ++i; |
| 483 | } |
| 484 | GRN_TABLE_EACH_END(ctx, cursor); |
| 485 | GRN_OBJ_FIN(ctx, ¢roid); |
| 486 | } else { |
| 487 | GRN_TABLE_EACH_BEGIN_FLAGS(ctx, |
| 488 | data->lexicon, |
| 489 | cursor, |
| 490 | id, |
| 491 | GRN_CURSOR_BY_ID) |
| 492 | { |
| 493 | void *key; |
| 494 | auto key_size = grn_table_cursor_get_key(ctx, cursor, &key); |
| 495 | memcpy(options->centroids.data() + (options->n_dimensions * i), |
| 496 | key, |
| 497 | key_size); |
| 498 | options->centroid_index_to_record_id[i] = id; |
| 499 | ++i; |
| 500 | } |
| 501 | GRN_TABLE_EACH_END(ctx, cursor); |
| 502 | } |
| 503 | } |
| 504 | #ifdef GRN_FAISS_HAVE_MAYBE_OWNED_VECTOR |
| 505 | options->centroid_searcher.codes = |
| 506 | faiss::MaybeOwnedVector<uint8_t>::create_view(options->centroids.data(), |
| 507 | sizeof(float) * |
| 508 | options->centroids.size(), |
| 509 | nullptr); |
| 510 | #else |
| 511 | options->centroid_searcher.codes.resize(sizeof(float) * |
| 512 | options->centroids.size()); |
| 513 | memcpy(options->centroid_searcher.codes.data(), |
| 514 | options->centroids.data(), |
| 515 | options->centroid_searcher.codes.size()); |
| 516 | #endif |
| 517 | options->centroid_searcher.ntotal = |
| 518 | options->centroids.size() / options->n_dimensions; |
| 519 | |
| 520 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 521 | options->random_rotation_matrix.d_in = options->n_dimensions; |
| 522 | options->random_rotation_matrix.d_out = options->n_dimensions; |
| 523 | options->random_rotation_matrix.init(SEED); |
| 524 | |
| 525 | // We can use inner product here because we normalize generated |
| 526 | // embeddings. |
| 527 | options->rabitq = |
| 528 | faiss::RaBitQuantizer(options->n_dimensions, |
| 529 | faiss::MetricType::METRIC_INNER_PRODUCT); |
| 530 | #endif |
| 531 | |
| 532 | return options; |
| 533 | } |
| 534 | |
| 535 | class Builder { |
| 536 | public: |
| 537 | Builder(grn_ctx *ctx, grn_tokenizer_build_data *data) |
| 538 | : ctx_(ctx), |
| 539 | data_(data), |
| 540 | lexicon_(grn_tokenizer_build_data_get_lexicon(ctx_, data_)), |
| 541 | source_table_(grn_tokenizer_build_data_get_source_table(ctx_, data_)), |
| 542 | n_source_records_(grn_table_size(ctx, source_table_)), |
| 543 | source_columns_( |
| 544 | grn_tokenizer_build_data_get_source_columns(ctx_, data_)), |
| 545 | source_column_(GRN_PTR_VALUE_AT(source_columns_, 0)), |
| 546 | index_column_(grn_tokenizer_build_data_get_index_column(ctx_, data_)), |
| 547 | options_(nullptr), |
| 548 | embeddings_path_(), |
| 549 | embeddings_map_(nullptr), |
| 550 | embeddings_(), |
| 551 | embeddings_raw_(), |
| 552 | transformed_embeddings_raw_(nullptr) |
| 553 | { |
| 554 | GRN_FLOAT32_INIT(&embeddings_, GRN_OBJ_VECTOR | GRN_OBJ_DO_SHALLOW_COPY); |
| 555 | } |
| 556 | |
| 557 | ~Builder() |
| 558 | { |
| 559 | GRN_OBJ_FIN(ctx_, &embeddings_); |
| 560 | if (embeddings_map_) { |
| 561 | grn_memory_map_close(ctx_, embeddings_map_); |
| 562 | grn_unlink(embeddings_path_.data()); |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | bool |
| 567 | build() |
| 568 | { |
| 569 | if (!prepare_options()) { |
| 570 | return false; |
| 571 | } |
| 572 | faiss::IndexFlatIP index(options_->n_dimensions); |
| 573 | if (!build_clusters(index)) { |
| 574 | return false; |
| 575 | } |
| 576 | if (!build_inverted_index(index)) { |
| 577 | return false; |
| 578 | } |
| 579 | return true; |
| 580 | } |
| 581 | |
| 582 | private: |
| 583 | grn_ctx *ctx_; |
| 584 | grn_tokenizer_build_data *data_; |
| 585 | grn_obj *lexicon_; |
| 586 | grn_obj *source_table_; |
| 587 | uint32_t n_source_records_; |
| 588 | grn_obj *source_columns_; |
| 589 | grn_obj *source_column_; |
| 590 | grn_obj *index_column_; |
| 591 | Options *options_; |
| 592 | std::string embeddings_path_; |
| 593 | grn_memory_map *embeddings_map_; |
| 594 | grn_obj embeddings_; |
| 595 | float *embeddings_raw_; |
| 596 | float *transformed_embeddings_raw_; |
| 597 | |
| 598 | bool |
| 599 | prepare_options() |
| 600 | { |
| 601 | OpenOptionsData open_options_data; |
| 602 | open_options_data.lexicon = lexicon_; |
| 603 | open_options_data.source_table = source_table_; |
| 604 | options_ = static_cast<Options *>( |
| 605 | grn_table_cache_default_tokenizer_options(ctx_, |
| 606 | lexicon_, |
| 607 | open_options, |
| 608 | close_options, |
| 609 | &open_options_data)); |
| 610 | return ctx_->rc == GRN_SUCCESS; |
| 611 | } |
| 612 | |
| 613 | bool |
| 614 | build_clusters(faiss::IndexFlatIP &index) |
| 615 | { |
| 616 | if (options_->n_clusters == 0) { |
| 617 | // Heuristic default |
| 618 | if (n_source_records_ >= 1000000) { // 1M records |
| 619 | options_->n_clusters = |
| 620 | static_cast<uint32_t>(std::sqrt(n_source_records_)); |
| 621 | } else { |
| 622 | options_->n_clusters = (n_source_records_ / 1000) + 1; |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | // Generate embeddings |
| 627 | auto cursor = grn_table_cursor_open(ctx_, |
| 628 | source_table_, |
| 629 | nullptr, |
| 630 | 0, |
| 631 | nullptr, |
| 632 | 0, |
| 633 | 0, |
| 634 | -1, |
| 635 | GRN_CURSOR_BY_ID); |
| 636 | if (!cursor) { |
| 637 | if (ctx_->rc == GRN_SUCCESS) { |
| 638 | GRN_PLUGIN_ERROR(ctx_, |
| 639 | GRN_UNKNOWN_ERROR, |
| 640 | "%s failed to open source table cursor", |
| 641 | TOKENIZER_TAG); |
| 642 | } else { |
| 643 | std::string message(ctx_->errbuf); |
| 644 | GRN_PLUGIN_ERROR(ctx_, |
| 645 | ctx_->rc, |
| 646 | "%s failed to open source table cursor: %s", |
| 647 | TOKENIZER_TAG, |
| 648 | message.data()); |
| 649 | } |
| 650 | return false; |
| 651 | } |
| 652 | |
| 653 | grn_tokenizer_build_data_start_vectorize(ctx_, data_, n_source_records_); |
| 654 | embeddings_path_ = grn_obj_path(ctx_, index_column_); |
| 655 | embeddings_path_ += ".embeddings"; |
| 656 | size_t embeddings_size = |
| 657 | sizeof(float) * options_->n_dimensions * n_source_records_; |
| 658 | embeddings_map_ = |
| 659 | grn_memory_map_open(ctx_, |
| 660 | embeddings_path_.data(), |
| 661 | GRN_MEMORY_MAP_READ | GRN_MEMORY_MAP_WRITE, |
| 662 | 0, |
| 663 | // The former part is for raw embeddings and |
| 664 | // the latter part is for transformed embeddings. |
| 665 | embeddings_size * 2); |
| 666 | embeddings_raw_ = |
| 667 | static_cast<float *>(grn_memory_map_get_address(ctx_, embeddings_map_)); |
| 668 | transformed_embeddings_raw_ = |
| 669 | embeddings_raw_ + (embeddings_size / sizeof(float)); |
| 670 | GRN_BINARY_SET_REF(&embeddings_, embeddings_raw_, embeddings_size); |
| 671 | GRN_BULK_REWIND(&embeddings_); |
| 672 | { |
| 673 | bool need_progress = grn_ctx_get_progress_callback(ctx_); |
| 674 | struct UserData { |
| 675 | grn_tokenizer_build_data *data; |
| 676 | } user_data; |
| 677 | user_data.data = data_; |
| 678 | auto progress_callback = |
| 679 | [](grn_ctx *ctx, grn_progress *progress, void *user_data) { |
| 680 | auto user_data_ = static_cast<UserData *>(user_data); |
| 681 | auto n_processed_records = |
| 682 | grn_progress_language_model_inferencer_get_n_processed_records( |
| 683 | ctx, |
| 684 | progress); |
| 685 | grn_tokenizer_build_data_processed_n_records(ctx, |
| 686 | user_data_->data, |
| 687 | n_processed_records); |
| 688 | }; |
| 689 | if (need_progress) { |
| 690 | grn_language_model_inferencer_set_progress_callback( |
| 691 | ctx_, |
| 692 | options_->inferencer, |
| 693 | progress_callback, |
| 694 | &user_data); |
| 695 | } |
| 696 | grn_language_model_inferencer_vectorize_in_batch(ctx_, |
| 697 | options_->inferencer, |
| 698 | cursor, |
| 699 | source_column_, |
| 700 | &embeddings_); |
| 701 | if (need_progress) { |
| 702 | grn_language_model_inferencer_set_progress_callback( |
| 703 | ctx_, |
| 704 | options_->inferencer, |
| 705 | nullptr, |
| 706 | nullptr); |
| 707 | } |
| 708 | } |
| 709 | grn_table_cursor_close(ctx_, cursor); |
| 710 | |
| 711 | if (GRN_BULK_VSIZE(&embeddings_) != embeddings_size) { |
| 712 | GRN_PLUGIN_ERROR(ctx_, |
| 713 | GRN_UNKNOWN_ERROR, |
| 714 | "%s failed to generate " |
| 715 | "float[%u] * %u (%" PRIu64 " bytes) embeddings: " |
| 716 | "%" PRIu64 " bytes are only generated", |
| 717 | TOKENIZER_TAG, |
| 718 | options_->n_dimensions, |
| 719 | n_source_records_, |
| 720 | static_cast<uint64_t>(embeddings_size), |
| 721 | static_cast<uint64_t>(GRN_BULK_VSIZE(&embeddings_))); |
| 722 | return false; |
| 723 | } |
| 724 | |
| 725 | // Compute clusters |
| 726 | grn_tokenizer_build_data_start_cluster(ctx_, data_, n_source_records_); |
| 727 | size_t n_centroids = options_->n_clusters; |
| 728 | faiss::Clustering clustering(options_->n_dimensions, n_centroids); |
| 729 | if (options_->quantizer == Quantizer::RABITQ) { |
| 730 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 731 | options_->random_rotation_matrix.apply_noalloc( |
| 732 | n_source_records_, |
| 733 | embeddings_raw_, |
| 734 | transformed_embeddings_raw_); |
| 735 | clustering.train(n_source_records_, transformed_embeddings_raw_, index); |
| 736 | #endif |
| 737 | } else { |
| 738 | clustering.train(n_source_records_, embeddings_raw_, index); |
| 739 | } |
| 740 | options_->centroid_index_to_record_id.reserve(n_centroids); |
| 741 | if (options_->centroid_column) { |
| 742 | grn_obj centroid; |
| 743 | GRN_FLOAT32_INIT(¢roid, GRN_OBJ_VECTOR | GRN_OBJ_DO_SHALLOW_COPY); |
| 744 | for (size_t i = 0; i < n_centroids; ++i) { |
| 745 | uint32_t key = i; |
| 746 | grn_id id = |
| 747 | grn_table_add(ctx_, lexicon_, &key, sizeof(uint32_t), nullptr); |
| 748 | GRN_TEXT_SET_REF(¢roid, |
| 749 | clustering.centroids.data() + |
| 750 | (options_->n_dimensions * i), |
| 751 | sizeof(float) * options_->n_dimensions); |
| 752 | grn_obj_set_value(ctx_, |
| 753 | options_->centroid_column, |
| 754 | id, |
| 755 | ¢roid, |
| 756 | GRN_OBJ_SET); |
| 757 | options_->centroid_index_to_record_id.push_back(id); |
| 758 | } |
| 759 | GRN_OBJ_FIN(ctx_, ¢roid); |
| 760 | } else { |
| 761 | for (size_t i = 0; i < n_centroids; ++i) { |
| 762 | grn_id id = grn_table_add(ctx_, |
| 763 | lexicon_, |
| 764 | clustering.centroids.data() + |
| 765 | (options_->n_dimensions * i), |
| 766 | sizeof(float) * options_->n_dimensions, |
| 767 | nullptr); |
| 768 | options_->centroid_index_to_record_id.push_back(id); |
| 769 | } |
| 770 | } |
| 771 | options_->centroids = std::move(clustering.centroids); |
| 772 | #ifdef GRN_FAISS_HAVE_MAYBE_OWNED_VECTOR |
| 773 | options_->centroid_searcher.codes = |
| 774 | faiss::MaybeOwnedVector<uint8_t>::create_view( |
| 775 | options_->centroids.data(), |
| 776 | sizeof(float) * options_->centroids.size(), |
| 777 | nullptr); |
| 778 | #else |
| 779 | options_->centroid_searcher.codes.resize(sizeof(float) * |
| 780 | options_->centroids.size()); |
| 781 | memcpy(options_->centroid_searcher.codes.data(), |
| 782 | options_->centroids.data(), |
| 783 | options_->centroid_searcher.codes.size()); |
| 784 | #endif |
| 785 | options_->centroid_searcher.ntotal = n_centroids; |
| 786 | grn_tokenizer_build_data_processed_n_records(ctx_, data_, n_centroids); |
| 787 | |
| 788 | return true; |
| 789 | } |
| 790 | |
| 791 | bool |
| 792 | build_inverted_index(faiss::IndexFlatIP &index) |
| 793 | { |
| 794 | grn_obj tokens; |
| 795 | GRN_RECORD_INIT(&tokens, GRN_OBJ_VECTOR, grn_obj_id(ctx_, lexicon_)); |
| 796 | grn_obj code; |
| 797 | if (options_->quantizer == Quantizer::NONE) { |
| 798 | GRN_SHORT_BINARY_INIT(&code, GRN_OBJ_DO_SHALLOW_COPY); |
| 799 | } else if (options_->quantizer == Quantizer::RABITQ) { |
| 800 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 801 | GRN_SHORT_BINARY_INIT(&code, 0); |
| 802 | grn_bulk_space(ctx_, &code, options_->rabitq.code_size); |
| 803 | #endif |
| 804 | } |
| 805 | grn_tokenizer_build_data_start_load(ctx_, data_, n_source_records_); |
| 806 | size_t i = 0; |
| 807 | GRN_TABLE_EACH_BEGIN_FLAGS(ctx_, |
| 808 | source_table_, |
| 809 | cursor, |
| 810 | id, |
| 811 | GRN_CURSOR_BY_ID) |
| 812 | { |
| 813 | grn_tokenizer_build_data_start_record(ctx_, data_, id); |
| 814 | grn_tokenizer_build_data_start_section(ctx_, data_, 1); |
| 815 | |
| 816 | GRN_BULK_REWIND(&tokens); |
| 817 | const float *target_embedding = nullptr; |
| 818 | if (options_->quantizer == Quantizer::RABITQ) { |
| 819 | target_embedding = |
| 820 | transformed_embeddings_raw_ + (options_->n_dimensions * i); |
| 821 | } else { |
| 822 | target_embedding = embeddings_raw_ + (options_->n_dimensions * i); |
| 823 | } |
| 824 | float distances[1]; |
| 825 | faiss::idx_t indexes[1]; |
| 826 | index.search(1, target_embedding, 1, distances, indexes); |
| 827 | if (options_->quantizer == Quantizer::NONE) { |
| 828 | GRN_BINARY_SET_REF(&code, |
| 829 | target_embedding, |
| 830 | sizeof(float) * options_->n_dimensions); |
| 831 | } else if (options_->quantizer == Quantizer::RABITQ) { |
| 832 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 833 | const float *centroid = |
| 834 | options_->centroids.data() + (options_->n_dimensions * indexes[0]); |
| 835 | options_->rabitq.compute_codes_core( |
| 836 | target_embedding, |
| 837 | reinterpret_cast<uint8_t *>(GRN_BULK_HEAD(&code)), |
| 838 | 1, |
| 839 | centroid); |
| 840 | #endif |
| 841 | } |
| 842 | grn_obj_set_value(ctx_, options_->code_column, id, &code, GRN_OBJ_SET); |
| 843 | grn_id centroid_id = options_->centroid_index_to_record_id[indexes[0]]; |
| 844 | grn_uvector_add_element_record(ctx_, &tokens, centroid_id, 0.0); |
| 845 | grn_tokenizer_build_data_append_tokens(ctx_, data_, &tokens); |
| 846 | |
| 847 | grn_tokenizer_build_data_finish_section(ctx_, data_); |
| 848 | grn_tokenizer_build_data_finish_record(ctx_, data_); |
| 849 | |
| 850 | ++i; |
| 851 | } |
| 852 | GRN_TABLE_EACH_END(ctx_, cursor); |
| 853 | GRN_OBJ_FIN(ctx_, &code); |
| 854 | GRN_OBJ_FIN(ctx_, &tokens); |
| 855 | |
| 856 | return true; |
| 857 | } |
| 858 | }; |
| 859 | |
| 860 | grn_rc |
| 861 | build(grn_ctx *ctx, grn_tokenizer_build_data *data) |
| 862 | { |
| 863 | Builder builder(ctx, data); |
| 864 | builder.build(); |
| 865 | return ctx->rc; |
| 866 | } |
| 867 | |
| 868 | void * |
| 869 | init(grn_ctx *ctx, grn_tokenizer_query *query) |
| 870 | { |
| 871 | size_t query_size; |
| 872 | grn_id query_domain; |
| 873 | const char *raw_query = |
| 874 | grn_tokenizer_query_get_data(ctx, query, &query_size, &query_domain); |
| 875 | if (!grn_type_id_is_text_family(ctx, query_domain)) { |
| 876 | GRN_PLUGIN_ERROR(ctx, |
| 877 | GRN_INVALID_ARGUMENT, |
| 878 | "%s query must be text: %s(%u)", |
| 879 | TAG, |
| 880 | grn_type_id_to_string_builtin(ctx, query_domain), |
| 881 | query_domain); |
| 882 | return nullptr; |
| 883 | } |
| 884 | |
| 885 | auto lexicon = grn_tokenizer_query_get_lexicon(ctx, query); |
| 886 | auto source_column = grn_tokenizer_query_get_source_column(ctx, query); |
| 887 | auto source_table = grn_ctx_at(ctx, source_column->header.domain); |
| 888 | OpenOptionsData open_options_data; |
| 889 | open_options_data.lexicon = lexicon; |
| 890 | open_options_data.source_table = source_table; |
| 891 | auto options = static_cast<Options *>( |
| 892 | grn_table_cache_default_tokenizer_options(ctx, |
| 893 | lexicon, |
| 894 | open_options, |
| 895 | close_options, |
| 896 | &open_options_data)); |
| 897 | grn_obj_unref(ctx, source_table); |
| 898 | if (ctx->rc != GRN_SUCCESS) { |
| 899 | return nullptr; |
| 900 | } |
| 901 | |
| 902 | auto tokenizer = |
| 903 | tokenizer_open(ctx, options, std::string_view(raw_query, query_size)); |
| 904 | if (!tokenizer) { |
| 905 | return nullptr; |
| 906 | } |
| 907 | |
| 908 | return tokenizer; |
| 909 | } |
| 910 | |
| 911 | void |
| 912 | next(grn_ctx *ctx, |
| 913 | grn_tokenizer_query *query, |
| 914 | grn_token *token, |
| 915 | void *user_data) |
| 916 | { |
| 917 | auto tokenizer = static_cast<Tokenizer *>(user_data); |
| 918 | |
| 919 | if (tokenizer->options->passage_prefix.empty()) { |
| 920 | grn_language_model_inferencer_vectorize(ctx, |
| 921 | tokenizer->options->inferencer, |
| 922 | tokenizer->query.data(), |
| 923 | tokenizer->query.size(), |
| 924 | &(tokenizer->embedding)); |
| 925 | } else { |
| 926 | auto prefixed_query = tokenizer->options->passage_prefix; |
| 927 | prefixed_query.append(tokenizer->query); |
| 928 | grn_language_model_inferencer_vectorize(ctx, |
| 929 | tokenizer->options->inferencer, |
| 930 | prefixed_query.data(), |
| 931 | prefixed_query.size(), |
| 932 | &(tokenizer->embedding)); |
| 933 | } |
| 934 | if (ctx->rc != GRN_SUCCESS) { |
| 935 | GRN_PLUGIN_ERROR(ctx, |
| 936 | ctx->rc, |
| 937 | "%s failed to vectorize: <%.*s>", |
| 938 | TAG, |
| 939 | static_cast<int>(tokenizer->query.size()), |
| 940 | tokenizer->query.data()); |
| 941 | return; |
| 942 | } |
| 943 | |
| 944 | auto embedding = |
| 945 | reinterpret_cast<const float *>(GRN_BULK_HEAD(&(tokenizer->embedding))); |
| 946 | const float *target_embedding = nullptr; |
| 947 | if (tokenizer->options->quantizer == Quantizer::RABITQ) { |
| 948 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 949 | grn_bulk_space(ctx, |
| 950 | &(tokenizer->transformed_embedding), |
| 951 | GRN_BULK_VSIZE(&(tokenizer->embedding))); |
| 952 | auto transformed_embedding = reinterpret_cast<float *>( |
| 953 | GRN_BULK_HEAD(&(tokenizer->transformed_embedding))); |
| 954 | tokenizer->options->random_rotation_matrix.apply_noalloc( |
| 955 | 1, |
| 956 | embedding, |
| 957 | transformed_embedding); |
| 958 | target_embedding = transformed_embedding; |
| 959 | #endif |
| 960 | } else { |
| 961 | target_embedding = embedding; |
| 962 | } |
| 963 | size_t k = 1; |
| 964 | float distances[1]; |
| 965 | faiss::idx_t indexes[1]; |
| 966 | tokenizer->options->centroid_searcher.search(1, |
| 967 | target_embedding, |
| 968 | k, |
| 969 | distances, |
| 970 | indexes); |
| 971 | const float *centroid = tokenizer->options->centroids.data() + |
| 972 | (tokenizer->options->n_dimensions * indexes[0]); |
| 973 | if (tokenizer->options->centroid_column) { |
| 974 | // We need to keep token data until the next next() is |
| 975 | // called. If we use a local variable here, token data is |
| 976 | // invalid after this block. |
| 977 | tokenizer->current_centroid_id = indexes[0]; |
| 978 | auto key = |
| 979 | reinterpret_cast<const char *>(&(tokenizer->current_centroid_id)); |
| 980 | grn_token_set_data(ctx, token, key, sizeof(uint32_t)); |
| 981 | grn_token_set_domain(ctx, token, GRN_DB_UINT32); |
| 982 | } else { |
| 983 | grn_token_set_data(ctx, |
| 984 | token, |
| 985 | reinterpret_cast<const char *>(centroid), |
| 986 | sizeof(float) * tokenizer->options->n_dimensions); |
| 987 | grn_token_set_domain(ctx, token, GRN_DB_SHORT_BINARY); |
| 988 | } |
| 989 | grn_token_set_status(ctx, token, GRN_TOKEN_LAST); |
| 990 | if (grn_tokenizer_query_get_mode(ctx, query) == GRN_TOKENIZE_ADD) { |
| 991 | if (tokenizer->options->quantizer == Quantizer::NONE) { |
| 992 | GRN_BINARY_SET_REF(&(tokenizer->code), |
| 993 | target_embedding, |
| 994 | sizeof(float) * tokenizer->options->n_dimensions); |
| 995 | } else if (tokenizer->options->quantizer == Quantizer::RABITQ) { |
| 996 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 997 | grn_bulk_space(ctx, |
| 998 | &(tokenizer->code), |
| 999 | tokenizer->options->rabitq.code_size); |
| 1000 | tokenizer->options->rabitq.compute_codes_core( |
| 1001 | target_embedding, |
| 1002 | reinterpret_cast<uint8_t *>(GRN_BULK_HEAD(&(tokenizer->code))), |
| 1003 | 1, |
| 1004 | centroid); |
| 1005 | #endif |
| 1006 | } |
| 1007 | grn_id source_id = grn_tokenizer_query_get_source_id(ctx, query); |
| 1008 | grn_obj_set_value(ctx, |
| 1009 | tokenizer->options->code_column, |
| 1010 | source_id, |
| 1011 | &(tokenizer->code), |
| 1012 | GRN_OBJ_SET); |
| 1013 | } |
| 1014 | } |
| 1015 | |
| 1016 | void |
| 1017 | fin(grn_ctx *ctx, void *user_data) |
| 1018 | { |
| 1019 | auto tokenizer = static_cast<Tokenizer *>(user_data); |
| 1020 | |
| 1021 | if (!tokenizer) { |
| 1022 | return; |
| 1023 | } |
| 1024 | |
| 1025 | tokenizer_close(ctx, tokenizer); |
| 1026 | } |
| 1027 | |
| 1028 | struct Candidate { |
| 1029 | grn_id record_id = GRN_ID_NIL; |
| 1030 | float similarity = 0.0; |
| 1031 | |
| 1032 | Candidate(grn_id record_id, float similarity) |
| 1033 | : record_id(record_id), |
| 1034 | similarity(similarity) |
| 1035 | { |
| 1036 | } |
| 1037 | }; |
| 1038 | |
| 1039 | class Searcher { |
| 1040 | public: |
| 1041 | Searcher(grn_ctx *ctx, |
| 1042 | grn_obj *table, |
| 1043 | grn_obj *index, |
| 1044 | std::string_view query, |
| 1045 | uint32_t n_probes, |
| 1046 | uint32_t k) |
| 1047 | : ctx_(ctx), |
| 1048 | table_(table), |
| 1049 | index_(index), |
| 1050 | query_(query), |
| 1051 | n_probes_(n_probes), |
| 1052 | k_(k), |
| 1053 | query_embedding_(), |
| 1054 | transformed_query_embedding_(), |
| 1055 | code_() |
| 1056 | { |
| 1057 | GRN_FLOAT32_INIT(&query_embedding_, GRN_OBJ_VECTOR); |
| 1058 | GRN_FLOAT32_INIT(&transformed_query_embedding_, GRN_OBJ_VECTOR); |
| 1059 | GRN_VOID_INIT(&code_); |
| 1060 | } |
| 1061 | |
| 1062 | ~Searcher() |
| 1063 | { |
| 1064 | GRN_OBJ_FIN(ctx_, &query_embedding_); |
| 1065 | GRN_OBJ_FIN(ctx_, &transformed_query_embedding_); |
| 1066 | GRN_OBJ_FIN(ctx_, &code_); |
| 1067 | } |
| 1068 | |
| 1069 | template <typename Filter> |
| 1070 | std::optional<std::vector<Candidate>> |
| 1071 | search(Filter filter, bool ascending) |
| 1072 | { |
| 1073 | auto lexicon = grn_ctx_at(ctx_, index_->header.domain); |
| 1074 | OpenOptionsData open_options_data; |
| 1075 | open_options_data.lexicon = lexicon; |
| 1076 | open_options_data.source_table = table_; |
| 1077 | auto options = static_cast<Options *>( |
| 1078 | grn_table_cache_default_tokenizer_options(ctx_, |
| 1079 | lexicon, |
| 1080 | open_options, |
| 1081 | close_options, |
| 1082 | &open_options_data)); |
| 1083 | |
| 1084 | if (options->query_prefix.empty()) { |
| 1085 | grn_language_model_inferencer_vectorize(ctx_, |
| 1086 | options->inferencer, |
| 1087 | query_.data(), |
| 1088 | query_.size(), |
| 1089 | &query_embedding_); |
| 1090 | } else { |
| 1091 | auto prefixed_query = options->query_prefix; |
| 1092 | prefixed_query.append(query_); |
| 1093 | grn_language_model_inferencer_vectorize(ctx_, |
| 1094 | options->inferencer, |
| 1095 | prefixed_query.data(), |
| 1096 | prefixed_query.size(), |
| 1097 | &query_embedding_); |
| 1098 | } |
| 1099 | auto raw_query_embedding = |
| 1100 | reinterpret_cast<const float *>(GRN_BULK_HEAD(&query_embedding_)); |
| 1101 | const float *raw_target_embedding = nullptr; |
| 1102 | if (options->quantizer == Quantizer::RABITQ) { |
| 1103 | #ifdef GRN_FAISS_HAVE_RABITQ |
| 1104 | grn_bulk_space(ctx_, |
| 1105 | &transformed_query_embedding_, |
| 1106 | GRN_BULK_VSIZE(&query_embedding_)); |
| 1107 | auto raw_transformed_query_embedding = reinterpret_cast<float *>( |
| 1108 | GRN_BULK_HEAD(&transformed_query_embedding_)); |
| 1109 | options->random_rotation_matrix.apply_noalloc( |
| 1110 | 1, |
| 1111 | raw_query_embedding, |
| 1112 | raw_transformed_query_embedding); |
| 1113 | raw_target_embedding = raw_transformed_query_embedding; |
| 1114 | #endif |
| 1115 | } else { |
| 1116 | raw_target_embedding = raw_query_embedding; |
| 1117 | } |
| 1118 | |
| 1119 | auto n_probes = |
| 1120 | std::min(n_probes_, |
| 1121 | static_cast<uint32_t>(options->centroid_searcher.ntotal)); |
| 1122 | std::vector<float> centroid_distances(n_probes); |
| 1123 | std::vector<faiss::idx_t> centroid_indexes(n_probes, -1); |
| 1124 | options->centroid_searcher.search(1, |
| 1125 | raw_target_embedding, |
| 1126 | n_probes, |
| 1127 | centroid_distances.data(), |
| 1128 | centroid_indexes.data()); |
| 1129 | |
| 1130 | std::vector<Candidate> candidates; |
| 1131 | for (auto centroid_index : centroid_indexes) { |
| 1132 | if (centroid_index == -1) { |
| 1133 | break; |
| 1134 | } |
| 1135 | |
| 1136 | auto lexicon_record_id = |
| 1137 | options->centroid_index_to_record_id[centroid_index]; |
| 1138 | auto ii = reinterpret_cast<grn_ii *>(index_); |
| 1139 | auto cursor = grn_ii_cursor_open(ctx_, |
| 1140 | ii, |
| 1141 | lexicon_record_id, |
| 1142 | GRN_ID_NIL, |
| 1143 | GRN_ID_MAX, |
| 1144 | 0, |
| 1145 | 0); |
| 1146 | if (!cursor) { |
| 1147 | continue; |
| 1148 | } |
| 1149 | |
| 1150 | // TODO: Bulk similarity computation for performance. |
| 1151 | #ifdef GRN_FAISS_HAVE_FLAT_CODES_DISTANCE_COMPUTER |
| 1152 | faiss::FlatCodesDistanceComputer *distance_computer = nullptr; |
| 1153 | if (options->quantizer == Quantizer::NONE) { |
| 1154 | distance_computer = |
| 1155 | options->centroid_searcher.get_FlatCodesDistanceComputer(); |
| 1156 | } else if (options->quantizer == Quantizer::RABITQ) { |
| 1157 | # ifdef GRN_FAISS_HAVE_RABITQ |
| 1158 | uint8_t n_scalar_quantization_bits = 8; |
| 1159 | const float *centroid = options->centroids.data() + |
| 1160 | (options->n_dimensions * centroid_index); |
| 1161 | distance_computer = |
| 1162 | options->rabitq.get_distance_computer(n_scalar_quantization_bits, |
| 1163 | centroid); |
| 1164 | # endif |
| 1165 | } |
| 1166 | distance_computer->set_query(raw_target_embedding); |
| 1167 | #else |
| 1168 | grn_obj target_embedding; |
| 1169 | GRN_FLOAT32_INIT(&target_embedding, |
| 1170 | GRN_OBJ_VECTOR | GRN_OBJ_DO_SHALLOW_COPY); |
| 1171 | GRN_TEXT_SET_REF(&target_embedding, |
| 1172 | raw_target_embedding, |
| 1173 | sizeof(float) * options->n_dimensions); |
| 1174 | grn_obj candidate_embedding; |
| 1175 | GRN_FLOAT32_INIT(&candidate_embedding, |
| 1176 | GRN_OBJ_VECTOR | GRN_OBJ_DO_SHALLOW_COPY); |
| 1177 | #endif |
| 1178 | |
| 1179 | while (true) { |
| 1180 | auto posting = grn_ii_cursor_next(ctx_, cursor); |
| 1181 | if (!posting) { |
| 1182 | break; |
| 1183 | } |
| 1184 | auto source_record_id = posting->rid; |
| 1185 | |
| 1186 | if (!filter(source_record_id)) { |
| 1187 | continue; |
| 1188 | } |
| 1189 | |
| 1190 | GRN_BULK_REWIND(&code_); |
| 1191 | grn_obj_get_value(ctx_, |
| 1192 | options->code_column, |
| 1193 | source_record_id, |
| 1194 | &code_); |
| 1195 | #ifdef GRN_FAISS_HAVE_FLAT_CODES_DISTANCE_COMPUTER |
| 1196 | auto similarity = distance_computer->distance_to_code( |
| 1197 | reinterpret_cast<const uint8_t *>(GRN_BULK_HEAD(&code_))); |
| 1198 | #else |
| 1199 | GRN_TEXT_SET_REF(&candidate_embedding, |
| 1200 | GRN_BULK_HEAD(&code_), |
| 1201 | GRN_BULK_VSIZE(&code_)); |
| 1202 | auto similarity = |
| 1203 | 1 - grn_distance_inner_product(ctx_, |
| 1204 | &target_embedding, |
| 1205 | &candidate_embedding); |
| 1206 | #endif |
| 1207 | candidates.emplace_back(source_record_id, similarity); |
| 1208 | } |
| 1209 | #ifdef GRN_FAISS_HAVE_FLAT_CODES_DISTANCE_COMPUTER |
| 1210 | delete distance_computer; |
| 1211 | #else |
| 1212 | GRN_OBJ_FIN(ctx_, &target_embedding); |
| 1213 | GRN_OBJ_FIN(ctx_, &candidate_embedding); |
| 1214 | #endif |
| 1215 | grn_ii_cursor_close(ctx_, cursor); |
| 1216 | } |
| 1217 | |
| 1218 | auto k = std::min(k_, static_cast<uint32_t>(candidates.size())); |
| 1219 | if (ascending) { |
| 1220 | std::partial_sort(candidates.begin(), |
| 1221 | candidates.begin() + k, |
| 1222 | candidates.end(), |
| 1223 | [](const Candidate &a, const Candidate &b) { |
| 1224 | return b.similarity > a.similarity; |
| 1225 | }); |
| 1226 | } else { |
| 1227 | std::partial_sort(candidates.begin(), |
| 1228 | candidates.begin() + k, |
| 1229 | candidates.end(), |
| 1230 | [](const Candidate &a, const Candidate &b) { |
| 1231 | return a.similarity > b.similarity; |
| 1232 | }); |
| 1233 | } |
| 1234 | return candidates; |
| 1235 | } |
| 1236 | |
| 1237 | private: |
| 1238 | grn_ctx *ctx_; |
| 1239 | grn_obj *table_; |
| 1240 | grn_obj *index_; |
| 1241 | std::string_view query_; |
| 1242 | uint32_t n_probes_; |
| 1243 | uint32_t k_; |
| 1244 | grn_obj query_embedding_; |
| 1245 | grn_obj transformed_query_embedding_; |
| 1246 | grn_obj code_; |
| 1247 | }; |
| 1248 | |
| 1249 | grn_rc |
| 1250 | language_model_knn_selector(grn_ctx *ctx, |
| 1251 | grn_obj *table, |
| 1252 | grn_obj *index, |
| 1253 | int n_args, |
| 1254 | grn_obj **args, |
| 1255 | grn_obj *res, |
| 1256 | grn_operator op) |
| 1257 | { |
| 1258 | const char *tag = "language_model_knn():"; |
| 1259 | |
| 1260 | if (!(n_args == 3 || n_args == 4)) { |
| 1261 | /* args[0] is function. */ |
| 1262 | GRN_PLUGIN_ERROR(ctx, |
| 1263 | GRN_INVALID_ARGUMENT, |
| 1264 | "%s wrong number of arguments (%d for 2..3)", |
| 1265 | tag, |
| 1266 | n_args - 1); |
| 1267 | return ctx->rc; |
| 1268 | } |
| 1269 | |
| 1270 | grn_obj *query = args[2]; |
| 1271 | uint32_t n_probes = 10; |
| 1272 | uint32_t k = 10; |
| 1273 | if (n_args == 4 && args[3]->header.type == GRN_TABLE_HASH_KEY) { |
| 1274 | int32_t arg_k = -1; |
| 1275 | grn_rc rc = grn_proc_options_parse(ctx, |
| 1276 | args[3], |
| 1277 | tag, |
| 1278 | "k", |
| 1279 | GRN_PROC_OPTION_VALUE_INT32, |
| 1280 | &arg_k, |
| 1281 | NULL); |
| 1282 | if (rc != GRN_SUCCESS) { |
| 1283 | return ctx->rc; |
| 1284 | } |
| 1285 | if (arg_k == 0) { |
| 1286 | return GRN_SUCCESS; |
| 1287 | } else if (arg_k > 0) { |
| 1288 | k = static_cast<uint32_t>(arg_k); |
| 1289 | } else { |
| 1290 | int32_t new_k = grn_table_size(ctx, table) + arg_k + 1; |
| 1291 | if (new_k <= 0) { |
| 1292 | return GRN_SUCCESS; |
| 1293 | } |
| 1294 | k = static_cast<uint32_t>(new_k); |
| 1295 | } |
| 1296 | } |
| 1297 | |
| 1298 | if (GRN_TEXT_LEN(query) == 0) { |
| 1299 | grn_ii_resolve_sel_and(ctx, reinterpret_cast<grn_hash *>(res), op); |
| 1300 | return ctx->rc; |
| 1301 | } |
| 1302 | |
| 1303 | Searcher searcher( |
| 1304 | ctx, |
| 1305 | table, |
| 1306 | index, |
| 1307 | std::string_view{GRN_TEXT_VALUE(query), GRN_TEXT_LEN(query)}, |
| 1308 | n_probes, |
| 1309 | k); |
| 1310 | const bool ascending = false; |
| 1311 | std::optional<std::vector<Candidate>> maybe_candidates; |
| 1312 | if (op == GRN_OP_AND) { |
| 1313 | maybe_candidates = searcher.search( |
| 1314 | [&](grn_id id) { |
| 1315 | return grn_table_get(ctx, res, &id, sizeof(grn_id)) != GRN_ID_NIL; |
| 1316 | }, |
| 1317 | ascending); |
| 1318 | } else { |
| 1319 | maybe_candidates = |
| 1320 | searcher.search([](grn_id id) { return true; }, ascending); |
| 1321 | } |
| 1322 | if (!maybe_candidates) { |
| 1323 | return ctx->rc; |
| 1324 | } |
| 1325 | |
| 1326 | auto candidates = *maybe_candidates; |
| 1327 | k = std::min(k, static_cast<uint32_t>(candidates.size())); |
| 1328 | auto posting = grn_posting_open(ctx); |
| 1329 | posting->sid = 0; |
| 1330 | posting->pos = 0; |
| 1331 | for (size_t i = 0; i < k; ++i) { |
| 1332 | const auto &candidate = candidates[i]; |
| 1333 | posting->rid = candidate.record_id; |
| 1334 | grn_posting_set_weight_float(ctx, posting, candidate.similarity); |
| 1335 | grn_result_set_add_record(ctx, |
| 1336 | reinterpret_cast<grn_hash *>(res), |
| 1337 | posting, |
| 1338 | op); |
| 1339 | } |
| 1340 | grn_ii_resolve_sel_and(ctx, reinterpret_cast<grn_hash *>(res), op); |
| 1341 | grn_posting_close(ctx, posting); |
| 1342 | |
| 1343 | return ctx->rc; |
| 1344 | } |
| 1345 | |
| 1346 | grn_rc |
| 1347 | language_model_knn_sorter(grn_ctx *ctx, grn_sorter_data *data) |
| 1348 | { |
| 1349 | const char *tag = "language_model_knn():"; |
| 1350 | |
| 1351 | size_t n_args; |
| 1352 | grn_obj **args = grn_sorter_data_get_args(ctx, data, &n_args); |
| 1353 | if (!(n_args == 2 || n_args == 3)) { |
| 1354 | GRN_PLUGIN_ERROR(ctx, |
| 1355 | GRN_INVALID_ARGUMENT, |
| 1356 | "%s wrong number of arguments (%u for 2..3)", |
| 1357 | tag, |
| 1358 | static_cast<uint32_t>(n_args)); |
| 1359 | return ctx->rc; |
| 1360 | } |
| 1361 | |
| 1362 | grn_obj *table = grn_sorter_data_get_table(ctx, data); |
| 1363 | size_t offset = grn_sorter_data_get_offset(ctx, data); |
| 1364 | size_t limit = grn_sorter_data_get_limit(ctx, data); |
| 1365 | grn_obj *result = grn_sorter_data_get_result(ctx, data); |
| 1366 | bool ascending = grn_sorter_data_is_ascending(ctx, data); |
| 1367 | |
| 1368 | grn_obj *target = args[0]; |
| 1369 | grn_obj *query = args[1]; |
| 1370 | uint32_t n_probes = 10; |
| 1371 | uint32_t k = offset + limit; |
| 1372 | if (n_args == 3 && args[2]->header.type == GRN_TABLE_HASH_KEY) { |
| 1373 | // TODO: Parse options by grn_proc_options_parse() |
| 1374 | } |
| 1375 | |
| 1376 | if (grn_obj_is_column(ctx, target)) { |
| 1377 | grn_index_datum index_data; |
| 1378 | unsigned int n_indexes = |
| 1379 | grn_column_find_index_data(ctx, target, GRN_OP_SIMILAR, &index_data, 1); |
| 1380 | if (n_indexes == 0) { |
| 1381 | grn_obj inspected; |
| 1382 | GRN_TEXT_INIT(&inspected, 0); |
| 1383 | grn_inspect(ctx, &inspected, target); |
| 1384 | GRN_PLUGIN_ERROR(ctx, |
| 1385 | GRN_INVALID_ARGUMENT, |
| 1386 | "%s no index: <%.*s>", |
| 1387 | tag, |
| 1388 | static_cast<int>(GRN_TEXT_LEN(&inspected)), |
| 1389 | GRN_TEXT_VALUE(&inspected)); |
| 1390 | GRN_OBJ_FIN(ctx, &inspected); |
| 1391 | return ctx->rc; |
| 1392 | } |
| 1393 | |
| 1394 | Searcher searcher( |
| 1395 | ctx, |
| 1396 | table, |
| 1397 | index_data.index, |
| 1398 | std::string_view(GRN_TEXT_VALUE(query), GRN_TEXT_LEN(query)), |
| 1399 | n_probes, |
| 1400 | k); |
| 1401 | auto maybe_candidates = |
| 1402 | searcher.search([](grn_id id) { return true; }, ascending); |
| 1403 | if (!maybe_candidates) return ctx->rc; |
| 1404 | |
| 1405 | auto candidates = *maybe_candidates; |
| 1406 | for (size_t i = offset; i < k; ++i) { |
| 1407 | const auto &candidate = candidates[i]; |
| 1408 | void *value; |
| 1409 | auto id = |
| 1410 | grn_array_add(ctx, reinterpret_cast<grn_array *>(result), &value); |
| 1411 | if (id == GRN_ID_NIL) { |
| 1412 | break; |
| 1413 | } |
| 1414 | auto sorted_id = static_cast<grn_id *>(value); |
| 1415 | *sorted_id = candidate.record_id; |
| 1416 | } |
| 1417 | } else if (grn_obj_is_accessor(ctx, target)) { |
| 1418 | /* Filtered result set. */ |
| 1419 | std::vector<grn_obj *> accessor_stack; |
| 1420 | grn_obj *leaf_target = target; |
| 1421 | while (true) { |
| 1422 | grn_obj *next_target = grn_accessor_get_next(ctx, leaf_target); |
| 1423 | if (!next_target) { |
| 1424 | leaf_target = grn_accessor_get_obj(ctx, leaf_target); |
| 1425 | break; |
| 1426 | } |
| 1427 | accessor_stack.push_back(leaf_target); |
| 1428 | leaf_target = next_target; |
| 1429 | } |
| 1430 | |
| 1431 | grn_index_datum index_data; |
| 1432 | unsigned int n_indexes = grn_column_find_index_data(ctx, |
| 1433 | leaf_target, |
| 1434 | GRN_OP_SIMILAR, |
| 1435 | &index_data, |
| 1436 | 1); |
| 1437 | if (n_indexes == 0) { |
| 1438 | grn_obj inspected; |
| 1439 | GRN_TEXT_INIT(&inspected, 0); |
| 1440 | grn_inspect(ctx, &inspected, target); |
| 1441 | GRN_PLUGIN_ERROR(ctx, |
| 1442 | GRN_INVALID_ARGUMENT, |
| 1443 | "%s no index: <%.*s>", |
| 1444 | tag, |
| 1445 | static_cast<int>(GRN_TEXT_LEN(&inspected)), |
| 1446 | GRN_TEXT_VALUE(&inspected)); |
| 1447 | GRN_OBJ_FIN(ctx, &inspected); |
| 1448 | return ctx->rc; |
| 1449 | } |
| 1450 | |
| 1451 | auto resolve_id = [&](grn_id id) -> grn_id { |
| 1452 | for (auto i = accessor_stack.size(); i > 0; --i) { |
| 1453 | auto accessor = accessor_stack[i - 1]; |
| 1454 | auto obj = grn_accessor_get_obj(ctx, accessor); |
| 1455 | auto next_id = grn_table_get(ctx, obj, &id, sizeof(grn_id)); |
| 1456 | if (next_id == GRN_ID_NIL) { |
| 1457 | return GRN_ID_NIL; |
| 1458 | } |
| 1459 | id = next_id; |
| 1460 | } |
| 1461 | return id; |
| 1462 | }; |
| 1463 | |
| 1464 | grn_obj *leaf_table = grn_ctx_at(ctx, leaf_target->header.domain); |
| 1465 | Searcher searcher( |
| 1466 | ctx, |
| 1467 | leaf_table, |
| 1468 | index_data.index, |
| 1469 | std::string_view(GRN_TEXT_VALUE(query), GRN_TEXT_LEN(query)), |
| 1470 | n_probes, |
| 1471 | k); |
| 1472 | grn_obj_unref(ctx, leaf_table); |
| 1473 | auto maybe_candidates = |
| 1474 | searcher.search([&](grn_id id) { return resolve_id(id) != GRN_ID_NIL; }, |
| 1475 | ascending); |
| 1476 | if (!maybe_candidates) return ctx->rc; |
| 1477 | |
| 1478 | auto candidates = *maybe_candidates; |
| 1479 | for (size_t i = offset; i < k; ++i) { |
| 1480 | const auto &candidate = candidates[i]; |
| 1481 | void *value; |
| 1482 | auto id = |
| 1483 | grn_array_add(ctx, reinterpret_cast<grn_array *>(result), &value); |
| 1484 | if (id == GRN_ID_NIL) { |
| 1485 | break; |
| 1486 | } |
| 1487 | auto sorted_id = static_cast<grn_id *>(value); |
| 1488 | *sorted_id = resolve_id(candidate.record_id); |
| 1489 | } |
| 1490 | } |
| 1491 | |
| 1492 | return ctx->rc; |
| 1493 | } |
| 1494 | } // namespace |
| 1495 | |
| 1496 | extern "C" { |
| 1497 | grn_rc |
| 1498 | GRN_PLUGIN_INIT(grn_ctx *ctx) |
| 1499 | { |
| 1500 | return GRN_SUCCESS; |
| 1501 | } |
| 1502 | |
| 1503 | grn_rc |
| 1504 | GRN_PLUGIN_REGISTER(grn_ctx *ctx) |
| 1505 | { |
| 1506 | { |
| 1507 | grn_obj *tokenizer = grn_tokenizer_create(ctx, "TokenLanguageModelKNN", -1); |
| 1508 | if (tokenizer) { |
| 1509 | grn_tokenizer_set_build_func(ctx, tokenizer, build); |
| 1510 | grn_tokenizer_set_init_func(ctx, tokenizer, init); |
| 1511 | grn_tokenizer_set_next_func(ctx, tokenizer, next); |
| 1512 | grn_tokenizer_set_fin_func(ctx, tokenizer, fin); |
| 1513 | } |
| 1514 | } |
| 1515 | |
| 1516 | { |
| 1517 | grn_obj *proc = grn_proc_create(ctx, |
| 1518 | "language_model_knn", |
| 1519 | -1, |
| 1520 | GRN_PROC_FUNCTION, |
| 1521 | nullptr, |
| 1522 | nullptr, |
| 1523 | nullptr, |
| 1524 | 0, |
| 1525 | nullptr); |
| 1526 | grn_proc_set_selector(ctx, proc, language_model_knn_selector); |
| 1527 | grn_proc_set_selector_operator(ctx, proc, GRN_OP_SIMILAR); |
| 1528 | grn_proc_set_sorter(ctx, proc, language_model_knn_sorter); |
| 1529 | } |
| 1530 | return ctx->rc; |
| 1531 | } |
| 1532 | |
| 1533 | grn_rc |
| 1534 | GRN_PLUGIN_FIN(grn_ctx *ctx) |
| 1535 | { |
| 1536 | return GRN_SUCCESS; |
| 1537 | } |
| 1538 | } |