Skip to content

Commit 5d77b73

Browse files
committed
examples : Add tokenize
1 parent d96ca7d commit 5d77b73

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

examples/CMakeLists.txt

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ else()
2424
add_subdirectory(llama-bench)
2525
add_subdirectory(llava)
2626
add_subdirectory(main)
27+
add_subdirectory(tokenize)
2728
add_subdirectory(parallel)
2829
add_subdirectory(perplexity)
2930
add_subdirectory(quantize)

examples/tokenize/CMakeLists.txt

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
set(TARGET tokenize)
2+
add_executable(${TARGET} tokenize.cpp)
3+
install(TARGETS ${TARGET} RUNTIME)
4+
target_link_libraries(${TARGET} PRIVATE common llama ${CMAKE_THREAD_LIBS_INIT})
5+
target_compile_features(${TARGET} PRIVATE cxx_std_11)

examples/tokenize/tokenize.cpp

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include "common.h"
2+
#include "llama.h"
3+
4+
#include <cmath>
5+
#include <cstdio>
6+
#include <string>
7+
#include <vector>
8+
9+
int main(int argc, char ** argv) {
10+
if (argc < 3 || argv[1][0] == '-') {
11+
printf("usage: %s MODEL_PATH PROMPT [--ids]\n" , argv[0]);
12+
return 1;
13+
}
14+
15+
auto model_path = argv[1];
16+
auto prompt = argv[2];
17+
18+
const bool printing_ids = argc > 3 && std::string(argv[3]) == "--ids";
19+
20+
llama_backend_init(false);
21+
22+
llama_model_params model_params = llama_model_default_params();
23+
model_params.vocab_only = true;
24+
llama_model * model = llama_load_model_from_file(model_path, model_params);
25+
26+
llama_context_params ctx_params = llama_context_default_params();
27+
llama_context * ctx = llama_new_context_with_model(model, ctx_params);
28+
29+
const bool add_bos = true;
30+
31+
std::vector<llama_token> tokens;
32+
33+
tokens = ::llama_tokenize(model, prompt, add_bos, true);
34+
35+
for (int i = 0; i < (int) tokens.size(); i++) {
36+
if (printing_ids) {
37+
printf("%d\n", tokens[i]);
38+
} else {
39+
printf("%6d -> '%s'\n", tokens[i], llama_token_to_piece(ctx, tokens[i]).c_str());
40+
}
41+
}
42+
43+
return 0;
44+
}

0 commit comments

Comments
 (0)