From 3492f848d73ddb3211d34572d3b1d3a04ffd0d3f Mon Sep 17 00:00:00 2001 From: klosax <131523366+klosax@users.noreply.github.com> Date: Fri, 28 Jul 2023 22:45:24 +0200 Subject: [PATCH] gguf : add gguf_find_key (#2438) * gguf.cpp : find key example * ggml.h : add gguf_find_key * ggml.c : add gguf_find_key --- examples/gguf/gguf.cpp | 14 ++++++++++++++ ggml.c | 15 +++++++++++++++ ggml.h | 1 + 3 files changed, 30 insertions(+) diff --git a/examples/gguf/gguf.cpp b/examples/gguf/gguf.cpp index c3494a343..35a870a83 100644 --- a/examples/gguf/gguf.cpp +++ b/examples/gguf/gguf.cpp @@ -253,6 +253,20 @@ bool gguf_ex_read_0(const std::string & fname) { } } + // find kv string + { + char findkey[32]; + sprintf(findkey, "some.parameter.string"); + + int keyidx = gguf_find_key(ctx, findkey); + if (keyidx == -1) { + fprintf(stdout, "%s: find key: %s not found.\n", __func__, findkey); + } else { + const char * key_value = gguf_get_val_str(ctx, keyidx); + fprintf(stdout, "%s: find key: %s found, kv[%d] value = %s\n", __func__, findkey, keyidx, key_value); + } + } + // tensor info { const int n_tensors = gguf_get_n_tensors(ctx); diff --git a/ggml.c b/ggml.c index 96c7ebd34..d402daa67 100644 --- a/ggml.c +++ b/ggml.c @@ -18745,6 +18745,21 @@ int gguf_get_n_kv(struct gguf_context * ctx) { return ctx->header.n_kv; } +int gguf_find_key(struct gguf_context * ctx, const char * key) { + // return -1 if key not found + const int n_kv = gguf_get_n_kv(ctx); + int keyfound = -1; + + for (int i = 0; i < n_kv; ++i) { + if (strcmp(key, gguf_get_key(ctx, i)) == 0) { + keyfound = i; + break; + } + } + + return keyfound; +} + const char * gguf_get_key(struct gguf_context * ctx, int i) { return ctx->header.kv[i].key.data; } diff --git a/ggml.h b/ggml.h index e857b3f14..a72c82a33 100644 --- a/ggml.h +++ b/ggml.h @@ -1653,6 +1653,7 @@ extern "C" { GGML_API void * gguf_get_data (struct gguf_context * ctx); GGML_API int gguf_get_n_kv(struct gguf_context * ctx); + GGML_API int gguf_find_key(struct gguf_context * ctx, const char * key); GGML_API const char * gguf_get_key (struct gguf_context * ctx, int i); GGML_API void gguf_get_val (struct gguf_context * ctx, int i, void * val);