MLOps Model Compression
MLOps Model Compression
Model Compression
Our objectives:
• Discuss about the motivation and definition of
Knowledge Distillation technique.
• Some current applications of Knowledge
Distillation.
• Basic approaches for Knowledge Distillation.
• Investigate how to implement the Response-
based Knowledge Distillation method using
PyTorch.
2
Outline
❖ Introduction
❖ Knowledge Distillation
❖ Response-based Knowledge
❖ Question
3
Introduction
4
Introduction
❖ Getting Started
DL Model
DL Model
Small Deep Learning (DL) model. Large Deep Learning (DL) model.
In Deep Learning, there are models differ in size. In theory, the larger the model, the better the performance.
5
Introduction
❖ Challenges & Motivation in Deploying Large Language Models (LLMs)
● LLMs are becoming increasingly popular
○ For example: GPT-3 has 175B parameters
and large ensemble models.
• Computationally heavy.
• resource-intensive.
• hard to deploy in real-world applications. Table: GPT-3 Model Sizes and Parameters. Source: link.
Subset Model 1
Subset Model 3
6
Figure: Ensemble Models Illustration.
Introduction
❖ Challenges & Motivation in Deploying Large Language Models (LLMs)
● Conflict between training and deployment stages
? How can we maintain high performance
○ Training: Requires large resources (RAM, GPU), no real-time constraints. in large models while ensuring practical
deployment?
○ Deployment: Demands high-speed processing and resource efficiency.
7
Introduction
❖ Model Compression – A Solution to Simplify Neural Networks
● Objective: Reduce the complexity of neural networks while maintaining high accuracy.
● Main Techniques:
○ Quantization.
○ Weights Pruning.
○ Knowledge Distillation.
○ High-performance libraries.
Knowledge
Transfer
Data
Figure: Butterfly Life Cycle. Source: link. Figure: Simple Visualization of Knowledge
Distillation Method.
9
Introduction
❖ Introduction to Knowledge Distillation
Knowledge Distillation is a technique that allows transferring knowledge from large, computationally expensive
models to smaller models without losing effectiveness.
soft labels
predictions
Teacher Model
pre-trained - deep/large neural network Knowledge
Training Transfer
Data
hard labels
predictions true labels
Student Model
11
Introduction
❖Knowledge Distillation: A Survey
2019 Jiao et al. - TinyBERT: Distilling BERT for Natural Language Understanding.
2024 Ko et al. - DistiLLM: Towards Streamlined Distillation for Large Language Models.
13
Introduction
❖ Survey: Knowledge Distillation Research (2015–2024)
2015 Hinton et al. - Distilling the Knowledge in a Neural Network. Established KD as a method to transfer
First introduced the concept of Knowledge Distillation. knowledge from a large "teacher" model to a
smaller "student" model via soft logits.
2016
2019
Table: Frame classification accuracy and WER showing that the distilled
2021 single model performs about as well as the averaged predictions of 10 models
that were used to create the soft targets. Source: link.
2023
2024
14
Introduction
❖Survey: Knowledge Distillation Research (2015–2024)
2019
2021
2023
2024
15
Introduction
❖Survey: Knowledge Distillation Research (2015–2024)
2019 Jiao et al. - TinyBERT: Distilling BERT for Natural First to use layer-wise distillation to create a compact
Language Understanding. version of BERT, enabling NLP applications on low-
Contribution to NLP applications applied KD. resource devices.
2021
2023
2024
Figure: The illustration of TinyBERT learning. Source: link. Figure: TinyBERT application visualization.
16
Introduction
❖Survey: Knowledge Distillation Research (2015–2024)
2021 Anderson et al. - Compressing Visual-linguistic Model via Adapted KD to multimodal tasks such as Visual
Question Answering (VQA) and image captioning,
Knowledge Distillation.
improving efficiency and scalability.
First to apply KD to visual-linguistic models.
2023
2024
2023 Gu et al. - MiniLLM: Knowledge Distillation of Large Applied KD to compress large language models
(LLMs) while maintaining high performance,
Language Models.
facilitating deployment on edge devices.
MiniLLM enhances SeqKD by improving efficiency and
addressing data sparsity for LLMs.
2024
2024 Ko et al. - DistiLLM: Towards Streamlined Distillation Introduced adaptive techniques to optimize
inference and memory efficiency, enabling virtual
for Large Language Models.
assistants and real-time NLP systems.
First to refine KD pipelines for real-time LLM applications.
Figure: Adaptive Off-Policy Approaches. Source: link. Figure: DistiLLM applications visualization.
19
Knowledge Distillation
20
Knowledge Distillation
❖ Introduction
Figure: The generic teacher-student framework for knowledge distillation. Source: link.
21
Knowledge Distillation
❖ Introduction
KD uses different types of knowledge:
22
Knowledge Distillation
❖ Introduction
KD uses different types of knowledge:
23
Knowledge Distillation
❖ Introduction to Knowledge Distillation
soft labels
Teacher’s
Training predictions
data
Teacher Model
hard labels
Student’s predictions true labels
Training
data
Student Model
Teacher Model
Student Model
Instance Relations
Teacher …
Student …
Instance Relations
26
Response-based Knowledge
27
Response-based Knowledge
❖ Introduction
Response-based Knowledge Distillation (KD): Utilizes the outputs (logits) of the Teacher model to train the Student
model. This is the most common and straightforward method in KD.
29
Response-based Knowledge
❖ Distillation Loss
where
Input
Distillation Loss
Data
Idea: Let the student try to align
Student Model Logits its logits with the teacher’s logits
through loss function.
Figure: The generic response-based knowledge distillation. Source: link.
30
Response-based Knowledge
❖ Distillation loss: KL-Divergence
31
Response-based Knowledge
❖ Distillation loss: KL-Divergence
• When applying to the context of Knowledge Distillation (KD), this formula can be written as:
32
Response-based Knowledge
❖ How to distill the knowledge: Generalization
33
1 [Link]
Response-based Knowledge
❖ How to distill the knowledge: Generalization
Idea1: If somehow we can scale (soften) the teacher output, the relationship between classes is revealed.
34
1 [Link]
Response-based Knowledge
❖ How to distill the knowledge: Temperature Scaling
35
Response-based Knowledge
❖ Softmax with Temperature • T = 1: Standard Softmax.
• T>1: Softmax reduces the gap between the top-1
class probability and others, decreasing top-1 and
increasing the rest.
increase
Top-1 decrease
increase
36
Response-based Knowledge
❖ Softmax with Temperature
39
Response-based Knowledge
❖ Distillation Loss
where
Input
Distillation Loss
Data
41
Response-based Knowledge
❖ Weather Dataset
hail: 591
glaze: 639
rime: 1160
lightning: 377
rainbow: 232
fogsmog: 851
rain: 526
sandstorm: 692
dew: 698
frost: 475
snow: 621
42
Response-based Knowledge
❖ Weather Dataset
43
Response-based Knowledge
❖ Knowledge Distillation Scenarios
Knowledge Knowledge
Transfer Transfer
Data Data
Case 1: Teacher and Student are trained on the same data. Case 2: Teacher and Student are trained on different data.
44
Response-based Knowledge
❖ Pipeline Case 1
Dataset
Evaluation
45
Response-based Knowledge
❖ Pipeline Case 2
Dataset
Evaluation
46
Response-based Knowledge
❖ ResNet Models
47
Response-based Knowledge
❖ Student
n
cl
as
se
CE Loss
s
Figure: Example with ResNet18.
48
Response-based Knowledge
❖ Teacher
n
cl
as
se
s
CE Loss
49
Response-based Knowledge
❖ Pipeline Case 1
Dataset
Evaluation
50
Response-based Knowledge
❖ Coding Step 1: Import libraries and set random seed
51
Response-based Knowledge
❖ Coding Step 2: Read dataset
52
Response-based Knowledge
❖ Coding Step 2: Read dataset
53
Response-based Knowledge
❖ Coding Step 3: Train, val, test split
54
Response-based Knowledge
❖ Coding Step 4: Create PyTorch Dataset
55
Response-based Knowledge
❖ Coding Step 5: Create DataLoader
We must also declare the
value of batch size for
training and testing.
DataLoader is an iterator,
so we can get a sample
(image_path, label) and
visualize it.
56
Response-based Knowledge
❖ Coding Step 6: ResNet Architecture
57
Response-based Knowledge
❖ Coding Step 6: Implement Residual Block
weight layer
relu
identity
weight layer
+
relu
58
Response-based Knowledge
❖ Coding Step 6: Implement Residual Block
weight layer
relu
identity
weight layer
+
relu
59
Response-based Knowledge
❖ Coding Step 7: Implement ResNet
60
Response-based Knowledge
❖ Coding Step 7: Implement ResNet
61
Response-based Knowledge
❖ Coding Step 7: Implement ResNet
62
Response-based Knowledge
❖ Coding Step 7: Implement ResNet
63
Response-based Knowledge
❖ Coding Step 7: ResNet for Teacher and Student
64
Response-based Knowledge
❖ Coding Step 8: Implement training function
65
Response-based Knowledge
❖ Coding Step 9: Training
66
Response-based Knowledge
❖ Coding Step 10: Evaluation
67
Response-based Knowledge
❖ Results
Student
Val accuracy: 0.7283
Test accuracy: 0.7278
Teacher
Val accuracy: 0.7655
Test accuracy: 0.7540
68
Response-based Knowledge
❖ Pipeline Case 1
Dataset
Evaluation
69
Response-based Knowledge
❖ Train KD Student
n
cl
as
se
s
CE Loss
70
Response-based Knowledge
❖ Train KD Student
n
cl
as
se
s
CE Loss
Soft Target
Loss
n
cl
as
se
s
71
Response-based Knowledge
❖ Train KD Student
n
cl
as
se
s
CE Loss
Soft Target
Loss
Total Loss
n
cl
as
se
s
72
Response-based Knowledge
❖ Coding Step 1: Initialize Teacher and New Student
Knowledge
Transfer
73
Response-based Knowledge
❖ Coding Step 2: Implement training function
74
Response-based Knowledge
❖ Results
Student
Val accuracy: 0.7691
Test accuracy: 0.7467
KD with Teacher
on the same dataset
Val accuracy: 0.7865
Test accuracy: 0.7758
75
Response-based Knowledge
❖ Pipeline Case 2
Dataset
Evaluation
76
Response-based Knowledge
❖ Initialize Teacher (pre-trained on ImageNet) and New Student
Knowledge
Transfer
KD with Teacher
Teacher on the same dataset
Val accuracy: 0.7669
Val accuracy: 0.7865
Test accuracy: 0.7583
Test accuracy: 0.7758
78
Response-based Knowledge
❖ Results
79
QUIZ
80
Summarization and Q&A
81
Summarization and Q&A
❖ Summarization
82
Question
?
83
84
Quantization
Model Compression Series
2
Outline
FP16 S 5 bits 10 bits
SECTION 1
SECTION 3
Quantization in NN
3
Motivation
! Problem
v The growth of deep learning model size
The growth of deep learning model size: NLP vs. Computer vision (2014 - 2021)
4
Motivation
! Problem
But how about memory?
Correlation between model scale and performance: Increasing the number of parameters leads to
superior problem-solving abilities in Math, Coding, and Science.
5
Motivation
! Why do we need Quantization?
v The growth of deep learning model size
Model Size VRAM Needed (FP32)
v During model inference, we need to load all
GPT-2-0.1B 0.1B 0.5GB
parameters into memory
Tiny Llama-1.1B-Chat 1.1B 4.6GB
v Hardware Constraints: Standard PCs and Mistral-7B-v0.2 7B 33GB
smartphones cannot accommodate the high Llama-3-70B-Instruct 70B 311GB
memory footprint of modern LLMs Mistral-8x22B-v0.1 141B 631GB
6
Motivation
! Why do we need Quantization?
7
Motivation
! Why do we need Quantization?
Design Systems
Distillation
Pruning
Compression Methods 8
Quantization
! Definition
v Quantization aims to reduce the total amount of bits required to represent each parameter, usually by converting
floating-point numbers into integers
v Quantization can also speed up computation, as working with smaller data types is faster.
-0.2 1 0.3 1 3 2
Quantization
0.1 -0.6 -0.7 1 0 0
1.2 0.4 0 3 2 1
32 bit 8 bit
9
Quantization
! Quantized Model Size
VRAM Needed
Model Size
FP32 FP16 INT8
10
Quantization
! Number representation: Decimal
v Decimal numbers are just numbers that also include negative powers of the base.
11
Quantization
! Number representation: Binary
But where do we put the point?
v In binary:
2m 2 m-1 … 22 21 20 2 -1 2 -2 2 -3 … 2 - (n - 1) 2-n
× × × × × × × × × ×
bm bm - b2 b1 b0 . b-1 b-2 b-3 b- n - bn
1 … … 1
12
Quantization
! Fixed-point representation
1 1 0 0 1 0 1 1 0 1 1 0 1 1 1 1 1
● Example: 00000000.00001012
We must store a lot of meaningless bits
11100000.00000002
13
Quantization
! Floating-point representation
31 30 23 22 0
0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Sign = 0
(positive)
The exponent field stores it
14
Quantization
! Floating-point representation
31 30 23 22 0
0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
15
Quantization
! Floating-point representation
31 30 23 22 0
0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
16
Quantization
! Floating-point representation
31 30 23 22 0
0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Sign = 0
(positive)
E = exponent − bias
17
Quantization
! Floating-point representation
18
Quantization
! Idea of Quantization
α Real value (Floating-point) β
quantize
Integer
Asymmetric Quantization
Uniform Quantization
Symmetric Quantization
Quantization
Non-uniform Quantization
19
Quantization
! Uniform Quantization vs. Non-Uniform Quantization
20
Quantization
! Types of Uniform Quantization : Asymmetric and Symmetric
Asymmetric Symmetric
β 0 α -α 0 α
z acts as an anchor point mapping the original range into the discrete integer range.
21
Quantization
! Asymmetric Formula
Asymmetric
β 0 α
Scaling Factor
Qmin -z 0 Qmax
Zero-point
Clipping range
22
Quantization
! Understand Asymmetric Formula
Asymmetric
Scaling Factor β 0 α
Qmin -z 0 Qmax
23
Quantization
! Understand Asymmetric Formula
Asymmetric
Zero-point β 0 α
Qmin -z 0 Qmax
24
Quantization
! Understand Asymmetric Formula
Asymmetric
β 0 α
Qmin -z 0 Qmax
Position of quantized value in integer range!
25
Quantization
! Asymmetric Dequantization
Asymmetric
β 0 α
Qmin -z 0 Qmax
26
Quantization
! Asymmetric Dequantization
27
Quantization
! Asymmetric Dequantization
-1.3521 -1.8095 0.2968 -1.3974 0.9779 0.7762 2.8330 0.7332 -0.8949 -0.8428
Quantize
Dequantize
-1.3472 -1.8024 0.2913 -1.4019 0.9831 0.7829 2.8401 0.7282 -0.8921 -0.8375
Quantization
! Lossy Compression
29
Quantization
! Symmetric Quantization
Symmetric
-α 0 α
30
Quantization
! Symmetric Quantization
31
Quantization
! Symmetric Quantization
0.7339 0.4977 0.9103 -0.4479 -0.3806 -0.0671 0.1176 1.9213 0.6556 0.0380
Quantize
Dequantize
0.7413 0.4992 0.9077 -0.4539 -0.3782 -0.0605 0.1210 1.9213 0.6505 0.0454
32
Quantization
! Asymmetric vs. Symmetric Comparison
33
Quantization
! Asymmetric vs. Symmetric Comparison
34
Quantization
! Calibration
35
Quantization
! Calibration
vulnerable to outliers!
36
Quantization
! Calibration
Outlier!!!
Quantize
0 1 0 -1 0 1 -127 0
Dequantize
37
Quantization
! Calibration Strategy: Percentile
Percentile (Vietnamese: “Bách phân vị”) is a statistical measure that indicates the value below which a given
percentage of observations in a dataset fall.
Ignore outlier
38
Quantization
! Calibration Strategy: Percentile
Do not select it!
Quantize
Dequantize
39
Quantization
! Non-Uniform Quantization
40
Quantization
! Non-Uniform Quantization
Fewer values
41
Outline
FP16 S 5 bits 10 bits
SECTION 1
SECTION 3
Quantization in NN
42
Quantization In NN
! Neural Network
Weight
Bias
Y = XW + B Usually quantized as int32
Perform all operations using
integer arithmetic
Input
sometimes called “activation”
43
Quantization In NN
! Neural Network Quantization Methods
Static PTQ
44
Quantization In NN
! Post Training Quantization: Static
Pre-trained Model
Attach Observers
Quantized Model
45
Quantization In NN
! Post Training Quantization: Static
Input Output
FP32 FP32
46
Quantization In NN
! Post Training Quantization: Static
Pre-trained Model
Attach Observers
Quantized Model
47
Quantization In NN
! Post Training Quantization: Static
Pre-trained Model
Attach Observers
Quantized Model
48
Quantization In NN
! Dynamic PTQ
In this method, the model performs calibration and quantization on-the-fly before each layer during inference,
converting the data back to FP32 (dequantize) after each operation is completed
49
Quantization In NN
! Dynamic PTQ
50
Quantization In NN
! Quantization Aware Training Sequence of Quantize and Dequantize operations
● Insert some fake modules in the computational graph of the model to simulate the effect of the
quantization during training.
● The loss function gets used to update weights that constantly suffer from the effect of quantization,
usually leads to a more robust model.
51
Quantization In NN
! Quantization Aware Training
(FP) (INT)
1.1 2.2 1 2
Forward Pass
-1.7 3.6 -2 2
52
Quantization In NN
! Quantization Aware Training Non differentiable
(FP) (INT)
1.1 2.2 1 2
Forward Pass
-1.7 3.6 -2 2
53
Quantization In NN
! Quantization Aware Training Non differentiable
(FP) (INT)
1.1 2.2 1 2
Forward Pass
-1.7 3.6 -2 2
54
Quantization In NN
! Quantization Aware Training
55
56
Summary
Introduction to Quantization Quantization in Neural Network
v Motivation v Neural Network Quantization Methods
v Quantization v Post Training Quantization
v Floating-point Representation v Quantization Aware Training
v Uniform vs Non-Uniform Quantization v Experimentation
57
Thanks!
Any questions?
58
ONNX and TensorRT
Class: Model Compression Series
Thuan Duong – TA
Phat Dat – sTA
ONNX
24/1/26 2
Objective
AI VIETNAM
All-in-One Course
(TA Session)
TensorRT
24/1/26 3
AI VIETNAM
All-in-One Course
(TA Session)
Outline
Ø Motivation
Ø ONNX
Ø TensorRT
Ø Questions
24/1/26 4
AI VIETNAM
All-in-One Course
(TA Session)
Motivation
24/1/26 5
Motivation
AI VIETNAM
All-in-One Course
(TA Session)
v Problems
• There is no single tool for all tasks. Data
scientists use various frameworks based
on their specific needs.
Microsoft
Research flexibility
Deep Learning
Frameworks
Production efficiency
24/1/26 6
Motivation
AI VIETNAM
All-in-One Course
(TA Session)
v Framework lock-in
• To move a model from research to production, engineers often have to rewrite the model from scratch in a
different language or framework, which is time-consuming and prone to errors.
24/1/26 7
Motivation
AI VIETNAM
All-in-One Course
(TA Session)
CPU GPU
Mobile devices
CPU TPU
24/1/26 8
Motivation
AI VIETNAM
All-in-One Course
(TA Session)
v Production requires
24/1/26 9
Motivation
AI VIETNAM
All-in-One Course
(TA Session)
v ONNX
24/1/26 [Link] 10
Motivation
AI VIETNAM
All-in-One Course
(TA Session)
v TensorRT
24/1/26 [Link] 11
AI VIETNAM
All-in-One Course
(TA Session)
ONNX
24/1/26 12
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v What is ONNX?
• Open Neural Network Exchange (ONNX) is an open standard for exchanging AI models.
• ONNX defines a common set of operators and a common file format to enable AI developers to use models
with a variety of frameworks, tools, runtimes, and compilers.
Frameworks Devices
Converters Deploy
24/1/26 13
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v ONNX in AI stack
Devices
.onnx
Hardware-optimized execution
(ONNX Runtime, TensorRT).
24/1/26 14
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v Concepts
Metadata: contains information
about the model
Version/ Opset
Model Graph
• Version info • Inputs and Outputs
• Metadata • List of computation nodes
• Acrylic computation dataflow graph • Graph name
Computation node
• Number of inputs of defined types
• Operator
• Operator parameters
v Graph Components
Nodes (Operators) Edges
a x
• Represent computational operations (e.g., Conv, Relu, MatMul).
• Act as function calls: they consume Inputs and produce Outputs. Mul
• Defined by the Opset version to ensure compatibility. b
Edge Nodes
Add
• Represent the data flow between Nodes.
• Establish the topology of the DAG (Directed Acyclic Graph).
• Carry data (Tensors) from one operation to the next.
output
24/1/26 17
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v Graph Components
Attributes
a x
• Static parameters specific to a Node (e.g., kernel_size, strides, padding).
• Fixed configurations that do not change during inference. Mul
b
Inputs & Outputs
• Define the graph's interfaces
Add
• Strongly typed: Must specify shape (dimensions) and
data type (e.g., FP32, INT64).
output
24/1/26 18
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v ONNX Operators
• ONNX defines a specifics for every operation (Math, NN Layers, Activation).
Ø Ensures consistent math behavior across all platforms.
v ONNX Operators
Versioning Strategy:
• Each operator has versions
• All operators are managed via Opset versions.
24/1/26 20
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v Opset
The Opset (Operator Set) in ONNX defines a collection of
operators that a model can use
Update operations
Opset 14 Opset 18
ReLU ver. 13 Add ver. 6 ArgMax Ver. 11 ReLU ver. 14 Add ver. 14 ArgMax Ver. 13
24/1/26 21
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v Netron visualization
[Link]
24/1/26 22
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
[Link]
Validate/ Check
24/1/26 23
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v Converters
tensorflow-onnx
sklearn-onnx
???
LibSVM onnxmltools
24/1/26 24
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v Tensorflow to ONNX
Converter
24/1/26 25
ONNX
AI VIETNAM
All-in-One Course
(TA Session) Ref: [01]_Tensorflow2ONNX_VGG16.ipynb
24/1/26 26
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v Pytorch to ONNX
Dummy input
for tracing
Converter
24/1/26 27
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
2
Ref: [00]_Pytorch2ONNX_Resnet50_CPU.ipynb
24/1/26 28
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v ONNX Runtime
ONNX Runtime: A high-performance, cross-platform inference
engine specifically designed to run ONNX models.
Devices
24/1/26 29
Ref [Link]
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
Write once,
run anywhere!
Performance Boost
Hybrid Execution
Production Readiness
Lightweight
v PyTorch, Tensorflow
to ONNX Runtime
24/1/26 34
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
24/1/26 35
ONNX
AI VIETNAM
All-in-One Course
(TA Session)
v Demo 1: multi-platform
v Limitations
Limited Operator Support
Not all operators (especially newer/dynamic ones) map 1-1 from frameworks to ONNX, causing export failures.
Hard to Debug
As a static graph, tracing errors is much harder compared to native PyTorch/TensorFlow code.
24/1/26 37
AI VIETNAM
All-in-One Course
(TA Session)
Processor
24/1/26 38
Processor
AI VIETNAM
All-in-One Course
(TA Session)
v CPU vs GPU
24/1/26
39
Processor
AI VIETNAM
All-in-One Course
(TA Session)
v CPU vs GPU
v CUDA
NVIDIA CUDA (Compute Unified Device Architecture) is NVIDIA’s parallel computing platform
that allows developers to use GPUs to accelerate general-purpose computations beyond graphics
24/1/26 42
NVIDIA GPU
AI VIETNAM
All-in-One Course
(TA Session)
24/1/26 43
NVIDIA GA100
AI VIETNAM
All-in-One Course
(TA Session)
TensorRT
24/1/26 45
TensorRT
AI VIETNAM
All-in-One Course
(TA Session)
v What is TensorRT
Ø A high performance SDK for optimizing trained deep-learning models and running on NVIDIA hardwares.
Ø Perform optimization such as layer fusion, kernel autotuning, quantization and more.
Ø TensorRT contains a deep learning inference optimizer and a runtime for execution.
Ø Speedup inference time and reduced latency.
24/1/26 46
TensorRT
AI VIETNAM
All-in-One Course
(TA Session)
v TensorRT Ecosystem
TensorRT-LLM
24/1/26 47
TensorRT
AI VIETNAM
All-in-One Course
(TA Session)
v Use TensorRT
ONNX Conversion Before TensorRT
24/1/26 48
TensorRT
AI VIETNAM
All-in-One Course
(TA Session)
v Optimization techniques
24/1/26 49
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Mixed
• DNNs often trained with full precision (FP32). α Real value (FP32) β
INT8
24/1/26 50
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Precision modes
Pros Cons
Risk of accuracy
Fastest throughput
INT8 Smallest model size
degradation if the model
is sensitive.
Exponent
Sign Mantissa
INT8 8 bits
24/1/26 51
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Kernel Auto-Tuning
• Kernel: A low-level function written to be executed on the GPU.
• The actual "worker" performing operations (MatMul, Conv2d, Element-wise ops).
• There are multiples kernel for common operations.
X
Kernel 2: Optimized for Bignum.
Matrix multiplication
Kernel 3: Optimized for Ampere chip
24/1/26 52
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Kernel Auto-Tuning
• TensorRT selects the optimal kernels based on user’s parameters: batch-size, input data size…
• TensorRT selects the optimal kernel based on user’s target flatform.
0.01 ns
0.02 ns write to
X
TensorRT Optimizer
Matrix multiplication 0.001 ns .engine
0.015 ns
24/1/26 53
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
Load Read
Conv
Write
Add
Read
GPU
VRAM
Bias
Write
Compute
Read
ReLU
Write
24/1/26 54
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Layer Fusion
Conv
ReLU
Load and compute
within cache
24/1/26 55
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Layer Fusion
Load
Kernel Load One
Load Load kernel kernel
Input Input
Kernel Kernel for all
24/1/26 56
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Layer Fusion
Concat Concat
Input Input
24/1/26 57
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Tensor Fusion
Compute
Solutio A
Compute
Input n
B
Allocat
e Concat
24/1/26 58
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Tensor Fusion
Output Output
Delete
Concat
Input Input
24/1/26 59
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v Multi-Stream Execution
• Allow processing multiple input streams in parallel
• Increase throughput
Memory is loading
24/1/26 61
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v trtexec
• A command-line tool designed for TensorRT performance benchmarking
• The tool can build tensorrt engine and measure .onnx files performance directly
trtexec
24/1/26 62
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
v trtexec
trtexec --onnx=[Link] --shapes=data:4x3x224x224 --fp16 --noDataTransfers --useCudaGraph --
useSpinWait
After running the trtexec command, trtexec will parse ONNX file, build a TensorRT plan file, measure the performance of
this plan file, and then print a performance summary as follows:
Flexible
.engine
224 x 224
.engine
224 x 224
TensorRT need to know the range of all possible input sizes so it can prepare memory
24/1/26 64
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
trtexec --onnx=[Link] \
--minShapes=input:1x3x224x224 \
--optShapes=input:8x3x512x512 \
--maxShapes=input:16x3x1024x1024 \
--saveEngine=model_dynamic.engine
24/1/26 65
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
Build .engine
TensorRT TensorRT
Trained ONNX Check .onnx Optimizer builder
DNN Conversion by trtexec
● Engine file only run on device it is built in (e. g. If you build .engine in RTX 3060, the .engine file only run on GTX 3060)
Send .onnx file along with .engine so user can build engine file on new device.
● TensorRT does not fallback to CPU. If an operator is not supported by GPU, it will fails.
24/1/26 66
Optimization techniques
AI VIETNAM
All-in-One Course
(TA Session)
TensorrtExecutionProvider
build + inference
Trained ONNX
DNN Conversion
Else: automatically fallback to CPU
The model always run
Don’t need to modify TensorRT for new operator
24/1/26 67
TensorRT
AI VIETNAM
All-in-One Course
(TA Session)
Related repositories:
• [Link]
• [Link]
• [Link]
v Installation (Ubuntu)
1. Install CUDA ([Link]
2. Download TensorRT package (.deb) that matches the Ubuntu version and CPU architecture.
3. Install TensoRT via .deb package
CUDA version
v Installation (Ubuntu)
1. Install CUDA Ref: [Link]
2. Download TensorRT package (.deb) that matches the Ubuntu version and CPU architecture.
3. Install TensoRT via .deb package
Install
v Build Pipeline
Initialize TensorRT Builder & Logger
Configure builder:
• Set WORKSPACE memory (1 GB) for
layer optimization
• Define optimization profile for dynamic
batch size (1 → 8)
Ref: [Link]
24/1/26 72
library/[Link]#deserializing-a-plan
24/1/26 73
TensorRT
AI VIETNAM
All-in-One Course
(TA Session)
v Demo 2: multi-platform
?
24/1/26 75
24/1/26 76