Description: The DenseLightningIndexerGradKlLoss operator is the backward operator of LightningIndexer and integrates the loss calculation function. The LightningIndexer operator selects the top K tokens with the highest intrinsic relationship between the query token and key token, reducing the amount of attention computation in long-sequence scenarios and accelerating the inference and training performance of long-sequence networks. In the dense scenario, the inputs query, key, query_index, and key_index of LightningIndexerGrad do not need to be sparsified.
Formulas:
The formula for calculating the top-k value is as follows:
- is the corresponding to the th token.
- is the result of combining query heads of the th token in the matrix.
- is the th row of the matrix.
The forward Softmax formula is as follows:
- is the Softmax result corresponding to the th token.
- is the result of combining query heads of the th token in the matrix.
- is the th row of the matrix.
npu_lightning_indexer is trained independently. The corresponding loss function is as follows:
is the target distribution, which is obtained by summing up all heads of the main attention score and then performing L1 regularization on the sum result along the context direction. is the KL divergence, and its expression is as follows:
The gradient expression of the loss can be obtained by derivation:
The gradients of the weights, query, and key matrices can be calculated using the chain rule.
is the result of the matrix multiplication of and .
Each operator has calls. First, [object Object] is called to obtain the input parameters and compute the required workspace size based on the process. Then, [object Object] is called to perform computation.
Parameters:
[object Object]Returns
[object Object]: status code. For details, see .The first-phase API implements input parameter validation. The following error codes may be returned.
[object Object]
The data types of the query, key, queryIndex, and keyIndex parameters must be the same.
If the weights parameter is not of type float32, the data types of the query, key, queryIndex, keyIndex, and weights parameters must be the same.
Common constraints
- Deterministic computation:
[object Object]defaults to non-deterministic implementation. You can call[object Object]to enable deterministic computation. - Processing when the input parameter is empty:
- If the query, key, query_index, key_index, or weight is an empty tensor, the current version does not support this operation and an error will be reported.
- Deterministic computation:
Constraints
[object Object]Typ.
[object Object]
The following example is for reference only. For details, see .