To enable INT8 precision, set int8_mode=True. Because INT8 can significantly impact accuracy, calibration is required.
Calibration Methods
Input Data Calibration: By default, torch2trt uses the inputs provided to the function for calibration. Use this for small datasets that fit in memory.
Dataset Calibration: For larger datasets, use the int8_calib_dataset parameter. You must provide a class that implements __len__ (returning the number of samples) and __getitem__ (returning a list of input tensors matching the model's input shapes).
Calibration Configuration
- Algorithm: Override the default algorithm using
int8_calib_algorithm with a tensorrt.CalibrationAlgoType value. - Batch Size: Control the number of samples pulled during calibration using
int8_calib_batch_size.
# Method 1: Calibrate using provided input data
data = torch.randn(64, 3, 224, 224).cuda().eval()
model_trt = torch2trt(model, [data], int8_mode=True)
# Method 2: Calibrate using a custom dataset object
class ImageFolderCalibDataset():
def __init__(self, root):
self.dataset = ImageFolder(root=root, transform=Compose([...]))
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
image, _ = self.dataset[idx]
image = image[None, ...]
return [image]
dataset = ImageFolderCalibDataset('images')
model_trt = torch2trt(model, [data], int8_calib_dataset=dataset)
# Method 3: Custom algorithm and batch size
import tensorrt as trt
model_trt = torch2trt(model, [data], int8_mode=True, int8_calib_algorithm=trt.CalibrationAlgoType.MINMAX_CALIBRATION, int8_calib_batch_size=32)