Generation with Quantization#

Source NVIDIA/TensorRT-LLM.

 1### Generation with Quantization
 2import logging
 3
 4import torch
 5
 6from tensorrt_llm import SamplingParams
 7from tensorrt_llm._tensorrt_engine import LLM
 8from tensorrt_llm.llmapi import CalibConfig, QuantAlgo, QuantConfig
 9
10major, minor = torch.cuda.get_device_capability()
11enable_fp8 = major > 8 or (major == 8 and minor >= 9)
12enable_nvfp4 = major >= 10
13
14quant_and_calib_configs = []
15
16if not enable_nvfp4:
17    # Example 1: Specify int4 AWQ quantization to QuantConfig.
18    # We can skip specifying CalibConfig or leave a None as the default value.
19    quant_and_calib_configs.append(
20        (QuantConfig(quant_algo=QuantAlgo.W4A16_AWQ), None))
21
22if enable_fp8:
23    # Example 2: Specify FP8 quantization to QuantConfig.
24    # We can create a CalibConfig to specify the calibration dataset and other details.
25    # Note that the calibration dataset could be either HF dataset name or a path to local HF dataset.
26    quant_and_calib_configs.append(
27        (QuantConfig(quant_algo=QuantAlgo.FP8,
28                     kv_cache_quant_algo=QuantAlgo.FP8),
29         CalibConfig(calib_dataset='cnn_dailymail',
30                     calib_batches=256,
31                     calib_max_seq_length=256)))
32else:
33    logging.error(
34        "FP8 quantization only works on post-ada GPUs. Skipped in the example.")
35
36if enable_nvfp4:
37    # Example 3: Specify NVFP4 quantization to QuantConfig.
38    quant_and_calib_configs.append(
39        (QuantConfig(quant_algo=QuantAlgo.NVFP4,
40                     kv_cache_quant_algo=QuantAlgo.FP8),
41         CalibConfig(calib_dataset='cnn_dailymail',
42                     calib_batches=256,
43                     calib_max_seq_length=256)))
44else:
45    logging.error(
46        "NVFP4 quantization only works on Blackwell. Skipped in the example.")
47
48
49def main():
50
51    for quant_config, calib_config in quant_and_calib_configs:
52        # The built-in end-to-end quantization is triggered according to the passed quant_config.
53        llm = LLM(model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
54                  quant_config=quant_config,
55                  calib_config=calib_config)
56
57        # Sample prompts.
58        prompts = [
59            "Hello, my name is",
60            "The president of the United States is",
61            "The capital of France is",
62            "The future of AI is",
63        ]
64
65        # Create a sampling params.
66        sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
67
68        for output in llm.generate(prompts, sampling_params):
69            print(
70                f"Prompt: {output.prompt!r}, Generated text: {output.outputs[0].text!r}"
71            )
72        llm.shutdown()
73
74    # Got output like
75    # Prompt: 'Hello, my name is', Generated text: 'Jane Smith. I am a resident of the city. Can you tell me more about the public services provided in the area?'
76    # Prompt: 'The president of the United States is', Generated text: 'considered the head of state, and the vice president of the United States is considered the head of state. President and Vice President of the United States (US)'
77    # Prompt: 'The capital of France is', Generated text: 'located in Paris, France. The population of Paris, France, is estimated to be 2 million. France is home to many famous artists, including Picasso'
78    # Prompt: 'The future of AI is', Generated text: 'an open and collaborative project. The project is an ongoing effort, and we invite participation from members of the community.\n\nOur community is'
79
80
81if __name__ == '__main__':
82    main()