Entropic 2.9.4
Local-first agentic inference engine
Loading...
Searching...
No Matches
llama_cpp_tokenizer.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
17#include "llama_cpp_tokenizer.h"
19
20#include <llama.h>
21
22#include <vector>
23
24static auto logger = entropic::log::get("inference.tokenizer");
25
26namespace entropic {
27
37LlamaCppTokenizer::LlamaCppTokenizer(const llama_vocab* vocab)
38 : vocab_(vocab) {}
39
49std::vector<int32_t> LlamaCppTokenizer::tokenize(
50 const std::string& text, bool add_special) const
51{
52 if (vocab_ == nullptr) { return {}; }
53
54 // First call: get required size (negative return = required size).
55 int n = llama_tokenize(vocab_, text.c_str(),
56 static_cast<int32_t>(text.size()),
57 nullptr, 0, add_special, true);
58 if (n < 0) { n = -n; }
59
60 std::vector<int32_t> tokens(static_cast<size_t>(n));
61 int actual = llama_tokenize(vocab_, text.c_str(),
62 static_cast<int32_t>(text.size()),
63 tokens.data(), n, add_special, true);
64 if (actual < 0) {
65 logger->error("Tokenization failed for text of length {}",
66 text.size());
67 return {};
68 }
69 tokens.resize(static_cast<size_t>(actual));
70 return tokens;
71}
72
86std::string LlamaCppTokenizer::detokenize(int32_t token) const {
87 if (vocab_ == nullptr) { return {}; }
88
89 // special=false — special tokens don't render to surface text.
90 // History (gh#68, gh#65): defensive flag, kept regardless of
91 // whether the current model fleet emits special tokens.
92 char buf[256];
93 int n = llama_token_to_piece(
94 vocab_, token, buf, sizeof(buf), 0, false);
95 if (n >= 0) { return std::string(buf, static_cast<size_t>(n)); }
96
97 // Buffer too small — retry with exact size. n holds -required_size.
98 std::vector<char> large(static_cast<size_t>(-n));
99 n = llama_token_to_piece(vocab_, token, large.data(),
100 static_cast<int32_t>(large.size()),
101 0, false);
102 return n > 0
103 ? std::string(large.data(), static_cast<size_t>(n))
104 : std::string{};
105}
106
107} // namespace entropic
std::string detokenize(int32_t token) const override
Decode a single token id to its surface string.
std::vector< int32_t > tokenize(const std::string &text, bool add_special) const override
Encode text into token ids via the wrapped vocab.
LlamaCppTokenizer(const llama_vocab *vocab)
Construct with a borrowed vocab pointer.
Concrete llama.cpp tokenizer (v2.3.10 seam impl).
spdlog initialization and logger access.
ENTROPIC_EXPORT std::shared_ptr< spdlog::logger > get(const std::string &name)
Get or create a named logger.
Definition logging.cpp:211
Activate model on GPU (WARM → ACTIVE).
@ tokens
Gate on generated tokens since the last tool call.