File size: 18,417 Bytes
c7567e8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 | # Local-Llama-Inference



**A Production-Ready Python SDK for GPU-Accelerated LLM Inference**
Local-Llama-Inference is a comprehensive Python SDK that integrates **llama.cpp** and **NVIDIA NCCL** to enable high-performance inference of GGUF-quantized Large Language Models (LLMs) on single and multiple NVIDIA GPUs.
---
## ๐ฏ Features
### ๐ Core Capabilities
- **Single GPU Inference** - Automatic memory optimization and layer offloading
- **Multi-GPU Support** - Tensor parallelism with automatic split suggestions
- **30+ REST API Endpoints** - Full llama.cpp endpoint coverage
- **OpenAI-Compatible API** - Drop-in compatible `/v1/chat/completions` endpoint
- **Streaming Responses** - Token-by-token streaming via Python generators
- **Production-Ready** - Error handling, process management, health checks
### ๐ API Support
```python
# Chat & Completions
client.chat() # Chat completion (non-streaming)
client.stream_chat() # Chat with token streaming
client.complete() # Text completion
client.stream_complete() # Streaming completion
# Embeddings & Reranking
client.embed() # Generate embeddings
client.rerank() # Cross-encoder reranking
# Token Utilities
client.tokenize() # Text to tokens
client.detokenize() # Tokens to text
client.apply_template() # Apply chat template
# Advanced Features
client.infill() # Code infilling
client.set_lora_adapters() # LoRA support
client.save_slot() # Slot management
client.restore_slot() # Restore saved state
# Server Management
client.health() # Health check
client.get_props() # Get server properties
client.get_metrics() # Performance metrics
```
### ๐ฎ GPU Utilities
```python
from local_llama_inference import detect_gpus, suggest_tensor_split, check_cuda_version
# Detect available GPUs
gpus = detect_gpus()
# Get automatic tensor split for multi-GPU
tensor_split = suggest_tensor_split(gpus)
# Check CUDA version
cuda_version = check_cuda_version()
```
### ๐ NCCL Collective Operations
```python
from local_llama_inference._bindings.nccl_binding import NCCLBinding
# Direct access to NCCL primitives
nccl = NCCLBinding('/path/to/libnccl.so.2')
nccl.all_reduce(sendbuff, recvbuff, ncclFloat32, ncclSum, comm)
nccl.broadcast(buffer, ncclFloat32, root, comm)
nccl.all_gather(sendbuff, recvbuff, ncclFloat32, comm)
```
---
## ๐ System Requirements
### Minimum
- **GPU**: NVIDIA compute capability 5.0+ (sm_50)
- Tesla K80, K40 | GeForce GTX 750 Ti
- **VRAM**: 2GB+ per GPU
- **Python**: 3.8+
- **OS**: Linux x86_64
- **RAM**: 8GB+ system memory
### Recommended
- **GPU**: RTX 2060 or newer (sm_75+)
- **VRAM**: 4GB+ per GPU
- **RAM**: 16GB+ system memory
- **CUDA**: Any version 11.5+ (runtime included)
### Supported GPUs
โ
Kepler (sm_50) - Tesla K80, K40, GTX 750 Ti
โ
Maxwell (sm_61) - GTX 750, GTX 950, GTX 1050
โ
Pascal (sm_61) - GTX 1060, GTX 1080
โ
Volta (sm_70) - Tesla V100
โ
Turing (sm_75) - RTX 2060, RTX 2080
โ
Ampere (sm_80) - RTX 3060, RTX 3090
โ
Ada (sm_86) - RTX 4080, RTX 6000
โ
Hopper (sm_89) - H100, H200
---
## โก Quick Start (5 Minutes)
### 1. Installation
#### Option A: From Release Package (Recommended)
```bash
# Download from GitHub Releases
# https://github.com/Local-Llama-Inference/Local-Llama-Inference/releases/tag/v0.1.0
tar -xzf local-llama-inference-complete-v0.1.0.tar.gz
cd local-llama-inference-v0.1.0
pip install -e ./python
```
#### Option B: From Source (Developer)
```bash
git clone https://github.com/Local-Llama-Inference/Local-Llama-Inference.git
cd Local-Llama-Inference/local-llama-inference
pip install -e .
```
### 2. Verify Installation
```bash
python -c "from local_llama_inference import LlamaServer, detect_gpus; print('โ
SDK Ready'); print(detect_gpus())"
```
### 3. Download a Model
```bash
# Download Mistral 7B Q4 (quantized, ~4GB)
wget https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.1-GGUF/resolve/main/Mistral-7B-Instruct-v0.1.Q4_K_M.gguf
# Or find more models at: https://huggingface.co/models?search=gguf
```
### 4. Run Your First Inference
```python
from local_llama_inference import LlamaServer, LlamaClient
# Start the server
server = LlamaServer(
model_path="./Mistral-7B-Instruct-v0.1.Q4_K_M.gguf",
n_gpu_layers=33, # Offload all layers to GPU
n_ctx=2048, # Context window
host="127.0.0.1",
port=8000
)
print("Starting server...")
server.start()
server.wait_ready(timeout=60)
print("โ
Server ready!")
# Create client and send request
client = LlamaClient(base_url="http://127.0.0.1:8000")
response = client.chat_completion(
messages=[
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "What is machine learning?"}
],
temperature=0.7,
max_tokens=256
)
print("Assistant:", response.choices[0].message.content)
# Cleanup
server.stop()
```
---
## ๐ Getting Started Tutorials
### Basic Chat Example
```python
from local_llama_inference import LlamaServer, LlamaClient
# Configure and start server
server = LlamaServer(
model_path="model.gguf",
n_gpu_layers=33, # Use GPU
main_gpu=0, # Primary GPU
n_ctx=2048, # Context size
n_batch=512, # Batch size
)
server.start()
server.wait_ready()
# Simple chat
client = LlamaClient()
response = client.chat_completion(
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
# Multi-turn conversation
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is Python?"},
]
response = client.chat_completion(messages=messages)
print("Assistant:", response.choices[0].message.content)
messages.append({"role": "assistant", "content": response.choices[0].message.content})
messages.append({"role": "user", "content": "How is it used in AI?"})
response = client.chat_completion(messages=messages)
print("Assistant:", response.choices[0].message.content)
server.stop()
```
### Streaming Responses
```python
from local_llama_inference import LlamaServer, LlamaClient
server = LlamaServer(model_path="model.gguf", n_gpu_layers=33)
server.start()
server.wait_ready()
client = LlamaClient()
# Stream tokens in real-time
for token in client.stream_chat(
messages=[{"role": "user", "content": "Write a poem about AI"}]
):
print(token.choices[0].delta.content, end="", flush=True)
print()
server.stop()
```
### Multi-GPU Inference
```python
from local_llama_inference import (
LlamaServer, LlamaClient, detect_gpus, suggest_tensor_split
)
# Detect GPUs
gpus = detect_gpus()
print(f"Found {len(gpus)} GPU(s)")
# Get suggested tensor split
tensor_split = suggest_tensor_split(gpus)
print(f"Suggested tensor split: {tensor_split}")
# Start with multi-GPU
server = LlamaServer(
model_path="model.gguf",
n_gpu_layers=33,
tensor_split=tensor_split, # Distribute layers across GPUs
)
server.start()
server.wait_ready()
# Use normally
client = LlamaClient()
response = client.chat_completion(
messages=[{"role": "user", "content": "Process this on multiple GPUs!"}]
)
print(response.choices[0].message.content)
server.stop()
```
### Embeddings
```python
from local_llama_inference import LlamaServer, LlamaClient
server = LlamaServer(model_path="embedding-model.gguf", n_gpu_layers=33)
server.start()
server.wait_ready()
client = LlamaClient()
# Single embedding
embedding = client.embed(input="What is machine learning?")
print(f"Embedding dimension: {len(embedding.data[0].embedding)}")
# Batch embeddings
embeddings = client.embed(
input=[
"Machine learning is a subset of AI",
"Deep learning uses neural networks",
"LLMs are large language models"
]
)
print(f"Generated {len(embeddings.data)} embeddings")
server.stop()
```
### Advanced: NCCL Operations
```python
from local_llama_inference._bindings.nccl_binding import NCCLBinding, NCCLDataType, NCCLRedOp
import numpy as np
# Load NCCL
nccl = NCCLBinding('/path/to/libnccl.so.2')
# AllReduce operation
sendbuff = np.array([1.0, 2.0, 3.0], dtype=np.float32)
recvbuff = np.zeros_like(sendbuff)
# This would require NCCL communicator setup
# nccl.all_reduce(sendbuff.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
# recvbuff.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
# len(sendbuff), NCCLDataType.FLOAT32, NCCLRedOp.SUM, comm)
```
---
## ๐ง Configuration
### Server Configuration
```python
from local_llama_inference import ServerConfig, SamplingConfig
# Create configuration
config = ServerConfig(
# Model
model_path="./model.gguf",
# Server
host="127.0.0.1",
port=8000,
api_key=None, # Optional API key
# GPU settings
n_gpu_layers=33, # Layers to offload to GPU
tensor_split=[0.5, 0.5], # Multi-GPU distribution
main_gpu=0, # Primary GPU
# Context
n_ctx=2048, # Context window size
n_batch=512, # Batch size
n_ubatch=512, # Micro-batch size
# Performance
flash_attn=True, # Use Flash Attention v2
numa=False, # NUMA optimization
# Advanced
use_mmap=True, # Memory mapped I/O
use_mlock=False, # Lock memory
embedding_only=False, # Embedding mode
)
# Generate CLI arguments
args = config.to_args()
# Create server
server = LlamaServer(config)
```
### Sampling Configuration
```python
from local_llama_inference import SamplingConfig
sampling_config = SamplingConfig(
temperature=0.7, # Higher = more random
top_k=40, # Nucleus sampling
top_p=0.9, # Cumulative probability
min_p=0.05, # Minimum probability
repeat_penalty=1.1, # Penalize repetition
mirostat=0, # Mirostat sampling (0=off)
seed=42, # Random seed
grammar=None, # Grammar constraints
json_schema=None, # JSON schema
)
# Use in request
response = client.chat_completion(
messages=[{"role": "user", "content": "Hello"}],
temperature=sampling_config.temperature,
top_k=sampling_config.top_k,
top_p=sampling_config.top_p,
)
```
---
## ๐ API Reference
### `LlamaServer` - Process Management
```python
server = LlamaServer(config, binary_path=None)
# Methods
server.start(wait_ready=False, timeout=60) # Start server
server.stop() # Stop server
server.restart() # Restart server
server.is_running() # Check status
server.wait_ready(timeout=60) # Wait for /health
```
### `LlamaClient` - HTTP REST Client
```python
client = LlamaClient(base_url="http://127.0.0.1:8000", api_key=None)
# Chat & Completions
client.chat_completion(messages, model=None, **kwargs)
client.stream_chat(messages, model=None, **kwargs)
client.complete(prompt, model=None, **kwargs)
client.stream_complete(prompt, model=None, **kwargs)
# Embeddings
client.embed(input, model=None)
client.rerank(model, query, documents)
# Tokens
client.tokenize(prompt, add_special=True)
client.detokenize(tokens)
client.apply_template(messages, add_generation_prompt=True)
# Server Info
client.health() # GET /health
client.get_props() # GET /props
client.set_props(props) # POST /props
client.get_metrics() # GET /metrics
client.get_models() # GET /models
client.get_slots() # GET /slots
```
### `detect_gpus()` - GPU Detection
```python
gpus = detect_gpus()
# Returns: List[GPUInfo]
# Each GPUInfo has: index, name, uuid, compute_capability, total_memory_mb, free_memory_mb
for gpu in gpus:
print(f"GPU {gpu.index}: {gpu.name}")
print(f" Compute Capability: {gpu.compute_capability}")
print(f" VRAM: {gpu.total_memory_mb} MB ({gpu.free_memory_mb} MB free)")
print(f" Supports Flash Attention: {gpu.supports_flash_attn()}")
```
### `suggest_tensor_split()` - Auto Multi-GPU
```python
tensor_split = suggest_tensor_split(gpus)
# Automatically calculates optimal layer distribution
# Returns: List[float] summing to 1.0
```
---
## ๐ ๏ธ Troubleshooting
### "CUDA out of memory"
```python
# Solution 1: Reduce GPU layers
server = LlamaServer(model_path="model.gguf", n_gpu_layers=15)
# Solution 2: Use smaller quantization
# Download Q2 or Q3 instead of Q5/Q6
# Solution 3: Reduce batch size
server = LlamaServer(model_path="model.gguf", n_batch=256)
```
### "GPU not found"
```bash
# Check NVIDIA driver
nvidia-smi
# Verify NVIDIA driver is installed
# https://www.nvidia.com/Download/driverDetails.aspx
# Check compute capability
python -c "from local_llama_inference import detect_gpus; print(detect_gpus())"
```
### "libcudart.so.12 not found"
```bash
# The complete package includes CUDA runtime
# Or install NVIDIA drivers:
sudo apt update
sudo apt install nvidia-driver-XXX # Replace XXX with version
sudo reboot
```
### "Server startup timeout"
```python
# Increase timeout
server.wait_ready(timeout=120) # Default is 60 seconds
# Or check server logs for errors
server.start(wait_ready=False)
time.sleep(5)
# Check console for error messages
```
### Slow Inference
```python
# Increase GPU offloading
n_gpu_layers=33 # Offload all layers
# Check GPU utilization
nvidia-smi -l 1 # Refresh every second
# Use larger models with better quantization (Q5, Q6 instead of Q2)
# Reduce context size if not needed
```
---
## ๐ Key Files & Directories
```
local-llama-inference/
โโโ src/local_llama_inference/ # Python SDK source
โ โโโ __init__.py # Public API
โ โโโ server.py # LlamaServer class
โ โโโ client.py # LlamaClient REST wrapper
โ โโโ config.py # Configuration classes
โ โโโ gpu.py # GPU utilities
โ โโโ exceptions.py # Custom exceptions
โ โโโ _bindings/
โ โ โโโ llama_binding.py # libllama.so ctypes wrapper
โ โ โโโ nccl_binding.py # libnccl.so.2 ctypes wrapper
โ โโโ _bootstrap/
โ โโโ finder.py # Binary locator
โ โโโ extractor.py # Bundle extractor
โโโ examples/ # Tutorial scripts
โ โโโ single_gpu_chat.py
โ โโโ multi_gpu_tensor_split.py
โ โโโ streaming_chat.py
โ โโโ embeddings_example.py
โ โโโ nccl_bindings_example.py
โโโ tests/ # Unit tests
โโโ pyproject.toml # Package metadata
โโโ README.md # This file
โโโ LICENSE # MIT License
โโโ releases/v0.1.0/ # Release artifacts
โโโ local-llama-inference-complete-v0.1.0.tar.gz
โโโ local-llama-inference-sdk-v0.1.0.tar.gz
โโโ CHECKSUMS.txt
```
---
## ๐ฆ Dependencies
### Required
- **httpx** >= 0.24.0 - Async HTTP client for REST API
- **pydantic** >= 2.0 - Data validation and settings management
### Optional (Development)
- **pytest** >= 7.0 - Unit testing
- **pytest-asyncio** >= 0.21.0 - Async test support
### System
- **NVIDIA CUDA** - Any version 11.5+ (runtime included in package)
- **NVIDIA Drivers** - Required, any recent version
---
## ๐ Performance Tips
1. **Use Flash Attention** - Set `flash_attn=True` for 2-3x speedup
2. **Increase Context** - Larger `n_ctx` = slower but better context
3. **Batch Size** - `n_batch=512` good for most cases
4. **GPU Layers** - Higher `n_gpu_layers` = faster but more VRAM
5. **Quantization** - Q4 = 4GB, Q5 = 5GB, Q6 = 6GB typical sizes
6. **Multi-GPU** - Use `tensor_split` to distribute across GPUs
7. **Keep Alive** - Reuse server instance instead of restart/start cycles
---
## ๐ Security
- **API Keys** - Optional API key support via `ServerConfig.api_key`
- **Local Only** - Bind to `127.0.0.1` for local development
- **Production** - Consider authentication/TLS for production deployments
- **Model Files** - Keep GGUF files private, don't share URLs publicly
---
## ๐ License
MIT License - See `LICENSE` file for details
---
## ๐ค Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit changes (`git commit -m 'Add amazing feature'`)
4. Push to branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
---
## ๐ Support & Resources
- **GitHub Issues**: [Report bugs or request features](https://github.com/Local-Llama-Inference/Local-Llama-Inference/issues)
- **GitHub Discussions**: [Ask questions and share ideas](https://github.com/Local-Llama-Inference/Local-Llama-Inference/discussions)
- **Releases**: [Download packages](https://github.com/Local-Llama-Inference/Local-Llama-Inference/releases)
### Related Projects
- **llama.cpp** - Core inference engine: https://github.com/ggml-org/llama.cpp
- **NCCL** - GPU collective communication: https://github.com/NVIDIA/nccl
- **Hugging Face GGUF Models** - https://huggingface.co/models?search=gguf
---
## ๐ Project Status
- **Version**: 0.1.0 (Beta)
- **Status**: Production Ready
- **Last Updated**: February 24, 2026
- **Python Support**: 3.8 - 3.12
- **GPU Support**: NVIDIA sm_50 and newer
---
## ๐ Learning Resources
### Official Documentation
- See `00-START-HERE.md` in release package
- See `RELEASE_NOTES_v0.1.0.md` for detailed feature list
- Check `examples/` directory for code samples
### External Resources
- **llama.cpp Documentation**: https://github.com/ggml-org/llama.cpp/tree/master/docs
- **GGUF Format**: https://github.com/ggml-org/gguf
- **NCCL Documentation**: https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/
---
**Built with โค๏ธ for the open-source ML community**
โญ If you find this project useful, please consider starring the repository!
|