Skip to content

Commit d8d898e

Browse files
committed
examples : Add tokenize
1 parent d96ca7d commit d8d898e

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-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

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#include "common.h"
2+
#include "llama.h"
3+
4+
#include <cmath>
5+
#include <cstdio>
6+
#include <string>
7+
#include <vector>
8+
9+
template <typename C, typename T>
10+
inline std::string LOG_TOKENS_TOSTR_LINES(const C & ctx, const T & tokens)
11+
{
12+
std::stringstream buf;
13+
14+
for (const auto &token : tokens)
15+
{
16+
auto detokenized = llama_token_to_piece(ctx, token);
17+
18+
detokenized.erase(
19+
std::remove_if(
20+
detokenized.begin(),
21+
detokenized.end(),
22+
[](const unsigned char c) { return !std::isprint(c); }),
23+
detokenized.end());
24+
25+
buf << std::to_string(token) << "=" << detokenized << std::endl;
26+
}
27+
28+
return buf.str();
29+
}
30+
31+
int main(int argc, char ** argv) {
32+
gpt_params params;
33+
34+
if (argc != 3 || argv[1][0] == '-') {
35+
printf("usage: %s MODEL_PATH PROMPT\n" , argv[0]);
36+
return 1;
37+
}
38+
39+
params.model = argv[1];
40+
41+
params.prompt = argv[2];
42+
43+
llama_backend_init(params.numa);
44+
45+
llama_model_params model_params = llama_model_default_params();
46+
model_params.vocab_only = true;
47+
llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);
48+
49+
llama_context_params ctx_params = llama_context_default_params();
50+
llama_context * ctx = llama_new_context_with_model(model, ctx_params);
51+
52+
const bool add_bos = true;
53+
54+
std::vector<llama_token> tokens;
55+
56+
tokens = ::llama_tokenize(model, params.prompt, add_bos, true);
57+
58+
std::cout << LOG_TOKENS_TOSTR_LINES(ctx, tokens).c_str();
59+
60+
return 0;
61+
}

0 commit comments

Comments
 (0)