Quantization and inference method of a video visual self-attention encoder
By setting a four-bit activation quantizer and a weight quantizer in the video visual self-attention encoder, and utilizing gradient statistics and Hadamard transform, the problems of error coordination and storage computation in ultra-low bit deployment are solved, achieving efficient resource utilization.
Patent Information
- Application Number
- CN202611708333.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-10-31
- Publication Date
- 2026-11-27
AI Technical Summary
In video visual self-attention encoders, during the deployment of extremely low bit, there is insufficient coordination between activation quantization and weight quantization errors, and there is an intermediate storage and computational burden during compressed weight inference.
By setting a four-bit activation quantizer in the encoder, jointly training the weights and the scaling and offset parameters of the quantizer, utilizing the gradient statistics of the input and output matrices, performing random symbolic Hadamard transform and block decomposition, constructing a feedback factor, and using the Viterbi algorithm to quantize the weights, online Hadamard transform and lookup table reconstruction are achieved, reducing intermediate storage and computation.
It effectively coordinates the errors of activation quantization and weight quantization, reduces the amount of weight storage and intermediate computation requirements during inference, and improves the resource utilization efficiency of the model.
Smart Images

Figure CN123180253A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of neural network model quantization technology for video visual encoders, and particularly to a quantization and inference method for a video visual self-attention encoder. Background Technology
[0002] With the development of video understanding technology, visual self-attention encoders are used to extract features from video frame sequences. These encoders typically include multi-head self-attention modules and multilayer perceptron modules, requiring querying, key-value projection, and matrix operations across multiple linear layers. As the number of network layers, hidden feature dimensions, and video terms increases, the storage overhead for model weights and the computational overhead for inference also increase. Reducing the storage bandwidth of model parameters and the precision of data involved in computation through low-bit quantization is a technical approach to reduce model resource consumption.
[0003] Existing technologies include quantization methods suitable for visual self-attention models. These methods maintain full-precision weights in the initial stage, employ channel-level quantizers for layer-normalized activation values, shift-uniform logarithmic quantizers for softmax activation values, and layer-by-layer quantizers for other activation values. Subsequently, scale-reparameterization techniques are used to convert the channel-level quantizers into corresponding layer-level quantizers, and joint quantization of activation values and weights is performed in later stages. These methods reduce the impact of low-bit quantization on the performance of visual self-attention models by setting quantization methods for different activation value distributions and by implementing staged optimization.
[0004] Furthermore, quantization methods for visual autoregressive video generation models exist, which perform offline quantization and storage of model weights, and determine the quantization format and scaling factor based on the activation value distribution of different network layers during inference. These methods also employ smoothing factors and grouped rotation transformations to adjust the data distribution, calculate the product of the quantized activation index and the corresponding weight index using a lookup table, and then use the scaling factor to recover the calculation result, thereby reducing the computational overhead in video generation model inference.
[0005] The aforementioned techniques offer different implementations for low-bit quantization of visual models. However, when video visual self-attention encoders employ lower bit-width weight and activation representations, activation quantization errors and weight quantization errors can jointly affect the model output. Adjusting the quantizer only for the activation distribution, or handling the quantization errors of weights and activations separately, is insufficient to fully reflect the impact of weight changes on the model output under quantized activation conditions. Furthermore, extremely low-bit weights need to be restored to their corresponding calculated values during inference. If weight restoration is performed separately from matrix operations, it may also increase intermediate data storage and access overhead.
[0006] Therefore, how to coordinate the errors generated by activation quantization and weight quantization during the extremely low-bit deployment of video visual self-attention encoders, and reduce the intermediate storage and computational burden of compressed weights during inference, has become an urgent technical problem to be solved. Summary of the Invention
[0007] This invention provides a quantization and inference method for a video visual self-attention encoder, which solves the problems of insufficient utilization of weight quantization error feedback information under quantized activation conditions and the need for complete dequantization of intermediate weight storage when compressing weight inference.
[0008] To achieve the above objectives, this invention proposes a quantization and inference method for a video visual self-attention encoder, comprising: The query, key, value, attention output projection layer, and fully connected layer of the multilayer perceptron in the encoder are identified as linear layers to be quantized. A four-bit activation quantizer is set at the output of the linear layer to be quantized and at the two operands of the attention matrix multiplication. The weights are kept in 32-bit floating-point form. The weights, the scaling parameters of the quantizer, and the offset parameters of the quantizer are trained together to obtain the activation quantization model. The calibration video is input into the activated quantization model. The target category is sampled according to the category probability distribution output by the model to construct the cross-entropy self-distillation loss and backpropagate. The video-by-video weight gradient of each linear layer to be quantized is collected. The input-side matrix and output-side matrix are established by the sample mean of the product of gradient transpose and gradient, and the product of gradient and its transpose, respectively. Apply a corresponding transformation consisting of a random symbol vector and a normalized Hadamard transform to the weights and two-sided matrices of each linear layer to be quantized. Then, perform block decomposition on the transformed two-sided matrices to obtain the input-side feedback factor and the output-side feedback factor. The transformed weights are divided into blocks. Based on the feedback factor and the quantized block error, a quantization target containing input-side, output-side, and cross-term feedback is constructed according to the anti-diagonal order. The Viterbi algorithm is used to find the optimal value in the displacement state transition lattice. The blocks are encoded into a state encoding sequence of two bits per weight. The state encoding sequence is packaged and stored, and the weight reconstruction lookup table and transformation parameters are saved. During inference, an online Hadamard transformation is applied to the activation value processed by the activation quantizer. In the fusion kernel, the encoding sequence is decoded, the weight blocks are reconstructed by looking up the table, and matrix multiplication is performed. Then, the corresponding output-side transformation is performed without generating a complete inverse quantization weight matrix.
[0009] Preferably, the four-bit active quantizer located at the output of the linear layer to be quantized performs quantization according to the following formula: ; in, To input the activation value, The activation value after quantization. For learnable scaling parameters, For learnable offset parameters, This is the lower bound of the quantization index. The upper limit of the quantization index is set; the scaling parameter and offset parameter are set according to the output channel, and the backpropagation gradient of the quantization rounding operation is estimated using a pass-through estimator.
[0010] Preferably, the attention matrix multiplication includes matrix multiplication of the query vector and the transpose of the key vector, and matrix multiplication of the attention weight and the value vector; a tensor-wise four-bit activation quantizer is set for each of the two operands of each matrix multiplication, and each tensor-wise four-bit activation quantizer uses a set of scaling parameters and offset parameters for the corresponding entire operand tensor.
[0011] Preferably, linear projection, four-bit activation quantization, and tensor rearrangement are performed on the query vector, key vector, and value vector, respectively; rotation position encoding is performed on the rearranged query vector and key vector, followed by matrix multiplication of the transpose of the query vector and key vector; scaling and 32-bit floating-point Softmax normalization are performed on the obtained results in sequence to generate attention weights, then matrix multiplication of the attention weights and value vectors is performed, and four-bit activation quantization is performed on the attention output projection result.
[0012] Preferably, when jointly training the weights, quantizer scaling parameters, and quantizer offset parameters, the corresponding 32-bit floating-point model is used as the teacher model, and the attention pooler output features of the teacher model and the activated quantization model are obtained respectively; principal component projection and whitening parameters are fitted according to the output features of the teacher model, and principal component projection and whitening processing are performed on the corresponding output features of the two models, the mean square error between the whitened features is calculated, and the mean square error and classification cross-entropy are used together as the joint training loss.
[0013] Preferably, before joint training, activation samples corresponding to each four-bit activation quantizer are collected using thirty-two calibration videos; for each channel-by-channel four-bit activation quantizer, quantization parameters are initialized with quantization points of 0.999, 0.9999, and 0.99999 respectively, and the initial scaling parameters and initial offset parameters of the corresponding channels are selected according to the L2 norm error of the activation values before and after quantization of each output channel.
[0014] Preferably, the construction of the cross-entropy self-distillation loss includes: inputting the calibration video into the activated quantization model, forming a class probability distribution based on the classification prediction value output by the model, sampling the target class from the class probability distribution, and constructing the cross-entropy loss with the target class; performing a custom backpropagation operation on the linear layer to be quantized, and calculating the weight gradient corresponding to each calibration video based on the cross-entropy loss.
[0015] Preferably, when acquiring the weight gradient, forward and backward propagation are performed in batches of single calibration videos. Automatic mixing precision is turned off and 32-bit floating-point precision is used to accumulate the input-side matrix and output-side matrix, while gradient checkpointing is enabled. The accumulated matrices are stored in the central processing unit memory, loaded into the graphics processor layer by layer during weight quantization, and the corresponding matrix data is released after the quantization of the corresponding linear layer is completed.
[0016] Preferably, for each linear layer to be quantized, an input-side random symbol vector and an output-side random symbol vector are generated respectively, wherein each element of the random symbol vector takes the value of... or The weights are generated using a fixed random seed corresponding to the linear layer; the input-side random symbol vector, the output-side random symbol vector, and the corresponding normalized Hadamard matrix are used to perform a two-sided transformation on the weights, and the input-side matrix and the output-side matrix are respectively subjected to a conjugate transformation corresponding to the weight transformation.
[0017] Preferably, the transformed input-side matrix and output-side matrix are respectively implemented by performing block-based Cholesky operations. Decomposition, in which blocks Decomposition is the process of representing the matrix to be decomposed as a unit lower triangular factor. Block diagonal matrix The transpose of the unit lower triangular factor matrix The product, superscript This represents the matrix transpose; the block size is sixteen, yielding the corresponding unit lower triangular feedback factor and block diagonal matrix; when decomposition fails or the decomposition result is non-numerical, the diagonal elements of the matrix to be decomposed are accumulated with a regularization increment before re-decomposition, where the regularization increment is... .
[0018] Preferably, the two-sided error feedback quantization result is determined using the following formula: ; in, The weight matrix is obtained after random symbolic Hadamard transformation. This is the quantized weight matrix. For the two-bit quantization operation based on the state transition lattice, The quantization error matrix is generated from the quantized blocks. The lower triangular feedback factor corresponding to the input-side matrix. The lower triangular feedback factor corresponding to the output matrix, with superscript... Indicates matrix transpose; The weight blocks are processed in anti-diagonal order, so that the quantization target of the current block depends on the quantization error of the processed blocks, and multiple weight blocks located on the same anti-diagonal are jointly subjected to Viterbi quantization.
[0019] Preferably, the state transition lattice is a displacement lattice, where nodes are represented by 16-bit states. Transitions between adjacent states satisfy the condition that the high 12 bits of the successor state are the same as the low 12 bits of the predecessor state. Four new state information bits are introduced at each transition to encode two weights. The weight blocks are used as a weight sequence to be quantized.
[0020] Preferably, for each weight sequence to be quantized, the sequence is first cyclically shifted according to half the length of the lattice state, and the first unconstrained Viterbi optimization is performed; the midpoint state of the first optimization path is extracted as the state constraint for the second Viterbi optimization, the sequence is restored to its original order, and the Viterbi optimization is performed again, and the state encoding sequence is generated according to the state path obtained from the second optimization.
[0021] Preferably, when reconstructing the weights based on the state coding sequence, a weight reconstruction lookup table containing 512 entries is used, with each entry storing two 16-bit floating-point reconstruction values; the corresponding lookup table index is calculated based on the trellis state number, and the calculation relationship is as follows: ; in, Assign a grid state number, For the corresponding lookup table index, This represents a bitwise right shift in binary. This represents a binary bitwise AND operation; the entries in the weighted reconstruction lookup table are determined by performing clustering on a two-dimensional Gaussian distributed sample.
[0022] Preferably, the fusion kernel extracts the trellis state from the packaged state encoding sequence according to the weight blocks, reconstructs the corresponding weight blocks by looking up a table, retains the reconstructed weight blocks in a register, performs matrix multiplication with the activation blocks after online Hadamard transformation, accumulates the matrix multiplication results with 32-bit floating-point precision, and does not generate a complete inverse quantization weight buffer.
[0023] Preferably, the weight scaling factor for each linear layer to be quantized is determined according to the following formula: ; in, This is the weight scaling factor. The weights are those that have undergone a random symbol Hadamard transform. To reconstruct the weights, look up the set of reconstructed values in the lookup table. is the root mean square calculation function, and 0.9 is the scaling factor; The weight scaling factor is folded to the output-side random symbol vector of the corresponding linear layer, and the online Hadamard output is transformed by the folded output-side transformation vector during inference.
[0024] Preferably, the encoder is a video vision Transformer encoder containing twenty-four encoder layers. Each encoder layer includes a query projection layer, a key projection layer, a value projection layer, an attention output projection layer, and two fully connected layers in a multilayer perceptron, for a total of one hundred and forty-four linear layers to be quantized. The output activation values of the 3D convolutional block embedding layer are quantized by one channel eight bits, and the weights of the 3D convolutional block embedding layer, predictor, attention pooler, and classifier are preserved in a sixteen-bit floating-point format during deployment.
[0025] The above technical solution has the following advantages: This invention first trains a four-bit activation quantizer while maintaining floating-point weights. Then, it collects sample-by-sample weight gradients based on the quantized and activated model, enabling subsequent weight quantization to utilize the input-side and output-side matrices corresponding to the current activation quantization conditions. By applying corresponding randomized symbolic Hadamard transforms and block decomposition to the weights and both matrices, a two-sided error feedback relationship can be established within the same transform domain. Adjusting the quantization target of weight blocks using input-side, output-side, and cross-term feedback helps control the output bias introduced by extremely low bit-width weight quantization. Converting the weights into a two-bit state-encoded sequence per weight using Viterbigram quantization reduces the weight storage requirements of the linear layer to be quantized. During inference, online Hadamard transform, state encoding / decoding, lookup table reconstruction of weights, and fusion matrix multiplication allow compressed weights to directly participate in forward computation, reducing the intermediate expansion and storage requirements of the complete dequantized weight matrix. Attached Figure Description
[0026] The present invention will now be described in detail with reference to specific embodiments and accompanying drawings, wherein: Figure 1 This is a schematic diagram illustrating the process of activation quantization training, bilateral matrix acquisition, block feedback quantization, state encoding storage, and online fusion inference of the video visual self-attention encoder of the present invention.
[0027] Figure 2 A comparison chart of Top-1 and Top-5 quantization calibrators for different quantization configurations in the Something-Something-V2 video classification task.
[0028] Figure 3 This is a comparison chart of memory usage and inference speed for the original floating-point model, the GPTQ quantization model, and the quantization model of this invention. Detailed Implementation
[0029] The following is combined Figure 1 The technical content of this application is clearly and completely described below with specific embodiments. It should be understood that the following embodiments are used to illustrate the technical solution of this application and are not intended to limit the scope of protection of this application. Based on their understanding of the technical concept of this application, those skilled in the art can select the appropriate implementation configuration according to the actual model structure, data processing conditions, and computing resources. Unless otherwise explicitly stated, the model training, data reading, tensor operation, and program storage and calling methods used in this embodiment can all be implemented using existing computer hardware and software technologies in the art.
[0030] This embodiment relates to a quantization and inference method for a video visual self-attention encoder. This method is applicable to neural network models that use a visual Transformer to encode features from video frame sequences, and is particularly suitable for scenarios requiring extremely low-bit quantization of model weights and intermediate activation values. The method can be executed by a computing device equipped with a processor and memory. The processor calls the corresponding program in memory to complete video sample reading, activation quantization training, weight gradient acquisition, bilateral matrix processing, weight quantization encoding, and quantization model inference. Quantization training and actual inference can be executed on the computing device according to the corresponding computational tasks.
[0031] Example 1 This embodiment provides a quantization and inference method for a video visual self-attention encoder, using the V-JEPA2 video visual encoder as a specific implementation. The method first quantizes and trains the model's activation values, obtaining a four-bit activation quantization model while maintaining floating-point weights. Then, based on the quantized activation values, weight gradients are acquired, and two-sided error feedback rounding is performed using gradient statistics from both the input and output sides, converting the weights of the linear layers to be quantized within the encoder into a two-bit trellis encoding representation. Finally, the quantized weights are compressed and stored, and during inference, video feature encoding is completed through online transformation, trellis decoding, and fusion matrix multiplication.
[0032] Figure 1 The first flowchart corresponds to determining the linear layer to be quantized, activating the quantizer deployment, and training. The second flowchart corresponds to cross-entropy self-distillation gradient acquisition. The third flowchart corresponds to randomized symbolic Hadamard transform and block decomposition. The fourth flowchart corresponds to anti-angle two-sided feedback and lattice state encoding. The fifth flowchart corresponds to encoding packaging and online fusion inference. The arrows between the flowcharts indicate that the data generated in the previous stage is used in the next stage.
[0033] In this embodiment, the four-bit activation quantization model refers to a model formed by setting a four-bit activation quantizer at the output of the linear layer of the encoder and at the operand position of the attention matrix multiplication, and determining the quantizer parameters through training. The two-sided matrix refers to the input-side matrix and the output-side matrix obtained by taking the sample mean of the product of the transpose and gradient of the video-by-video weight gradient and the product of the gradient and its transpose. Two-sided error feedback refers to simultaneously correcting the current quantization target using the input-side feedback factor, the output-side feedback factor, and the error of the quantized blocks when determining the quantization result of the current weight block. Graph encoding refers to an encoding method that represents quantized weights as continuous state paths using a state transition graph with binary displacement state transition relationships. The fusion kernel refers to a computational program that completes online decoding, numerical reconstruction, and matrix multiplication of compressed weights in the same computation process, avoiding the generation of a complete intermediate inverse quantization weight buffer.
[0034] This embodiment uses the V-JEPA2 ViT-L video visual encoder, specifically configured with vitl-fpc16-256-ssv2. The model comprises 24 encoder layers with a hidden feature dimension of 1024. Each encoder layer has 16 attention heads, each with a feature dimension of 64. Attention calculation employs rotational position encoding, which organizes positional frequency information according to the time, height, and width dimensions corresponding to the video features.
[0035] After video preprocessing, the input video is converted into a video word sequence by a 3D convolutional block embedding layer. Specifically, the model uses a temporal block containing 2 frames and a spatial size of... Image blocks are used for feature embedding. For the video input configuration used in this embodiment, each video segment generates 2048 video terms, each term corresponding to a 1024-dimensional hidden feature. The video terms are processed according to the computational order of each layer of the encoder, and after encoding, a video feature representation is formed.
[0036] In this embodiment, the query projection layer, key projection layer, value projection layer, attention output projection layer of each layer in the encoder, as well as the two fully connected layers in the multilayer perceptron, are used as linear layers to be quantized. Each encoder layer contains 6 linear layers to be quantized, and the 24 encoder layers contain a total of 144 linear layers to be quantized.
[0037] The weight matrices of the query projection layer, key projection layer, value projection layer, and attention output projection layer have the following dimensions: The first fully connected layer in the multilayer perceptron is used to expand the feature dimension from 1024 to 4096, and its weight matrix size is... The second fully connected layer is used to restore the feature dimension from 4096 to 1024, and its weight matrix size is... The matrix dimensions mentioned above are all represented with the number of output channels first, followed by the number of input channels.
[0038] For the aforementioned 144 linear layers, this embodiment employs a process of first performing activation quantization training and then weight quantization. During the activation quantization training phase, the weights of the linear layers to be quantized maintain a 32-bit floating-point representation and participate in training along with the activation quantizer parameters. In the subsequent weight quantization phase, a two-sided matrix is generated using the model trained by activation quantization, and then the weights of the linear layers to be quantized are encoded into a two-bit representation per weight.
[0039] For the 3D convolutional block embedding layer, predictor, attention pooler and classifier, the two-bit graph weight quantization is not performed in this embodiment; in the deployment configuration of this embodiment, the weights of these modules are stored in sixteen-bit floating-point representation.
[0040] like Figure 1 As shown, this embodiment sequentially executes five processing stages: activation quantization training, bilateral matrix acquisition, transform domain weight block feedback quantization, state encoding and storage, and online fusion inference. Figure 1 The five process frames in the diagram correspond to the five stages described below, with each stage connected via model weights, activation quantization parameters, two-sided matrices, feedback factors, and state-coded data. Each process stage follows... Figure 1 The steps shown will be executed sequentially.
[0041] First, the pre-trained video visual encoder and video samples for quantization processing are obtained. These video samples can be selected from the SSv2 video dataset. During data loading, video frames are read using a video decoding program, and corresponding frame images are extracted according to uniformly distributed video sampling positions. The video frames are converted into input data that the V-JEPA2 model can accept through a video processing program, and then formed into video word sequences through a block embedding layer.
[0042] Before quantization training, the linear layers to be quantized and the attention calculation paths in the model are processed to set the corresponding activation quantizers.
[0043] Specifically, a four-bit activation quantizer is set after the query projection layer, key projection layer, value projection layer, and attention output projection layer. In the multilayer perceptron, a four-bit activation quantizer is set between the first fully connected layer and the GELU activation function, and a four-bit activation quantizer is set at the output position of the second fully connected layer.
[0044] The activation quantizer at the output position of the aforementioned linear layer employs a channel-by-channel quantization method. Channel-by-channel quantization refers to setting quantization parameters for each output channel individually, enabling different output channels to perform quantization according to their respective activation value distributions.
[0045] For matrix multiplication in attention computation, this embodiment also sets up a per-tensor 4-bit activation quantizer. Per-tensor quantization refers to using the same set of quantization parameters for an operand tensor.
[0046] In the matrix multiplication of the query vector and the transpose of the key vector, tensor-wise quantizers are set for both the query operand and the key operand. Similarly, in the matrix multiplication of the attention weights and the value vector, tensor-wise quantizers are set for both the attention weight operand and the value vector operand. This ensures that both operands involved in the matrix multiplication during attention computation undergo corresponding activation quantization.
[0047] To ensure that the processing relationship of attention calculation after setting the quantizer corresponds to the original model, this embodiment performs explicit calculation of the attention path.
[0048] Specifically, video terms first pass through a query projection layer, a key projection layer, and a value projection layer, respectively, and are then processed by their respective four-bit activation quantizers. The quantized results are then tensor rearranged according to the attention head organization. Rotational position encoding is performed on the rearranged query and key vectors, followed by matrix multiplication of the transposes of the query and key vectors, and attention scaling is applied to the result.
[0049] The two operands of the matrix multiplication above are processed by their respective tensor-wise 4-bit activation quantizers. The scaled attention result is then subjected to Softmax normalization with 32-bit floating-point precision to obtain the attention weights.
[0050] Next, the attention weights and value vectors are processed by their respective tensor-wise 4-bit activation quantizers, and then a matrix multiplication is performed between them. The matrix multiplication result passes through the attention output projection layer and is processed by the channel-wise 4-bit activation quantizer after the projection layer.
[0051] By using the above calculation order, quantization positions can be set at the query, key-value projection, and attention matrix multiplication operands, while maintaining the correspondence between rotation position encoding, attention scaling, and Softmax normalization in the original calculation path.
[0052] After setting up the four-bit activation quantizer, each quantizer is initialized and trained.
[0053] The four-bit activation quantizer used in this embodiment employs a uniform quantization method that includes learnable scaling parameters and learnable offset parameters. For the input activation value, quantization is performed according to the following formula: .
[0054] in, This indicates the input activation value received by the quantizer. This represents the activation value obtained after quantization mapping. This represents the learnable scaling parameter. This represents the learnable offset parameter. Indicates the lower bound of the quantization index. This indicates the upper limit of the quantization index.
[0055] For the signed four-bit quantizer used in this embodiment, , Here, round represents the rounding operation, and clamp represents restricting the rounded result to the given quantization index range.
[0056] In the quantization process described above, the input activation value is first adjusted using the offset parameter, and then the adjusted activation value is mapped to the quantization index range based on the scaling parameter. After rounding and truncation, the quantized numerical representation is then restored using the scaling and offset parameters.
[0057] The per-channel quantizer maintains scaling and offset parameters for each output channel separately. The per-tensor quantizer, on the other hand, applies a corresponding set of scaling and offset parameters to the entire operand tensor. Both quantizers employ corresponding parameter organization methods, using a four-bit quantization index to form the quantized activation value.
[0058] Since the quantization process includes a rounding operation, and the rounding operation itself cannot be directly propagated according to the gradient of a normal continuous function, this embodiment uses a pass-through estimator to estimate the gradient of the rounding operation.
[0059] Specifically, in the forward computation, the quantized activation value is obtained according to the above quantization expression; in the backpropagation process, the corresponding gradient is transmitted using the pass-through estimator, and the gradient of the quantization parameter is normalized according to the number of quantized elements and the upper limit of the quantization index, so that the scaling parameter and the offset parameter can participate in the optimization.
[0060] In one specific implementation, the scaling and offset parameters corresponding to different quantization bit widths can be organized into parameter tables. The parameter tables cover 2-bit to 8-bit quantization configurations, and the corresponding parameters are read according to the currently selected quantization bit width. In this embodiment, the parameter configuration corresponding to four bits is read when quantization training is activated.
[0061] Before formal training, the scaling and offset parameters of the quantizer are initialized.
[0062] Specifically, 32 calibration videos are selected and input into an encoder that retains 32-bit floating-point weights for forward computation. Activation samples are collected by activating quantizers set at each quantization position, and the distribution of activation values is statistically analyzed according to the quantization granularity of the quantizers.
[0063] For a channel-by-channel activated quantizer, initialization parameters can be selected using a quantile search method. Candidate quantile values include 0.999, 0.9999, and 0.99999.
[0064] For each output channel to be quantized, the corresponding activation quantization range is determined based on the aforementioned candidate quantization points, and the corresponding initial scaling and initial offset parameters are calculated. The acquired activation samples are quantized using each candidate parameter, and the L2 norm error of the activation values before and after quantization is calculated. The candidate parameter with the smaller corresponding error is selected as the initialization parameter for that channel.
[0065] In this way, the activation quantizer can use the actual activation value distribution generated by the calibration video to determine the initial quantization parameters, providing initial parameter values for subsequent training.
[0066] After the quantizer is initialized, the model is trained using activation quantization.
[0067] In this embodiment, activating quantization training not only adjusts the scaling and offset parameters of the quantizer, but also allows relevant parameters of the encoder backbone, attention pooler, and classifier to participate in optimization. During training, the weights of the linear layers to be quantized retain their 32-bit floating-point representation and are not subjected to 2-bit weight quantization.
[0068] In order to constrain the video feature representation during activation quantization training, this embodiment uses classification cross-entropy loss and feature distillation loss for training.
[0069] The classification cross-entropy loss is calculated based on the model's classification output and the corresponding class labels of the training samples. The feature distillation loss is used to constrain the feature differences between the activation quantization model and the corresponding floating-point model.
[0070] Specifically, the 32-bit floating-point base model without activation quantization is used as the teacher model, and the currently trained activated quantization model is used as the student model.
[0071] This embodiment uses a V-JEPA2 video encoder that does not set CLS category terms, but instead aggregates video term features through an attention pooler. Therefore, the output features of the attention pooler are selected as the feature distillation object.
[0072] The corresponding video samples are input into the teacher model and the student model respectively, and the feature vectors output by the attention poolers of both are extracted. The teacher model is used to provide reference features, and the student model is used to generate the quantized features that need to be adjusted.
[0073] Before calculating the feature distillation loss, principal component analysis is performed on the output features of the teacher model to obtain the corresponding principal component projection and whitening parameters.
[0074] In one specific implementation configuration, principal component analysis parameters are fitted using the output features of the teacher model corresponding to 1024 videos, and the first 256 principal components are selected. Based on these principal components and their corresponding whitening parameters, the output features of the teacher model and the student model are mapped to the same whitening feature subspace, respectively.
[0075] The mean squared error of the features of the teacher model and the student model in this subspace is calculated, and the obtained error is used as the feature distillation loss.
[0076] The joint training loss can be expressed as: .
[0077] in, This indicates the joint loss used in activation quantization training. Represents the classification cross-entropy loss. The weighting coefficients representing the characteristic distillation loss, This represents the mean square error function. This represents the principal component projection and whitening process fitted based on the teacher model features. This represents the output features of the attention pooler in the student model. This represents the output features of the attention pooler in the teacher model.
[0078] In this embodiment, .
[0079] By applying the feature distillation loss to the output of the attention pooler, the aggregated video features of the student model can be constrained by the corresponding features of the teacher model during quantizer training. Since the distillation error is calculated in the feature subspace after principal component whitening, the training process can be optimized for feature differences in this subspace.
[0080] In one specific training configuration, 1000 SSv2 training videos are used for one round of training, the optimizer is AdamW, and the learning rate is... No learning rate decay is set, and the effective batch size is 4 through gradient accumulation.
[0081] During training, the gradients of the model parameters and quantizer parameters are calculated based on the joint training loss, and then the corresponding parameters are updated by the optimizer.
[0082] After activating quantization training, save the encoder model parameters, the scaling and offset parameters of each quantizer, and the parameter configurations related to model recovery and subsequent training processing in this stage.
[0083] Through the above processing, an activation quantization model is obtained in which the linear layer to be quantized still retains a 32-bit floating-point weight, and the activation value at the predetermined position is mapped using a 4-bit quantization method. This model serves as the basis for subsequent 2-bit weight quantization calculations.
[0084] Next, the obtained activation quantization model is used to collect weight gradients, and input-side and output-side matrices are established.
[0085] During weight gradient acquisition, the four-bit activation quantization relationship established in the first stage is maintained, ensuring that the weight gradients originate from the forward computation after activation quantization. Therefore, the obtained gradient statistics can reflect the changes in the model output under the current activation quantization conditions.
[0086] In this embodiment, 128 calibration videos were selected from the training data. The calibration videos were selected using a fixed random seed and were distinguished from the model validation data.
[0087] When explaining the sources of error during quantization, let the weight matrix of a linear layer to be quantized in the original coordinate system be... The reconstructed weight matrix, after quantization and restoration to the original coordinate system, is: The corresponding input vector is The in-layer output error can be described using the following quadratic surrogate target: .
[0088] in, As a proxy target for the output error within the layer, This is the original floating-point weight matrix for this layer. To restore the quantized reconstructed weight matrix to the original coordinate system, Input column vectors for this layer. Let be a second-order matrix of the input vector. This means taking the expectation of the input sample. Represents the trace of a matrix, with superscript This indicates matrix transpose. This formula is used to describe the error target of traditional in-layer weight quantization; the two-sided feedback rounding in this embodiment actually uses the input-side matrix and output-side matrix calculated based on the self-distillation gradient as described below.
[0089] To acquire the weight gradients of the linear layer to be quantized, the computation of the corresponding linear layer is replaced with a linear operation that supports custom backpropagation. The custom backpropagation operation preserves the weight and bias processing relationship of the linear layer and obtains the corresponding weight gradients during the backpropagation process.
[0090] Specifically, the calibration video is input into the activation quantization model, and a forward computation including four-bit activation quantization is performed to obtain the classification prediction value output by the model.
[0091] A class probability distribution is formed based on the current model output, and the target class is then sampled from this distribution. A cross-entropy self-distillation loss is constructed using the sampled target class, and this loss is backpropagated.
[0092] This self-distillation process utilizes the model's own output distribution to generate target categories for gradient acquisition, rather than using an additional external teacher model to alter the current model's weight gradient calculation relationships.
[0093] The difference between the reference activation quantization model and the unquantized weight model for the model output distribution can also be expressed as: .
[0094] in, This indicates the input video data. This represents the mapping between model parameters and input video to determine the probability distribution of the output category. This represents the activation quantization model parameters used as a distribution reference. This represents the parameters of the model to be weighted and quantized. Represents relative entropy. This indicates the expectation of the input video. This indicates that the minimum value is sought using the parameters of the model to be quantized as optimization variables. This distribution objective is approximated during implementation by video-by-video gradient statistics generated from the following sampling cross-entropy, rather than by directly solving for the complete second-order matrix of all parameters.
[0095] By backpropagation, the weight gradients of the current calibration video at each linear layer to be quantized are obtained.
[0096] For one of the linear layers to be quantized, its weight matrix is defined as W, and the corresponding weight gradient is: .
[0097] in, Indicates the first The weight gradient matrix corresponding to each calibration video. Indicates the calibration video sequence number. This represents the cross-entropy self-distillation loss corresponding to the calibration video. This represents the weight matrix of the current linear layer. This represents the operation of calculating the gradient of the weight matrix. Wherein, Indicates the first The input activation matrix corresponding to each video in the current linear layer. This represents the loss gradient matrix at the output of the corresponding linear layer. This represents the weight gradient obtained by the matrix product of the two.
[0098] For a weight matrix that uses the number of output channels first and the number of input channels second, let it have... One output channel and If there are input channels, then the size of the weight gradient matrix is .in, Indicates the number of output channels. Indicates the number of input channels.
[0099] Based on the weight gradients corresponding to each calibration video, the input-side matrix and the output-side matrix are constructed respectively.
[0100] The input-side matrix is calculated according to the following formula: .
[0101] The output matrix is calculated according to the following formula: .
[0102] in, Represents the input-side matrix. Represents the output matrix. This indicates the number of calibration videos involved in the current matrix estimation. Indicates the first The weight gradient matrix corresponding to each calibration video, superscript Indicates matrix transpose. This indicates that the matrix results of the corresponding calibration video are accumulated.
[0103] In this embodiment, For those with One output channel and A linear layer with n input channels, the size of the input-side matrix is... The size of the output matrix is .
[0104] For second-order transformations of the model output distribution, the two-sided matrix can also be used to represent an approximation of the Kronecker form: .in, This represents the second-order curvature matrix corresponding to the output distribution loss. Indicates an approximate relationship. Represents the Kronecker product. and These are the output-side matrix and the input-side matrix, respectively. The above relationship only illustrates the approximate effect of the two-sided statistical matrices and does not consider them as the directly calculated complete Hessian matrices.
[0105] Both the input-side and output-side matrices described above are formed by the sample-by-sample weight gradients, belonging to the two-sided gradient statistical matrices used to approximate the changes in the model output distribution. This embodiment does not need to directly construct the complete Hessian matrix corresponding to all model parameters, but instead uses the product of the gradients on the input and output sides to form the two-sided information required for subsequent weight quantization.
[0106] During gradient acquisition, each video can be treated as an independent batch for forward and backward propagation.
[0107] When processing the first calibration video, the accumulated matrix result corresponding to the current linear layer is initialized. Subsequently, the gradient product matrices generated by each calibration video are accumulated. After processing the last calibration video, the accumulated result is divided by the number of calibration videos to obtain the corresponding input-side and output-side matrices.
[0108] In the specific implementation, the gradient statistics process uses 32-bit floating-point precision for matrix accumulation and disables automatic mixed precision. For the high-dimensional tensors involved in the weight gradient calculation, the corresponding high-order tensor operations can be split into batch matrix multiplications to control the scale of intermediate data in a single calculation.
[0109] Since the V-JEPA2 model contains multiple encoder layers, a significant amount of computational results need to be stored during backpropagation. Therefore, gradient checkpointing can be used to reduce the intermediate activation storage required for backpropagation. Gradient checkpointing is used to recalculate some forward intermediate results during backpropagation, thereby reducing the number of intermediate tensors retained simultaneously.
[0110] After obtaining the input and output matrices for each linear layer, these matrices can be stored in the central processing unit's memory. When performing weight quantization for a specific linear layer, the required matrix data for that linear layer is then loaded into the graphics processor.
[0111] After completing the weight quantization of the current linear layer, its corresponding intermediate matrix and temporary computation data are released before processing subsequent linear layers. This layer-by-layer processing method avoids the long-term simultaneous occupation of graphics processor storage space by both sides of the matrices of all linear layers during the weight quantization process.
[0112] After completing the acquisition of the two-sided matrix, a randomized symbolic Hadamard transform is performed on the weights of the linear layer to be quantized and the corresponding input-side and output-side matrices.
[0113] The random symbolic Hadamard transform described in this embodiment refers to combining the random symbolic transform with the normalized Hadamard transform to perform an invertible numerical transformation on the matrix to be processed. This transformation changes the distribution of matrix elements and maintains the correspondence between the weight matrix and the two-sided matrix in the transform domain.
[0114] Specifically, for each linear layer to be quantized, an input-side random symbol vector and an output-side random symbol vector are generated. The lengths of the two random symbol vectors correspond to the number of input channels and the number of output channels of the current linear layer, respectively.
[0115] The elements of the random symbol vector take values of or .in, Indicates that the sign is retained at the corresponding position. This indicates the inversion sign at the corresponding position.
[0116] To ensure consistent transformations between quantization and deployment processes, each linear layer to be quantized uses a fixed random seed to generate a corresponding random symbol vector. This random symbol vector remains consistent throughout the quantization of the current linear layer and subsequent inference processes.
[0117] When performing a transformation on the weight matrix, the signs of the elements in the corresponding directions of the weight matrix are first adjusted according to the random sign vectors on the input and output sides, and then the corresponding normalized Hadamard transform is performed along the input and output channel directions.
[0118] For the input and output matrices, random signs and Hadamard conjugate transformations consistent with the directions of the weight matrices are applied. This ensures that the transformed weight matrix and the two-sided matrix are in corresponding computational coordinates.
[0119] The Hadamard transform can be implemented using fast butterfly operations. For the corresponding input and output channels of 1024 and 4096 dimensions in this embodiment, the Hadamard transform operations can be organized according to the integer powers of two dimensions.
[0120] During the transformation process, butterfly operations are used to perform addition and subtraction on paired data, and normalization is performed according to the transformation dimension. The random sign transformation and Hadamard transformation together adjust the numerical distribution in the weight matrix, so that larger values that were originally concentrated in local channels can be redistributed in the transformation domain.
[0121] In this embodiment, the above transformation is referred to as a distributed transformation process, the purpose of which is to provide a weight representation adapted to the quantizer for subsequent two-bit lattice quantization. This process applies to both the weights and the two-sided matrix, so the subsequent feedback rounding calculation uses the two-sided matrix corresponding to the transformed weights, rather than the original untransformed matrix.
[0122] To clarify the transformation correspondence between the weights and the two-sided matrix, let and These are random symbol vectors for the input and output sides, respectively. , Let be the corresponding diagonal sign matrix. , .in, , These represent the number of input and output channels, respectively. This means placing the vector elements on the diagonal to form a diagonal matrix. , These are the normalized Hadamard matrices for the corresponding dimensions. and These are the orthogonal transformation matrices for the input and output sides, respectively.
[0123] The transformation relationship between the weights and the matrices on both sides can be written as: , , .in, The transformation domain weight matrix, This is the original floating-point weight matrix. and These are the transformed input-side matrix and output-side matrix, respectively. and The gradient statistics matrix before transformation is shown in the superscript. This indicates the matrix transpose.
[0124] After the transformation is completed, the input and output matrices are numerically normalized and decomposed into blocks.
[0125] Specifically, the matrix can be normalized using the mean of its diagonal elements at 64-bit floating-point precision. The normalized matrix is then used for subsequent block decomposition.
[0126] This embodiment uses blocks of size sixteen. Decomposition, that is, representing the matrix to be decomposed as a unit lower triangular factor. Block diagonal matrix and The product, superscript This represents the matrix transpose; the input-side unit lower triangular feedback factor, the output-side unit lower triangular feedback factor, and their respective block diagonal parts are obtained using block Cholesky operations.
[0127] Before performing block decomposition, let the mean of the diagonal elements of the transformed input-side matrix and output-side matrix be respectively... and The corresponding normalized matrix is and .in, , The corresponding diagonal mean. , These are the normalized two-sided matrices. , These are the matrices on both sides of the aforementioned transformation domain; the normalization is performed with 64-bit floating-point precision.
[0128] The block decomposition relation of the normalized matrix is written as: , .in, and These are the unit lower triangular input-side feedback factor and output-side feedback factor, respectively. and These are the corresponding block diagonal matrices, with superscripts... This indicates the matrix transpose.
[0129] The lower triangular factor on the input side and the lower triangular factor on the output side are used to describe the error feedback relationship of the processed weighted blocks in the input and output directions, respectively.
[0130] If a decomposition fails or produces a non-numerical result during the block decomposition process, a regularization factor is added to the diagonal elements of the matrix to be decomposed, and the decomposition is re-executed.
[0131] In this embodiment, the regularization increment is Diagonal regularization can provide conditions for recalculating matrix decompositions that exhibit numerical anomalies.
[0132] After the two-sided matrix is decomposed, the corresponding input-side feedback factor and output-side feedback factor are used to perform weighted block two-sided error feedback quantization.
[0133] Unlike the approach of determining the quantization result solely based on the current weight value, this embodiment also considers the errors generated by previously quantized weight blocks when quantizing the current weight block.
[0134] Specifically, the weight matrix, after randomized symbolic Hadamard transform, is divided into multiple weight blocks. For each linear layer to be quantized, this embodiment uses a weight block of size [size missing]. Weighted blocks.
[0135] Each weight block is processed in anti-diagonal order according to the block matrix. Before processing the current block, the blocks that have already been quantized have corresponding reconstruction weight values and quantization errors. These errors form an error matrix according to the corresponding block positions and participate in the quantization target calculation of the current block.
[0136] The two-sided error feedback relationship used in this embodiment is expressed as follows: .
[0137] in, This represents the weight matrix to be quantized after undergoing a randomized Hadamard transform. This represents the weight matrix obtained after two-sided error feedback and quantization processing. This indicates a two-bit weighted quantization operation performed using a state transition trellis. This represents the quantization error matrix generated by the weighted blocks that have completed quantization. This represents the lower triangular feedback factor corresponding to the input-side matrix. The superscript indicates the lower triangular feedback factor corresponding to the output matrix. This indicates the matrix transpose.
[0138] In the above expression, This represents a cross-feedback term that represents the combined effect of the input and output sides. Indicates the output-side feedback term. This indicates the input-side feedback item.
[0139] For the current weight block to be quantized, the above feedback term is first calculated based on the error matrix formed by the quantized blocks and the corresponding feedback factor. Then, the feedback result is combined with the original transform domain weights of the current weight block to form the quantization target of the current block.
[0140] The quantizer determines the corresponding two-bit encoding result based on the quantization target and incorporates the deviation between the reconstruction result of the current block and the quantization target into the subsequent error feedback processing.
[0141] Through this processing relationship, the quantization target of subsequent weight blocks is affected by the previous quantization error, enabling the weight quantization process to adjust the error using the information provided by the input and output matrices.
[0142] This embodiment processes the weight matrix in anti-diagonal block order. For multiple weight blocks on the same anti-diagonal line, since the results of the previous blocks required for their feedback calculation have been determined, the corresponding blocks can be organized into a batch and joint quantization can be performed.
[0143] Under the condition of using the Kronecker approximation for the two-sided matrix, the structural zero-power of the two-sided feedback iteration has The theoretical upper limit, of which and These represent the number of output channels and the number of input channels of the current weight matrix, respectively. The actual calculation follows the anti-angle weight block organization to complete the dependencies between quantized blocks; the theoretical upper limit is not used as the actual number of running steps.
[0144] This processing order enables batch computation of weighted blocks that meet the conditions for parallel processing, while respecting the dependencies between the data blocks.
[0145] After determining the quantization target of the current weight block, two-bit quantization encoding is performed using the state transition trellis.
[0146] This embodiment employs a displacement-based state transition lattice. A displacement-based state transition lattice is a lattice structure that connects adjacent states according to a predetermined binary displacement relationship. Each node in the lattice corresponds to a binary state, and the quantized encoding sequence is represented by the transition relationship between nodes.
[0147] Specifically, the trellis state is represented by 16 bits of binary data, corresponding to 65,536 states. Each state transition introduces 4 bits of new state information, which correspond to the encoding of 2 weights, so each weight is assigned two bits of encoded information.
[0148] The state transition satisfies the relationship that the high 12 bits of the successor state are the same as the low 12 bits of the predecessor state. For a given predecessor state, the newly introduced 4 bits of information correspond to 16 candidate successor states.
[0149] Through the aforementioned state transition constraints, adjacent states of the lattice graph have a definite binary displacement relationship, and the successor state can be determined based on the current state and the newly introduced state information.
[0150] When performing grid quantization on the weighted blocks, the current The weight values in the weighted blocks are organized into a sequence to be quantized according to a predetermined order. The Viterbi algorithm is used to search for state paths in the state transition trellis, such that the deviation between the reconstructed weight values corresponding to the state path and the weight sequence to be quantized conforms to the quantization optimization objective.
[0151] For including A displacement-based lattice diagram of bit state information, assuming Let be the number of state transition steps in the weight sequence to be quantized. Then, the time complexity of the Viterbi dynamic programming can be written as: .in, This is the order notation for the algorithm's complexity. For the number of bits in the trellis state, The number of encoding steps is the sequence number. For the fixed lattice transition configuration in this embodiment, the number of encoding steps increases linearly with the length of the weight sequence.
[0152] The Viterbi algorithm calculates candidate paths step by step according to the state transition relationship and retains the path information that satisfies the current quantization objective in each state. After processing the entire weight sequence, the state encoding sequence corresponding to the block is obtained based on the determined state path.
[0153] To handle the initial state and encoding connection of the state sequence, this embodiment uses two Viterbi passes.
[0154] First, the sequence of weights to be quantized is cyclically shifted, with the shift amount determined by half the length of the lattice used. Then, the shifted sequence undergoes a first pass of unconstrained Viterbi optimization to obtain the corresponding state path.
[0155] Intermediate states are extracted from the first optimization path and used as state constraints for subsequent optimizations. Then, the weight sequence to be quantized is restored to its original order, and a second Viterbi optimization is performed according to the extracted state constraints.
[0156] The final trellis state path for the current block is obtained through two optimization passes, and the state encoding sequence is determined accordingly. This processing method is used to reduce the additional overhead caused by the initial state processing during the encoding process to the overall low-bit representation.
[0157] The grid state is also used to determine the corresponding weight reconstruction value.
[0158] This embodiment uses a weighted reconstruction lookup table to establish a mapping relationship between the grid state and the reconstructed weight values. The weighted reconstruction lookup table contains 512 entries, and each entry stores 2 sixteen-bit floating-point reconstructed values.
[0159] The reconstructed values in the lookup table can be determined by clustering two-dimensional Gaussian distribution samples. Specifically, a clustering algorithm is used to process the two-dimensional samples, and the obtained cluster centers are used as the corresponding reconstructed values, which are then adjusted according to the numerical scale used by the lattice quantizer.
[0160] During quantization and reasoning, the lattice state is mapped to a lookup table index via a predefined hash relation. This hash relation is represented as: .
[0161] in, Indicates the grid state number, This represents the lookup table index obtained through a hash relation. This indicates a bitwise right shift of a binary integer. This indicates a binary bitwise AND operation.
[0162] During the calculation, the corresponding integer product is first formed according to the status number. Then, the integer product is right-shifted by six bits in binary and a bitwise AND operation is performed with 511 as the mask. The lower nine bits are retained to obtain the lookup table index from zero to 511.
[0163] The two corresponding reconstruction values are read according to the lookup table index, and the required symbol processing is determined according to the value of the corresponding symbol bit in the state code, so as to obtain the weight reconstruction result corresponding to the grid state.
[0164] In this embodiment, the lookup table and state hashing together constitute the trellis weight reconstruction method. The trellis encoding sequence is used to store the compressed weight information, and the lookup table is used to restore the state encoding to the weight values required for matrix multiplication.
[0165] To adapt to the weight value range of different linear layers, a corresponding weight scaling factor can also be determined for each linear layer to be quantized.
[0166] The weight scaling factor calculation relationship used in this embodiment is as follows: .
[0167] in, This represents the scaling factor of the weights of the current linear layer to be quantized. This represents the weighted data after a randomized Hadamard transform. This represents the set of reconstructed values corresponding to the weight reconstruction lookup table. This represents the root mean square calculation function, and 0.9 is the preset scale adjustment coefficient used in this embodiment.
[0168] During the quantization stage, the weight scaling factor is determined based on the root mean square of the transformed weights and the root mean square of the reconstructed values from the lookup table, so that the reconstructed values of the grid correspond to the numerical scale of the current weight matrix.
[0169] Once the weight scaling factor is determined, it can be folded into the output random symbol vector of the current linear layer. The folded vector contains both output symbol transformation information and weight scaling information, and participates in the output transformation during the inference phase, thus eliminating the need for a separate weight matrix scaling operation for this scaling factor.
[0170] After the weight blocks of each linear layer to be quantized have completed bilateral feedback quantization and lattice encoding, the resulting state encoding sequence is packaged and stored.
[0171] Specifically, the state encoding information of each block is organized into a continuous compressed bit stream according to a predetermined storage order and stored in integer storage units. Each linear layer to be quantized stores its compressed state encoding data, weight reconstruction lookup table, input-side random symbol vector, output-side random symbol vector containing weight scaling information, and corresponding bias parameters.
[0172] The compressed state-encoded data is used to recover the two-bit weight representation, the weight reconstruction lookup table is used to obtain the reconstructed value based on the state index, the random symbol vector is used for subsequent online Hadamard transform and output scaling processing, and the bias parameter is used to recover the output calculation relationship of the linear layer.
[0173] In this embodiment, the weight reconstruction lookup table and corresponding auxiliary vectors can be stored in 16-bit floating-point format. The grid state encoding information is stored in compressed integer data form, thus eliminating the need to store the complete 32-bit floating-point value for each weight to be quantized in the model file.
[0174] For 3D convolutional block embedding layers, predictors, attention poolers, and classifiers that have not undergone two-bit weight quantization, the corresponding weights can be stored in sixteen-bit floating-point format according to the deployment configuration of this embodiment.
[0175] At this point, we have obtained model deployment data that includes the grid compression weights and corresponding quantization parameters.
[0176] During the model inference phase, the quantization model configuration and the saved weight encoding data are loaded first, and the video to be processed is read.
[0177] After undergoing corresponding video preprocessing and block embedding processes, the video to be processed forms a video word sequence. The video words then enter each encoder layer, where they are sequentially processed by attention calculation and multilayer perceptron calculation.
[0178] For positions where the activation quantizer has been set, a four-bit quantization mapping is performed on the corresponding activation value based on the scaling and offset parameters obtained in the first stage of training. The activation value obtained from the quantization mapping participates in subsequent processing according to its corresponding calculation position.
[0179] When executing a linear layer that has undergone two-bit lattice quantization, the complete high-precision weight matrix is not read directly. Instead, the weight blocks required for the current calculation are restored based on the already saved compressed state encoded data.
[0180] Specifically, the current linear layer receives the input activation values obtained from the previous stage. The input activation values undergo input-side random symbol processing consistent with the quantization stage, followed by the corresponding online Hadamard transform.
[0181] Online Hadamard transformation refers to performing the corresponding transformation on the input activation values during inference, rather than pre-applying the transformation to unknown inference inputs. This online transformation is coordinated with the transformation relationships used on weights and bilateral matrices during the quantization phase.
[0182] After the input-side transformation is completed, the corresponding activation data is sent to the fusion kernel. The fusion kernel can be implemented using the Triton program.
[0183] In this embodiment, the fusion kernel performs weight state decoding and matrix multiplication in the same computation process. The fusion kernel accesses the compressed bitstream according to the weight block organization of the current linear layer and reads the state-encoded data required for the current computation.
[0184] For a weight block to be computed, the fusion kernel first extracts the encoded information from the corresponding integer storage unit and restores the state of the grid according to the state transition rules of the shifted grid.
[0185] When information about a state spans adjacent integer storage units, the complete state can be obtained by reading the adjacent storage units and performing corresponding shift, mask, and concatenation operations. For compressed data represented as signed 16-bit integers, the corresponding unsigned bit mode can be used when performing bit operations to avoid sign extension affecting state recovery.
[0186] After restoring the grid state, the fusion kernel determines the lookup table index according to the predetermined state hash relationship, reads the corresponding reconstruction value from the weight reconstruction lookup table, and obtains the reconstruction result of the current weight block according to the symbol relationship determined by the state encoding.
[0187] The reconstructed weight blocks do not need to be written to the complete dequantized weight matrix first. The fusion kernel can retain the reconstruction result of the current block in a register and use it directly for subsequent matrix multiplications.
[0188] In one specific implementation, the fusion kernel follows... The weight blocks are reconstructed. For the current input activation block, matrix multiplication is called to multiply the transformed activation value with the reconstructed weight block, and the corresponding results are accumulated.
[0189] The fusion calculation in this embodiment can perform matrix multiplication using activation values and reconstructed weight values represented by 16-bit floating-point numbers, and accumulate using 32-bit floating-point precision.
[0190] For the current linear layer, the fusion kernel processes all weight blocks sequentially according to the input channel direction. During each processing, the corresponding compressed state data is read, the current weight block is restored, and matrix multiplication is performed with the corresponding activated block.
[0191] Once the current weight block is used, its reconstruction result can be overwritten by subsequent calculations, without needing to store the complete high-precision weight matrix for a long time. For other weight blocks in the same linear layer, the above state extraction, hash table lookup, weight reconstruction, and fusion matrix multiplication processes are repeated.
[0192] Once all input channels of the current linear layer have been processed in blocks, the corresponding matrix multiplication and accumulation results are obtained.
[0193] Subsequently, the output-side Hadamard transformation is performed on the matrix multiplication result, and the corresponding sign and scale processing is performed based on the output-side random sign vector with the already folded weight scaling factor.
[0194] For linear layers with bias parameters, the corresponding bias parameters are added to the output. Depending on the data format requirements of subsequent network computations, the output can be converted to the appropriate data type and sent to the next computation layer.
[0195] Through the above-mentioned online transformation on the input side, lattice state decoding, matrix multiplication, and transformation on the output side, the numerical calculation relationship in the inference process corresponds to the weight transformation relationship used in the quantization stage.
[0196] The online Hadamard transform in this embodiment can be organized according to the actual input and output channel dimensions. For the corresponding linear layers of 1024 and 4096 dimensions in the encoder, the corresponding operations can be performed using a fast Hadamard transform program.
[0197] In the fused kernel, the state decoding results and the reconstructed weight blocks required for matrix multiplication can directly participate in the current computation, without having to generate a complete floating-point weight buffer covering the entire linear layer. Therefore, a direct data processing relationship is formed between weight compressed storage and online matrix operations.
[0198] In a specific fusion kernel configuration, a processing block configuration with 256 input activation data can be used, along with 8 parallel worker thread groups and 2 pipelined execution stages. The corresponding parameters control the parallel execution of the computation program and the data processing method, without altering the fundamental processing relationships of trellis weight encoding and two-sided error feedback quantization.
[0199] For different linear layers to be quantized in the same encoder layer, the above reasoning is performed according to their respective weight matrix shapes, compressed state encoded data, and auxiliary quantization parameters.
[0200] The query projection layer, key projection layer, and value projection layer generate the feature representations required for attention computation. The attention output projection layer projects the computation results of multi-head attention. The two fully connected layers in the multilayer perceptron sequentially perform feature dimension expansion and restoration.
[0201] Between each linear layer, necessary normalization, nonlinear activation, and residual processing are performed according to the original computational relationships of the encoder. For locations where an activation quantizer is set, quantization mapping is performed using the corresponding four-bit activation quantization parameters. For modules that do not use two-bit trellis weighted quantization, forward processing is performed according to their retained floating-point weights and corresponding calculation methods.
[0202] After all computations are completed in an encoder layer, the video lexical features output by that layer are passed to subsequent encoder layers. This process is repeated in sequence for each encoder layer until all 24 encoder layers have been processed.
[0203] Subsequently, the video lexical features output from the last encoder layer are input into the attention pooler. The attention pooler processes the video lexical features according to their corresponding feature aggregation relationships, obtaining the video feature representation for downstream tasks.
[0204] For the SSv2 video classification task used in this embodiment, the output of the attention pooler is fed into the classifier to obtain the corresponding video category prediction result.
[0205] This completes the entire processing from the input video to the inference result of the quantization encoder.
[0206] In this embodiment, the activation quantization training in the first stage and the weight quantization in the second stage are not independent processes.
[0207] The first stage trains the quantizer parameters so that the activation values at the positions to be quantized participate in the model's forward computation according to the four-bit quantization rule. The second stage collects the weight gradients under this activation quantization condition and forms the input-side matrix and output-side matrix based on these gradients.
[0208] Since the gradients corresponding to the two-sided matrices come from the activated quantized model, their statistical information has a different computational basis than the gradient information generated under unquantized activation conditions. Subsequent weight quantization uses these matrices to construct feedback factors, ensuring that the rounding of two-bit weights is based on the computational conditions of the current activated quantized model.
[0209] Furthermore, after the input-side matrix and output-side matrix undergo random symbolic Hadamard transformation and block decomposition corresponding to the weights, they can provide error feedback information on the input direction, output direction, and the combined effect of the two for weight quantization.
[0210] During lattice quantization, the quantization objective of the current weight block is simultaneously affected by the original transform domain weights and the errors of the quantized blocks. After determining this quantization objective, the Viterbi algorithm further obtains a two-bit weight encoding through a state transition lattice.
[0211] Through the above processing, the deviation generated by the quantization of two-bit weights can be adjusted by feedback under the condition of quantization activation. Compared with the processing method that determines the quantization result only based on the local weight values, this technical solution can use the bilateral gradient statistics related to the changes in model output to participate in weight rounding.
[0212] On the other hand, this embodiment does not take representing the weights as two-bit codes as the end point of the entire process, but further associates the obtained state codes with the weight reconstruction lookup table, online Hadamard transformation and fusion matrix multiplication.
[0213] After being encoded in a grid, the weights are stored as compressed state information. During inference, the encoded information is read in blocks according to the weights required for the actual calculation, and the corresponding weight values are directly restored in the fusion kernel.
[0214] This execution method enables the model to perform forward matrix operations while compressing the storage of weights, reducing the intermediate expansion and storage requirements of the complete floating-point weight matrix.
[0215] In the model deployment configuration used in this embodiment, the compressed model file size is 214 MB, while the uncompressed model file size is 1.4 GB. This change in file size corresponds to the storage configuration of converting the linear layer weights to be quantized by the encoder into two-bit trellis encoding, and retaining the floating-point weights for the unquantized modules.
[0216] The computational overhead in actual inference is also related to state encoding and decoding, online Hadamard transformation, matrix multiplication calculation, and the execution conditions of the computing device. Therefore, this embodiment achieves the deployment of the quantized model through weighted compressed storage and fusion computation, and does not directly replace the measurement results of inference speed or model accuracy with changes in model file size.
[0217] This embodiment first trains the activation quantizer, then uses the two-sided matrix under the quantization activation condition to perform two-bit weight quantization, and uses the quantization result for online fusion inference, forming a complete processing flow from model quantization training to compressed weight deployment.
[0218] Specifically, activation quantization training is used to determine the four-bit activation representation at a predetermined position in the model; two-sided matrix acquisition and error feedback are used to adjust the two-bit weight quantization process; lattice encoding is used to form a low-bit-width weight representation; and online decoding and fusion matrix multiplication are used to apply the compressed weights in actual inference.
[0219] The above processing steps are sequentially linked through quantized activation, two-sided feedback factors, weighted block error, and grid state encoding, so that the data generated at each stage can be used for subsequent processing, and finally the quantized encoder outputs the corresponding video features and classification results.
[0220] Thus, this embodiment completes the processing of the video visual self-attention encoder from a floating-point model to a two-bit weight, four-bit activation quantization model, and realizes the corresponding forward inference through online grid decoding and fusion matrix operations.
[0221] Example 2 This embodiment, based on Embodiment 1, further explains the parameter organization, quantization location, and activation quantization training process of the four-bit activation quantizer. This embodiment focuses on how to set the quantizer according to the activation value characteristics of different computation locations in the video visual encoder, and how to ensure that the quantization parameters obtained during training remain consistent during subsequent weight quantization and model inference.
[0222] The activation quantizers used in this embodiment include a channel-wise activation quantizer and a tensor-wise activation quantizer. Both quantizers employ uniform quantization with learnable scaling and learnable offset parameters, but the granularity of the parameters differs.
[0223] For the per-channel activation quantizer, the scaling and offset parameters are set separately for each output channel of the corresponding linear layer. Specifically, suppose a linear layer contains... There are 1 output channel, of which This indicates the number of output channels for the linear layer, and each output channel has its corresponding scaling and offset parameters.
[0224] In one specific implementation, the quantizer supports quantization configurations from 2 bits to 8 bits. For each output channel, the scaling parameters corresponding to different quantization bit widths can be organized into a format of size [size missing]. The parameter table is used, and the offset parameters are organized into parameter tables of the same size. The 7 in the parameter table indicates the 7 supported quantization bit width configurations. Indicates the number of output channels.
[0225] Once the quantization bit width is determined, the corresponding parameters from the parameter table are selected based on the current quantization bit width. For the four-bit active quantization used in this embodiment, the scaling and offset parameters corresponding to the four-bit configuration are read and used for the quantization processing of each output channel.
[0226] This parameter organization method allows the same quantizer program to call corresponding parameters according to different bit width configurations without changing the basic numerical mapping relationship of the quantizer. In the actual quantization training of this embodiment, the output of the linear layer to be quantized uses a four-bit parameter configuration.
[0227] For the per-tensor activation quantizer, a set of scaling and offset parameters is set for the entire operand tensor. This set of parameters applies to all elements in the current operand tensor.
[0228] In video visual self-attention encoders, the channel-wise activation quantizer is mainly set at the corresponding output positions of the query projection layer, key projection layer, value projection layer, attention output projection layer, and multilayer perceptron. The tensor-wise activation quantizer is mainly set at the operand positions of attention matrix multiplication.
[0229] Specifically, the query projection layer, key projection layer, and value projection layer generate the query features, key features, and value features required for attention computation, respectively. The features output by each projection layer first pass through the corresponding channel-wise four-bit activation quantizer before entering the subsequent attention computation.
[0230] For matrix multiplication between query features and key features, tensor-by-tensor quantizers are set at the two input positions of the matrix multiplication. Each quantizer determines the quantization result based on the numerical distribution of its corresponding operand, rather than having both operands share the same set of quantization parameters.
[0231] The result of attention matrix multiplication is scaled and Softmax normalized to generate attention weights. The Softmax normalization is performed with 32-bit floating-point precision.
[0232] In the matrix multiplication between the attention weights and the value features, tensor-wise four-bit activation quantization is also performed on both operands. Subsequently, the matrix multiplication result is fed into the attention output projection layer, and channel-wise four-bit quantization is performed on the output of the projection layer.
[0233] In a multilayer perceptron, the first fully connected layer expands the input feature dimension, and the second fully connected layer recovers the feature dimension. The output of the first fully connected layer is passed through a corresponding channel-wise 4-bit activation quantizer and then input into the GELU activation function; the output of the second fully connected layer is processed by another channel-wise 4-bit activation quantizer.
[0234] For the 3D convolutional block embedding layer, this embodiment uses a channel-wise 8-bit activation quantizer to process its output. This quantizer is not within the range of the subsequent 144 linear layers' 2-bit weight quantization, and its quantization bit width and parameter configuration are determined separately from the 4-bit activation quantizer inside the encoder.
[0235] During quantizer training, for a four-bit activation quantizer, the quantization index is first calculated based on the input activation value and the corresponding scaling and offset parameters, and then the quantized activation value is restored according to the corresponding parameters.
[0236] The quantization calculation adopts the uniform quantization expression described in Example 1. During backpropagation, a pass-through estimator is used for gradient estimation of the rounding operation.
[0237] For the gradient of the quantizer parameters, the following normalization coefficients can be used: .
[0238] in, This represents the normalization coefficient of the gradient of the quantizer parameters. This indicates the number of active elements currently participating in the quantization calculation. This represents the upper limit of the positive vectorization index for the current signed quantization configuration.
[0239] Under four-bit quantization configuration .
[0240] The normalization coefficient adjusts the gradient scale of the quantization parameters, allowing the scaling and offset parameters to participate in training along with the model weights. This normalization coefficient is used only for gradient processing of the quantization parameters and does not alter the numerical mapping relationship of the quantizer in the forward computation.
[0241] Before training, activation samples are first collected at each quantization location.
[0242] In this embodiment, 32 calibration videos are selected from the training videos. The calibration videos undergo frame sampling, video data conversion, and block embedding processing according to the model requirements, and are then input into an encoder with a pre-configured quantizer.
[0243] For each quantization location, the corresponding activation value is collected during the forward computation, and the corresponding sample set is determined according to the quantization granularity of the quantizer.
[0244] For a channel-wise quantizer, activation value statistics and parameter initialization are performed separately for each output channel. For a tensor-wise quantizer, the parameters are determined based on the activation value statistics of the entire operand tensor.
[0245] For a channel-by-channel quantizer, 0.999, 0.9999, and 0.99999 can be used as candidate quantization points in sequence. For each candidate quantization point, the corresponding quantization range is determined, and the candidate scaling parameter and candidate offset parameter are set accordingly.
[0246] Subsequently, the activated samples of the output channel are quantized using the corresponding candidate parameters, and the L2 error between the quantization result and the original activated samples is calculated. Different candidate parameters are compared according to the magnitude of the error, and the candidate parameter with the smaller error is selected as the initialization parameter for that channel.
[0247] After each quantizer has completed initialization, activation quantization training is performed.
[0248] This embodiment uses the V-JEPA2 model as the student model and the corresponding original 32-bit floating-point model as the teacher model. The student model performs 4-bit activation quantization at predetermined positions, while the teacher model maintains the corresponding floating-point computation path.
[0249] Since the V-JEPA2 model does not set CLS terms for classification aggregation, the model aggregates video term features through an attention pooler. Therefore, in this embodiment, the output of the attention pooler is selected as the feature distillation location.
[0250] Specifically, video samples for fitting principal component projections are input into the teacher model, and the output features of the teacher model's attention pooler are collected. Principal component analysis is then performed based on these output features to obtain the principal component projection directions and the corresponding whitening parameters.
[0251] In this embodiment, the output features of the teacher model corresponding to 1024 videos are used to fit the principal component analysis parameters, and the first 256 principal components are retained.
[0252] The whitening parameter is determined based on the feature statistics of the teacher model and is used together with the principal component projection parameter to process the output features of the teacher model and the student model.
[0253] For the same training video, the attention pooler output features of the teacher model and the student model are extracted separately and processed using the same principal component projection and whitening parameters. Then, the mean squared error between the two sets of whitening features is calculated.
[0254] The mean squared error is added to the classification cross-entropy loss of the student model to obtain the joint loss used for activation quantization training. In this embodiment, the weight coefficient of the feature distillation loss is 1.0.
[0255] During training, the scaling and offset parameters of the quantizer, as well as the corresponding parameters of the encoder backbone, attention pooler, and classifier, are jointly optimized. The weights of the linear layers to be quantized are still used in calculations and parameter updates in 32-bit floating-point format.
[0256] In one specific implementation configuration, the AdamW optimizer is used for one round of training, with 1000 training videos and a learning rate of [missing information]. And through gradient accumulation, a training batch with an effective batch size of 4 is formed.
[0257] After training is complete, save the model weights, quantizer scaling and offset parameters, and the corresponding training configuration to the model storage directory. Principal component analysis and whitening parameters can be saved together to restore the model and corresponding feature processing configuration for this stage.
[0258] When entering the subsequent two-bit weight quantization stage, the already trained model parameters and four-bit activation quantization parameters are read, so that the forward computation of the second stage still uses the activation quantization relationship determined in the first stage.
[0259] This embodiment maps the quantization granularity of different computation locations to specific activation distributions and combines attention pooling feature distillation, thus subjecting the activation quantization training process to constraints from both classification output and video aggregation features. The resulting activation quantization model can then be used as the input model for subsequent two-sided matrix acquisition and two-bit weight quantization.
[0260] Example 3 Based on Example 1, this embodiment further explains the execution methods of bilateral matrix acquisition, numerical normalization, block decomposition, and bilateral error feedback under quantized activation conditions.
[0261] This embodiment uses a V-JEPA2 encoder that has already completed four-bit activation quantization training as the base model for weight quantization. The 144 linear layers to be quantized inside the encoder still retain floating-point weights, and their corresponding activation quantizers have been loaded with scaling and offset parameters obtained in the first stage of training.
[0262] When performing dual-sided matrix acquisition, the model still completes the forward calculation according to the four-bit activation quantization configuration, without replacing the activation quantizer with the original floating-point calculation.
[0263] In order to obtain the weight gradient of each linear layer to be quantized, this embodiment uses a custom backpropagation calculation for the linear layers to be quantized.
[0264] Custom backpropagation calculations preserve the weights and biases of the linear layers, and obtain the weight gradient corresponding to the current video sample during backpropagation.
[0265] During the data collection process, 128 videos were selected from the SSv2 training data using a fixed random seed. The selected videos did not overlap with the model evaluation data.
[0266] After frame sampling and video preprocessing, each video is input to the encoder, which has already activated a four-bit quantizer.
[0267] The model performs forward computation to obtain the classification output corresponding to the current video. Based on the classification output, a category probability distribution is formed. The target category is sampled from this distribution, and then a cross-entropy self-distillation loss is constructed based on the target category.
[0268] The purpose of employing the aforementioned cross-entropy self-distillation loss is to correlate the weight gradient acquisition with the current model's output distribution. By sampling the model's own output distribution and calculating the negative logarithmic probability using the sampled categories, the expected form of which differs from the relative entropy target of the corresponding output distribution only by the entropy term determined by the reference distribution. Therefore, this sampling calculation method can be used to obtain gradient statistics for approximating changes in the output distribution.
[0269] The expected relationship of the above cross-entropy self-distillation can be written as: .in, This represents the class probability distribution of the activation quantization model used as a reference. This represents the class probability distribution of the weight model to be quantized. This represents the target category extracted from the reference probability distribution. This indicates the expected value of a sample from that category. Represents logarithmic operations. Represents relative entropy. This represents the entropy of the reference distribution, which remains unchanged for a fixed reference distribution regardless of the parameters of the model to be quantized.
[0270] This embodiment performs backpropagation independently for each video, enabling each video to form a corresponding weight gradient matrix, instead of directly replacing the video-by-video gradient with the merged gradient obtained after combining multiple videos into a batch.
[0271] For a certain having One output channel and A linear layer with n input channels to be quantized, where the weight gradient generated by the current video is G, where Indicates the number of output channels. Indicates the number of input channels. This represents the weight gradient matrix corresponding to the current video.
[0272] Based on this weight gradient, calculate the input-side gradient product matrix. and the gradient product matrix on the output side Among them, superscript This indicates the matrix transpose.
[0273] The size of the input-side gradient product matrix is The size of the output gradient product matrix is .
[0274] Before processing the first calibration video, the accumulated results of the two matrices of the current linear layer are cleared to zero. When processing each video, the resulting input-side gradient product matrix and output-side gradient product matrix are accumulated separately.
[0275] After all video processing is completed, the average of the two cumulative matrices is calculated based on the number of valid videos to obtain the input-side matrix and the output-side matrix.
[0276] The two-sided matrix used in this embodiment belongs to the empirical Fisher approximation information formed by the weight gradients. This process avoids directly constructing a complete second-order matrix containing all the model parameters, and instead uses the gradient statistics matrices of the input and output sides to represent the information in the two directions required for subsequent error feedback.
[0277] When performing weight gradient acquisition, gradient checkpointing can be used to control the amount of intermediate activation values stored.
[0278] Specifically, gradient checkpointing is enabled in model execution modes that support backpropagation, allowing some forward intermediate results to be recalculated during backpropagation.
[0279] In the V-JEPA2 model configuration used in this embodiment, the random inactivation probability is 0, and the random depth path is treated with identity. Therefore, under this configuration, using gradient checkpoints and the corresponding model execution mode does not require additional consideration of the issue of these random operations altering the forward output.
[0280] For the high-order tensor operations involved in forming the two-sided matrix of the weight gradient, they can be broken down into multiple batch matrix multiplications.
[0281] The matrix accumulation uses 32-bit floating-point precision, and automatic mixed precision is disabled. After completing the dual-sided matrix acquisition, the resulting matrix is transferred to the central processing unit's memory for storage.
[0282] During subsequent weight quantization, the two-sided matrix corresponding to the current linear layer is read sequentially from the central processing unit memory and sent to the graphics processor to complete the transformation, decomposition and feedback quantization.
[0283] For each linear layer to be quantized, the original weight matrix, input matrix, and output matrix of that layer are first obtained.
[0284] Subsequently, random symbol vectors are generated according to the number of input and output channels of the linear layer. Different linear layers can use their own corresponding fixed random seeds to ensure that the same linear layer uses the same transformation configuration during quantization and deployment.
[0285] By combining the random symbol vector with the normalized Hadamard matrix, the input-side transform and output-side transform of the current linear layer are constructed.
[0286] The weight matrix undergoes a two-sided transformation on both the input and output sides, and simultaneously performs a conjugate transformation on the input and output matrices corresponding to the weights.
[0287] For the input-side matrix, its transformation uses the correspondence determined by the input-side random symbols and the Hadamard transform. For the output-side matrix, its transformation uses the correspondence determined by the output-side random symbols and the Hadamard transform.
[0288] By maintaining the correspondence between the weights and the transformation of the two-sided matrix, the feedback factor calculated subsequently based on the two-sided matrix can be applied to the weight data in the same transformation domain.
[0289] After completing the corresponding transformation, the input matrix and the output matrix are numerically normalized respectively.
[0290] In one specific implementation, the matrix is first converted into 64-bit floating-point data, and then normalized based on the mean of its diagonal elements. The normalized matrix is then used for block decomposition.
[0291] This embodiment uses blocks of size sixteen. Decomposition, that is, representing the matrix to be decomposed as a unit lower triangular factor. Block diagonal matrix and The product, superscript This represents the matrix transpose; the unit lower triangular feedback factor and the corresponding block diagonal part are obtained through block Cholesky calculation.
[0292] If a calculation failure or non-numerical result occurs during the decomposition process, the diagonal elements of the matrix are corrected according to the predetermined regularization increment, and the decomposition is re-executed.
[0293] The regularization increment used in this embodiment is .
[0294] If a decomposition fails, the regularization amount can be increased on the diagonal part of the matrix to be decomposed, and the decomposition can be retried. If the decomposition still cannot be completed, numerical regularization and decomposition retry should continue according to the same incremental processing relationship.
[0295] After decomposing the two matrices, the input-side feedback factor and the output-side feedback factor are obtained respectively.
[0296] In this embodiment, the weight matrix is arranged according to size... The processing is performed in blocks. Two-sided feedback quantization uses an anti-diagonal block order, starting with the block that already has the conditions for feedback calculation and progressively processing subsequent weight blocks.
[0297] For the current block, read the quantized error associated with that block and form a feedback correction based on the input-side feedback factor and the output-side feedback factor.
[0298] Feedback correction includes single-way feedback on the input side, single-way feedback on the output side, and cross-feedback where the input and output sides work together.
[0299] Among them, the input-side single-way feedback is used to reflect the influence of the quantized error along the input channel direction on the current quantization target, the output-side single-way feedback is used to reflect the influence of the quantized error along the output channel direction on the current quantization target, and the cross-feedback is used to reflect the correction produced by the combined effect of the feedback factors in both directions.
[0300] By combining the weight values of the current block in the transform domain with the above feedback correction results, the target to be quantized for the current block is obtained.
[0301] Subsequently, the target to be quantized in the current block is handed over to the two-bit lattice quantizer for processing.
[0302] After the current block is quantized, its reconstruction result is obtained, and the quantization error of the current block is updated according to the corresponding numerical relationship before and after quantization, so as to be used for the feedback calculation of subsequent blocks.
[0303] When using the anti-diagonal block processing order, blocks on the same anti-diagonal line can be organized into joint quantization batches according to their feedback dependencies.
[0304] Specifically, the required feedback terms for each block on the current anti-diagonal line are first calculated based on the already processed blocks. For blocks that do not need to wait for each other's quantization results, their corresponding quantization targets can be merged into batch data, and then the grid quantizer can be called to obtain the corresponding state encoding results respectively.
[0305] After the blocks on the same anti-diagonal line are quantized, the corresponding error data is updated before proceeding to the next anti-diagonal line.
[0306] This processing order allows for joint quantization of blocks that meet parallel conditions while maintaining the data dependencies between the two sides.
[0307] The two-sided matrix used in this embodiment is derived from a model that has already undergone four-bit activation quantization. Therefore, the error feedback relationship formed during the weight quantization stage corresponds to the input conditions generated during the activation quantization stage.
[0308] Meanwhile, the weights and bilateral matrices undergo a matched random symbolic Hadamard transformation, enabling bilateral feedback computation to be performed within the transform domain used by the lattice quantizer.
[0309] Through the above methods, bilateral gradient statistics, matrix transformation, block decomposition, and feedback rounding constitute a continuous weight quantization process, the output of which is the target to be quantized and the two-bit lattice encoding result corresponding to each weight block.
[0310] Example 4 This embodiment, based on Embodiments 1 and 3, further explains the state structure of the two-bit lattice quantizer, the weight reconstruction lookup table, the Viterbi encoding process, and the storage method of the quantization results.
[0311] The lattice quantizer used in this embodiment is a displacement-type state transition lattice quantizer, which forms an allowed state path through the binary displacement relationship between predetermined states and uses the state path to represent the weight value.
[0312] The Grid quantizer has three main configuration parameters: the number of bits in the state, the number of bits in the encoding per unit weight, and the number of weights corresponding to each state transition.
[0313] The configuration used in this embodiment is represented as follows: .
[0314] in, The number of binary bits representing the state of the trellis. This indicates the number of bits used in the encoding for each weight allocation. This represents the number of weights corresponding to each state transition.
[0315] Under the above configuration, the number of grid states is ,in Indicates by The number of states that a bit of binary state can represent.
[0316] Each state transition requires the introduction of New encoded information, in which This indicates the number of new bits added to the encoding for each state transition.
[0317] Based on the 4 newly added coding information, 16 candidate successor states can be formed.
[0318] The displacement-based state transition trellis used in this embodiment has defined binary state connection rules. Specifically, both the predecessor and successor states are represented in 16-bit binary form. The high 12 bits of the successor state are the same as the low 12 bits of the predecessor state, and the remaining 4 bits are determined by the new encoding information introduced in this state transition.
[0319] Therefore, for a given predecessor state, the corresponding candidate successor state can be determined based on the 4-bit new encoding information, without the need to additionally save the complete trellis connection relationship.
[0320] Before performing two-bit weight quantization, the target to be quantized corresponding to the current weight block is first serialized.
[0321] This embodiment adopts The weights are divided into blocks, each containing 256 weight values. These blocks are then organized into a continuous sequence to be quantized according to a predetermined weight order.
[0322] Under a two-bit encoding configuration per weight, a Weighted block corresponding The bit-encoded information is packaged and stored in 32 sixteen-bit integer storage units. Here, 512 represents the target encoding bit length for each block, and 32 represents the number of sixteen-bit storage units; the aforementioned cyclic concatenation encoding avoids the need to increase the initial state storage bit length.
[0323] The lattice quantizer processes two consecutive weight values each time and determines the degree of matching between the current transition and the quantization target based on the reconstructed values corresponding to the candidate states.
[0324] The reconstructed values corresponding to the grid state are obtained through a weighted reconstruction lookup table.
[0325] The weight reconstruction lookup table in this embodiment contains 512 entries, and each entry stores two reconstruction values. The reconstruction values are stored in 16-bit floating-point format.
[0326] When generating the weighted reconstruction lookup table, independent and identically distributed two-dimensional Gaussian samples can be used as clustering data. The two-dimensional samples are processed using a clustering algorithm to obtain two reconstructed values representing each table entry.
[0327] Specifically, the K-means clustering algorithm can be used to determine the cluster centers of the two-dimensional samples. After corresponding scaling adjustments, the cluster centers are used as the reconstruction values in the weight reconstruction lookup table.
[0328] In one specific implementation, the following is adopted: The corresponding scaling coefficients are used to adjust the scale of the reconstructed values and make the lookup table values correspond to the standard deviation of the weights to be quantized.
[0329] The target standard deviation relationship for reconstructing numerical values from a lookup table is: .in, The standard deviation of the reconstructed values in the scaled lookup table. This represents the standard deviation of the weights to be quantized in the current transform domain; this relationship corresponds to the scale configuration of the reconstructed values from the aforementioned lookup table.
[0330] Once the lookup table is initially generated, it can be saved as reusable data. When different linear layers use the same raster quantizer configuration, the already generated lookup table can be read without having to re-execute clustering on each quantization.
[0331] When determining the reconstructed value corresponding to the grid state, the lookup table index is first calculated based on the state number.
[0332] Specifically, let the current grid state number be i, where i represents the state number represented by a 16-bit binary integer. The lookup table index is calculated according to the state hash relationship described in Example 1. .
[0333] in, Indicates the status number The corresponding lookup table index.
[0334] Based on the lookup table index, read the corresponding two reconstructed values from 512 table entries.
[0335] For the corresponding symbol processing, this embodiment uses the 15th bit in the integer product of the state number to determine the symbol flip relationship of the first reconstructed value, and combines the symbol processing result with the corresponding value in the lookup table to obtain the weight reconstruction result of the current grid state representation.
[0336] During quantization, the lattice quantizer compares the reconstructed value corresponding to the candidate state with the current target to be quantized, and selects the state path that satisfies the quantization optimization objective according to the Viterbi dynamic programming process.
[0337] Since each transition corresponds to two weight values, the Viterbi algorithm can proceed by processing two weights at a time, gradually recording the path cost and predecessor state relationship of the corresponding candidate state.
[0338] After processing the entire weight sequence, the trellis encoding result corresponding to the weight block is obtained according to the state path determined by the Viterbi algorithm.
[0339] To reduce the coding overhead caused by initial state constraints, this embodiment uses two Viterbi passes.
[0340] In the first pass, the unquantized weight sequence is first cyclically shifted according to half the length of the lattice state, and then unconstrained Viterbi optimization is performed.
[0341] After the first optimization pass is completed, the corresponding intermediate states are obtained from the obtained state path. These intermediate states are used as state connection constraints during the second Viterbi optimization pass.
[0342] In the second pass, the weight sequence is restored to its original order, and Viterbi optimization is performed again based on the obtained intermediate state constraints.
[0343] Through the above processing, the state path corresponding to the original weight arrangement order is obtained, and it is converted into state-encoded data for storage.
[0344] This embodiment uses the above-described two-pass processing method to approximately achieve cyclically connected state encoding, so as to reduce the impact of the initial state on the encoding storage overhead.
[0345] After the weighted blocks complete the grid encoding, the corresponding state encoded data is stored in the compressed bit stream in a predetermined order.
[0346] For a linear layer to be quantized, the compressed bitstream is stored according to the organization order of the weight blocks. Each weight block corresponds to its own state encoding information, and the subsequent inference process reads the corresponding state encoding data according to the block position.
[0347] In the specific storage implementation, a 16-bit integer can be used as the basic storage unit for compressed data, and the corresponding status information can be organized into continuous integer data.
[0348] For those with One output channel, One input channel and using The block-based linear layer to be quantized, the block-encoded data can be... The two-dimensional data shape organization. Among them, and These represent the number of output and input channels, respectively. The first dimension represents the number of weighted blocks, and the second dimension represents the number of 16-bit integer storage units corresponding to each block. In this embodiment, the channel size is divisible by 16.
[0349] When the state information in the compressed bitstream spans adjacent integer storage units, the subsequent decoding program can read the adjacent storage units and restore the complete state through offset, masking, and concatenation operations.
[0350] For data stored using a signed 16-bit integer view, when performing bit operations on the grid state, the corresponding 16-bit unsigned bit pattern can be retained first to avoid sign extension affecting state recovery.
[0351] To ensure that the quantization stage and the inference stage use the same weight reconstruction results, this embodiment saves the corresponding weight reconstruction lookup table and the required auxiliary transformation parameters when saving the state encoding sequence.
[0352] Among them, the weight reconstruction lookup table is used to map the state code to the reconstructed weight value, the input-side random symbol vector is used for input transformation during inference, and the output-side random symbol vector is used for output transformation during inference.
[0353] For the current linear layer to be quantized, it is also necessary to save the weight scaling information corresponding to the range of reconstructed weight values.
[0354] In this embodiment, the weight scaling factor is determined based on the root mean square of the transformed weights and the root mean square of the reconstructed values from the lookup table.
[0355] Let the weight scaling factor of the current linear layer be... ,in This represents the scaling factor that makes the reconstructed weight values of the grid correspond to the current weight scale.
[0356] The scaling factor can be determined according to the root mean square ratio calculation relationship described in Example 1.
[0357] After obtaining the weight scaling factor, it is folded into the output-side random symbol vector. Specifically, each element in the output-side random symbol vector is combined with the weight scaling factor to form output-side transformation parameters containing symbol information and weight scaling information.
[0358] It should be noted that the values of each element in the output-side random symbol vector before folding are... or After the weight scaling factor is folded, the value stored in the vector simultaneously performs the functions of sign transformation and scale adjustment.
[0359] Therefore, during inference, symbol processing and scaling can be completed through the corresponding output-side transformation, without having to separately recover a complete floating-point weight matrix and then adjust the weight scale.
[0360] In this embodiment, there is a correspondence between the graph encoding, the weight reconstruction lookup table, and the weight scaling factor. If the lookup table or scaling parameter used in the quantization stage changes, the deployment stage should use the parameter data corresponding to the encoding result to maintain the consistency of the reconstruction result.
[0361] Through the above processing, the floating-point weights of each linear layer to be quantized are converted into compressed state codes and their auxiliary reconstruction parameters. The quantization results can then be directly used as data input for subsequent online lattice decoding and fusion matrix multiplication.
[0362] Example 5 This embodiment, based on Embodiment 1, further explains the deployment of compressed weights, online Hadamard transformation, fusion matrix multiplication, and the end-to-end execution process of the model.
[0363] This embodiment uses a computing device containing a graphics processor to perform quantization model inference. Before deployment, the model has completed training of a four-bit activation quantizer, acquisition of two-sided matrices, and quantization of two-bit trellis weights, and the corresponding model configuration has been saved.
[0364] For each linear layer that has completed graph quantization, the model deployment data includes a compressed state encoding sequence, a weight reconstruction lookup table, an input-side random symbol vector, an output-side transform vector containing weight scaling information, and the corresponding bias parameters.
[0365] The compressed state encoding sequence is stored in blocks according to weights. The weight reconstruction lookup table and auxiliary transformation parameters can be stored in 16-bit floating-point format. During model loading, the above data is read according to the correspondence of each linear layer.
[0366] This embodiment uses a Triton-based fusion computation program for compressed weight inference. This program performs online input transformation, lattice decoding, weight reconstruction, matrix multiplication, and corresponding output processing based on the input activation data and the current compressed weight configuration of the linear layer.
[0367] Before executing the current linear layer, the input activation data from the previous layer is obtained.
[0368] For a location with a four-bit activation quantizer, quantization mapping is performed according to the trained quantizer scaling and offset parameters to obtain the quantization activation value required for the current calculation.
[0369] Subsequently, element-wise symbol processing is performed on the activation value based on the input-side random symbol vector corresponding to the current linear layer.
[0370] After symbol processing is completed, an online Hadamard transform is performed on the input side. The online Hadamard transform uses a transform configuration corresponding to the weight quantization stage, so that the transformed input activation and compressed weights participate in matrix multiplication under the same computational relationship.
[0371] In one specific implementation, the online Hadamard transform can be executed by calling the Fast Hadamard transform program, which transforms the input features through butterfly operations.
[0372] For a linear layer with 1024 input channels, it can be processed according to the 1024 Vihadamard transform configuration; for a linear layer with 4096 input channels, it can be processed according to the 4096 Vihadamard transform configuration.
[0373] The normalization relation of the online Hadamard transform corresponds to the specific transform dimension and is consistent with the normalization method used in the offline weight transform.
[0374] The transformed activation data is converted into the corresponding data format according to the computational precision requirements of the fusion kernel. In this embodiment, 16-bit floating-point activation data can be used to perform subsequent fusion matrix multiplication.
[0375] The fusion kernel establishes a computational task based on the size of the weight matrix of the linear layer to be quantized.
[0376] For those with One output channel and In this embodiment, a linear layer with one input channel is organized into blocks of 16 output channels along the output channel direction, and the corresponding 16 weight blocks are processed one by one along the input channel direction.
[0377] in, This indicates the number of output channels of the current linear layer. This indicates the number of input channels in the current linear layer.
[0378] For input batches, a predetermined data block configuration can also be used. In this embodiment, 256 is used as the corresponding input data processing block parameter, and the kernel is configured with 8 parallel worker thread groups and 2 pipelined execution stages at startup.
[0379] The above computational configuration is used to arrange program execution and data segmentation in the graphics processor without changing the encoding method of the two-bit graph weights.
[0380] During the fusion computing process, each execution unit reads the compressed state encoded data according to the bitstream storage location corresponding to the current processing block.
[0381] After reading the encoded data, the corresponding grid state is restored according to the displacement relationship of the state transition grid, and the weight corresponding to the current state is calculated to reconstruct the lookup table index.
[0382] Subsequently, the corresponding reconstruction value is read from the weight reconstruction lookup table, and the weight block data is restored according to the symbol relationship determined by the grid state.
[0383] In one specific implementation, the current The weights are reconstructed completely in the registers. The reconstructed weight values are directly provided to the current matrix multiplication operation without first writing to the full dequantized weight buffer in the graphics processor.
[0384] When a lattice state spans adjacent 16-bit integer storage units, the corresponding data is first extracted from the adjacent storage units, and then the complete state is obtained by splicing through offset and mask operations.
[0385] When using signed integer data to store bit streams, the state parsing can be performed according to the corresponding unsigned bit pattern by masking the valid bits.
[0386] After restoring the current weight block, perform matrix multiplication with the corresponding input activation block.
[0387] In this embodiment, the activation value and reconstruction weight used for matrix multiplication can be represented by a 16-bit floating-point number, and the matrix multiplication result can be accumulated using 32-bit floating-point precision.
[0388] For the current linear layer, the fusion kernel processes all weight blocks sequentially according to the input channel direction. Each weight block is processed in the following order: reading the encoding, restoring the grid state, looking up the table to reconstruct the weights, and performing matrix multiplication.
[0389] After the current block is calculated, the subsequent weight blocks are processed, and the matrix multiplication results are accumulated to the corresponding output positions.
[0390] After completing the block calculations corresponding to all input channels, obtain the matrix multiplication accumulation result of the current linear layer.
[0391] Subsequently, an online Hadamard transform is performed on the output side of the matrix multiplication accumulation result, and symbol processing and weight scaling are completed based on the output side transform vector.
[0392] For a linear layer that includes a bias, the corresponding bias parameter is added after the output-side transformation is completed to obtain the output of the current linear layer.
[0393] Under the condition that the corresponding transformation and reconstruction parameters remain consistent, the above calculations have a corresponding algebraic relationship with the linear operations performed using the reconstruction weight matrix.
[0394] Let the input activation matrix be The reconstructed linear layer weight matrix is The linear layer is biased as The final output of the linear layer is Then its linear calculation relationship is: .
[0395] in, This represents the input activation matrix received by the current linear layer. This represents the weight matrix corresponding to the two-bit lattice graph encoding after numerical reconstruction. This represents the bias parameters of the current linear layer. Represents the output matrix of the current linear layer, with superscript... This indicates the matrix transpose.
[0396] The aforementioned quantization fixed-point relationship The transform domain reconstruction weights are represented by , while in this formula... This represents the reconstruction weights that, after the corresponding inverse transformation, restore the original linear layer coordinate system. The two satisfy the following relationship: ; here It contains the reconstructed values of the transform domain recovered through weight scaling factors. Among them, , These are the output-side and input-side orthogonal transformation matrices defined above, with superscripts indicating their respective values. This indicates the matrix transpose.
[0397] According to the above orthogonal transformation relationship, if the input matrix that has completed the activation quantization mapping is denoted as... The online transformation result on the input side can be denoted as Reconstructing weights using the transform domain After performing the fusion matrix multiplication, the output can be represented as .in, This represents the input-side activation matrix that matches the reconstructed weights in the transform domain. This represents the orthogonal transformation matrix on the input side. This represents the orthogonal transformation matrix on the output side. As the input activation matrix, For the output matrix of the linear layer, For bias parameters, This indicates that the transform domain reconstruction weights already include the corresponding scale recovery relation; this relation is similar to the aforementioned... Consistent.
[0398] For linear layers with no bias configuration, bias addition is not performed.
[0399] This embodiment achieves the above calculation relationship through online input transformation, lattice decoding, fusion matrix multiplication, and online output transformation, so that it is not necessary to restore and save the complete floating-point weight matrix of all linear layers in advance during inference.
[0400] After completing the calculation of the current linear layer, the output is sent to the corresponding attention calculation, normalization processing, multilayer perceptron or residual processing stage according to the subsequent calculation relationship in the encoder.
[0401] For the query projection layer, key projection layer, value projection layer, and attention output projection layer in the model, their corresponding compression weights and quantization parameters are loaded respectively. The two fully connected layers in the multilayer perceptron are also loaded with the same compression weights and fused calculations.
[0402] Therefore, each encoder layer can perform the corresponding linear calculations using the compressed trellis weights, following the original network structure sequence.
[0403] After all encoder layers have been executed, the video lexical features output by the model enter the attention pooler, and then the classifier outputs the classification result corresponding to the current video.
[0404] In this embodiment, the compression of the model file mainly stems from the change in the weight representation of the 144 linear layers to be quantized within the encoder. Modules not involved in two-bit graph quantization are still saved in their corresponding floating-point format.
[0405] In the specific deployment configuration used in this embodiment, the model file size was reduced from 1.4 GB to 214 MB. The above result corresponds to the two-bit trellis encoding of the encoder's linear layer weights, and the storage combination of other modules retaining floating-point weights.
[0406] For the actual inference process, the fusion kernel reduces the intermediate storage requirements for fully reconstructing the weight tensor by performing online decoding and instant matrix calculation on the required weight blocks.
[0407] The actual inference latency of the model is also affected by factors such as input batch size, hardware resources, online Hadamard transformation, and the computational cost of lattice state decoding. This embodiment adopts a fusion computation approach, allowing lattice weight reconstruction and matrix multiplication to be performed concurrently in the same computation process.
[0408] Example 6 This embodiment, based on the aforementioned embodiments, further explains the software organization, model parameter storage, data flow, and execution result checking of the quantization pipeline.
[0409] This embodiment uses the PyTorch framework to organize the model training and weight quantization process, and implements a fusion inference kernel with compressed weights through the Triton program.
[0410] In terms of software organization, the quantization process can be divided into model adaptation, activation quantization, weight quantization, and deployment evaluation.
[0411] The model adaptation section is used to load the V-JEPA2 pedestal model and identify the linear layer to be quantized and the corresponding activation quantization position.
[0412] The activation quantization section is used to set up the channel-by-channel and tensor-by-tensor activation quantizers, acquire activation samples corresponding to the calibration video, initialize quantization parameters, and perform activation quantization training.
[0413] The weight quantization section is used to acquire the two-sided matrix under the already quantized activation conditions, transform, decompose and perform feedback calculations on the weights and the two-sided matrix, and call the lattice quantizer to generate two-bit codes.
[0414] The deployment evaluation section is used to convert the grid encoding into compressed model storage data, construct the corresponding fusion computing program, and perform forward inference on the video verification data.
[0415] In a specific software implementation, the model adaptation part may include a model module replacement program, an attention calculation path processing program, and a quantization parameter initialization program.
[0416] The module replacement program identifies the linear layer to be quantized in the encoder and sets a four-bit activation quantizer at the appropriate location. The attention computation path handler is used to explicitly perform matrix multiplication between the query and the key, as well as matrix multiplication between the attention weight and the value, so that the corresponding operands can call the tensor-wise activation quantizer.
[0417] The quantization parameter initialization procedure determines the initial scaling and offset parameters based on the activation samples generated from the calibration video.
[0418] After activating quantization training, save the model parameters and corresponding quantization configurations to the model storage directory.
[0419] During the second stage of weight quantization, the base model, activation quantizer structure, and trained parameters are loaded from the model storage directory, and the trained activation quantization model is restored according to the corresponding configuration.
[0420] After recovery, forward computation under floating-point weights and four-bit activation conditions can be performed first to obtain the corresponding model output before entering the dual-sided matrix acquisition process.
[0421] Two-sided matrix acquisition is performed by a custom linear layer backpropagation procedure. For each calibration video, the corresponding weight gradient is obtained, and the gradient product is accumulated in both the input and output matrices.
[0422] After the 128 calibration videos have been processed, the matrix average is calculated according to the corresponding number of samples.
[0423] After obtaining the two-sided matrix, the matrix data is transferred to the central processing unit's memory for storage. During weight quantization, the required matrix is read layer by layer, and the corresponding transformation and decomposition are performed according to the number of input and output channels of the current linear layer.
[0424] Numerical checks can be performed on the relevant data during two-sided matrix decomposition and lattice quantization.
[0425] For the Hadamard transform, a round-trip check can be performed between the forward and inverse transforms.
[0426] Specifically, a forward Hadamard transform is performed on the test input, and then a corresponding inverse transform is performed on the transform result. The maximum absolute error between the final recovered result and the original input is calculated.
[0427] In the implementation configuration of this embodiment, the maximum round-trip error is less than This serves as a numerical check condition for the Hadamard transform. This condition is used to check the numerical consistency of the corresponding program implementation.
[0428] For the matrix factorization process, check whether the factorization is complete and whether non-numerical data appears in the result. When an anomaly occurs during factorization, handle it according to the diagonal regularization retry method described in Example 3.
[0429] For the lattice quantization process, Viterbi quantization is performed according to the feedback target of the current block, and the resulting state code is checked to see if it conforms to the state bit width and transition relationship of the current lattice.
[0430] After completing the lattice quantization of a linear layer to be quantized, save its encoding results and corresponding auxiliary parameters to the current model configuration, and release the two-sided matrix and temporary computation data of that layer.
[0431] Then, the next linear layer to be quantized is processed until all 144 linear layers to be quantized have been processed.
[0432] After completing the two-bit weight quantization, a fusion inference model can be constructed based on the saved model configuration.
[0433] The fusion inference model retains the original computation order of each encoder layer and replaces the linear layers that have undergone lattice quantization with computational units that can read compressed state codes and perform fusion matrix multiplication.
[0434] For the current linear layer, the fusion computing unit restores the weight blocks according to the compressed state encoding and performs matrix multiplication with the corresponding activation data.
[0435] For modules that do not use two-bit lattice quantization, the saved floating-point weights and corresponding calculation methods will be used.
[0436] In terms of video data processing, this embodiment uses the SSv2 video dataset as the specific application data source.
[0437] First, the input video is read using a video decoding program, and the video frames required by the model are extracted according to uniform sampling positions. Then, the sampled video frames are input into the video processing program corresponding to the V-JEPA2 model to generate the model input tensor.
[0438] In one specific implementation, the data output by the video processing program is named pixel_values_videos. This field is used to pass the video input data to the encoder model.
[0439] After processing by the 3D convolutional block embedding layer, the video data is converted into a video word sequence. For the model configuration used in this embodiment, a single video segment corresponds to 2048 video words, and each word has 1024 hidden features.
[0440] When the batch contains When there are multiple videos, the size of the video term tensor is 1. ,in This indicates the number of videos in the current video batch, 2048 indicates the number of tokens corresponding to a single video, and 1024 indicates the hidden feature dimension of each token.
[0441] The video terms are sequentially input into 24 encoder layers for processing.
[0442] In each encoder layer, the query, key-value projection layers, and the linear layers corresponding to the multilayer perceptron read their compressed weight data and perform corresponding matrix calculations through the fusion kernel. The operands of the attention matrix multiplication are processed according to the corresponding four-bit activation quantization configuration.
[0443] The video features output by the encoder are processed by an attention pooler and a classifier to obtain the classification output of the current video.
[0444] During the evaluation process, the original floating-point model, the model trained with activation quantization, and the final two-bit weighted and four-bit activated quantized model can be loaded respectively, and forward computation can be performed on the corresponding video verification data.
[0445] The same input preprocessing method is used for each model so that the model outputs can be compared under the corresponding task conditions.
[0446] The model was validated using the Something-Something-V2 video action recognition dataset, which contains approximately 220,000 annotated videos covering 174 categories of object interaction actions. For the original 32-bit floating-point weighted model, the Top-1 accuracy was 73.6%, and the Top-5 accuracy was 94.0%. For the quantized model in this embodiment, which uses 2-bit encoded weights and 4-bit activation, the Top-1 accuracy was 72.9%, and the Top-5 accuracy was 94.2%. Top-1 accuracy is the proportion of samples where the predicted probability category matches the labeled category, and Top-5 accuracy is the proportion of samples where the labeled category is among the top five predicted probabilities. Therefore, the quantized model's Top-1 accuracy is 0.7 percentage points lower than the original model, while its Top-5 accuracy is 0.2 percentage points higher. Figure 2 The above accuracy rates are shown, along with comparisons of other quantization configurations shown in the accompanying figures.
[0447] According to the supplementary test records of the inventors, the peak memory usage of the original 32-bit floating-point weighted model was 1930 MB, while the peak memory usage of the quantization model in this embodiment was 766 MB; the end-to-end inference throughput of the two models was 4.52 videos per second and 5.26 videos per second, respectively. Figure 3 The comparison of memory usage and processing speed is shown above, with the GPTQ weighted quantization configurations marked in the figure listed as a reference. These values are used to illustrate the actual results of quantization encoding and online fusion computation in this embodiment, and do not directly imply that the same values exist under different computing devices or input configurations. Figure 2 The GPTQ is labeled as having four-bit weights and sixteen-bit activation. Figure 3 The GPTQ reference is labeled with four-bit weights and thirty-two-bit activation; the two figures show different reference configurations.
[0448] For model parameter storage, the storage status of floating-point weights, activation quantization parameters, grid-compressed bitstream, reconstruction lookup table, and auxiliary transformation parameters can be checked separately.
[0449] For the actual inference process, you can check whether the compressed state encoding is loaded correctly, whether the parameters required for the online Hadamard transform match the corresponding linear layer, and whether the fusion kernel can complete the corresponding matrix multiplication calculation.
[0450] When using different input batches for inference, the fusion kernel can organize the corresponding computation tasks according to the data size of the current batch and repeatedly execute the same trellis state decoding and weight reconstruction relationship.
[0451] This embodiment organizes model adaptation, activation quantization training, two-sided matrix acquisition, two-bit weight quantization, and fusion inference into callable processing parts, so that the model parameters and quantization data generated at each stage have a clear storage and loading relationship.
[0452] The activation quantization parameters saved in the first stage are used for the forward computation in the second stage; the two-sided matrix generated in the second stage is used for weight feedback rounding; the state code and auxiliary parameters obtained by weight quantization are used for final deployment; the deployment model completes the forward computation of the video encoder through online state decoding and fusion matrix multiplication.
[0453] Therefore, the complete quantization pipeline can be executed in the order of model loading, activation quantization training, bilateral matrix acquisition, weight block quantization, grid encoding and saving, and model inference, and the corresponding video visual encoding results can be obtained.
[0454] The above embodiments are only used to illustrate the technical solutions of this application and do not constitute a limitation on the scope of protection of this application. Based on an understanding of the technical concept of this application, those skilled in the art can make appropriate adjustments or equivalent substitutions to the specific implementation forms in the above embodiments according to the actual model structure, computing resources, and deployment conditions. The corresponding adjustments or substitutions should maintain the technical coordination relationship between activation quantization, bilateral matrix acquisition, error feedback rounding, lattice encoding, and fusion inference, and should not change the basic principles of the technical solution of this application.
[0455] Regarding the specific parameters, data organization methods, algorithm implementation forms, and program execution configurations disclosed in the above embodiments, those skilled in the art can make corresponding equivalent modifications without departing from the technical concept of this application. Whether any equivalent substitutions or modifications made based on the technical content disclosed in this application fall within the protection scope of this application shall be determined by the scope defined in the claims.
Claims
1. A quantization and inference method for a video visual self-attention encoder, characterized in that, include: The encoder's query, key, value, attention output projection layer, and fully connected layer of the multilayer perceptron are taken as linear layers to be quantized. A four-bit activation quantizer is set at its output and attention matrix multiplication operands. The weights of the linear layers to be quantized are kept to be thirty-two-bit floating-point. The weights, quantizer scaling parameters, and quantizer offset parameters are trained together to obtain the activation quantization model. The calibration video is input into the activation quantization model, the target category is sampled according to the output category probability distribution, the cross-entropy self-distillation loss is constructed and backpropagated to obtain the video-by-video weight gradient; the input-side matrix and the output-side matrix are established using the sample mean of the product of the gradient transpose and the gradient, and the product of the gradient and its transpose. Apply corresponding random signs and normalized Hadamard transforms to the linear layer weights to be quantized, the input-side matrix, and the output-side matrix; The input-side feedback factor and the output-side feedback factor are obtained by decomposing the two matrices after the block decomposition transformation. The transformed weights are divided into weight blocks. Based on the input-side feedback factor, the output-side feedback factor, and the quantized block error, quantization targets for the input-side, output-side, and cross-term feedback are constructed in anti-diagonal order. The Viterbi algorithm is used to optimize the displacement state transition lattice to obtain a two-bit state encoding sequence for each weight. The state encoding sequence is packaged and stored, and the weight reconstruction lookup table and transformation parameters are saved. During inference, the Hadamard transform is applied online to the activation values processed by the four-bit activation quantizer. The weight blocks are decoded, reconstructed by looking up the table in the fusion kernel, and matrix multiplication is performed with the transformed activation values. Then, the output-side transformation is performed without generating a complete inverse quantization weight matrix.
2. The quantization and inference method for the video visual self-attention encoder according to claim 1, characterized in that, The four-bit active quantizer set at the output of the linear layer to be quantized performs quantization according to the following formula: ; in, To input the activation value, The activation value after quantization. For learnable scaling parameters, For learnable offset parameters, This is the lower bound of the quantization index. The upper limit of the quantization index is set; the four-bit active quantizer set at the output of the linear layer to be quantized is a channel-by-channel four-bit active quantizer, whose scaling parameters and offset parameters are set separately according to the output channels of each linear layer to be quantized, and the backpropagation gradient of the quantization rounding operation is estimated by a pass-through estimator.
3. The quantization and inference method for the video visual self-attention encoder according to claim 2, characterized in that, The attention matrix multiplication includes matrix multiplication of the query vector and the key vector transpose, and matrix multiplication of the attention weight and the value vector. For each matrix multiplication, a tensor-wise four-bit activation quantizer is set for each of the two operands. Each tensor-wise four-bit activation quantizer uses a set of scaling parameters and offset parameters for the corresponding entire operand tensor.
4. The quantization and inference method for the video visual self-attention encoder according to claim 3, characterized in that, Linear projection, four-bit activation quantization, and tensor rearrangement are performed on the query vector, key vector, and value vector, respectively. Rotation position encoding is performed on the rearranged query vector and key vector, followed by matrix multiplication of the transpose of the query vector and key vector. The results are then scaled and normalized by 32-bit floating-point Softmax to generate attention weights. Matrix multiplication of the attention weights and value vector is then performed, and four-bit activation quantization is applied to the attention output projection result.
5. The quantization and inference method for the video visual self-attention encoder according to claim 1, characterized in that, When jointly training the weights of each linear layer to be quantized, the scaling parameters of the four-bit activation quantizer, and its offset parameters, the corresponding 32-bit floating-point model is used as the teacher model, and the attention pooler output features of the teacher model and the activation quantization model are obtained respectively. Based on the output features of the teacher model, principal component projection and whitening parameters are fitted. Principal component projection and whitening processing are performed on the corresponding output features of the two models. The mean square error between the whitened features is calculated, and the mean square error and classification cross-entropy are used together as the joint training loss.
6. The quantization and inference method for the video visual self-attention encoder according to claim 2, characterized in that, Before joint training, activation samples corresponding to the four-bit activation quantizer set at the output of the linear layer to be quantized were acquired using thirty-two calibration videos. For the channel-by-channel four-bit activation quantizer, the quantization parameters were initialized with quantization points of 0.999, 0.9999, and 0.99999, respectively. The initial scaling parameters and initial offset parameters of the corresponding channels were selected according to the L2 norm error of the activation values before and after quantization of each output channel.
7. The quantization and inference method for the video visual self-attention encoder according to claim 1, characterized in that, The construction of the cross-entropy self-distillation loss includes: inputting the calibration video into the activated quantization model, forming a class probability distribution based on the classification prediction value output by the model, sampling the target class from the class probability distribution, and constructing the cross-entropy loss with the target class; using a custom backpropagation operation on the linear layer to be quantized, and calculating the weight gradient corresponding to each calibration video based on the cross-entropy loss.
8. The quantization and inference method for the video visual self-attention encoder according to claim 7, characterized in that, When acquiring the weight gradient, forward and backward propagation are performed in batches of single calibration videos. Automatic mixing precision is turned off and 32-bit floating-point precision is used to accumulate the input-side matrix and output-side matrix, while gradient checkpointing is enabled. The accumulated matrices are stored in the central processing unit memory and loaded into the graphics processor layer by layer during weight quantization. After the quantization of the corresponding linear layer is completed, the corresponding matrix data is released.
9. The quantization and inference method for the video visual self-attention encoder according to claim 1, characterized in that, For each linear layer to be quantized, an input-side random symbol vector and an output-side random symbol vector are generated, where each element of the input-side and output-side random symbol vectors takes the value of... or The weights are generated using a fixed random seed corresponding to the linear layer; the input-side random symbol vector, the output-side random symbol vector, and the corresponding normalized Hadamard matrix are used to perform a two-sided transformation on the weights, and the input-side matrix and the output-side matrix are respectively subjected to a conjugate transformation corresponding to the weight transformation.
10. The quantization and inference method for the video visual self-attention encoder according to claim 9, characterized in that, The transformed input and output matrices are implemented using block-based Cholesky operations. Decomposition, in which blocks Decomposition is the process of representing the matrix to be decomposed as a unit lower triangular factor. Block diagonal matrix The transpose of the unit lower triangular factor matrix The product, superscript This represents the matrix transpose; the block size is sixteen, yielding the corresponding unit lower triangular feedback factor and block diagonal matrix; when decomposition fails or the decomposition result is non-numerical, the diagonal elements of the matrix to be decomposed are accumulated with a regularization increment before re-decomposition, where the regularization increment is... .
11. The quantization and inference method for the video visual self-attention encoder according to claim 10, characterized in that, The two-sided error feedback quantization result, consisting of the input-side feedback factor and the output-side feedback factor, is determined using the following formula: ; in, The weight matrix is obtained after random symbolic Hadamard transformation. This is the quantized weight matrix. This is a two-bit quantization operation based on the aforementioned displacement-based state transition lattice. The quantization error matrix is generated from the quantized blocks. The lower triangular feedback factor corresponding to the input-side matrix. The lower triangular feedback factor corresponding to the output matrix, indicated by the superscript. Indicates matrix transpose; The weight blocks are processed in anti-diagonal order, so that the quantization target of the current block depends on the quantization error of the processed blocks, and multiple weight blocks located on the same anti-diagonal are jointly subjected to Viterbi quantization.
12. The quantization and inference method for the video visual self-attention encoder according to claim 1, characterized in that, The state transition lattice is a displacement lattice, where nodes are represented by 16-bit states. Transitions between adjacent states satisfy the condition that the high 12 bits of the successor state are the same as the low 12 bits of the predecessor state. Four new state information bits are introduced at each transition to encode two weights. Each of the transformed weights... The weight blocks are used as a weight sequence to be quantized.
13. The quantization and inference method for the video visual self-attention encoder according to claim 12, characterized in that, For each weight sequence to be quantized, the sequence is first cyclically shifted according to half the length of the trellis state, and the first unconstrained Viterbi optimization is performed. The midpoint state of the first optimization path is extracted as the state constraint for the second Viterbi optimization. After restoring the sequence to its original order, Viterbi optimization is performed again, and the state encoding sequence is generated based on the state path obtained from the second optimization.
14. The quantization and inference method for the video visual self-attention encoder according to claim 13, characterized in that, When reconstructing the weights based on the state coding sequence, a weight reconstruction lookup table containing 512 entries is used, with each entry storing two 16-bit floating-point reconstruction values; the corresponding lookup table index is calculated based on the trellis state number, and the calculation relationship is as follows: ; in, Assign a grid state number, For the corresponding lookup table index, This represents a bitwise right shift in binary. This represents a binary bitwise AND operation; the entries in the weighted reconstruction lookup table are determined by performing clustering on a two-dimensional Gaussian distributed sample.
15. The quantization and inference method for the video visual self-attention encoder according to claim 1, characterized in that, The fusion kernel extracts the trellis state from the packaged state encoding sequence according to the weight blocks, reconstructs the corresponding weight blocks by looking up a table, retains the reconstructed weight blocks in the register, performs matrix multiplication with the activation blocks after online Hadamard transformation, accumulates the matrix multiplication results with 32-bit floating-point precision, and does not generate a complete inverse quantization weight buffer.
16. The quantization and inference method for the video visual self-attention encoder according to claim 9, characterized in that, The weight scaling factor for each linear layer to be quantized is determined according to the following formula: ; in, This is the weight scaling factor. The weights are those that have undergone a random symbol Hadamard transform. To reconstruct the weights, look up the set of reconstructed values in the lookup table. is the root mean square calculation function, and 0.9 is the scaling factor; The weight scaling factor is folded onto the output-side random symbol vector, and during inference, the folded output-side transformation vector is used to perform symbol and scaling transformation on the online Hadamard output.
17. The quantization and inference method for the video visual self-attention encoder according to claim 1, characterized in that, The encoder is a video vision Transformer encoder containing twenty-four encoder layers. Each encoder layer has a linear layer to be quantized, including a query projection layer, a key projection layer, a value projection layer, an attention output projection layer, and two fully connected layers in a multilayer perceptron, for a total of one hundred and forty-four linear layers to be quantized. The output activation values of the 3D convolutional block embedding layer are quantized by one channel eight bits, and the weights of the 3D convolutional block embedding layer, predictor, attention pooler, and classifier are preserved in sixteen-bit floating-point format during deployment.
