Debian Codegraph @

lib/language_model.cpp

raw symbols SCIP
1 // Copyright (C) 2024-2025 Sutou Kouhei <[email protected]>
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
17 #include "grn_ctx.hpp"
18 #include "grn_db.h"
19 #include "grn_http_client.h"
20 #include "grn_language_model.hpp"
21 #include "grn_progress.h"
22 #include "grn_util.h"
23
24 #include <groonga/smart_obj.hpp>
25
26 #ifdef GRN_WITH_LLAMA_CPP
27 # include <ggml-backend.h>
28 # include <llama.h>
29 #endif
30
31 #ifdef GRN_WITH_SIMDJSON
32 # include <simdjson.h>
33 #endif
34
35 #include <algorithm>
36 #include <cerrno>
37 #include <cmath>
38 #include <condition_variable>
39 #include <cstring>
40 #include <fstream>
41 #include <functional>
42 #include <map>
43 #include <mutex>
44
45 #define GRN_LM_ERROR(default_rc, message) \
46 do { \
47 grn_rc rc = ctx->rc == GRN_SUCCESS ? (default_rc) : ctx->rc; \
48 char errbuf[GRN_CTX_MSGSIZE]; \
49 grn_strcpy(errbuf, GRN_CTX_MSGSIZE, ctx->errbuf); \
50 ERR(rc, "%s: %s", (message), errbuf); \
51 } while (false)
52
53 namespace grn {
54 namespace language_model {
55 #ifdef GRN_WITH_LLAMA_CPP
56 namespace {
57 void
58 log_callback(ggml_log_level level, const char *text, void *user_data)
59 {
60 grn_ctx *ctx = static_cast<grn_ctx *>(user_data);
61 switch (level) {
62 case GGML_LOG_LEVEL_ERROR:
63 ERR(GRN_UNKNOWN_ERROR, "%s", text);
64 break;
65 case GGML_LOG_LEVEL_WARN:
66 if (grn_logger_pass(ctx, GRN_LOG_WARNING)) {
67 grn_logger_put(ctx,
68 GRN_LOG_WARNING,
69 __FILE__,
70 __LINE__,
71 __FUNCTION__,
72 "%s",
73 text);
74 }
75 break;
76 case GGML_LOG_LEVEL_INFO:
77 if (grn_logger_pass(ctx, GRN_LOG_INFO)) {
78 grn_logger_put(ctx,
79 GRN_LOG_INFO,
80 __FILE__,
81 __LINE__,
82 __FUNCTION__,
83 "%s",
84 text);
85 }
86 break;
87 case GGML_LOG_LEVEL_DEBUG:
88 if (grn_logger_pass(ctx, GRN_LOG_DEBUG)) {
89 grn_logger_put(ctx,
90 GRN_LOG_DEBUG,
91 __FILE__,
92 __LINE__,
93 __FUNCTION__,
94 "%s",
95 text);
96 }
97 break;
98 default:
99 ERR(GRN_UNKNOWN_ERROR, "%s", text);
100 break;
101 }
102 }
103 } // namespace
104 #endif
105
106 static char ggml_backends_dir[GRN_ENV_BUFFER_SIZE];
107 static char language_models_dir[GRN_ENV_BUFFER_SIZE];
108 static char language_model_download_cache_dir[GRN_ENV_BUFFER_SIZE];
109
110 void
111 init_from_env()
112 {
113 grn_getenv("GRN_GGML_BACKENDS_DIR",
114 ggml_backends_dir,
115 GRN_ENV_BUFFER_SIZE);
116 grn_getenv("GRN_LANGUAGE_MODELS_DIR",
117 language_models_dir,
118 GRN_ENV_BUFFER_SIZE);
119 grn_getenv("GRN_LANGUAGE_MODEL_DOWNLOAD_CACHE_DIR",
120 language_model_download_cache_dir,
121 GRN_ENV_BUFFER_SIZE);
122 }
123
124 #ifdef GRN_WITH_LLAMA_CPP
125 struct ModelCacheKey {
126 std::string path;
127 int32_t n_gpu_layers;
128 };
129
130 bool
131 operator<(const ModelCacheKey &a, const ModelCacheKey &b)
132 {
133 return std::tie(a.path, a.n_gpu_layers) <
134 std::tie(b.path, b.n_gpu_layers);
135 }
136
137 struct ModelCache {
138 ModelCache() = default;
139 ~ModelCache() = default;
140
141 std::shared_ptr<LanguageModel>
142 get(const ModelCacheKey &key,
143 std::function<std::shared_ptr<LanguageModel>()> load)
144 {
145 std::lock_guard<std::mutex> lock(mutex_);
146 auto it = models_.find(key);
147 if (it != models_.end()) {
148 return it->second;
149 }
150
151 auto model = load();
152 if (model) {
153 models_[key] = model;
154 }
155 return model;
156 }
157
158 void
159 clear()
160 {
161 models_.clear();
162 }
163
164 private:
165 std::map<ModelCacheKey, std::shared_ptr<LanguageModel>> models_;
166 std::mutex mutex_;
167 };
168
169 static ModelCache model_cache;
170
171 static bool initialized = false;
172 static std::once_flag initialize_once;
173
174 namespace {
175 # ifdef GRN_WITH_LLAMA_CPP_BUNDLED
176 # ifdef _WIN32
177 const char *
178 get_default_ggml_backends_dir()
179 {
180 static char *windows_ggml_backends_dir = nullptr;
181 static char windows_ggml_backends_dir_buffer[PATH_MAX];
182 if (!windows_ggml_backends_dir) {
183 auto base_dir = grn_windows_base_dir();
184 auto base_dir_length = strlen(base_dir);
185 grn_strcpy(windows_ggml_backends_dir_buffer, PATH_MAX, base_dir);
186 grn_strcat(windows_ggml_backends_dir_buffer, PATH_MAX, "/");
187 grn_strcat(windows_ggml_backends_dir_buffer,
188 PATH_MAX,
189 GRN_RELATIVE_GGML_BACKENDS_DIR);
190 windows_ggml_backends_dir = windows_ggml_backends_dir_buffer;
191 }
192 return windows_ggml_backends_dir;
193 }
194 # else
195 const char *
196 get_default_ggml_backends_dir()
197 {
198 return GRN_GGML_BACKENDS_DIR;
199 }
200 # endif
201
202 const char *
203 get_ggml_backends_dir()
204 {
205 if (ggml_backends_dir[0]) {
206 return ggml_backends_dir;
207 } else {
208 return get_default_ggml_backends_dir();
209 }
210 }
211 # endif
212
213 void
214 init_external_libraries()
215 {
216 llama_log_set(log_callback, &grn_gctx);
217 # ifdef GRN_WITH_LLAMA_CPP_BUNDLED
218 ggml_backend_load_all_from_path(get_ggml_backends_dir());
219 # endif
220 llama_backend_init();
221 initialized = true;
222 }
223
224 void
225 ensure_init_external_libraries()
226 {
227 std::call_once(initialize_once, init_external_libraries);
228 }
229 } // namespace
230 #else
231 namespace {
232 void
233 ensure_init_external_libraries()
234 {
235 }
236 } // namespace
237 #endif
238
239 void
240 fin_external_libraries()
241 {
242 #ifdef GRN_WITH_LLAMA_CPP
243 if (!initialized) return;
244
245 model_cache.clear();
246 llama_backend_free();
247 llama_log_set(nullptr, nullptr);
248 #endif
249 }
250
251 #ifdef GRN_WITH_LLAMA_CPP
252 # ifdef _WIN32
253 static char *windows_language_models_dir = NULL;
254 static char windows_language_models_dir_buffer[PATH_MAX];
255 namespace {
256 const char *
257 default_system_language_models_dir()
258 {
259 if (!windows_language_models_dir) {
260 const char *base_dir;
261 const char *relative_path = GRN_RELATIVE_LANGUAGE_MODELS_DIR;
262
263 base_dir = grn_windows_base_dir();
264 grn_strcpy(windows_language_models_dir_buffer, PATH_MAX, base_dir);
265 grn_strcat(windows_language_models_dir_buffer, PATH_MAX, "/");
266 grn_strcat(windows_language_models_dir_buffer,
267 PATH_MAX,
268 relative_path);
269 windows_language_models_dir = windows_language_models_dir_buffer;
270 }
271 return windows_language_models_dir;
272 }
273 } // namespace
274 # else
275 namespace {
276 const char *
277 default_system_language_models_dir()
278 {
279 return GRN_LANGUAGE_MODELS_DIR;
280 }
281 } // namespace
282 # endif
283
284 const char *
285 system_language_models_dir()
286 {
287 if (language_models_dir[0]) {
288 return language_models_dir;
289 } else {
290 return default_system_language_models_dir();
291 }
292 }
293
294 static std::mutex capture_error_mutex;
295 class CaptureError {
296 public:
297 CaptureError(grn_ctx *ctx) : lock_(capture_error_mutex)
298 {
299 llama_log_set(log_callback, ctx);
300 }
301
302 ~CaptureError() { llama_log_set(log_callback, &grn_gctx); }
303
304 private:
305 std::lock_guard<std::mutex> lock_;
306 };
307 #endif
308 }; // namespace language_model
309
310 class LanguageModel::Impl {
311 #ifdef GRN_WITH_LLAMA_CPP
312 public:
313 Impl(llama_model *model)
314 : model_(model),
315 default_pooling_type_(LLAMA_POOLING_TYPE_NONE)
316 {
317 auto params = llama_context_default_params();
318 params.n_ctx = 0;
319 params.embeddings = true;
320 auto llama_ctx = llama_init_from_model(model_, params);
321 if (llama_ctx) {
322 default_pooling_type_ = llama_pooling_type(llama_ctx);
323 llama_free(llama_ctx);
324 }
325 }
326
327 ~Impl() { llama_model_free(model_); }
328
329 llama_model *
330 get_raw()
331 {
332 return model_;
333 }
334
335 enum llama_pooling_type
336 default_pooling_type()
337 {
338 return default_pooling_type_;
339 }
340
341 private:
342 llama_model *model_;
343 enum llama_pooling_type default_pooling_type_;
344 #endif
345 };
346
347 LanguageModel::LanguageModel(Impl *impl) : impl_(impl) {}
348
349 LanguageModel::~LanguageModel() = default;
350
351 std::shared_ptr<LanguageModel>
352 LanguageModelLoader::load()
353 {
354 auto ctx = ctx_;
355
356 #ifdef GRN_WITH_LLAMA_CPP
357 if (model_path.empty()) {
358 ERR(GRN_INVALID_ARGUMENT,
359 "[language-model-loader][load] model path is missing");
360 return nullptr;
361 }
362
363 auto model = language_model::model_cache.get(
364 language_model::ModelCacheKey{model_path, n_gpu_layers},
365 [this]() -> std::shared_ptr<LanguageModel> {
366 auto ctx = ctx_;
367 auto params = llama_model_default_params();
368 params.n_gpu_layers = n_gpu_layers;
369 params.progress_callback = [](float progress, void *ctx) {
370 return true;
371 };
372
373 {
374 language_model::CaptureError capture(ctx_);
375 auto raw_model =
376 llama_model_load_from_file(model_path.c_str(), params);
377 if (!raw_model) {
378 GRN_LM_ERROR(GRN_INVALID_ARGUMENT,
379 "[language-model-loader][load] failed to load model");
380 return nullptr;
381 }
382
383 if (llama_model_has_encoder(raw_model) &&
384 !llama_model_has_decoder(raw_model)) {
385 ERR(GRN_INVALID_ARGUMENT,
386 "[language-model-loader][load] encoder-decoder model isn't "
387 "supported yet: <%s>",
388 model_path.c_str());
389 llama_model_free(raw_model);
390 return nullptr;
391 }
392
393 return std::make_shared<LanguageModel>(
394 new LanguageModel::Impl(raw_model));
395 }
396 });
397 return model;
398 #else
399 ERR(GRN_FUNCTION_NOT_IMPLEMENTED,
400 "[language-model-loader][load] llama.cpp isn't enabled");
401 return nullptr;
402 #endif
403 }
404
405 class LanguageModelInferencer::Impl {
406 #ifdef GRN_WITH_LLAMA_CPP
407 struct BatchReleaser {
408 llama_batch *batch_;
409
410 BatchReleaser(llama_batch *batch) : batch_(batch) {}
411 ~BatchReleaser()
412 {
413 if (batch_) {
414 llama_batch_free(*batch_);
415 }
416 }
417 };
418
419 # ifdef GRN_WITH_LLAMA_CPP
420 class Vectorizer {
421 public:
422 Vectorizer(llama_model *model_raw,
423 enum llama_pooling_type default_pooling_type)
424 : llama_ctx_(nullptr),
425 llama_model_(model_raw),
426 n_dimensions_(llama_model_n_embd(llama_model_)),
427 has_encoder_(llama_model_has_encoder(llama_model_)),
428 has_decoder_(llama_model_has_decoder(llama_model_)),
429 // We want document vector not token vectors. We want to use the
430 // default pooling type in a model but it seems that most models
431 // don't provide the default pooling type (LLAMA_POOLING_TYPE_NONE
432 // is used). If LLAMA_POOLING_TYPE_NONE is used, token vectors are
433 // generated. So we force to use LLAMA_POOLING_TYPE_MEAN here.
434 pooling_type_(default_pooling_type == LLAMA_POOLING_TYPE_NONE
435 ? LLAMA_POOLING_TYPE_MEAN
436 : default_pooling_type),
437 max_n_tokens_limit_(llama_model_n_ctx_train(llama_model_)),
438 max_n_tokens_(llama_context_default_params().n_ubatch),
439 pooling_buffer_(n_dimensions_)
440 {
441 }
442
443 ~Vectorizer()
444 {
445 if (llama_ctx_) {
446 llama_free(llama_ctx_);
447 }
448 }
449
450 void
451 vectorize(grn_ctx *ctx,
452 std::string_view text,
453 grn_obj *output_vector,
454 const char *tag)
455 {
456 std::vector<llama_token> tokens;
457 tokenize(text, tokens);
458 auto n_tokens = static_cast<uint32_t>(tokens.size());
459 adjust_max_n_tokens(ctx, GRN_ID_NIL, n_tokens, tag);
460 auto batch = llama_batch_init(max_n_tokens_, 0, 1);
461 BatchReleaser batch_releaser(&batch);
462 if (n_tokens > max_n_tokens_) {
463 const llama_seq_id sequence_id = 0;
464 auto n_chunks = ((n_tokens - 1) / max_n_tokens_) + 1;
465 for (size_t i = 0; i < n_chunks; ++i) {
466 auto offset = max_n_tokens_ * i;
467 auto size =
468 std::min(n_tokens - offset, static_cast<size_t>(max_n_tokens_));
469 add_tokens(batch, tokens, offset, size, sequence_id);
470
471 if (!vectorize_batch(ctx, batch, sequence_id + 1)) {
472 return;
473 }
474
475 if (!pool_embedding(ctx, batch, sequence_id, i, tag)) {
476 return;
477 }
478
479 batch.n_tokens = 0;
480 offset += size;
481 }
482
483 normalize_embedding(
484 pooling_buffer_.data(),
485 [&](int32_t dimension, float normalized_value) {
486 GRN_FLOAT32_PUT(ctx, output_vector, normalized_value);
487 });
488 } else {
489 const llama_seq_id sequence_id = 0;
490 add_tokens(batch, tokens, 0, tokens.size(), sequence_id);
491
492 if (!vectorize_batch(ctx, batch, sequence_id + 1)) {
493 return;
494 }
495
496 if (!store_embedding(ctx, batch, sequence_id, output_vector, tag)) {
497 return;
498 }
499 }
500 }
501
502 template <typename IDProducer, typename Output>
503 void
504 vectorize_in_batch(grn_ctx *ctx,
505 IDProducer id_producer,
506 grn_obj *input_column,
507 std::string_view prefix,
508 Output output,
509 const char *tag)
510 {
511 struct Target {
512 grn_id id;
513 size_t current_chunk_index;
514 size_t n_chunks;
515 };
516
517 std::vector<Target> targets;
518 auto batch = llama_batch_init(max_n_tokens_, 0, 1);
519 BatchReleaser batch_releaser(&batch);
520
521 grn_obj embedding;
522 GRN_FLOAT32_INIT(&embedding, GRN_OBJ_VECTOR);
523 grn::UniqueObj smart_embedding(ctx, &embedding);
524
525 auto flush_batch = [&]() {
526 const auto n_sequences = targets.size();
527 if (!vectorize_batch(ctx, batch, n_sequences)) {
528 return false;
529 }
530 for (size_t i = 0; i < n_sequences; ++i) {
531 const auto &target = targets[i];
532 const auto sequence_id = static_cast<llama_seq_id>(i);
533 if (target.n_chunks == 1) {
534 GRN_BULK_REWIND(&embedding);
535 if (!store_embedding(ctx, batch, sequence_id, &embedding, tag)) {
536 return false;
537 }
538 output(ctx, target.id, &embedding);
539 } else {
540 if (!pool_embedding(ctx,
541 batch,
542 sequence_id,
543 target.current_chunk_index,
544 tag)) {
545 return false;
546 }
547 if (target.current_chunk_index == target.n_chunks - 1) {
548 GRN_BULK_REWIND(&embedding);
549 normalize_embedding(
550 pooling_buffer_.data(),
551 [&](int32_t dimension, float normalized_value) {
552 GRN_FLOAT32_PUT(ctx, &embedding, normalized_value);
553 });
554 output(ctx, target.id, &embedding);
555 }
556 }
557 }
558 targets.clear();
559 batch.n_tokens = 0;
560 return true;
561 };
562
563 std::vector<llama_token> tokens;
564
565 auto batch_is_full = [&](uint32_t n_tokens) {
566 auto next_n_tokens = batch.n_tokens + n_tokens;
567 if (next_n_tokens > max_n_tokens_) {
568 return true;
569 }
570
571 auto n_sequences = static_cast<uint32_t>(targets.size());
572 if (n_sequences == 0) {
573 return false;
574 }
575
576 auto actual_next_n_tokens =
577 normalize_n_tokens(next_n_tokens, n_sequences);
578 return actual_next_n_tokens < max_n_tokens_;
579 };
580
581 grn_id id;
582 while ((id = id_producer()) != GRN_ID_NIL) {
583 uint32_t input_size = 0;
584 auto input = grn_obj_get_value_(ctx, input_column, id, &input_size);
585 if (prefix.empty()) {
586 tokenize(std::string_view(input, input_size), tokens);
587 } else {
588 auto prefixed_input = std::string(prefix);
589 prefixed_input.append(input, input_size);
590 tokenize(prefixed_input, tokens);
591 }
592 auto n_tokens = static_cast<uint32_t>(tokens.size());
593 if (n_tokens == 0) {
594 continue;
595 }
596 if (batch_is_full(n_tokens)) {
597 if (batch.n_tokens > 0) {
598 if (!flush_batch()) {
599 return;
600 }
601 }
602 if (adjust_max_n_tokens(ctx, id, n_tokens, tag)) {
603 llama_batch_free(batch);
604 batch_releaser.batch_ = nullptr;
605 batch = llama_batch_init(max_n_tokens_, 0, 1);
606 batch_releaser.batch_ = &batch;
607 }
608 }
609 auto n_chunks = ((n_tokens - 1) / max_n_tokens_) + 1;
610 for (size_t i = 0; i < n_chunks; ++i) {
611 auto offset = max_n_tokens_ * i;
612 auto size =
613 std::min(n_tokens - offset, static_cast<size_t>(max_n_tokens_));
614 if (batch.n_tokens > 0 && batch_is_full(size)) {
615 if (!flush_batch()) {
616 return;
617 }
618 }
619 add_tokens(batch, tokens, offset, size, targets.size());
620 targets.push_back({id, i, n_chunks});
621 }
622 }
623 if (targets.size() > 0) {
624 if (!flush_batch()) {
625 return;
626 }
627 }
628 }
629
630 template <typename Output>
631 void
632 vectorize_in_batch(grn_ctx *ctx,
633 grn_table_cursor *cursor,
634 grn_obj *input_column,
635 std::string_view prefix,
636 Output output,
637 const char *tag)
638 {
639 vectorize_in_batch(
640 ctx,
641 [&]() { return grn_table_cursor_next(ctx, cursor); },
642 input_column,
643 prefix,
644 output,
645 tag);
646 }
647
648 template <typename Output>
649 void
650 vectorize_in_batch(grn_ctx *ctx,
651 const std::vector<grn_id> &ids,
652 grn_obj *input_column,
653 std::string_view prefix,
654 Output output,
655 const char *tag)
656 {
657 size_t i = 0;
658 vectorize_in_batch(
659 ctx,
660 [&]() {
661 grn_id id = GRN_ID_NIL;
662 if (i < ids.size()) {
663 id = ids[i];
664 }
665 ++i;
666 return id;
667 },
668 input_column,
669 prefix,
670 output,
671 tag);
672 }
673
674 private:
675 llama_context *llama_ctx_;
676 llama_model *llama_model_;
677 const int32_t n_dimensions_;
678 const bool has_encoder_;
679 const bool has_decoder_;
680 const enum llama_pooling_type pooling_type_;
681 const uint32_t max_n_tokens_limit_;
682 uint32_t max_n_tokens_;
683 std::vector<float> pooling_buffer_;
684
685 void
686 tokenize(std::string_view text, std::vector<llama_token> &tokens)
687 {
688 constexpr auto add_special = true;
689 constexpr auto parse_special = false;
690 // Guess enough size
691 int n_tokens = text.length() + 2 * add_special;
692 if (tokens.capacity() < static_cast<size_t>(n_tokens)) {
693 tokens.reserve(n_tokens);
694 }
695 auto vocab = llama_model_get_vocab(llama_model_);
696 n_tokens = llama_tokenize(vocab,
697 text.data(),
698 text.length(),
699 tokens.data(),
700 tokens.size(),
701 add_special,
702 parse_special);
703 if (n_tokens < 0) {
704 // If guessed size isn't enough, use the real size.
705 tokens.resize(-n_tokens);
706 llama_tokenize(vocab,
707 text.data(),
708 text.length(),
709 tokens.data(),
710 tokens.size(),
711 add_special,
712 parse_special);
713 } else {
714 tokens.resize(n_tokens);
715 }
716 }
717
718 // Return true when max_n_tokens_ is updated.
719 bool
720 adjust_max_n_tokens(grn_ctx *ctx,
721 grn_id id,
722 size_t n_tokens,
723 const char *tag)
724 {
725 bool max_n_tokens_updated = false;
726 if (n_tokens == 0) {
727 return max_n_tokens_updated;
728 }
729
730 if (max_n_tokens_ != max_n_tokens_limit_) {
731 while (max_n_tokens_ < n_tokens) {
732 max_n_tokens_ *= 2;
733 }
734 if (max_n_tokens_ > max_n_tokens_limit_) {
735 max_n_tokens_ = max_n_tokens_limit_;
736 }
737 max_n_tokens_updated = true;
738 }
739
740 return max_n_tokens_updated;
741 }
742
743 // TODO: We want to use std::span instead of std::vector +
744 // tokens_star + toekns_size. It requires C++20 but llama.cpp
745 // isn't C++20 ready.
746 void
747 add_tokens(llama_batch &batch,
748 const std::vector<llama_token> &tokens,
749 size_t tokens_start,
750 size_t n_target_tokens,
751 llama_seq_id sequence_id)
752 {
753 const auto offset = batch.n_tokens;
754 memcpy(batch.token + offset,
755 tokens.data() + tokens_start,
756 sizeof(llama_token) * n_target_tokens);
757 for (size_t i = 0; i < n_target_tokens; ++i) {
758 const auto offset_i = offset + i;
759 batch.pos[offset_i] = i;
760 batch.n_seq_id[offset_i] = 1;
761 batch.seq_id[offset_i][0] = sequence_id;
762 batch.logits[offset_i] = true;
763 }
764 batch.n_tokens += n_target_tokens;
765 }
766
767 // n_tokens must be multiple of n_sequences.
768 uint32_t
769 normalize_n_tokens(uint32_t n_tokens, uint32_t n_sequences)
770 {
771 # ifdef GGML_KQ_MASK_PAD
772 if (n_tokens < GGML_KQ_MASK_PAD) {
773 n_tokens = GGML_KQ_MASK_PAD;
774 }
775 # endif
776 return ((n_tokens + (n_sequences - 1)) / n_sequences) * n_sequences;
777 }
778
779 bool
780 vectorize_batch(grn_ctx *ctx,
781 llama_batch &batch,
782 uint32_t max_n_sequences)
783 {
784 if (llama_ctx_ && llama_n_ubatch(llama_ctx_) == max_n_tokens_ &&
785 llama_n_seq_max(llama_ctx_) == max_n_sequences) {
786 auto memory = llama_get_memory(llama_ctx_);
787 if (memory) {
788 llama_memory_clear(memory, true);
789 }
790 } else {
791 if (llama_ctx_) {
792 llama_free(llama_ctx_);
793 }
794 auto params = llama_context_default_params();
795 params.n_ctx =
796 llama_model_n_ctx_train(llama_model_) * max_n_sequences;
797 params.embeddings = true;
798 params.n_batch = normalize_n_tokens(batch.n_tokens, max_n_sequences);
799 params.n_ubatch = params.n_batch;
800 params.n_seq_max = max_n_sequences;
801 params.pooling_type = pooling_type_;
802 llama_ctx_ = llama_init_from_model(llama_model_, params);
803 if (!llama_ctx_) {
804 return false;
805 }
806 }
807
808 if (has_encoder_ && !has_decoder_) {
809 // encoder-only model
810 if (llama_encode(llama_ctx_, batch) < 0) {
811 GRN_LM_ERROR(
812 GRN_UNKNOWN_ERROR,
813 "[language-model-inferencer][vectorize-batch] failed to encode");
814 return false;
815 }
816 } else if (!has_encoder_ && has_decoder_) {
817 // decoder-only model
818 if (llama_decode(llama_ctx_, batch) < 0) {
819 GRN_LM_ERROR(
820 GRN_UNKNOWN_ERROR,
821 "[language-model-inferencer][vectorize-batch] failed to decode");
822 return false;
823 }
824 } else {
825 GRN_LM_ERROR(
826 GRN_FUNCTION_NOT_IMPLEMENTED,
827 "[language-model-inferencer][vectorize-batch] "
828 "model that has both of encoder and docoder isn't supported yet");
829 return false;
830 }
831
832 return true;
833 }
834
835 const float *
836 get_embedding(grn_ctx *ctx,
837 llama_batch &batch,
838 llama_seq_id id,
839 const char *tag)
840 {
841 // pooling_type_ must not be LLAMA_POOLING_TYPE_NONE.
842 auto raw_embedding = llama_get_embeddings_seq(llama_ctx_, id);
843 if (!raw_embedding) {
844 std::string message(tag);
845 message += " failed to get embedding";
846 GRN_LM_ERROR(GRN_UNKNOWN_ERROR, message.data());
847 return nullptr;
848 }
849 return raw_embedding;
850 }
851
852 template <typename Output>
853 void
854 normalize_embedding(const float *raw_embedding, Output output)
855 {
856 // TODO: grn::distance::compute_l2_norm()
857 float square_sum = 0.0;
858 for (int32_t dimension = 0; dimension < n_dimensions_; ++dimension) {
859 square_sum += raw_embedding[dimension] * raw_embedding[dimension];
860 }
861 auto magnitude = std::sqrt(square_sum);
862 const float normalize = magnitude > 0.0 ? 1.0 / magnitude : 0.0f;
863 for (int32_t dimension = 0; dimension < n_dimensions_; ++dimension) {
864 auto normalized_value = raw_embedding[dimension] * normalize;
865 output(dimension, normalized_value);
866 }
867 }
868
869 bool
870 pool_embedding(grn_ctx *ctx,
871 llama_batch &batch,
872 llama_seq_id id,
873 size_t n_pooled_embeddings,
874 const char *tag)
875 {
876 auto raw_embedding = get_embedding(ctx, batch, id, tag);
877 if (!raw_embedding) {
878 return false;
879 }
880 for (int32_t dimension = 0; dimension < n_dimensions_; ++dimension) {
881 // Use average pooling to generate document embedding from
882 // split embeddings. This is a SWEM-aver like approach.
883 //
884 // See also: Baseline Needs More Love: On Simple
885 // Word-Embedding-Based Models and Associated Pooling
886 // Mechanisms: https://arxiv.org/abs/1805.09843
887 //
888 // TODO: We can improve error of incremental/online average
889 // computation. For example, merging averages, using Kahan
890 // summation algorithm and so on.
891 if (n_pooled_embeddings == 0) {
892 pooling_buffer_[dimension] = raw_embedding[dimension];
893 } else {
894 pooling_buffer_[dimension] +=
895 (raw_embedding[dimension] - pooling_buffer_[dimension]) /
896 (n_pooled_embeddings + 1);
897 }
898 }
899 return true;
900 }
901
902 bool
903 store_embedding(grn_ctx *ctx,
904 llama_batch &batch,
905 llama_seq_id id,
906 grn_obj *output_vector,
907 const char *tag)
908 {
909 auto raw_embedding = get_embedding(ctx, batch, id, tag);
910 if (!raw_embedding) {
911 return false;
912 }
913 auto output = [&](int32_t dimension, float normalized_value) {
914 GRN_FLOAT32_PUT(ctx, output_vector, normalized_value);
915 };
916 normalize_embedding(raw_embedding, output);
917 return true;
918 }
919 };
920 # endif
921
922 #endif
923 public:
924 #ifdef GRN_WITH_LLAMA_CPP
925 Impl(std::shared_ptr<LanguageModel> model,
926 llama_model *model_raw,
927 enum llama_pooling_type default_pooling_type)
928 : model_(std::move(model)),
929 llama_model_(model_raw),
930 default_pooling_type_(default_pooling_type),
931 vectorizer_(llama_model_, default_pooling_type_),
932 input_column_value_prefix_(),
933 progress_callback_(nullptr),
934 progress_callback_user_data_(nullptr)
935 {
936 }
937
938 ~Impl() {}
939 #endif
940
941 void
942 set_input_column_value_prefix(std::string prefix)
943 {
944 input_column_value_prefix_ = std::move(prefix);
945 }
946
947 void
948 set_progress_callback(grn_progress_callback_func callback, void *user_data)
949 {
950 progress_callback_ = callback;
951 progress_callback_user_data_ = user_data;
952 }
953
954 void
955 vectorize(grn_ctx *ctx, std::string_view text, grn_obj *output_vector)
956 {
957 const char *tag = "[language-model-inferencer][vectorize]";
958 #ifdef GRN_WITH_LLAMA_CPP
959 language_model::CaptureError capture(ctx);
960 vectorizer_.vectorize(ctx, text, output_vector, tag);
961 #else
962 ERR(GRN_FUNCTION_NOT_IMPLEMENTED, "%s llama.cpp isn't enabled", tag);
963 #endif
964 }
965
966 template <typename Output>
967 void
968 vectorize_in_batch(grn_ctx *ctx,
969 grn_table_cursor *cursor,
970 grn_obj *input_column,
971 Output output)
972 {
973 const char *tag = "[language-model-inferencer][vectorize-in-batch]";
974 #ifdef GRN_WITH_LLAMA_CPP
975 language_model::CaptureError capture(ctx);
976
977 grn_progress progress;
978 progress.type = GRN_PROGRESS_LANGUAGE_MODEL_INFERENCER;
979
980 auto task_executor = grn_ctx_get_task_executor(ctx);
981 if (!task_executor->is_parallel()) {
982 if (progress_callback_) {
983 progress.value.language_model_inferencer.n_processed_records = 1;
984 auto output_with_progress =
985 [&](grn_ctx *ctx, grn_id id, grn_obj *embedding) {
986 output(ctx, id, embedding);
987 progress_callback_(ctx, &progress, progress_callback_user_data_);
988 };
989 vectorizer_.vectorize_in_batch(ctx,
990 cursor,
991 input_column,
992 input_column_value_prefix_,
993 output_with_progress,
994 tag);
995 } else {
996 vectorizer_.vectorize_in_batch(ctx,
997 cursor,
998 input_column,
999 input_column_value_prefix_,
1000 output,
1001 tag);
1002 }
1003 return;
1004 }
1005
1006 auto parallel_tag = std::string(tag) + "[parallel]";
1007
1008 size_t n_records_per_task = 100; // No reason
1009 std::mutex mutex;
1010 std::condition_variable cv;
1011 uintptr_t task_id = 0;
1012 struct ProcessedTask {
1013 ProcessedTask(grn_ctx *ctx) : ctx_(ctx), ids(), embeddings() {}
1014 ~ProcessedTask()
1015 {
1016 for (auto &embedding : embeddings) {
1017 GRN_OBJ_FIN(ctx_, &embedding);
1018 }
1019 }
1020 grn_ctx *ctx_;
1021 std::vector<grn_id> ids;
1022 std::vector<grn_obj> embeddings;
1023 };
1024 std::map<uintptr_t, std::unique_ptr<ProcessedTask>> processed_tasks;
1025
1026 auto execute = [&](uintptr_t task_id, std::vector<grn_id> target_ids) {
1027 auto child_ctx = grn_ctx_pull_child(ctx);
1028 grn::ChildCtxReleaser child_ctx_releaser(ctx, child_ctx);
1029 Vectorizer vectorizer(llama_model_, default_pooling_type_);
1030 auto processed_task = std::make_unique<ProcessedTask>(ctx);
1031 std::vector<std::vector<float>> embeddings;
1032 vectorizer.vectorize_in_batch(
1033 child_ctx,
1034 std::move(target_ids),
1035 input_column,
1036 input_column_value_prefix_,
1037 [&](grn_ctx *output_ctx, grn_id id, grn_obj *embedding) {
1038 processed_task->ids.push_back(id);
1039 processed_task->embeddings.emplace_back();
1040 auto &processed_embedding = processed_task->embeddings.back();
1041 GRN_FLOAT32_INIT(&processed_embedding, GRN_OBJ_VECTOR);
1042 grn_bulk_write(output_ctx,
1043 &processed_embedding,
1044 GRN_BULK_HEAD(embedding),
1045 GRN_BULK_VSIZE(embedding));
1046 },
1047 parallel_tag.data());
1048 if (child_ctx->rc != GRN_SUCCESS) {
1049 return false;
1050 }
1051 {
1052 std::lock_guard<std::mutex> lock(mutex);
1053 processed_tasks.insert(
1054 std::make_pair(task_id, std::move(processed_task)));
1055 }
1056 cv.notify_one();
1057 return child_ctx->rc == GRN_SUCCESS;
1058 };
1059
1060 std::vector<grn_id> target_ids;
1061 auto flush_task = [&]() {
1062 if (!task_executor->execute(
1063 task_id,
1064 [&, task_id, target_ids]() {
1065 return execute(task_id, std::move(target_ids));
1066 },
1067 tag)) {
1068 task_executor->wait_all();
1069 return false;
1070 }
1071 ++task_id;
1072 target_ids.clear();
1073 return true;
1074 };
1075 while (true) {
1076 auto id = grn_table_cursor_next(ctx, cursor);
1077 if (id == GRN_ID_NIL) {
1078 if (!target_ids.empty()) {
1079 if (!flush_task()) {
1080 return;
1081 }
1082 }
1083 break;
1084 }
1085 target_ids.push_back(id);
1086 if (target_ids.size() == n_records_per_task) {
1087 if (!flush_task()) {
1088 return;
1089 }
1090 }
1091 }
1092
1093 for (uintptr_t current_task_id = 0; current_task_id < task_id;
1094 ++current_task_id) {
1095 std::unique_ptr<ProcessedTask> processed_task;
1096 {
1097 std::unique_lock<std::mutex> lock(mutex);
1098 cv.wait(lock, [&] {
1099 return ctx->rc != GRN_SUCCESS ||
1100 processed_tasks.find(current_task_id) !=
1101 processed_tasks.end();
1102 });
1103 if (ctx->rc == GRN_SUCCESS) {
1104 auto iter = processed_tasks.find(current_task_id);
1105 processed_task = std::move(iter->second);
1106 processed_tasks.erase(iter);
1107 }
1108 }
1109 if (ctx->rc != GRN_SUCCESS) {
1110 break;
1111 }
1112 if (!processed_task) {
1113 break;
1114 }
1115 for (size_t i = 0; i < processed_task->ids.size(); ++i) {
1116 auto id = processed_task->ids[i];
1117 auto embedding = &(processed_task->embeddings[i]);
1118 output(ctx, id, embedding);
1119 }
1120 if (progress_callback_) {
1121 progress.value.language_model_inferencer.n_processed_records =
1122 processed_task->ids.size();
1123 progress_callback_(ctx, &progress, progress_callback_user_data_);
1124 }
1125 }
1126 task_executor->wait_all();
1127 #else
1128 ERR(GRN_FUNCTION_NOT_IMPLEMENTED, "%s llama.cpp isn't enabled", tag);
1129 #endif
1130 }
1131
1132 private:
1133 #ifdef GRN_WITH_LLAMA_CPP
1134 std::shared_ptr<LanguageModel> model_;
1135 llama_model *llama_model_;
1136 enum llama_pooling_type default_pooling_type_;
1137 Vectorizer vectorizer_;
1138 #endif
1139 std::string input_column_value_prefix_;
1140 grn_progress_callback_func progress_callback_;
1141 void *progress_callback_user_data_;
1142 };
1143
1144 LanguageModelInferencer::LanguageModelInferencer(Impl *impl)
1145 : impl_(std::unique_ptr<Impl>(impl))
1146 {
1147 }
1148
1149 LanguageModelInferencer::~LanguageModelInferencer() = default;
1150
1151 void
1152 LanguageModelInferencer::set_input_column_value_prefix(std::string prefix)
1153 {
1154 impl_->set_input_column_value_prefix(std::move(prefix));
1155 }
1156
1157 void
1158 LanguageModelInferencer::set_progress_callback(
1159 grn_progress_callback_func callback, void *user_data)
1160 {
1161 impl_->set_progress_callback(callback, user_data);
1162 }
1163
1164 void
1165 LanguageModelInferencer::vectorize(grn_ctx *ctx,
1166 std::string_view text,
1167 grn_obj *output_vector)
1168 {
1169 return impl_->vectorize(ctx, text, output_vector);
1170 }
1171
1172 void
1173 LanguageModelInferencer::vectorize_in_batch(grn_ctx *ctx,
1174 grn_table_cursor *cursor,
1175 grn_obj *input_column,
1176 grn_obj *output)
1177 {
1178 if (grn_obj_is_column(ctx, output)) {
1179 return impl_->vectorize_in_batch(
1180 ctx,
1181 cursor,
1182 input_column,
1183 [&](grn_ctx *ctx, grn_id id, grn_obj *embedding) {
1184 grn_obj_set_value(ctx, output, id, embedding, GRN_OBJ_SET);
1185 });
1186 } else {
1187 return impl_->vectorize_in_batch(
1188 ctx,
1189 cursor,
1190 input_column,
1191 [&](grn_ctx *ctx, grn_id id, grn_obj *embedding) {
1192 grn_bulk_write(ctx,
1193 output,
1194 GRN_BULK_HEAD(embedding),
1195 GRN_BULK_VSIZE(embedding));
1196 });
1197 }
1198 }
1199
1200 std::unique_ptr<LanguageModelInferencer>
1201 LanguageModel::make_inferencer(grn_ctx *ctx)
1202 {
1203 #ifdef GRN_WITH_LLAMA_CPP
1204 return std::make_unique<LanguageModelInferencer>(
1205 new LanguageModelInferencer::Impl(shared_from_this(),
1206 impl_->get_raw(),
1207 impl_->default_pooling_type()));
1208 #else
1209 ERR(GRN_FUNCTION_NOT_IMPLEMENTED,
1210 "[language-model][make-inferencer] llama.cpp isn't enabled");
1211 return nullptr;
1212 #endif
1213 }
1214
1215 uint32_t
1216 LanguageModel::get_n_embedding_dimensions(grn_ctx *ctx)
1217 {
1218 #ifdef GRN_WITH_LLAMA_CPP
1219 return llama_model_n_embd(impl_->get_raw());
1220 #else
1221 ERR(GRN_FUNCTION_NOT_IMPLEMENTED,
1222 "[language-model][get-n-embedding-dimensions] llama.cpp isn't enabled");
1223 return 0;
1224 #endif
1225 }
1226
1227 class LanguageModelDownloader {
1228 public:
1229 LanguageModelDownloader(grn_ctx *ctx,
1230 std::string_view hf_repo,
1231 std::string_view tag)
1232 : ctx_(ctx),
1233 hf_repo_(hf_repo),
1234 tag_(tag),
1235 client_(grn_http_client_open(ctx_)),
1236 db_path_(grn_obj_path(ctx, grn_ctx_db(ctx_))),
1237 manifest_path_(build_manifest_path()),
1238 endpoint_url_("https://huggingface.co/"),
1239 model_path_()
1240 {
1241 // We need to use "llama-cpp" as User-Agent to get "ggufFile"
1242 // information by manifest API.
1243 grn_http_client_set_user_agent(ctx_, client_, "llama-cpp");
1244 // We may need to set "Accept:" explicitly in the future.
1245 // grn_http_client_add_header(ctx_, client_, "Accept: application/json");
1246 }
1247
1248 ~LanguageModelDownloader() { grn_http_client_close(ctx_, client_); }
1249
1250 bool
1251 download()
1252 {
1253 auto ctx = ctx_;
1254 #ifdef GRN_WITH_SIMDJSON
1255 if (!ensure_manifest()) {
1256 return false;
1257 }
1258
1259 auto manifest_result = simdjson::padded_string::load(manifest_path_);
1260 if (manifest_result.error() != simdjson::SUCCESS) {
1261 // TODO: Convert simdjson::error_code to grn_rc
1262 ERR(GRN_UNKNOWN_ERROR,
1263 "%s can't read manifest: <%s>: <%s>: <%s>",
1264 TAG,
1265 hf_repo_.data(),
1266 tag_.data(),
1267 simdjson::error_message(manifest_result.error()));
1268 return false;
1269 }
1270 auto manifest = std::move(manifest_result.value());
1271 simdjson::ondemand::parser parser;
1272 auto doc = parser.iterate(manifest);
1273 auto model_file_name_result = doc["ggufFile"]["rfilename"].get_string();
1274 if (model_file_name_result.error() != simdjson::SUCCESS) {
1275 // TODO: add support multi modal projects ("mmprojFile.rfilename")
1276 ERR(GRN_INVALID_ARGUMENT,
1277 "%s GGUF file can't be detected: <%s>: <%s>: <%.*s>",
1278 TAG,
1279 hf_repo_.data(),
1280 tag_.data(),
1281 static_cast<int>(manifest.size()),
1282 manifest.data());
1283 return false;
1284 }
1285 auto model_file_name = model_file_name_result.value();
1286
1287 return ensure_model(model_file_name);
1288 #else
1289 ERR(GRN_FUNCTION_NOT_IMPLEMENTED, "%s simdjson isn't enabled", TAG);
1290 return false;
1291 #endif
1292 }
1293
1294 const std::string &
1295 model_path()
1296 {
1297 return model_path_;
1298 }
1299
1300 private:
1301 static constexpr const char *TAG = "[language-model-downloader]";
1302
1303 grn_ctx *ctx_;
1304 std::string_view hf_repo_;
1305 std::string_view tag_;
1306 grn_http_client *client_;
1307 std::string db_path_;
1308 std::string manifest_path_;
1309 std::string endpoint_url_;
1310 std::string model_path_;
1311
1312 bool
1313 enable_cache()
1314 {
1315 return language_model::language_model_download_cache_dir[0] != '\0';
1316 }
1317
1318 std::string
1319 build_base_path()
1320 {
1321 std::string safe_hf_repo = std::string(hf_repo_);
1322 std::replace(safe_hf_repo.begin(), safe_hf_repo.end(), '/', '_');
1323 return std::string("lm.") + safe_hf_repo + "_" + std::string(tag_);
1324 }
1325
1326 std::string
1327 build_cache_path_prefix()
1328 {
1329 std::string cache_dir(language_model::language_model_download_cache_dir);
1330 if (cache_dir.back() == '/') {
1331 cache_dir.pop_back();
1332 }
1333 return cache_dir + "/" + build_base_path();
1334 }
1335
1336 std::string
1337 build_path_prefix()
1338 {
1339 return db_path_ + "." + build_base_path();
1340 }
1341
1342 std::string
1343 build_cache_manifest_path()
1344 {
1345 return build_cache_path_prefix() + ".manifest";
1346 }
1347
1348 std::string
1349 build_manifest_path()
1350 {
1351 return build_path_prefix() + ".manifest";
1352 }
1353
1354 std::string
1355 build_model_base_path(std::string_view model_file_name)
1356 {
1357 std::string safe_model_file_name = std::string(model_file_name);
1358 std::replace(safe_model_file_name.begin(),
1359 safe_model_file_name.end(),
1360 '/',
1361 '_');
1362 return std::string("model.") + safe_model_file_name;
1363 }
1364
1365 std::string
1366 build_cache_model_path(std::string_view model_file_name)
1367 {
1368 return build_cache_path_prefix() + "." +
1369 build_model_base_path(model_file_name);
1370 }
1371
1372 std::string
1373 build_model_path(std::string_view model_file_name)
1374 {
1375 return build_path_prefix() + "." + build_model_base_path(model_file_name);
1376 }
1377
1378 std::string
1379 build_manifest_url()
1380 {
1381 return endpoint_url_ + "v2/" + std::string(hf_repo_) + "/manifests/" +
1382 std::string(tag_);
1383 }
1384
1385 std::string
1386 build_model_url(std::string_view model_file_name)
1387 {
1388 return endpoint_url_ + std::string(hf_repo_) + "/resolve/main/" +
1389 std::string(model_file_name);
1390 }
1391
1392 bool
1393 ensure_manifest()
1394 {
1395 if (grn_path_exist(manifest_path_.data())) {
1396 return true;
1397 }
1398
1399 std::string cache_manifest_path;
1400 if (enable_cache()) {
1401 cache_manifest_path = build_cache_manifest_path();
1402 if (grn_path_exist(cache_manifest_path.data()) &&
1403 grn_path_copy(ctx_,
1404 cache_manifest_path.data(),
1405 manifest_path_.data()) == GRN_SUCCESS) {
1406 return true;
1407 }
1408 }
1409
1410 auto url = build_manifest_url();
1411 grn_http_client_set_url(ctx_, client_, url.data());
1412 if (grn_http_client_download(ctx_, client_) != GRN_SUCCESS) {
1413 return false;
1414 }
1415 auto manifest = grn_http_client_get_output(ctx_, client_);
1416 auto tmp_manifest_path = manifest_path_ + ".tmp";
1417 {
1418 std::ofstream tmp_manifest;
1419 tmp_manifest.open(tmp_manifest_path,
1420 std::ios_base::binary | std::ios_base::trunc);
1421 if (!tmp_manifest) {
1422 auto ctx = ctx_;
1423 ERR(GRN_INVALID_ARGUMENT,
1424 "%s failed to save manifest: <%s>: <%s>: <%s>",
1425 TAG,
1426 url.data(),
1427 tmp_manifest_path.data(),
1428 std::strerror(errno));
1429 return false;
1430 }
1431 tmp_manifest.write(GRN_TEXT_VALUE(manifest), GRN_TEXT_LEN(manifest));
1432 }
1433 if (rename(tmp_manifest_path.data(), manifest_path_.data()) != 0) {
1434 auto ctx = ctx_;
1435 SERR("%s failed to rename downloaded manifest: <%s>: <%s> -> <%s>",
1436 TAG,
1437 url.data(),
1438 tmp_manifest_path.data(),
1439 manifest_path_.data());
1440 if (grn_path_exist(tmp_manifest_path.data())) {
1441 grn_unlink(tmp_manifest_path.data());
1442 }
1443 if (grn_path_exist(manifest_path_.data())) {
1444 grn_unlink(manifest_path_.data());
1445 }
1446 return false;
1447 }
1448
1449 if (enable_cache()) {
1450 grn_path_copy(ctx_, manifest_path_.data(), cache_manifest_path.data());
1451 }
1452
1453 return true;
1454 }
1455
1456 bool
1457 ensure_model(std::string_view model_file_name)
1458 {
1459 model_path_ = build_model_path(model_file_name);
1460 if (grn_path_exist(model_path_.data())) {
1461 return true;
1462 }
1463
1464 std::string cache_model_path;
1465 if (enable_cache()) {
1466 cache_model_path = build_cache_model_path(model_file_name);
1467 if (grn_path_exist(cache_model_path.data()) &&
1468 grn_path_copy(ctx_, cache_model_path.data(), model_path_.data()) ==
1469 GRN_SUCCESS) {
1470 return true;
1471 }
1472 }
1473
1474 auto url = build_model_url(model_file_name);
1475 grn_http_client_set_url(ctx_, client_, url.data());
1476 auto tmp_model_path = model_path_ + ".tmp";
1477 grn_http_client_set_output_path(ctx_, client_, tmp_model_path.data());
1478 if (grn_http_client_download(ctx_, client_) != GRN_SUCCESS) {
1479 grn_io_remove_if_exist(ctx_, tmp_model_path.data());
1480 return false;
1481 }
1482 if (rename(tmp_model_path.data(), model_path_.data()) != 0) {
1483 auto ctx = ctx_;
1484 SERR("%s failed to rename downloaded manifest: <%s>: <%s> -> <%s>",
1485 TAG,
1486 url.data(),
1487 tmp_model_path.data(),
1488 manifest_path_.data());
1489 grn_io_remove_if_exist(ctx_, tmp_model_path.data());
1490 grn_io_remove_if_exist(ctx_, model_path_.data());
1491 return false;
1492 }
1493
1494 if (enable_cache()) {
1495 grn_path_copy(ctx_, model_path_.data(), cache_model_path.data());
1496 }
1497
1498 return true;
1499 }
1500 };
1501 }; // namespace grn
1502
1503 extern "C" {
1504 struct grn_language_model_ {
1505 std::shared_ptr<grn::LanguageModel> model;
1506
1507 grn_language_model_() : model(nullptr) {}
1508 ~grn_language_model_() = default;
1509 };
1510
1511 struct grn_language_model_inferencer_ {
1512 std::shared_ptr<grn::LanguageModelInferencer> inferencer;
1513
1514 grn_language_model_inferencer_() : inferencer(nullptr) {}
1515 ~grn_language_model_inferencer_() = default;
1516 };
1517 struct grn_language_model_loader_ {
1518 grn::LanguageModelLoader loader;
1519
1520 grn_language_model_loader_(grn_ctx *ctx) : loader(ctx) {}
1521 ~grn_language_model_loader_() = default;
1522 };
1523
1524 grn_language_model_loader *
1525 grn_language_model_loader_open(grn_ctx *ctx)
1526 {
1527 grn::language_model::ensure_init_external_libraries();
1528 auto loader = new grn_language_model_loader_(ctx);
1529 return loader;
1530 }
1531
1532 grn_rc
1533 grn_language_model_loader_close(grn_ctx *ctx, grn_language_model_loader *loader)
1534 {
1535 delete loader;
1536 return GRN_SUCCESS;
1537 }
1538
1539 grn_rc
1540 grn_language_model_loader_set_model(grn_ctx *ctx,
1541 grn_language_model_loader *loader,
1542 const char *model,
1543 int64_t model_length)
1544 {
1545 GRN_API_ENTER;
1546 if (!loader) {
1547 ERR(GRN_INVALID_ARGUMENT,
1548 "[language-model-loader][set-model] loader must not be NULL");
1549 GRN_API_RETURN(ctx->rc);
1550 }
1551 #ifdef GRN_WITH_LLAMA_CPP
1552 if (model_length < 0) {
1553 loader->loader.model_path = std::string(model, strlen(model));
1554 } else {
1555 loader->loader.model_path = std::string(model, model_length);
1556 }
1557 if (!loader->loader.model_path.empty()) {
1558 const std::string_view hf_url_prefix(
1559 "hf:///"); // TODO: Add support for custom endpoint
1560 // TODO: We can use starts_with() with C++20.
1561 if (loader->loader.model_path.substr(0, hf_url_prefix.size()) ==
1562 hf_url_prefix) {
1563 auto hf_repo = loader->loader.model_path.substr(hf_url_prefix.size());
1564 auto tag_separator_position = hf_repo.find("#");
1565 std::string_view tag("latest");
1566 if (tag_separator_position != std::string_view::npos) {
1567 auto specified_tag = hf_repo.substr(tag_separator_position + 1);
1568 if (!specified_tag.empty()) {
1569 tag = specified_tag;
1570 }
1571 }
1572 grn::LanguageModelDownloader downloader(ctx, hf_repo, tag);
1573 if (!downloader.download()) {
1574 GRN_API_RETURN(ctx->rc);
1575 }
1576 loader->loader.model_path = downloader.model_path();
1577 } else {
1578 if (loader->loader.model_path[0] != '/') {
1579 std::string model_path =
1580 grn::language_model::system_language_models_dir();
1581 model_path += "/" + loader->loader.model_path + ".gguf";
1582 loader->loader.model_path = std::move(model_path);
1583 }
1584 }
1585 }
1586 #else
1587 ERR(GRN_FUNCTION_NOT_IMPLEMENTED,
1588 "[language-model-loader][set-model] llama.cpp isn't enabled");
1589 #endif
1590 GRN_API_RETURN(ctx->rc);
1591 }
1592
1593 grn_rc
1594 grn_language_model_loader_set_n_gpu_layers(grn_ctx *ctx,
1595 grn_language_model_loader *loader,
1596 int32_t n_gpu_layers)
1597 {
1598 const char *tag = "[language-model-loader][set-n-gpu-layers]";
1599 GRN_API_ENTER;
1600 if (!loader) {
1601 ERR(GRN_INVALID_ARGUMENT, "%s loader must not be NULL", tag);
1602 GRN_API_RETURN(ctx->rc);
1603 }
1604 #ifdef GRN_WITH_LLAMA_CPP
1605 loader->loader.n_gpu_layers = n_gpu_layers;
1606 #else
1607 ERR(GRN_FUNCTION_NOT_IMPLEMENTED, "%s llama.cpp isn't enabled", tag);
1608 #endif
1609 GRN_API_RETURN(ctx->rc);
1610 }
1611
1612 grn_language_model *
1613 grn_language_model_loader_load(grn_ctx *ctx, grn_language_model_loader *loader)
1614 {
1615 GRN_API_ENTER;
1616 if (!loader) {
1617 ERR(GRN_INVALID_ARGUMENT,
1618 "[language-model-loader][loader] loader must not be NULL");
1619 GRN_API_RETURN(NULL);
1620 }
1621 auto model = new grn_language_model();
1622 model->model = loader->loader.load();
1623 if (!model->model) {
1624 delete model;
1625 GRN_API_RETURN(NULL);
1626 }
1627 GRN_API_RETURN(model);
1628 }
1629
1630 uint32_t
1631 grn_language_model_get_n_embedding_dimensions(grn_ctx *ctx,
1632 grn_language_model *model)
1633 {
1634 GRN_API_ENTER;
1635 uint32_t n_dimensions = model->model->get_n_embedding_dimensions(ctx);
1636 GRN_API_RETURN(n_dimensions);
1637 }
1638
1639 grn_rc
1640 grn_language_model_close(grn_ctx *ctx, grn_language_model *model)
1641 {
1642 delete model;
1643 return GRN_SUCCESS;
1644 }
1645
1646 grn_language_model_inferencer *
1647 grn_language_model_open_inferencer(grn_ctx *ctx, grn_language_model *model)
1648 {
1649 grn::language_model::ensure_init_external_libraries();
1650
1651 GRN_API_ENTER;
1652 if (!model) {
1653 ERR(GRN_INVALID_ARGUMENT,
1654 "[language-model][open-inferencer] model must not be NULL");
1655 GRN_API_RETURN(NULL);
1656 }
1657 auto inferencer = new grn_language_model_inferencer_();
1658 inferencer->inferencer = model->model->make_inferencer(ctx);
1659 if (!inferencer->inferencer) {
1660 delete inferencer;
1661 GRN_API_RETURN(NULL);
1662 }
1663 GRN_API_RETURN(inferencer);
1664 }
1665
1666 grn_rc
1667 grn_language_model_inferencer_close(grn_ctx *ctx,
1668 grn_language_model_inferencer *inferencer)
1669 {
1670 delete inferencer;
1671 return GRN_SUCCESS;
1672 }
1673
1674 grn_rc
1675 grn_language_model_inferencer_set_input_column_value_prefix(
1676 grn_ctx *ctx,
1677 grn_language_model_inferencer *inferencer,
1678 const char *prefix,
1679 int64_t prefix_length)
1680 {
1681 GRN_API_ENTER;
1682 if (!inferencer) {
1683 ERR(GRN_INVALID_ARGUMENT,
1684 "[language-model-inferencer][input-column-value-prefix][set] "
1685 "inferencer must not be NULL");
1686 GRN_API_RETURN(ctx->rc);
1687 }
1688 if (prefix_length < 0) {
1689 inferencer->inferencer->set_input_column_value_prefix(prefix);
1690 } else {
1691 inferencer->inferencer->set_input_column_value_prefix(
1692 std::string(prefix, prefix_length));
1693 }
1694 GRN_API_RETURN(ctx->rc);
1695 }
1696
1697 grn_rc
1698 grn_language_model_inferencer_set_progress_callback(
1699 grn_ctx *ctx,
1700 grn_language_model_inferencer *inferencer,
1701 grn_progress_callback_func callback,
1702 void *user_data)
1703 {
1704 GRN_API_ENTER;
1705 if (!inferencer) {
1706 ERR(GRN_INVALID_ARGUMENT,
1707 "[language-model-inferencer][progress-callback][set] "
1708 "inferencer must not be NULL");
1709 GRN_API_RETURN(ctx->rc);
1710 }
1711 inferencer->inferencer->set_progress_callback(callback, user_data);
1712 GRN_API_RETURN(ctx->rc);
1713 }
1714
1715 grn_rc
1716 grn_language_model_inferencer_vectorize(
1717 grn_ctx *ctx,
1718 grn_language_model_inferencer *inferencer,
1719 const char *text,
1720 int64_t text_length,
1721 grn_obj *output_vector)
1722 {
1723 GRN_API_ENTER;
1724 if (!inferencer) {
1725 ERR(GRN_INVALID_ARGUMENT,
1726 "[language-model-inferencer][vectorize] inferencer must not be NULL");
1727 GRN_API_RETURN(ctx->rc);
1728 }
1729 if (!output_vector) {
1730 ERR(
1731 GRN_INVALID_ARGUMENT,
1732 "[language-model-inferencer][vectorize] output vector must not be NULL");
1733 GRN_API_RETURN(ctx->rc);
1734 }
1735 if (text_length < 0) {
1736 text_length = static_cast<int64_t>(strlen(text));
1737 }
1738 if (text_length > 0) {
1739 inferencer->inferencer->vectorize(ctx,
1740 std::string_view(text, text_length),
1741 output_vector);
1742 }
1743 GRN_API_RETURN(ctx->rc);
1744 }
1745
1746 grn_rc
1747 grn_language_model_inferencer_vectorize_applier(
1748 grn_ctx *ctx,
1749 grn_language_model_inferencer *inferencer,
1750 grn_obj *input_column,
1751 grn_applier_data *data)
1752 {
1753 GRN_API_ENTER;
1754 if (!inferencer) {
1755 ERR(GRN_INVALID_ARGUMENT,
1756 "[language-model-inferencer][vectorize-applier] "
1757 "inferencer must not be NULL");
1758 GRN_API_RETURN(ctx->rc);
1759 }
1760 grn_obj *table = grn_applier_data_get_table(ctx, data);
1761 grn_obj *output_column = grn_applier_data_get_output_column(ctx, data);
1762 if (!(grn_obj_is_vector_column(ctx, output_column) &&
1763 DB_OBJ(output_column)->range == GRN_DB_FLOAT32)) {
1764 grn_obj inspected;
1765 GRN_TEXT_INIT(&inspected, 0);
1766 grn_inspect(ctx, &inspected, output_column);
1767 ERR(GRN_INVALID_ARGUMENT,
1768 "[language-model-inferencer][vectorize-applier] "
1769 "output column must be a Float32 vector column: %.*s",
1770 static_cast<int>(GRN_TEXT_LEN(&inspected)),
1771 GRN_TEXT_VALUE(&inspected));
1772 GRN_API_RETURN(ctx->rc);
1773 }
1774 auto cursor =
1775 grn_table_cursor_open(ctx, table, nullptr, 0, nullptr, 0, 0, -1, 0);
1776 if (cursor) {
1777 grn_language_model_inferencer_vectorize_in_batch(ctx,
1778 inferencer,
1779 cursor,
1780 input_column,
1781 output_column);
1782 grn_table_cursor_close(ctx, cursor);
1783 }
1784 GRN_API_RETURN(ctx->rc);
1785 }
1786
1787 grn_rc
1788 grn_language_model_inferencer_vectorize_in_batch(
1789 grn_ctx *ctx,
1790 grn_language_model_inferencer *inferencer,
1791 grn_table_cursor *cursor,
1792 grn_obj *input_column,
1793 grn_obj *output)
1794 {
1795 GRN_API_ENTER;
1796 if (!inferencer) {
1797 ERR(GRN_INVALID_ARGUMENT,
1798 "[language-model-inferencer][vectorize-in-batch] "
1799 "inferencer must not be NULL");
1800 GRN_API_RETURN(ctx->rc);
1801 }
1802 inferencer->inferencer->vectorize_in_batch(ctx, cursor, input_column, output);
1803 GRN_API_RETURN(ctx->rc);
1804 }
1805 }