Method for quickly replacing binary operators to facilitate quantization
By automatically replacing the binary operators in the torch network with quantization operators, the problem of decreased accuracy and unstable training caused by the reduction of data bit width in quantization of artificial intelligence models is solved, and the model size and computational efficiency are reduced.
Patent Information
- Application Number
- CN202310277689.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2023-03-21
- Publication Date
- 2024-09-24
AI Technical Summary
In the process of quantizing artificial intelligence models, how to maintain model accuracy while reducing model data bit width, especially the lack of effective means for activation values, and the discontinuity caused by quantization makes neural network training unstable.
Propose a method to automatically replace the binary operators in the torch network with torch function operations, and finally replace them with quantization operators, including the replacement of +, * and other operators with torch.add and torch.mul to facilitate subsequent QuantizeAdd and QuantizeMul replacement to ensure network layer quantization.
It effectively reduces the size and calculation amount of the model, improves the computational efficiency of the model, solves the problem of decreased accuracy after quantification, and especially provides an effective means for quantification of activation values.
Smart Images

Figure CN118690795A
Abstract
Description
Technical Field
[0001] The present invention belongs to the technical field of artificial intelligence model quantization, and in particular relates to a method for quickly replacing binary operators for quantization. Background Art
[0002] With the popularization of artificial intelligence applications on mobile phones and IoT, the computing performance and storage capacity of terminal hardware are relatively weak due to the limitations of energy consumption and device size, which brings new challenges to artificial intelligence models - the models need to be smaller, faster and stronger. Quantization is one of the important means. Therefore, quantization has become a popular research direction in academia and industry in recent years. But at the same time, model quantization has also caused huge challenges. There are two major challenges: one is the decrease in accuracy caused by information loss due to the decrease in representation accuracy; the other is that the discontinuity caused by quantization makes the training of neural networks unstable. Most of the work in academia and industry is also centered around them.
[0003] Here, the benefits are quantified:
[0004] Quantization is to store floating point numbers that were previously expressed in 32 bits or 64 bits in a form that takes up less memory space, such as 8 bits, 16 bits, or even 1 bit or 2 bits. The benefits of this are:
[0005] 1. Reduce the model size and reduce the model storage space requirements;
[0006] 2. Reduce memory bandwidth requirements;
[0007] 3. Accelerated computing. Modern mobile devices basically support SIMD (Single Instruction Multiple Data). Taking a 128-bit register as an example, a single instruction can simultaneously calculate four 32-bit single-precision floating points, or eight 16-bit integers, or sixteen 8-bit integers. Obviously, with the support of SIMD, the calculation rate of 8-bit integers is faster.
[0008] However, quantification also faces the following problems:
[0009] The core challenge of quantization is how to reduce the model data bit width while maintaining the accuracy of the model, that is, to make a trade-off between compression rate and accuracy loss. This leads to many interesting sub-problems, such as what is the quantization object (weight, activation, gradient), how many bits are quantized (8 bits, 4 bits, 2 bits, 1 bit), which quantization parameters are selected (such as moving rate, clipping value), whether the quantization parameters can be automatically optimized, whether different layers require different quantization parameters, how to restore accuracy after quantization or consider quantization during training, etc.
[0010] Model quantization mainly includes two parts: one is the quantization of weights, and the other is the quantization of activation values. Only by quantizing both parts at the same time can the maximum computational efficiency be achieved. Weights can be distributed as compactly as possible to reduce outliers and uneven distributions with the help of network regularization and other means, but there is still a lack of effective means for activation values. Summary of the invention
[0011] In order to solve the above problems, the purpose of this application is to propose a method for automatically replacing binary operators in the torch network with torch function operations and finally replacing them with quantization operators. This method does not provide a quantization method, but quickly replaces the binary operators existing in the original network, which is beneficial to subsequent quantization.
[0012] Specifically, the present invention provides a method for quickly replacing binary operators for quantization. The method automatically replaces binary operators in a neural network constructed by torch with torch function operations, and finally replaces them with quantization operators; including +, * for replacing torch.add and torch.mul, which facilitates the subsequent replacement of QuantizeAdd and QuantizeMul to ensure that such operators are quantized.
[0013] The method first defines a neural network class: inherits the nn.Module class, and re-implements the constructor _init__ and the forward propagation calculation forward; through the inheritance mechanism, the required neural network class is defined according to nn.Module, and the constructor __init__ is initialized; that is, the method includes the following steps: setting
[0014] S1, inherited class: nn.Module, expressed as:
[0015] class Model(nn.Module);
[0016] S2, initialize all layers: _init_, expressed as:
[0017] def__init__(self,planes): All the layers placed in the constructor __init__ are the "intrinsic attributes" of this model;
[0018] Fixed content:
[0019] super(Model,self).__init__()
[0020] Define the relevant functions:
[0021] self.conv=nn.Conv2d(planes, planes, kernel_size=3, groups=planes, bias=True, padding=1)
[0022] self.bn=nn.BatchNorm2d(planes,eps=1e-05)
[0023] S3, defines the model's operation process: forward propagation process
[0024] Constructing the model structure:
[0025] The binary operations + and * with tensor parameters are selectively replaced with torch functions automatically, and the final network forward becomes:
[0026] def forward(self,x):
[0027] (1) out1 = self.conv(x)
[0028] (2) out2 = self.bn(out)
[0029] (3)out = torch.mul(out,x)
[0030] (4)out=torch.add(torch.add(out1,out2),out)
[0031] (5)out=torch.mul(torch.add(out,x),out)
[0032] (6)out = torch.mul(out,3)
[0033] (7) return out the final result
[0034] In this way, the binary operators + and * are automatically replaced with torch.add and torch.mul operators, so that we can know that it is indeed the network layer that needs to be quantized, so we can proceed to the next step of replacing the quantization operator with QuantizeAdd and QuantizeMul.
[0035] The method aims to quantify the layers in the network data flow such as convolutional layers, fully connected layers, addition layers, and multiplication layers that perform actual operations on the data.
[0036] Therefore, the advantages of the present application are: it solves the problems of the prior art well, performs quantization operations on floating-point models, and can effectively reduce the model size and the amount of calculation. BRIEF DESCRIPTION OF THE DRAWINGS
[0037] The drawings described herein are used to provide a further understanding of the present invention, constitute a part of this application, and do not constitute a limitation of the present invention.
[0038] Figure 1 This is a code diagram of the driver layer.
[0039] Figure 2 It is a schematic diagram of the application layer test code.
[0040] Figure 3 It is a flow chart of the method of the present application.
[0041] Figure 4 It is a pseudo code schematic diagram of step S3 in the prior art.
[0042] Figure 5 This is a schematic diagram of the entire network structure in forward.
[0043] Figure 6 It is a pseudo code diagram in step S3 of this method. DETAILED DESCRIPTION
[0044] In order to more clearly understand the technical content and advantages of the present invention, the present invention is now further described in detail in conjunction with the accompanying drawings.
[0045] First, the basic steps to build a neural network are as follows:
[0046] Define the neural network class
[0047] Inherit the nn.Module class and re-implement the constructor (__init__) and forward propagation calculation (forward). Through the inheritance mechanism, define the required neural network class according to nn.Module and initialize the constructor __init__; each subclass inherited from nn.Module must re-implement the forward calculation operation function of the input data in the method. Figure 1 shown.
[0048] Here, a neural network is constructed, which includes a flattening layer, three fully connected layers, and two linear rectifier units. An instance model of NeuralNetwork is created, the model is moved to the device, and its structure is printed:
[0049] model=NeuralNetwork().to(device)
[0050] print(model)
[0051] The running results obtained are as follows Figure 2 shown.
[0052] The torch.nn.Module class is the base class for all neural network modules, and its implementation is in torch / nn / modules / module.py. Models should also inherit this class, mainly overloading the __init__, forward, and extra_repr functions. Modules can also contain other modules, so that they can be nested in a tree structure. As long as the forward function is defined in your own class, it will be automatically implemented using Autograd. As long as you instantiate an object and pass in the corresponding parameters, the forward function can be automatically called.
[0053] This application relates to a method for quickly replacing binary operators to facilitate quantization, such as Figure 3 As shown: the method first defines a neural network class: inherits the nn.Module class, and re-implements the constructor _init__ and the forward propagation calculation forward; through the inheritance mechanism, the required neural network class is defined according to nn.Module, and the constructor __init__ is initialized; that is, the method includes the following steps: setting
[0054] S1, inherited class: nn.Module, expressed as:
[0055] class Model(nn.Module);
[0056] S2, initialize all layers: _init_, expressed as:
[0057] def__init__(self, planes): All the layers placed in the constructor __init__ are the "intrinsic properties" of this model; here, palnes is just a formal parameter, and no default value is set. The user must first import the parameters when calling. From the definition below, we can see that planes corresponds to the number of channels of conv;
[0058] Fixed content:
[0059] super(Model,self).__init__()
[0060] Define the relevant functions:
[0061] self.conv=nn.Conv2d(planes,planes,kernel_size=3,groups=planes,bias=True,padding=1),initialize a 2D convolution torch.nn.Conv2d operator, where the input channel is planes, the output channel is planes, the convolution kernel size is 3, divided into planes groups, with bias, and 1 pixel padded around;
[0062] self.bn = nn.BatchNorm2d(planes, eps = 1e-05), initialize a batch normalization operator torch.nn.BatchNorm2d, where the number of channels is planes;
[0063] S3, defines the model's operation process: forward propagation process,
[0064] Constructing the model structure:
[0065] The binary operations + and * with tensor parameters are selectively replaced with torch functions automatically, because the above-mentioned related functions are automatically replaced. In the prior art, Figure 4 As shown, it can be expressed as:
[0066] def forward(self,x):
[0067] (1) out1 = self.conv(x)
[0068] (2) out2 = self.bn(out1)
[0069] (3)out*=x
[0070] (4)out=out1+out2+out
[0071] (5)out=(out+x)*out
[0072] (6)out=out*3
[0073] Return the final result:
[0074] (7) return out
[0075] in,
[0076] In (3), out*=x is equivalent to out=out*x, and in (6), multiplying the tensor type out and a single value 3 is equivalent to multiplying each element of the tensor by 3.
[0077] It can be seen that in the above model, in addition to the conv and bn initialized in init, there are actually operations such as + and * in forward. The entire network structure is as follows Figure 5 As shown, although the + and * actually correspond to the Add and Mul nodes during the visualization conversion (pytorch to onnx), the + and * operators are still seen during the forward operation.
[0078] In addition, single values can also be subjected to such operations, but at this time they do not belong to the network layer, so there is no need to quantize them. For example, there is an operation in forward: y=1+planes, which is the addition of two values. It does not involve the tensor operation of torch, so it will not be replaced by torch.add, and there is no need to quantize the result. The layers that need to be quantized are the convolutional layers, fully connected layers, addition layers, multiplication layers, etc., which are the layers in the network data flow that perform actual operations on the data flow. Therefore, it is inappropriate to simply perform quantization such as + and - while ignoring numerical operations.
[0079] So here, this method selectively replaces the binary operations + and * with tensor parameters with torch functions, and finally the forward of the above network becomes, Figure 6 As shown: def forward(self,x):
[0080] (1) out1 = self.conv(x)
[0081] (2) out2 = self.bn(out)
[0082] (3) out = torch.mul(out,x)
[0083] The original is out*x, after replacement it is torch.mul(out,x), the symbolic function is replaced with the function implementation form of torch,
[0084] (4)out=torch.add(torch.add(out1,out2),out),
[0085] The original is out1+out2, after replacement it is torch.add(out1,out2), which is equivalent to replacing the symbolic function with the function implementation form of torch.
[0086] (5)out=torch.mul(torch.add(out,x),out)
[0087] (6)out = torch.mul(out,3)
[0088] (7) return out
[0089] In this way, the binary operators + and * are successfully replaced automatically with the desired torch.add and torch.mul operators. This also shows that it is indeed the network layer that needs to be quantized, so the next step is to replace the quantization operator with QuantizeAdd and QuantizeMul, etc.
[0090] In summary, the method of the present invention is:
[0091] The method automatically replaces binary operators in a neural network constructed by torch with torch function operations, and finally replaces them with quantization operators; for example, +, *, etc. are replaced with torch.add and torch.mul, which is convenient for subsequent replacement of QuantizeAdd and QuantizeMul. The binary operation operators also include subtraction and division, and the binary operators are replaced with the function forms corresponding to torch, including subtraction-replaced with torch.sub, and division / replaced with torch.div, which is convenient for subsequent replacement of QuantizeSub and QuantizeDiv, so as to ensure that such operators are quantized.
[0092] The above description is only a preferred embodiment of the present invention and is not intended to limit the present invention. For those skilled in the art, the embodiments of the present invention may have various modifications and variations. Any modification, equivalent replacement, improvement, etc. made within the spirit and principle of the present invention shall be included in the protection scope of the present invention.
Claims
1. A method for quickly replacing binary operators to facilitate quantification, characterized in that: The method first defines a neural network class: inherits the nn.Module class, and re-implements the constructor _init__ and the forward propagation calculation forward; through the inheritance mechanism, the required neural network class is defined according to nn.Module, and the constructor __init__ is initialized; that is, the method includes the following steps: setting S1, inherited class: nn.Module, expressed as: class Model(nn.Module); S2, initialize all layers: _init_, expressed as: def__init__(self, planes): All the layers placed in the constructor __init__ are the "intrinsic properties" of this model; here, palnes is just a formal parameter, and no default value is set. The user must import the parameters before calling. From the definition below, we can see that planes corresponds to the number of channels of conv; Fixed content: super(Model,self).__init__() Define the relevant functions: self.conv=nn.Conv2d(planes,planes,kernel_size=3,groups=planes,bias=True,padding=1),initialize a 2D convolution torch.nn.Conv2d operator, where the input channel is planes, the output channel is planes, the convolution kernel size is 3, divided into planes groups, with bias, and 1 pixel padded around; self.bn = nn.BatchNorm2d(planes, eps = 1e-05), initialize a batch normalization operator torch.nn.BatchNorm2d, where the number of channels is planes; S3, defines the model's operation process: forward propagation process, Constructing the model structure: The binary operations + and * with tensor parameters are selectively replaced with torch functions automatically. Because the above-mentioned related functions are automatically replaced, the final forward improvement of the network by this method becomes: def forward(self,x): (1) out1 = self.conv(x) (2) out2 = self.bn(out) (3) out = torch.mul(out, x), The original is out*x, after replacement it is torch.mul(out,x), the symbolic function is replaced with the function implementation form of torch, (4) out = torch.add(torch.add(out1, out2), out), The original is out1+out2, after replacement it is torch.add(out1,out2), which is equivalent to replacing the symbolic function with the function implementation form of torch. (5) out = torch.mul(torch.add(out, x), out) (6) out = torch.mul(out, 3) (7) return out the final result in, In this way, the binary operators + and * are automatically replaced with torch.add and torch.mul operators, so that we can know that it is indeed the network layer that needs to be quantized, so we can proceed to the next step of replacing the quantization operator with QuantizeAdd and QuantizeMul.
2. A method for quickly replacing binary operators for quantification according to claim 1, characterized in that: The method automatically replaces binary operators in a neural network constructed by torch with torch function operations, and finally replaces them with quantization operators; the binary operators also include subtraction and division, and the binary operators are replaced with function forms corresponding to torch, including subtraction- replaced with torch.sub, and division / replaced with torch.div, so as to facilitate the subsequent replacement of QuantizeSub and QuantizeDiv, so as to ensure that such operators are all quantized.
3. A method for quickly replacing binary operators for quantification according to claim 1, characterized in that: The method aims to quantify the layers in the network data flow, including convolutional layers, fully connected layers, addition layers, and multiplication layers, which perform actual operations on the data.
