Overview
The TensorRT-LLM Python API provides a high-level interface for inference without managing servers. It’s ideal for:- Batch processing and offline inference
- Integration into Python applications
- Research and experimentation
- Custom inference pipelines
Quick Start
LLM Class
Constructor Arguments
str
required
HuggingFace model name, local path, or TensorRT engine directory
str
default:"pytorch"
Inference backend:
pytorch, tensorrt, or _autodeployint
default:"1"
Number of GPUs for tensor parallelism
int
default:"1"
Number of GPUs for pipeline parallelism
int
default:"256"
Maximum number of requests in a batch
int
default:"8192"
Maximum tokens across all sequences in a batch
int
Maximum sequence length (prompt + generation). Auto-detected if not specified.
KvCacheConfig
KV cache configuration (see KV Cache Configuration)
bool
default:"false"
Allow execution of custom model code from HuggingFace
Generation Methods
generate() - Synchronous
generate_async() - Asynchronous
SamplingParams
Control generation behavior withSamplingParams:
Advanced Configuration
KV Cache Configuration
Multi-GPU Inference
MoE Models
Speculative Decoding
Streaming Responses
Performance Monitoring
Runtime Statistics
Async Statistics
LoRA Adapters
Quantization
Use pre-quantized models from NVIDIA Model Optimizer:Complete Example: Chat Application
Context Manager Usage
Best Practices
1
Reuse LLM instances
Creating an
LLM instance is expensive (loads model weights). Reuse the same instance for multiple requests.2
Use async for high throughput
generate_async() allows batching and better GPU utilization for concurrent requests.3
Tune KV cache settings
Adjust
free_gpu_memory_fraction based on your workload. Higher values allow more concurrent requests.4
Enable KV cache reuse
Set
enable_block_reuse=True for workloads with common prompt prefixes (e.g., system prompts).5
Monitor GPU memory
Use
get_stats() to track KV cache utilization and avoid OOM errors.Next Steps
trtllm-serve
Deploy with OpenAI-compatible REST API
Distributed Inference
Scale to multi-GPU and multi-node
API Reference
Complete API documentation
Examples
More code examples on GitHub