LLM Quantization
Source https://github.com/NVIDIA/TensorRT-LLM/tree/main/examples/llm-api/llm_quantization.py.
1### Generation with Quantization
2import logging
3
4import torch
5
6from tensorrt_llm import LLM, SamplingParams
7from tensorrt_llm.hlapi import QuantAlgo, QuantConfig
8
9major, minor = torch.cuda.get_device_capability()
10post_ada = major > 8 or (major == 8 and minor >= 9)
11
12quant_configs = [
13 QuantConfig(quant_algo=QuantAlgo.W4A16_AWQ),
14]
15
16if post_ada:
17 quant_configs.append(
18 QuantConfig(quant_algo=QuantAlgo.FP8,
19 kv_cache_quant_algo=QuantAlgo.FP8))
20else:
21 logging.error(
22 "FP8 quantization only works on post-ada GPUs, skipped in the example.")
23
24for quant_config in quant_configs:
25
26 llm = LLM(
27 model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
28 # define the quantization config to trigger built-in end-to-end quantization.
29 quant_config=quant_config)
30
31 # Sample prompts.
32 prompts = [
33 "Hello, my name is",
34 "The president of the United States is",
35 "The capital of France is",
36 "The future of AI is",
37 ]
38
39 # Create a sampling params.
40 sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
41
42 for output in llm.generate(prompts, sampling_params):
43 print(
44 f"Prompt: {output.prompt!r}, Generated text: {output.outputs[0].text!r}"
45 )
46
47# Got output like
48# 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?'
49# 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)'
50# 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'
51# 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'