1#include <pybind11/pybind11.h>
2#include <pybind11/stl.h>
3#include <pybind11/iostream.h>
14 TinyLlama.cpp Python Bindings
15 =============================
17 Python bindings for the tinyllama.cpp inference engine supporting both GGUF and SafeTensors formats.
20 - TinyLlamaSession: Main interface for model loading and text generation
21 - ModelConfig: Configuration object containing model parameters and metadata
27 session = tinyllama_cpp.TinyLlamaSession(
28 model_path="path/to/model.gguf",
29 tokenizer_path="path/to/tokenizer.json",
33 # GPU usage with quantized KV cache
34 session = tinyllama_cpp.TinyLlamaSession(
35 model_path="path/to/model.gguf",
36 tokenizer_path="path/to/tokenizer.json",
43 response = session.generate("What is AI?", steps=64, temperature=0.7)
47 prompts = ["What is AI?", "Explain quantum computing", "Tell me a joke"]
48 responses = session.generate_batch(prompts, steps=64)
49 for prompt, response in zip(prompts, responses):
50 print(f"Q: {prompt}\nA: {response}\n")
53 py::add_ostream_redirect(m, "ostream_redirect");
56 Model configuration containing architecture parameters and metadata.
58 This class holds all the configuration parameters for a loaded model,
59 including architecture details, tokenizer information, and model metadata.
60 Most fields are automatically populated when loading a model.
64 .def(py::init<>(), "Create an empty ModelConfig object")
87 std::string
tf_str =
"UNKNOWN";
90 return "<ModelConfig: vocab_size=" + std::to_string(
cfg.vocab_size) +
91 ", hidden_size=" + std::to_string(
cfg.hidden_size) +
92 ", tokenizer_family=" +
tf_str +
97 py::enum_<ModelConfig::TokenizerFamily>(
model_config_class,
"TokenizerFamily",
"Enumeration of supported tokenizer families")
103 py::class_<tinyllama::TinyLlamaSession>(
m,
"TinyLlamaSession", R
"pbdoc(
104 Main interface for TinyLlama model inference.
106 This class provides a high-level interface for loading models and generating text.
107 It supports both GGUF and SafeTensors formats, CPU and GPU inference, and various
108 sampling strategies for text generation.
110 The session manages the model, tokenizer, and KV cache, providing both single
111 prompt generation and efficient batch processing capabilities.
119 py::arg(
"model_path"),
120 py::arg(
"tokenizer_path"),
121 py::arg(
"threads") = 1,
122 py::arg(
"n_gpu_layers") = 0,
123 py::arg(
"use_mmap") =
true,
124 py::arg(
"use_kv_quant") =
false,
125 py::arg(
"use_batch_generation") =
false,
126 py::arg(
"max_batch_size") = 1,
128 Initialize a TinyLlama inference session.
131 model_path (str or Path): Path to model directory (SafeTensors) or .gguf file
132 tokenizer_path (str or Path): Path to tokenizer.json file. For GGUF models with
133 embedded tokenizer, this can be the same as model_path
134 threads (int, optional): Number of CPU threads for inference. Defaults to 1.
135 n_gpu_layers (int, optional): Number of layers to offload to GPU.
136 -1 = all layers, 0 = CPU only. Defaults to 0.
137 use_mmap (bool, optional): Use memory mapping for model loading. Defaults to True.
138 use_kv_quant (bool, optional): Use INT8 quantization for KV cache on GPU.
139 Reduces VRAM usage. Defaults to False.
140 use_batch_generation (bool, optional): Enable optimized batch generation mode.
142 max_batch_size (int, optional): Maximum number of sequences for batch processing.
146 RuntimeError: If model loading fails due to invalid paths, unsupported format,
147 or insufficient resources.
151 session = TinyLlamaSession("model.gguf", "tokenizer.json", threads=4)
153 # Using pathlib.Path objects
154 from pathlib import Path
155 session = TinyLlamaSession(
156 model_path=Path("model.gguf"),
157 tokenizer_path=Path("tokenizer.json"),
173 py::arg(
"steps") = 128,
174 py::arg(
"temperature") = 0.1f,
175 py::arg(
"top_k") = 40,
176 py::arg(
"top_p") = 0.9f,
177 py::arg(
"system_prompt") =
"",
178 py::arg(
"apply_q_a_format") =
true,
180 Generate text based on a prompt using various sampling strategies.
183 prompt (str): Input text prompt to generate from
184 steps (int, optional): Number of tokens to generate. Defaults to 128.
185 temperature (float, optional): Sampling temperature. Lower values (0.1)
186 produce more focused/deterministic output,
187 higher values (1.0+) more creative/random.
189 top_k (int, optional): Top-K sampling - limit to K most likely tokens.
190 Set to 0 to disable. Defaults to 40.
191 top_p (float, optional): Nucleus sampling - limit to tokens comprising
192 top P probability mass (0.0-1.0). Defaults to 0.9.
193 system_prompt (str, optional): System prompt to guide generation behavior.
194 Defaults to empty string.
195 apply_q_a_format (bool, optional): Apply Q:A formatting to prompt.
196 Recommended for most models. Defaults to True.
199 str: Generated text (excluding the original prompt)
202 RuntimeError: If generation fails due to tokenization errors or model issues.
206 response = session.generate("What is artificial intelligence?")
208 # Creative generation with higher temperature
209 story = session.generate(
216 # Focused generation with system prompt
217 answer = session.generate(
218 "Explain quantum computing",
221 system_prompt="You are a helpful physics teacher."
225 .def("generate_batch",
227 int top_k,
float top_p,
const std::string& system_prompt,
bool apply_q_a_format) {
228 std::vector<std::string>
out =
234 py::arg(
"steps") = 128,
235 py::arg(
"temperature") = 0.1f,
236 py::arg(
"top_k") = 40,
237 py::arg(
"top_p") = 0.9f,
238 py::arg(
"system_prompt") =
"",
239 py::arg(
"apply_q_a_format") =
true,
241 Generate text for multiple prompts in parallel (batch processing).
243 This method processes multiple independent prompts simultaneously, providing
244 significant efficiency gains over sequential generate() calls. Each prompt
245 maintains its own KV cache state and is processed independently.
248 prompts (List[str]): List of input prompts to process in batch
249 steps (int, optional): Number of tokens to generate per prompt. Defaults to 128.
250 temperature (float, optional): Sampling temperature applied to all prompts.
252 top_k (int, optional): Top-K sampling parameter for all prompts. Defaults to 40.
253 top_p (float, optional): Nucleus sampling parameter for all prompts. Defaults to 0.9.
254 system_prompt (str, optional): System prompt applied to all prompts.
255 Defaults to empty string.
256 apply_q_a_format (bool, optional): Apply Q:A formatting to all prompts.
260 List[str]: List of generated text strings, one for each input prompt
263 RuntimeError: If batch generation fails or prompts list is empty.
267 "What is machine learning?",
268 "Explain neural networks",
269 "How does backpropagation work?"
272 responses = session.generate_batch(
278 for prompt, response in zip(prompts, responses):
279 print(f"Q: {prompt}")
280 print(f"A: {response}\n")
284 py::return_value_policy::reference_internal,
286 Get the model configuration.
289 ModelConfig: Reference to the session's model configuration containing
290 architecture parameters, tokenizer info, and metadata.
293 config = session.get_config()
294 print(f"Model has {config.num_hidden_layers} layers")
295 print(f"Vocabulary size: {config.vocab_size}")
296 print(f"Hidden size: {config.hidden_size}")
PYBIND11_MODULE(tinyllama_bindings, m)
Represents an active TinyLlama session holding the loaded model and tokenizer.
const ModelConfig & get_config() const
Constants used throughout the TinyLlama model implementation.
std::string utf8_valid(const std::string &s)
Model configuration structure holding architecture and hyperparameters.
std::string chat_template_string
std::string pre_tokenizer_type
std::string chat_template_type
TokenizerFamily tokenizer_family
int max_position_embeddings