Skip to content

Commit 3492f84

Browse files
authored
gguf : add gguf_find_key (#2438)
* gguf.cpp : find key example * ggml.h : add gguf_find_key * ggml.c : add gguf_find_key
1 parent 11ef380 commit 3492f84

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

examples/gguf/gguf.cpp

+14
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,20 @@ bool gguf_ex_read_0(const std::string & fname) {
253253
}
254254
}
255255

256+
// find kv string
257+
{
258+
char findkey[32];
259+
sprintf(findkey, "some.parameter.string");
260+
261+
int keyidx = gguf_find_key(ctx, findkey);
262+
if (keyidx == -1) {
263+
fprintf(stdout, "%s: find key: %s not found.\n", __func__, findkey);
264+
} else {
265+
const char * key_value = gguf_get_val_str(ctx, keyidx);
266+
fprintf(stdout, "%s: find key: %s found, kv[%d] value = %s\n", __func__, findkey, keyidx, key_value);
267+
}
268+
}
269+
256270
// tensor info
257271
{
258272
const int n_tensors = gguf_get_n_tensors(ctx);

ggml.c

+15
Original file line numberDiff line numberDiff line change
@@ -18745,6 +18745,21 @@ int gguf_get_n_kv(struct gguf_context * ctx) {
1874518745
return ctx->header.n_kv;
1874618746
}
1874718747

18748+
int gguf_find_key(struct gguf_context * ctx, const char * key) {
18749+
// return -1 if key not found
18750+
const int n_kv = gguf_get_n_kv(ctx);
18751+
int keyfound = -1;
18752+
18753+
for (int i = 0; i < n_kv; ++i) {
18754+
if (strcmp(key, gguf_get_key(ctx, i)) == 0) {
18755+
keyfound = i;
18756+
break;
18757+
}
18758+
}
18759+
18760+
return keyfound;
18761+
}
18762+
1874818763
const char * gguf_get_key(struct gguf_context * ctx, int i) {
1874918764
return ctx->header.kv[i].key.data;
1875018765
}

ggml.h

+1
Original file line numberDiff line numberDiff line change
@@ -1653,6 +1653,7 @@ extern "C" {
16531653
GGML_API void * gguf_get_data (struct gguf_context * ctx);
16541654

16551655
GGML_API int gguf_get_n_kv(struct gguf_context * ctx);
1656+
GGML_API int gguf_find_key(struct gguf_context * ctx, const char * key);
16561657
GGML_API const char * gguf_get_key (struct gguf_context * ctx, int i);
16571658
GGML_API void gguf_get_val (struct gguf_context * ctx, int i, void * val);
16581659

0 commit comments

Comments
 (0)