## Contrib Operator Schemas
*This file is automatically generated from the registered contrib operator schemas by [this script](https://github.com/microsoft/onnxruntime/blob/main/tools/python/gen_contrib_doc.py).
Do not modify directly.*
* com.microsoft
* com.microsoft.Attention
* com.microsoft.AttnLSTM
* com.microsoft.BeamSearch
* com.microsoft.BiasAdd
* com.microsoft.BiasDropout
* com.microsoft.BiasGelu
* com.microsoft.BiasSoftmax
* com.microsoft.BiasSplitGelu
* com.microsoft.BifurcationDetector
* com.microsoft.BitmaskBiasDropout
* com.microsoft.BitmaskDropout
* com.microsoft.BranchwiseRMSNorm
* com.microsoft.CDist
* com.microsoft.CausalConvWithState
* com.microsoft.ComplexMul
* com.microsoft.ComplexMulConj
* com.microsoft.ConvTransposeWithDynamicPads
* com.microsoft.CropAndResize
* com.microsoft.DecoderAttention
* com.microsoft.DecoderMaskedMultiHeadAttention
* com.microsoft.DecoderMaskedSelfAttention
* com.microsoft.DequantizeBFP
* com.microsoft.DequantizeLinear
* com.microsoft.DequantizeWithOrder
* com.microsoft.DynamicQuantizeLSTM
* com.microsoft.DynamicQuantizeMatMul
* com.microsoft.DynamicSparseAttention
* com.microsoft.DynamicTimeWarping
* com.microsoft.EPContext
* com.microsoft.EmbedLayerNormalization
* com.microsoft.EngramGate
* com.microsoft.ExpandDims
* com.microsoft.FastGelu
* com.microsoft.FusedConv
* com.microsoft.FusedGemm
* com.microsoft.FusedMatMul
* com.microsoft.FusedMatMulActivation
* com.microsoft.GatedAdd
* com.microsoft.GatedDeltaNet
* com.microsoft.GatedRMSNorm
* com.microsoft.GatedRelativePositionBias
* com.microsoft.GatherBlockQuantized
* com.microsoft.GatherND
* com.microsoft.Gelu
* com.microsoft.GemmFastGelu
* com.microsoft.GemmFloat8
* com.microsoft.GemmaRotaryEmbedding
* com.microsoft.GreedySearch
* com.microsoft.GridSample
* com.microsoft.GroupNorm
* com.microsoft.GroupQueryAttention
* com.microsoft.HyperConnectionPostMix
* com.microsoft.HyperConnectionPreMix
* com.microsoft.Inverse
* com.microsoft.Irfft
* com.microsoft.LinearAttention
* com.microsoft.LinearAttentionGate
* com.microsoft.LongformerAttention
* com.microsoft.MRotaryEmbedding
* com.microsoft.MatMulBlockQuantizedFp4Weight
* com.microsoft.MatMulBlockQuantizedFp8Weight
* com.microsoft.MatMulBnb4
* com.microsoft.MatMulFpQ4
* com.microsoft.MatMulInteger16
* com.microsoft.MatMulIntegerToFloat
* com.microsoft.MatMulNBits
* com.microsoft.MatMulNBitsMlp
* com.microsoft.MatMulNBitsQkv
* com.microsoft.MaxpoolWithMask
* com.microsoft.MoE
* com.microsoft.MulInteger
* com.microsoft.MultiHeadAttention
* com.microsoft.MurmurHash3
* com.microsoft.NGramHashMapping
* com.microsoft.NGramRepeatBlock
* com.microsoft.NhwcConv
* com.microsoft.NhwcFusedConv
* com.microsoft.NhwcMaxPool
* com.microsoft.PackedAttention
* com.microsoft.PackedMultiHeadAttention
* com.microsoft.PackedSparseAttentionIndexer
* com.microsoft.Pad
* com.microsoft.PagedAttention
* com.microsoft.QAttention
* com.microsoft.QGemm
* com.microsoft.QLinearAdd
* com.microsoft.QLinearAveragePool
* com.microsoft.QLinearConcat
* com.microsoft.QLinearConv
* com.microsoft.QLinearGlobalAveragePool
* com.microsoft.QLinearLeakyRelu
* com.microsoft.QLinearMul
* com.microsoft.QLinearReduceMean
* com.microsoft.QLinearSigmoid
* com.microsoft.QLinearSoftmax
* com.microsoft.QLinearWhere
* com.microsoft.QMoE
* com.microsoft.QOrderedAttention
* com.microsoft.QOrderedGelu
* com.microsoft.QOrderedLayerNormalization
* com.microsoft.QOrderedLongformerAttention
* com.microsoft.QOrderedMatMul
* com.microsoft.QuantizeBFP
* com.microsoft.QuantizeLinear
* com.microsoft.QuantizeWithOrder
* com.microsoft.QuickGelu
* com.microsoft.Range
* com.microsoft.ReduceSumInteger
* com.microsoft.RelativePositionBias
* com.microsoft.RemovePadding
* com.microsoft.RestorePadding
* com.microsoft.Rfft
* com.microsoft.RotaryEmbedding
* com.microsoft.SampleOp
* com.microsoft.Sampling
* com.microsoft.ScaledSiLU
* com.microsoft.SkipGroupNorm
* com.microsoft.SkipLayerNormalization
* com.microsoft.SkipSimplifiedLayerNormalization
* com.microsoft.Snpe
* com.microsoft.SparseAttention
* com.microsoft.SparseAttentionIndexer
* com.microsoft.SparsePagedAttention
* com.microsoft.SparseToDenseMatMul
* com.microsoft.Tokenizer
* com.microsoft.TorchEmbedding
* com.microsoft.TransposeMatMul
* com.microsoft.Trilu
* com.microsoft.UnfoldTensor
* com.microsoft.Unique
* com.microsoft.VarlenCausalConvWithState
* com.microsoft.VarlenNGramHashMapping
* com.microsoft.WhisperBeamSearch
* com.microsoft.WordConvEmbedding
* experimental com.microsoft.IsAllFinite
* experimental com.microsoft.QEmbedLayerNormalization
## com.microsoft
### **com.microsoft.Attention**
Multi-Head Attention that can be either unidirectional (like GPT-2) or bidirectional (like BERT).
The weights for input projection of Q, K and V are merged. The data is stacked on the second dimension. Its shape
is (input_hidden_size, hidden_size + hidden_size + v_hidden_size). Here hidden_size is the hidden dimension of Q and K,
and v_hidden_size is that of V.
The mask_index is optional. Besides raw attention mask with shape (batch_size, total_sequence_length)
or (batch_size, sequence_length, total_sequence_length) with value 0 for masked and 1 otherwise,
we support other two formats: When input has right-side padding, mask_index is one dimension with shape (batch_size),
where value is actual sequence length excluding padding. When input has left-side padding, mask_index has
shape (2 * batch_size), where the values are the exclusive end positions followed by the inclusive start positions.
When unidirectional is 1, each token only attends to previous tokens.
Both past and present state are optional. They shall be used together, and not allowed to use only one of them.
The qkv_hidden_sizes is required only when K and V have different hidden sizes.
When there is past state, hidden dimension for Q, K and V shall be the same.
The total_sequence_length is past_sequence_length + kv_sequence_length. Here kv_sequence_length is the length of K or V.
For self attention, kv_sequence_length equals to sequence_length (sequence length of Q).
For cross attention, query and key might have different lengths.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- do_rotary : int
- Whether to use rotary position embedding. Default value is 0.
- mask_filter_value : float
- The value to be filled in the attention mask. Default value is -10000.0f
- num_heads : int (required)
- Number of attention heads
- past_present_share_buffer : int
- Corresponding past and present are same tensor, its size is (2, batch_size, num_heads, max_sequence_length, head_size)
- qkv_hidden_sizes : list of ints
- Hidden dimension of Q, K, V: hidden_size, hidden_size and v_hidden_size
- rotary_embedding_dim : int
- Dimension of rotary embedding. Limited to 32, 64 or 128. Default value is head_size
- scale : float
- Custom scale will be used if specified. Default value is 1/sqrt(head_size)
- unidirectional : int
- Whether every token can only attend to previous tokens. Default value is 0.
#### Inputs (2 - 7)
- input : T
- Input tensor with shape (batch_size, sequence_length, input_hidden_size)
- weights : T
- Merged Q/K/V weights with shape (input_hidden_size, hidden_size + hidden_size + v_hidden_size)
- bias (optional) : T
- Bias tensor with shape (hidden_size + hidden_size + v_hidden_size) for input projection
- mask_index (optional) : M
- Attention mask with shape (batch_size, 1, max_sequence_length, max_sequence_length), (batch_size, total_sequence_length) or (batch_size, sequence_length, total_sequence_length), or index with shape (batch_size) or (2 * batch_size) or (3 * batch_size + 2)
- past (optional) : T
- past state for key and value with shape (2, batch_size, num_heads, past_sequence_length, head_size)When past_present_share_buffer is set, its shape is (2, batch_size, num_heads, max_sequence_length, head_size)
- attention_bias (optional) : T
- additional add to QxK' with shape (batch_size or 1, num_heads or 1, sequence_length, total_sequence_length)
- past_sequence_length (optional) : M
- When past_present_share_buffer is used, it is required to specify past_sequence_length (could be 0).
#### Outputs (1 - 2)
- output : T
- 3D output tensor with shape (batch_size, sequence_length, v_hidden_size)
- present (optional) : T
- past state for key and value with shape (2, batch_size, num_heads, total_sequence_length, head_size). If past_present_share_buffer is set, its shape is (2, batch_size, num_heads, max_sequence_length, head_size), while effective_seq_length = (past_sequence_length + kv_sequence_length).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
- M : tensor(int32)
- Constrain mask index to integer types
### **com.microsoft.AttnLSTM**
Computes an one-layer RNN where its RNN Cell is an AttentionWrapper wrapped a LSTM Cell. The RNN layer
contains following basic component: LSTM Cell, Bahdanau Attention Mechanism, AttentionWrapp.
Activation functions:
Relu(x) - max(0, x)
Tanh(x) - (1 - e^{-2x})/(1 + e^{-2x})
Sigmoid(x) - 1/(1 + e^{-x})
(NOTE: Below are optional)
Affine(x) - alpha*x + beta
LeakyRelu(x) - x if x >= 0 else alpha * x
ThresholdedRelu(x) - x if x >= alpha else 0
ScaledTanh(x) - alpha*Tanh(beta*x)
HardSigmoid(x) - min(max(alpha*x + beta, 0), 1)
Elu(x) - x if x >= 0 else alpha*(e^x - 1)
Softsign(x) - x/(1 + |x|)
Softplus(x) - log(1 + e^x)
Softmax(x) - exp(x) / sum(exp(x))
Bahdanau Attention Mechanism:
`M` - Memory tensor.
`VALUES` - masked Memory by its real sequence length.
`MW` - Memory layer weight.
`KEYS` - Processed memory tensor by the memory layer.
KEYS = M * MW
`Query` - Query tensor, normally at specific time step in sequence.
`QW` - Query layer weight in the attention mechanism
`PQ` - processed query, = `Query` * `QW`
`V' - attention vector
`ALIGN` - calculated alignment based on Query and KEYS
ALIGN = softmax(reduce_sum(`V` * Tanh(`KEYS` + `PQ`)))
`CONTEXT` - context based on `ALIGN` and `VALUES`
CONTEXT = `ALIGN` * `VALUES`
LSTM Cell:
`X` - input tensor concat with attention state in the attention wrapper
`i` - input gate
`o` - output gate
`f` - forget gate
`c` - cell gate
`t` - time step (t-1 means previous time step)
`W[iofc]` - W parameter weight matrix for input, output, forget, and cell gates
`R[iofc]` - R recurrence weight matrix for input, output, forget, and cell gates
`Wb[iofc]` - W bias vectors for input, output, forget, and cell gates
`Rb[iofc]` - R bias vectors for input, output, forget, and cell gates
`P[iof]` - P peephole weight vector for input, output, and forget gates
`WB[iofc]` - W parameter weight matrix for backward input, output, forget, and cell gates
`RB[iofc]` - R recurrence weight matrix for backward input, output, forget, and cell gates
`WBb[iofc]` - W bias vectors for backward input, output, forget, and cell gates
`RBb[iofc]` - R bias vectors for backward input, output, forget, and cell gates
`PB[iof]` - P peephole weight vector for backward input, output, and forget gates
`H` - Hidden state
`num_directions` - 2 if direction == bidirectional else 1
Equations (Default: f=Sigmoid, g=Tanh, h=Tanh):
- it = f(Xt*(Wi^T) + Ht-1*(Ri^T) + Pi (.) Ct-1 + Wbi + Rbi)
- ft = f(Xt*(Wf^T) + Ht-1*(Rf^T) + Pf (.) Ct-1 + Wbf + Rbf)
- ct = g(Xt*(Wc^T) + Ht-1*(Rc^T) + Wbc + Rbc)
- Ct = ft (.) Ct-1 + it (.) ct
- ot = f(Xt*(Wo^T) + Ht-1*(Ro^T) + Po (.) Ct + Wbo + Rbo)
- Ht = ot (.) h(Ct)
AttentionWrapp Notations:
`lstm()' - wrapped inner cell.
Ht, Ct = lstm(concat(Xt, ATTNt-1), Ct-1)
`am()` - attention mechanism the wrapper used.
CONTEXTt, ALIGNt = am(Ht, ALIGNt-1)
`AW` - attention layer weights, optional.
`ATTN` - attention state, initial is zero. If `AW` provided, it is the output of the attention layer,
ATTNt = concat(Ht, CONTEXTt) * AW
otherwise,
ATTNt = CONTEXTt
RNN layer output:
`Y` - if needed is the sequence of Ht from lstm cell.
`Y_h` - is the last valid H from lstm cell.
`Y_c` - is the last valid C from lstm cell.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation_alpha : list of floats
- Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.
- activation_beta : list of floats
- Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.
- activations : list of strings
- A list of 3 (or 6 if bidirectional) activation functions for input, output, forget, cell, and hidden. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.
- clip : float
- Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.
- direction : string
- Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.
- hidden_size : int
- Number of neurons in the hidden layer.
- input_forget : int
- Couple the input and forget gates if 1, default 0.
#### Inputs (3 - 14)
- X : T
- The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`
- W : T
- The weight tensor for the gates. Concatenation of `W[iofc]` and `WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape `[num_directions, 4*hidden_size, input_size]`.
- R : T
- The recurrence weight tensor. Concatenation of `R[iofc]` and `RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 4*hidden_size, hidden_size]`.
- B (optional) : T
- The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not specified - assumed to be 0.
- sequence_lens (optional) : T1
- Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`
- initial_h (optional) : T
- Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.
- initial_c (optional) : T
- Optional initial value of the cell. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.
- P (optional) : T
- The weight tensor for peepholes. Concatenation of `P[iof]` and `PB[iof]` (if bidirectional) along dimension 0. It has shape `[num_directions, 3*hidde_size]`. Optional: If not specified - assumed to be 0.
- QW (optional) : T
- The weight tensor of the query layer in the attention mechanism. Should be of shape `[num_directions, am_query_depth(hidden_size of lstm), am_attn_size]`
- MW (optional) : T
- The weight tensor of the memory layer in the attention mechanism. Should be of shape `[num_directions, memory_depth, am_attn_size]`
- V (optional) : T
- The attention_v tensor in the attention mechanism. Should be of shape `[num_directions, am_attn_size]`
- M (optional) : T
- The sequence of the memory (input) for attention mechanism. Should be of `[batch_size, max_memory_step, memory_depth]`
- memory_seq_lens (optional) : T1
- The sequence length of the input memory for the attention mechanism. Should be of `[batch_size]`
- AW (optional) : T
- The weights of attention layer in the attention wrapper. If exists, should be of shape `[num_directions, memory_depth+hidden_size, aw_attn_size]. Please note that attention mechanism context depth is also memory_depth in the attention mechanism.`
#### Outputs (0 - 3)
- Y (optional) : T
- A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`
- Y_h (optional) : T
- The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.
- Y_c (optional) : T
- The last output value of the cell. It has shape `[num_directions, batch_size, hidden_size]`.
#### Type Constraints
- T : tensor(float), tensor(double)
- Constrain input and output types to float tensors.
- T1 : tensor(int32)
- Constrain seq_lens to integral tensors.
### **com.microsoft.BeamSearch**
Beam Search for text generation. Supports GPT-2 decoder.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- decoder : graph (required)
- Decoder subgraph to execute in a loop.
- decoder_start_token_id : int
- The id of the token that indicates decoding starts.
- early_stopping : int
- early stop or not
- encoder : graph
- The subgraph for initialization of encoder and decoder. It will be called once before decoder subgraph.
- eos_token_id : int (required)
- The id of the end-of-sequence token
- init_decoder : graph
- The subgraph for the first decoding run. It will be called once before `decoder` subgraph. This is relevant only for the GPT2 model. If this attribute is missing, the `decoder` subgraph will be used for all decoding runs
- model_type : int
- model type: 0 for GPT-2; 1 for encoder decoder like T5
- no_repeat_ngram_size : int
- no repeat ngrams size
- pad_token_id : int (required)
- The id of the padding token
- vocab_size : int
- Size of the vocabulary. If not provided, it will be inferred from the decoder subgraph's output shape
#### Inputs (5 - 12)
- input_ids : F
- The sequence used as a prompt for the generation in the encoder subgraph. Shape is (batch_size, sequence_length)
- max_length : I
- The maximum length of the sequence to be generated. Shape is (1)
- min_length (optional) : I
- The minimum length below which the score of eos_token_id is set to -Inf. Shape is (1)
- num_beams : I
- Number of beams for beam search. 1 means no beam search. Shape is (1)
- num_return_sequences : I
- The number of returned sequences in the batch. Shape is (1)
- length_penalty (optional) : T
- Exponential penalty to the length. Default value 1.0 means no penalty.Value > 1.0 encourages longer sequences, while values < 1.0 produces shorter sequences.Shape is (1,)
- repetition_penalty (optional) : T
- The parameter for repetition penalty. Default value 1.0 means no penalty. Accepts value > 0.0. Shape is (1)
- vocab_mask (optional) : M
- Mask of vocabulary. Words that masked with 0 are not allowed to be generated, and 1 is allowed. Shape is (vocab_size)
- prefix_vocab_mask (optional) : M
- Mask of vocabulary for first step. Words that masked with 0 are not allowed to be generated, and 1 is allowed. Shape is (batch_size, vocab_size)
- attention_mask (optional) : I
- Custom attention mask. Shape is (batch_size, sequence_length)
- decoder_input_ids (optional) : I
- The forced input id sequence for the decoder subgraph. Shape is (batch_size, initial_sequence_length)
- logits_processor (optional) : I
- Specific logits processor for different types of beamsearch models. Default value 0 means no specific logit processor. Accepts value >= 0. Shape is (1)
#### Outputs (1 - 3)
- sequences : I
- Word IDs of generated sequences. Shape is (batch_size, num_return_sequences, max_sequence_length)
- sequences_scores (optional) : T
- Final beam score of the generated sequences. Shape is (batch_size, num_return_sequences)
- scores (optional) : T
- Processed beam scores for each vocabulary token at each generation step.Beam scores consisting of log softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this beam.Shape is (max_length - sequence_length, batch_size, num_beams, vocab_size)
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain to float tensors.
- F : tensor(float), tensor(int32), tensor(float16)
- Constrain input type to float or int tensors.
- I : tensor(int32)
- Constrain to integer types
- M : tensor(int32)
- Constrain mask to integer types
### **com.microsoft.BiasAdd**
Add input with bias, then add residual inputs.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- X : T
- Input tensor. Dimensions are (N, S, C), where N is the batch size, S is image size H*W, and C is number of channels
- bias : T
- Bias tensor. Dimensions are (C)
- skip : T
- Residual tensor. Dimensions are (N, S, C)
#### Outputs
- Y : T
- The output tensor with dimensions (N, S, C)
#### Type Constraints
- T : tensor(float16), tensor(float)
- Constrain input and output types to float tensors.
### **com.microsoft.BiasDropout**
output, dropout_mask = Dropout(data + bias, ratio) + residual, Intended to specialize the dropout pattern commonly found in transformer models.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- seed : int
- (Optional) Seed to the random generator, if not specified we will auto generate one.
#### Inputs (2 - 5)
- data : T
- The input data as Tensor.
- bias : T
- The bias input, a vector with the same shape as last dim of data OR same shape with data
- residual (optional) : T
- The residual input, must have the same shape as data
- ratio (optional) : T1
- The ratio of random dropout, with value in [0, 1). If this input was not set, or if it was set to 0, the output would be a simple copy of the input. If it's non-zero, output will be a random dropout of the scaled input, which is typically the case during training. It is an optional value, if not specified it will default to 0.5.
- training_mode (optional) : T2
- If set to true then it indicates dropout is being used for training. It is an optional value hence unless specified explicitly, it is false. If it is false, ratio is ignored and the operation mimics inference mode where nothing will be dropped from the input data and if mask is requested as output it will contain all ones.
#### Outputs (1 - 2)
- output : T
- The output.
- mask (optional) : T2
- The output mask of dropout.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
- T1 : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input 'ratio' types to float tensors.
- T2 : tensor(bool)
- Constrain output 'mask' types to boolean tensors.
### **com.microsoft.BiasGelu**
Bias Gelu.
It's an extension of Gelu. It takes the sum of input A and bias input B as the input of Gelu activation.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- A : T
- The normal input data.
- B : T
- The bias input data that is a 1D tensor.
#### Outputs
- C : T
- The output.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.BiasSoftmax**
Y = softmax(scores + bias)) with simple broadcast on bias. Intended to specialize softmax(scores + additive_mask) commonly found in transformer models.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- axis : int
- apply softmax to elements for dimensions axis or higher
- is_inner_broadcast : int (required)
- true if broadcast bias across input for dimensions broadcast_axis to axis-1, otherwise broadcast bias across input for dimensions 0 to broadcast_axis - 1
#### Inputs
- data : T
- The input data as Tensor.
- bias : T
- The bias (or mask) as Tensor.
#### Outputs
- output : T
- The output.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double)
- Constrain input and output types to float tensors.
### **com.microsoft.BiasSplitGelu**
A fusion used in diffusion model that after adding bias, hidden state is sliced into two tensors of same size, then left
tensor multiplies the Gelu activation result of right tensor.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- X : T
- Input tensor. Dimensions are (N, S, D), where N is the batch size, S are image size, and D is hidden dimension
- bias : T
- Bias tensor. Dimensions are (D), where D is the same hidden dimension as input tensor
#### Outputs
- Y : T
- The output tensor with dimensions (N, S, D/2)
#### Type Constraints
- T : tensor(float16), tensor(float)
- Constrain input X and output Y types to float tensors.
### **com.microsoft.BifurcationDetector**
Component for aggressive decoding. Find the bifurcation index of predicted tokens, between source tokens,
starting from previous suffix match index, and predicted tokens.
Concat predicted tokens, starting from bifurcation index, to the back
of current tokens. This forms the output tokens.
Detect suffix match index in source tokens, between source tokens and output tokens.
Detection is based on finding the appearances of last n-gram in output tokens
in source tokens.
A match is considered found if source tokens contain a single matching n-gram.
Return the index of the start of the n-gram in source tokens.
No matching if found if src tokens contain multiple or zero matching n-grams. Return -1.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- max_ngram_size : int
- The maximum NGram size for suffix matching.
- min_ngram_size : int
- The minimum NGram size for suffix matching.
#### Inputs (3 - 4)
- src_tokens : T
- Encoder input ids.
- cur_tokens : T
- Decoder input ids.
- prev_suffix_match_idx : T
- Previous suffix match index
- pred_tokens (optional) : T
- Predicted token ids from aggressive decoding
#### Outputs
- tokens : T
- Decoder input ids after merging predicted tokens
- suffix_match_idx : T
- new suffix match index
#### Type Constraints
- T : tensor(int64)
- Constrain to integer types.
### **com.microsoft.BitmaskBiasDropout**
output, dropout_bitmask = Dropout(data + bias, ratio) + residual, Intended to specialize the dropout pattern commonly found in transformer models.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- seed : int
- (Optional) Seed to the random generator, if not specified we will auto generate one.
#### Inputs (2 - 5)
- data : T
- The input data as Tensor.
- bias : T
- The bias input, a vector with the same shape as last dim of data OR same shape with data
- residual (optional) : T
- The residual input, must have the same shape as data
- ratio (optional) : T1
- The ratio of random dropout, with value in [0, 1). If this input was not set, or if it was set to 0, the output would be a simple copy of the input. If it's non-zero, output will be a random dropout of the scaled input, which is typically the case during training. It is an optional value, if not specified it will default to 0.5.
- training_mode (optional) : T2
- If set to true then it indicates dropout is being used for training. It is an optional value hence unless specified explicitly, it is false. If it is false, ratio is ignored and the operation mimics inference mode where nothing will be dropped from the input data and if mask is requested as output it will contain all ones.
#### Outputs (1 - 2)
- output : T
- The output.
- mask (optional) : T3
- The output mask of dropout.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
- T1 : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input 'ratio' types to float tensors.
- T2 : tensor(bool)
- Constrain input 'training_mode' types to boolean tensors.
- T3 : tensor(uint32)
- Constrain output 'mask' types to uint32 tensors.
### **com.microsoft.BitmaskDropout**
BitmaskDropout takes an input floating-point tensor, an optional input ratio (floating-point scalar) and an optional input training_mode (boolean scalar).
It produces two tensor outputs: output (floating-point tensor) and mask (optional `Tensor`). If `training_mode` is true then the output Y will be a random dropout.
Note that this Dropout scales the masked input data by the following equation, so to convert the trained model into inference mode, the user can simply not pass `training_mode` input or set it to false.
```
output = scale * data * mask,
```
where
```
scale = 1. / (1. - ratio).
```
This op functions in much the same was as Dropout-11 and Dropout-13 do, except that the mask is output as a bit-packed uint32 tensor, instead of a boolean tensor.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- seed : int
- (Optional) Seed to the random generator, if not specified we will auto generate one.
#### Inputs (1 - 3)
- data : T
- The input data as Tensor.
- ratio (optional) : T1
- The ratio of random dropout, with value in [0, 1). If this input was not set, or if it was set to 0, the output would be a simple copy of the input. If it's non-zero, output will be a random dropout of the scaled input, which is typically the case during training. It is an optional value, if not specified it will default to 0.5.
- training_mode (optional) : T2
- If set to true then it indicates dropout is being used for training. It is an optional value hence unless specified explicitly, it is false. If it is false, ratio is ignored and the operation mimics inference mode where nothing will be dropped from the input data and if mask is requested as output it will contain all ones.
#### Outputs (1 - 2)
- output : T
- The output.
- mask (optional) : T3
- The bit-packed output mask.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
- T1 : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input 'ratio' types to float tensors.
- T2 : tensor(bool)
- Constrain 'training_mode' to boolean tensor.
- T3 : tensor(uint32)
- Constrain output 'mask' types to bit-packed uint32 tensor.
### **com.microsoft.BranchwiseRMSNorm**
Applies RMS normalization independently to each branch. X may use grouped shape
(..., C, H), or flattened shape (..., C * H) when num_branches is specified.
The optional scale may have shape (C * H), (C, H), or (H). Arithmetic is
performed in float32 and the result is converted to T.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- epsilon : float
- Epsilon added before reciprocal square root.
- num_branches : int
- Number of branches for flattened input. Omit or set to zero for grouped input.
#### Inputs (1 - 2)
- X : T
- Grouped (..., C, H) or flattened (..., C * H) input.
- scale (optional) : M
- Optional scale with shape (C * H), (C, H), or (H).
#### Outputs
- Y : T
- RMS-normalized output with the same shape as X.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output to floating-point tensors.
- M : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain scale to floating-point tensors.
### **com.microsoft.CDist**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- metric : string
- The distance metric to use. If a string, the distance function can be "braycurtis", "canberra", "chebyshev", "cityblock", "correlation", "cosine", "dice", "euclidean", "hamming", "jaccard", "jensenshannon", "kulsinski", "mahalanobis", "matching", "minkowski", "rogerstanimoto", "russellrao", "seuclidean", "sokalmichener", "sokalsneath", "sqeuclidean", "wminkowski", "yule".
#### Inputs
- A : T
- 2D matrix with shape (M,N)
- B : T
- 2D matrix with shape (K,N)
#### Outputs
- C : T
- A 2D Matrix that represents the distance between each pair of the two collections of inputs.
#### Type Constraints
- T : tensor(float), tensor(double)
- Constrains input to only numeric types.
### **com.microsoft.CausalConvWithState**
Stateful causal depthwise convolution, generalized to N spatial dimensions.
Used by Gated DeltaNet (Qwen3.5) and Mamba (Jamba, FalconMamba) as a preprocessing step.
Replaces the 3-op pattern (Concat + Conv + Slice) with a single fused operation.
The convolution is causal (looks only at current and past positions along the last
spatial dimension) and depthwise (each channel is convolved independently with its own kernel).
Input layout is channels-first: (batch_size, channels, ...).
Weight layout: (channels, 1, k_1, ...) for depthwise convolution.
The carry state stores the last (k-1) positions along the causal axis for incremental decode.
The ndim attribute generalizes the op to 1D, 2D, or 3D spatial dimensions. Causality is
enforced on the last spatial dimension only.
The optional activation attribute supports fused SiLU/Swish activation.
The dilation attribute spaces the kernel taps along the causal axis: output position t reads
input positions t - (k_1 - 1 - j) * dilation for tap j. The receptive field therefore spans
(k_1 - 1) * dilation positions before the current one, and the carry state grows to match:
past_state and present_state hold (k_1 - 1) * dilation positions instead of k_1 - 1. Dilation 1
(the default) is the undilated case and keeps the original state length, so models exported
before the attribute existed are unaffected.
The channels_last attribute selects a sequence-major layout for the activations and the carry
state, so a model that already produces channels-last activations does not have to transpose into
and out of the channels-first layout. With channels_last = 1 and ndim = 1, input and output are
(batch_size, sequence_length, d_1, ..., d_n) and the state tensors are
(batch_size, state_length, d_1, ..., d_n), where channels = d_1 * ... * d_n. Any number of trailing
channel axes is accepted, so an activation that keeps hyper-connections and hidden size as separate
axes needs no reshape either. weight and bias keep their channels-first (channels, 1, k_1) and
(channels) shapes because they have no sequence axis. The computed values are identical to the
channels-first layout; only the memory layout differs.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : string
- Fused activation function. One of: 'silu', 'swish', 'none'. Default is 'none'.
- channels_last : int
- When 1, input, output, past_state and present_state use a sequence-major, channels-last layout: input and output are (batch_size, sequence_length, d_1, ..., d_n) and the state tensors are (batch_size, state_length, d_1, ..., d_n), where channels = d_1 * ... * d_n. weight and bias keep their channels-first shapes. Requires ndim = 1. Default is 0 (channels-first).
- dilation : int
- Spacing between kernel taps along the causal (last spatial) axis. The receptive field spans (k_1 - 1) * dilation positions before the current one, and past_state / present_state hold that many positions. Must be >= 1. Default is 1 (undilated).
- ndim : int
- Spatial dimensionality: 1, 2, or 3. Default is 1.
- state_window : int
- Number of trailing per-position carry states held by past_state and present_state. When 0 (default) the state tensors have no window axis and hold only the state after the last position, i.e. the backward-compatible (batch_size, channels, state_length) where state_length = (k_1 - 1) * dilation. When W > 0 both gain a LEADING axis of extent W, right-aligned: slot j is the state after position (seq_len - W + j), so slot W-1 is always the state after the last position (identical to the W = 0 tensor) and is the slot past_state is read from. The window axis leads the batch axis so that each slot is one contiguous (batch_size, channels, state_length) block. Slots below max(0, W - seq_len) hold no position from this call and are filled with zeros. A window lets a speculative decoder roll the state back to an accepted prefix without replaying the forward. Valid range is [0, 8].
#### Inputs (2 - 4)
- input : T
- Input tensor with shape (batch_size, channels, ...) in the default channels-first layout. Spatial dims: 1D: (L,); 2D: (H, W); 3D: (D, H, W). When channels_last = 1 the shape is (batch_size, sequence_length, d_1, ..., d_n) instead.
- weight : T
- Depthwise convolution kernel with shape (channels, 1, k_1, ...). Spatial kernel sizes: (k_1, ..., k_ndim).
- bias (optional) : T
- Optional per-channel bias with shape (channels).
- past_state (optional) : T
- Carry state from previous step. For ndim=1: (batch_size, channels, state_length), or (W, batch_size, channels, state_length) when state_window = W > 0, in which case only slot W-1 is read, where state_length = (k_1 - 1) * dilation. When channels_last = 1 each slot is (batch_size, state_length, d_1, ..., d_n) instead. If not provided, padding is zero.
#### Outputs
- output : T
- Convolution output with same shape as input.
- present_state : T
- Updated carry state. For ndim=1: (batch_size, channels, state_length), or (W, batch_size, channels, state_length) when state_window = W > 0, and (batch_size, state_length, d_1, ..., d_n) per slot when channels_last = 1. Slot W-1 contains the last state_length values from the virtual input along the causal axis; slot j contains the same for the prefix ending at position (seq_len - W + j).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.ComplexMul**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- A : T
- input_0
- B : T
- input_1
#### Outputs
- C : T
- output tensor
#### Type Constraints
- T : tensor(float), tensor(double), tensor(float16)
- Constrain input and output types to float or half tensors.
### **com.microsoft.ComplexMulConj**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- A : T
- input_0
- B : T
- input_1
#### Outputs
- C : T
- output tensor
#### Type Constraints
- T : tensor(float), tensor(double), tensor(float16)
- Constrain input and output types to float or half tensors.
### **com.microsoft.ConvTransposeWithDynamicPads**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- auto_pad : string
- dilations : list of ints
- group : int
- kernel_shape : list of ints
- output_padding : list of ints
- strides : list of ints
#### Inputs (2 - 4)
- X : T
- W : T
- Pads (optional) : tensor(int64)
- B (optional) : T
#### Outputs
- Y : T
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double)
- Constrain input and output types to float tensors
### **com.microsoft.CropAndResize**
Extracts crops from the input image tensor and resizes them using bilinear sampling or nearest neighbor sampling
(possibly with aspect ratio change) to a common output size specified by crop_height and crop_width.
Returns a tensor with crops from the input image at positions defined at the bounding box locations in boxes.
The cropped boxes are all resized (with bilinear or nearest neighbor interpolation) to
a fixed size = [crop_height, crop_width]. The result is a 4-D tensor [num_boxes, crop_height, crop_width, depth].
The resizing is corner aligned.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- extrapolation_value : float
- Value used for extrapolation, when applicable. Default is 0.0f.
- mode : string
- The pooling method. Two modes are supported: 'bilinear' and 'nearest'. Default is 'bilinear'.
#### Inputs
- X : T1
- Input data tensor from the previous operator; 4-D feature map of shape (N, C, H, W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data.
- rois : T1
- RoIs (Regions of Interest) to pool over; rois is 2-D input of shape (num_rois, 4) given as [[y1, x1, y2, x2], ...]. The RoIs' coordinates are normalized in the coordinate system of the input image. Each coordinate set has a 1:1 correspondence with the 'batch_indices' input.
- batch_indices : T2
- 1-D tensor of shape (num_rois,) with each element denoting the index of the corresponding image in the batch.
- crop_size : T2
- 1-D tensor of 2 elements: [crop_height, crop_width]. All cropped image patches are resized to this size. Both crop_height and crop_width need to be positive.
#### Outputs
- Y : T1
- RoI pooled output, 4-D tensor of shape (num_rois, C, crop_height, crop_width). The r-th batch element Y[r-1] is a pooled feature map corresponding to the r-th RoI X[r-1].
#### Type Constraints
- T1 : tensor(float16), tensor(float), tensor(double)
- Constrain types to float tensors.
- T2 : tensor(int32)
- Constrain types to int tensors.
### **com.microsoft.DecoderAttention**
This DecoderAttention supports self attention and cross attention, key and value cache, and key_padding_mask. The attention mask is not support at the moment.
Some boolean parameters are passed by runtime input for generic purpose
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- mask_filter_value : float
- The value to be filled in the attention mask. Default value is -10000.0f
- num_heads : int (required)
- Number of attention heads
#### Inputs
- query : T
- 3D input tensor with shape (sequence_length, batch_size, hidden_size), hidden_size = num_heads * head_size
- key : T
- 3D input tensor with shape (total_sequence_length, batch_size, hidden_size)
- q_weight : T
- 2D input tensor with shape (hidden_size, hidden_size)
- kv_weight : T
- 2D input tensor with shape (hidden_size, 2 * hidden_size)
- bias : T
- 1D input tensor with shape (3 * hidden_size)
- key_padding_mask (optional) : B
- 2D input tensor with shape (batch_size, total_sequence_length)
- key_cache (optional) : T
- input tensor with shape (batch_size, num_heads, sequence_length or total_sequence_length, head_size)
- value_cache (optional) : T
- input tensor with shape (batch_size, num_heads, sequence_length or total_sequence_length, head_size)
- static_kv : B
- If static_kv = true, cross-attention; else self-attention
- use_past : B
- If use_past = true, use cache; else no cache
- has_layer_state : B
- If has_layer_state = true, layer_state = {} or [a,b]; else layer_state = None
- has_key_padding_mask : B
- has_key_padding_mask or not
#### Outputs (1 - 3)
- output : T
- 3D output tensor with shape (sequence_length, batch_size, hidden_size)
- new_key_cache (optional) : T
- output tensor with shape (batch_size, num_heads, new sequence_length, head_size)
- new_value_cache (optional) : T
- output tensor with shape (batch_size, num_heads, new sequence_length, head_size)
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output types to float and float16 tensors.
- B : tensor(bool)
- Constrain key_padding_mask to bool tensors.
### **com.microsoft.DecoderMaskedMultiHeadAttention**
Multihead attention that supports input sequence length of 1.
Similar to DecoderMaskedSelfAttention but this op excludes QKV MatMul and Bias.
This op supports both Self and Cross Attention.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- mask_filter_value : float
- The value to be filled in the attention mask. Default value is -10000.0f
- num_heads : int (required)
- Number of attention heads
- output_qk : int
- Need output the cross attention MatMul(Q, K)
- past_present_share_buffer : int
- Corresponding past and present are same tensor, its size is (batch_size, num_heads, max_sequence_length, head_size)
- scale : float
- Custom scale will be used if specified. Default value is 1/sqrt(head_size)
#### Inputs (1 - 11)
- query : T
- Query with shape (batch_size, 1, hidden_size) or packed QKV with shape (batch_size, 1, 2 * hidden_size + v_hidden_size)
- key (optional) : T
- Key with shape (batch_size, 1, hidden_size) for self attention or past_key with shape (batch_size, num_heads, kv_sequence_length, head_size) for cross attention
- value (optional) : T
- Value with shape (batch_size, 1, v_hidden_size) for self attention or past_value with shape (batch_size, num_heads, kv_sequence_length, head_size) for cross attention
- mask_index (optional) : M
- Mask values of shape (batch_size, total_sequence_length) or (batch_size, kv_sequence_length)
- attention_bias (optional) : T
- additional add to QxK' with shape (batch_size or 1, num_heads or 1, sequence_length, total_sequence_length)
- past_key (optional) : T
- past state for key with shape (batch_size, num_heads, past_sequence_length, head_size) for self attentionWhen past_present_share_buffer is set, its shape is (batch_size, num_heads, max_sequence_length, head_size). The keys buffer is re-ordered in such a way that its virtual sub-tensor of shape (batch_size, num_heads, max_sequence_length, head_size) which may be perceived as being of shape (batch_size, num_heads, max_sequence_length, head_size / x, x) is reordered to become (batch_size, num_heads, head_size / x, max_sequence_length, x) where `x = 16 / sizeof(T)`.
- past_value (optional) : T
- past state for value with shape (batch_size, num_heads, past_sequence_length, head_size) for self attentionWhen past_present_share_buffer is set, its shape is (batch_size, num_heads, max_sequence_length, head_size).
- past_sequence_length (optional) : M
- When past_present_share_buffer is used, it is required to specify past_sequence_length (could be 0).Cross Attention doesn't need this input.
- beam_width (optional) : M
- The beam width that is being used while decoding. If not provided, the beam width will be assumed to be 1.
- cache_indirection (optional) : M
- A buffer of shape [batch_size, beam_width, max_output_length] where an `[i, j, k]` entry specifies which beam the `k`-th token came from for the `j`-th beam for batch `i` in the current iteration
- bias (optional) : T
- Bias tensor with shape (hidden_size + hidden_size + v_hidden_size) from input projection
#### Outputs (1 - 4)
- output : T
- 3D output tensor with shape (batch_size, sequence_length, v_hidden_size)
- present_key (optional) : T
- present state for key with shape (batch_size, num_heads, total_sequence_length, head_size). If past_present_share_buffer is set, its shape is (batch_size, num_heads, max_sequence_length, head_size), while effective_seq_length = (past_sequence_length + kv_sequence_length).
- present_value (optional) : T
- present state for value with shape (batch_size, num_heads, total_sequence_length, head_size). If past_present_share_buffer is set, its shape is (batch_size, num_heads, max_sequence_length, head_size), while effective_seq_length = (past_sequence_length + kv_sequence_length).
- qk (optional) : QK
- normalized Q * K, of shape (batch_size, num_heads, 1, total_sequence_length).
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output types to float tensors.
- QK : tensor(float), tensor(float16)
- Constrain QK output to float32 or float16 tensors, independent of input type or output type.
- M : tensor(int32)
- Constrain mask index to integer types
### **com.microsoft.DecoderMaskedSelfAttention**
Self attention that supports input sequence length of 1.
The weights for input projection of Q, K and V are merged. The data is stacked on the second dimension. Its shape
is (input_hidden_size, hidden_size + hidden_size + v_hidden_size). Here hidden_size is the hidden dimension of Q and K,
and v_hidden_size is that of V.
The mask_index is optional. If it is provided, only raw attention mask with shape (batch_size, total_sequence_length) is supported currently.
Both past and present state need to be provided.
The qkv_hidden_sizes is required only when K and V have different hidden sizes.
The total_sequence_length is past_sequence_length + kv_sequence_length. Here kv_sequence_length is the length of K or V.
Currently, only self attention is supported which means that kv_sequence_length equals to sequence_length (sequence length of Q).
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- do_rotary : int
- Whether to use rotary position embedding. Default value is 0.
- mask_filter_value : float
- The value to be filled in the attention mask. Default value is -10000.0f
- num_heads : int (required)
- Number of attention heads
- past_present_share_buffer : int
- Corresponding past and present are same tensor, its size is (2, batch_size, num_heads, max_sequence_length, head_size)
- scale : float
- Custom scale will be used if specified. Default value is 1/sqrt(head_size)
#### Inputs (7 - 9)
- input : T
- Input tensor with shape (batch_size, 1, input_hidden_size)
- weights : T
- Merged Q/K/V weights with shape (input_hidden_size, hidden_size + hidden_size + v_hidden_size)
- bias : T
- Bias tensor with shape (hidden_size + hidden_size + v_hidden_size) for input projection
- mask_index (optional) : M
- Mask values of shape (batch_size, total_sequence_length)
- past : T
- past state for key and value with shape (2, batch_size, num_heads, past_sequence_length, head_size)When past_present_share_buffer is set, its shape is (2, batch_size, num_heads, max_sequence_length, head_size). The first `batch_size * num_heads * max_sequence_length * head_size` elements correspond to keys and the next `batch_size * num_heads * max_sequence_length * head_size` elements correspond to values. The keys buffer is re-ordered in such a way that its virtual sub-tensor of shape (batch_size, num_heads, max_sequence_length, head_size) which may be perceived as being of shape (batch_size, num_heads, max_sequence_length, head_size / x, x) is reordered to become (batch_size, num_heads, head_size / x, max_sequence_length, x) where `x = 16 / sizeof(T)`.
- attention_bias (optional) : T
- additional add to QxK' with shape (batch_size or 1, num_heads or 1, sequence_length, total_sequence_length)
- past_sequence_length : M
- When past_present_share_buffer is used, it is required to specify past_sequence_length (could be 0).
- beam_width (optional) : M
- The beam width that is being used while decoding. If not provided, the beam width will be assumed to be 1.
- cache_indirection (optional) : M
- A buffer of shape [batch_size, beam_width, max_output_length] where an `[i, j, k]` entry specifies which beam the `k`-th token came from for the `j`-th beam for batch `i` in the current iteration
#### Outputs
- output : T
- 3D output tensor with shape (batch_size, sequence_length, v_hidden_size)
- present : T
- past state for key and value with shape (2, batch_size, num_heads, total_sequence_length, head_size). If past_present_share_buffer is set, its shape is (2, batch_size, num_heads, max_sequence_length, head_size), while effective_seq_length = (past_sequence_length + kv_sequence_length).
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output types to float tensors.
- M : tensor(int32)
- Constrain mask index to integer types
### **com.microsoft.DequantizeBFP**
The BFP dequantization operator.
It consumes the raw BFP data and some metadata such as the shape and strides of the original tensor and computes the dequantized tensor.
More documentation on the BFP format can be found in this paper: https://www.microsoft.com/en-us/research/publication/pushing-the-limits-of-narrow-precision-inferencing-at-cloud-scale-with-microsoft-floating-point/
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- bfp_type : int (required)
- The type of BFP - must match with the BFPType enum
- block_dim : int
- Each bounding box spans this dimension.Typically, the block dimension corresponds to the reduction dimension of the matrix multipication that consumes the output of this operator.For example, for a 2D matrix multiplication A@W, QuantizeBFP(A) would use block_dim 1 and QuantizeBFP(W) would use block_dim 0.The default is the last dimension.
- dtype : int
- The datatype to dequantize to.
#### Inputs
- x : T1
- 1-D, contiguous, raw, BFP data to be de-quantized.
- shape : T2
- shape of the original tensor.
- strides : T2
- strides of the original tensor.
#### Outputs
- y : T3
- de-quantized tensor.
#### Type Constraints
- T1 : tensor(uint8)
- Constrain the input to uint8.
- T2 : tensor(int64)
- Constrain shape and strides to uint64.
- T3 : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain y to float and bfloat16.
### **com.microsoft.DequantizeLinear**
The linear dequantization operator. It consumes a quantized data, a scale, a zero point and computes the full precision data.
The dequantization formula is y = (x - x_zero_point) * x_scale.
Scale and zero point must have same shape. They must be either scalar (per tensor) or 1-D tensor (per 'axis').
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- axis : int
- The axis along which same quantization parameters are applied. It's optional.If it's not specified, it means per-tensor quantization and input 'x_scale' and 'x_zero_point' must be scalars.If it's specified, it means per 'axis' quantization and input 'x_scale' and 'x_zero_point' must be 1-D tensors.
#### Inputs (2 - 3)
- x : T1
- N-D quantized Input tensor to be de-quantized.
- x_scale : T2
- Scale for input 'x'. It can be a scalar, which means a per-tensor/layer dequantization, or a 1-D tensor for per-axis dequantization.
- x_zero_point (optional) : T1
- Zero point for input 'x'. Shape must match x_scale. It's optional. Zero point is 0 when it's not specified.
#### Outputs
- y : T2
- N-D full precision output tensor. It has same shape as input 'x'.
#### Type Constraints
- T1 : tensor(int8), tensor(uint8), tensor(int16), tensor(uint16), tensor(int32), tensor(int4), tensor(uint4)
- Constrain 'x' and 'x_zero_point' to 8-bit integer tensors, 16-bit integer tensors, or 32-bit signed integer tensors.
- T2 : tensor(float16), tensor(float)
- Constrain 'y', 'x_scale' to float tensors.
### **com.microsoft.DequantizeWithOrder**
Dequantize input matrix to specific layout used in cublaslt. attr to specify output type, float16 or float32
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- order_input : int (required)
- cublasLt order of input matrix. See the schema of QuantizeWithOrder for order definition.
- order_output : int (required)
- cublasLt order of output matrix
- to : int (required)
- The output data type, only support TensorProto_DataType_FLOAT (1) and TensorProto_DataType_FLOAT16 (10)
#### Inputs
- input : Q
- TODO: input tensor of (ROWS, COLS). if less than 2d, will broadcast to (1, X). If 3d, it is treated as (B, ROWS, COS)
- scale_input : S
- scale of the input
#### Outputs
- output : F
- output tensor
#### Type Constraints
- Q : tensor(int8)
- Constrain input and output types to int8 tensors.
- F : tensor(float16), tensor(float)
- Constrain to float types
- S : tensor(float)
- Constrain Scale to float32 types
### **com.microsoft.DynamicQuantizeLSTM**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation_alpha : list of floats
- Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.For example with LeakyRelu, the default alpha is 0.01.
- activation_beta : list of floats
- Optional scaling values used by some activation functions. The values are consumed in the order of activation functions, for example (f, g, h) in LSTM. Default values are the same as of corresponding ONNX operators.
- activations : list of strings
- A list of 3 (or 6 if bidirectional) activation functions for input, output, forget, cell, and hidden. The activation functions must be one of the activation functions specified above. Optional: See the equations for default if not specified.
- clip : float
- Cell clip threshold. Clipping bounds the elements of a tensor in the range of [-threshold, +threshold] and is applied to the input of activations. No clip if not specified.
- direction : string
- Specify if the RNN is forward, reverse, or bidirectional. Must be one of forward (default), reverse, or bidirectional.
- hidden_size : int
- Number of neurons in the hidden layer
- input_forget : int
- Couple the input and forget gates if 1.
#### Inputs
- X : T
- The input sequences packed (and potentially padded) into one 3-D tensor with the shape of `[seq_length, batch_size, input_size]`.
- W : T2
- The weight tensor for the gates. Concatenation of `W[iofc]` and `WB[iofc]` (if bidirectional) along dimension 0. The tensor has shape `[num_directions, input_size, 4*hidden_size]`.
- R : T2
- The recurrence weight tensor. Concatenation of `R[iofc]` and `RB[iofc]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, hidden_size, 4*hidden_size]`.
- B (optional) : T
- The bias tensor for input gate. Concatenation of `[Wb[iofc], Rb[iofc]]`, and `[WBb[iofc], RBb[iofc]]` (if bidirectional) along dimension 0. This tensor has shape `[num_directions, 8*hidden_size]`. Optional: If not specified - assumed to be 0.
- sequence_lens (optional) : T1
- Optional tensor specifying lengths of the sequences in a batch. If not specified - assumed all sequences in the batch to have length `seq_length`. It has shape `[batch_size]`.
- initial_h (optional) : T
- Optional initial value of the hidden. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.
- initial_c (optional) : T
- Optional initial value of the cell. If not specified - assumed to be 0. It has shape `[num_directions, batch_size, hidden_size]`.
- P (optional) : T
- The weight tensor for peepholes. Concatenation of `P[iof]` and `PB[iof]` (if bidirectional) along dimension 0. It has shape `[num_directions, 3*hidde_size]`. Optional: If not specified - assumed to be 0.
- W_scale : T
- W's scale. Its size is [num_directions] for per-tensor/layer quantization, or [num_directions, 4*hidden_size] for per-channel quantization on the axis input_size.
- W_zero_point : T2
- W's zero point. Its size is [num_directions] for per-tensor/layer quantization, or [num_directions, 4*hidden_size] for per-channel quantization on the axis input_size.
- R_scale : T
- R's scale. Its size is [num_directions] for per-tensor/layer quantization, or [num_directions, 4*hidden_size] for per-channel quantization on the axis input_size.
- R_zero_point : T2
- R's zero point. Its size is [num_directions] for per-tensor/layer quantization, or [num_directions, 4*hidden_size] for per-channel quantization on the axis input_size.
#### Outputs (0 - 3)
- Y (optional) : T
- A tensor that concats all the intermediate output values of the hidden. It has shape `[seq_length, num_directions, batch_size, hidden_size]`.
- Y_h (optional) : T
- The last output value of the hidden. It has shape `[num_directions, batch_size, hidden_size]`.
- Y_c (optional) : T
- The last output value of the cell. It has shape `[num_directions, batch_size, hidden_size]`.
#### Type Constraints
- T : tensor(float)
- Constrain input and output types to float tensors.
- T1 : tensor(int32)
- Constrain seq_lens to integer tensor.
- T2 : tensor(uint8), tensor(int8)
- Constrain weights types to 8 bit tensors.
### **com.microsoft.DynamicQuantizeMatMul**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (3 - 5)
- A : T1
- N-dimensional matrix A
- B : T2
- N-dimensional matrix B
- b_scale : T1
- Scale of quantized input 'B'. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'B'.
- b_zero_point (optional) : T2
- Zero point tensor for input 'B'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'B'.
- bias (optional) : T1
- 1D input tensor, whose dimension is same as B's last dimension
#### Outputs
- Y : T1
- Matrix multiply results from A * B
#### Type Constraints
- T1 : tensor(float)
- Constrain input A, b_scale and output Y data type as float tensor.
- T2 : tensor(int8), tensor(uint8)
- Constrain input B data type to 8-bit integer tensor.
### **com.microsoft.DynamicSparseAttention**
Model-neutral sparse grouped-query attention with a contiguous main KV cache.
`selected_indices` and `selected_counts` are produced by an external selector. The operator never computes selection
scores or TopK indices. The first `selected_counts[q]` entries in each selected-index row are valid; remaining entries
must be -1. Valid entries must be unique, non-negative request-local positions in the selected source.
`attention_mode="selected_only"` attends only to selected entries. `attention_mode="local_plus_selected"` jointly
normalizes causally valid main-cache entries in `local_window_size` and selected auxiliary entries. An optional
per-query-head sink can participate in either mode; it contributes to the shared softmax denominator but has no value
vector. A row with no entries and no sink produces zero output.
Supported mode/source combinations:
- `selected_only` + `main`: Qwen4-Exp QSA-compatible execution.
- `local_plus_selected` + `auxiliary`: DeepSeek V4 CSA-compatible execution and requires `local_window_size > 0`.
The main cache uses BNSH layout and ordinary contiguous append semantics. Selection changes reads, not cache writes.
Auxiliary K/V use BNSH layout and are read-only. When `auxiliary_kv_shared=1`, auxiliary_value may be omitted and
auxiliary_key is used as both K and V. DeepSeek-style post-attention inverse/conjugate RoPE and output projection remain
the exporter's responsibility.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- attention_mode : string
- One of 'selected_only' or 'local_plus_selected'.
- auxiliary_kv_shared : int
- Use auxiliary_key as both key and value when auxiliary_value is omitted.
- do_rotary : int
- Whether to apply rotary embedding to Q and newly appended K.
- is_causal : int
- Must be 1. DynamicSparseAttention version 1 supports causal attention only.
- kv_num_heads : int (required)
- Number of main and auxiliary KV heads.
- local_window_size : int
- Number of causally visible main-cache entries in local_plus_selected mode.
- num_heads : int (required)
- Number of query heads.
- qk_norm_epsilon : float
- Epsilon for optional per-head Q/K RMS normalization.
- rotary_interleaved : int
- Whether rotary pairs use interleaved layout.
- rotary_offset : int
- First head channel covered by rotary embedding. Must be nonnegative, a multiple of 8, and leave room for the rotary dimensions within head_size.
- scale : float
- Scaling factor applied to QK. Defaults to 1/sqrt(head_size).
- selected_kv_source : string
- Source addressed by selected indices: 'main' or 'auxiliary'.
- smooth_softmax : int
- Add a zero-valued sink logit when no explicit head_sink is supplied.
#### Inputs (11 - 17)
- query : T
- Query [batch, sequence, num_heads * head_size]. When key and value are omitted, each row contains Q, K, then V concatenated with total width (num_heads + 2 * kv_num_heads) * head_size.
- key (optional) : T
- Current main key [batch, sequence, kv_num_heads * head_size].
- value (optional) : T
- Current main value [batch, sequence, kv_num_heads * head_size].
- past_key (optional) : T
- Main key cache in BNSH layout.
- past_value (optional) : T
- Main value cache in BNSH layout.
- auxiliary_key (optional) : T
- Read-only auxiliary key sequence in BNSH layout.
- auxiliary_value (optional) : T
- Read-only auxiliary value sequence in BNSH layout.
- selected_indices : M
- Selected request-local source positions [batch * sequence, max_selected].
- selected_counts : M
- Number of valid entries per selected-index row [batch * sequence].
- seqlens_k : M
- Total logical main sequence length minus one for each batch entry.
- total_sequence_length : M
- Maximum total main sequence length, as a scalar or one-element tensor.
- cos_cache (optional) : T
- Rotary cosine cache [max_sequence_length, rotary_dim / 2].
- sin_cache (optional) : T
- Rotary sine cache [max_sequence_length, rotary_dim / 2].
- position_ids (optional) : tensor(int64)
- Optional rotary positions [batch, sequence].
- q_norm_weight (optional) : T
- Optional Q RMSNorm weight [head_size].
- k_norm_weight (optional) : T
- Optional K RMSNorm weight [head_size].
- head_sink (optional) : T
- Optional sink logit [num_heads]. Participates in the shared softmax denominator in both attention modes.
#### Outputs (1 - 3)
- output : T
- Attention output [batch, sequence, num_heads * head_size].
- present_key (optional) : T
- Updated main key cache in BNSH layout.
- present_value (optional) : T
- Updated main value cache in BNSH layout.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain all floating-point inputs and outputs to one element type.
- M : tensor(int32)
- Constrain selection and sequence metadata to int32.
### **com.microsoft.DynamicTimeWarping**
Input is cost matrix where each value in input[r][c] is the cost for pass the point (r, c). From current point(r, c), points (r+1, c), (r+1, c+1) or (r, c+1) could be arrived in next move. Given such cost matrix, return dynamic time warping of shape [2, x], where the path made by all points (output[0][t], output[1][t])have the lowest cost among all paths from (0, 0) to (M-1, N-1).
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- input : F
- Input cost tensor, it must be 2D tensor of shape M x N, or 1 x M x N
#### Outputs
- output : I
- Output tensor. shape is [2, x], where max(M, N) <= x < M + N
#### Type Constraints
- F : tensor(float)
- Constrain to float tensors.
- I : tensor(int32)
- Constrain to integer types.
### **com.microsoft.EPContext**
Onnx node container for EP context.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- embed_mode : int
- 1: indicate ep_cache_context is the context content. 0: indicate ep_cache_context is the file path to the context content.The path is relative to this Onnx file. Default is 1.
- ep_cache_context : string
- payload of the execution provider context if embed_mode=1, or path to the context file if embed_mode=0.
- ep_sdk_version : string
- (Optional) SDK version used to convert the model.
- hardware_architecture : string
- (Optional) Hardware architecture.
- main_context : int
- Usually each single EPContext associate with a graph partition.But for some case like QNN, it has single EPContext contains all partitions.In that case, the node with ep_cache_context should set main_context=1. Other nodes set main_context=0 and skip ep_cache_context.The path is relative to this Onnx file. Default is 1.
- max_size : int
- max size in the context. Usage depend on the EP.
- notes : string
- (Optional) Some notes for the model
- onnx_model_filename : string
- (Optional) Filename of the original ONNX model.
- partition_name : string
- (Optional) partitioned graph name.
- source : string
- (Optional) the source used to generate the engine/context cache file. Ort EP or native SDK tool chain
#### Inputs (0 - ∞)
- inputs (variadic, heterogeneous) : T
- List of tensors for inputs
#### Outputs (1 - ∞)
- outputs (variadic, heterogeneous) : T
- One or more outputs, list of tensors for outputs
#### Type Constraints
- T : tensor(bool), tensor(int8), tensor(int16), tensor(int32), tensor(int64), tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64), tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types.
### **com.microsoft.EmbedLayerNormalization**
EmbedLayerNormalization is the fusion of embedding layer in BERT model, with optional mask processing.
The embedding layer takes input_ids (word IDs) and segment_ids (sentence IDs) to look up word_embedding, position_embedding,
and segment_emedding; the embeddings are added then applied layer normalization using gamma and beta tensors.
The last input mask is optional. If mask is provided, mask index (that is position of first 0 in mask, or number of words)
will be calculated.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- epsilon : float
- The epsilon value to use to avoid division by zero.
- mask_index_type : int
- The mask index tensor type for shape inference (0: None, 1: 1D mask_index)
#### Inputs (7 - 9)
- input_ids : T1
- 2D words IDs with shape (batch_size, sequence_length)
- segment_ids (optional) : T1
- 2D segment IDs with shape (batch_size, sequence_length)
- word_embedding : T
- 2D with shape (,hidden_size)
- position_embedding : T
- 2D with shape (, hidden_size)
- segment_embedding (optional) : T
- 2D with shape (, hidden_size)
- gamma : T
- 1D gamma tensor for layer normalization with shape (hidden_size)
- beta : T
- 1D beta tensor for layer normalization with shape (hidden_size)
- mask (optional) : T1
- 2D attention mask with shape (batch_size, sequence_length)
- position_ids (optional) : T1
- 2D position ids with shape (batch_size, sequence_length) or (1, sequence_length)
#### Outputs (1 - 3)
- output : T
- 3D output tensor with shape (batch_size, sequence_length, hidden_size)
- mask_index (optional) : T1
- 1D mask_index tensor with shape (batch_size)
- embedding_sum (optional) : T
- sum of word_embedding and position_embedding without layer normalization
#### Type Constraints
- T1 : tensor(int32)
- Constrain input and output integer tensors types
- T : tensor(float), tensor(float16)
- Constrain input and output float tensors types.
### **com.microsoft.EngramGate**
Fuses the Engram gate.
The op consumes already projected keys in (batch_size, sequence_length, hc_mult, hidden_size) layout,
the hidden-state queries in the same layout, an already projected value in
(batch_size, sequence_length, hidden_size) layout that is shared by every hyper-connection, and the two
RMSNorm scales. The key and value projections stay outside the op so they can run on the execution
provider's tuned MatMul (weight prepacking, tensor cores, quantized weights) and so the value
projection is computed once per token instead of once per hyper-connection.
It computes the Engram gate:
gate = sigmoid(sign(dot) * sqrt(max(abs(dot), 1e-6))) where
dot = sum(RMSNorm(key) * RMSNorm(query)) / sqrt(hidden_size).
The output is gate * value, broadcast across the hyper-connections. The optional gated_value_normed
output applies RMSNorm to gate * value with conv_norm_scale, which can feed a following
CausalConvWithState. The final Engram residual value + short_conv(value) is then expressed with
RMSNorm, CausalConvWithState and Add.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- epsilon : float
- Epsilon used by both RMS normalization steps. Default is 1e-5.
#### Inputs (5 - 6)
- key : T
- Projected Engram keys with shape (batch_size, sequence_length, hc_mult, hidden_size).
- query : T
- Hidden-state queries with shape (batch_size, sequence_length, hc_mult, hidden_size).
- value : T
- Projected Engram value shared by every hyper-connection, with shape (batch_size, sequence_length, hidden_size).
- key_norm_scale : T
- RMSNorm scale for keys with shape (hc_mult, hidden_size).
- query_norm_scale : T
- RMSNorm scale for queries with shape (hc_mult, hidden_size).
- conv_norm_scale (optional) : T
- Optional RMSNorm scale for the gated value, with shape (hc_mult, hidden_size). Required when gated_value_normed is requested.
#### Outputs (1 - 2)
- output : T
- Gated value tensor with shape (batch_size, sequence_length, hc_mult, hidden_size).
- gated_value_normed (optional) : T
- Optional RMS-normalized gated value tensor with shape (batch_size, sequence_length, hc_mult, hidden_size).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.ExpandDims**
ExpandDims echo operator.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- X : T
- input
- axis : tensor(int32)
- Specified axis to insert a dimension
#### Outputs
- Y : T
- output
#### Type Constraints
- T : tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64), tensor(int8), tensor(int16), tensor(int32), tensor(int64), tensor(float16), tensor(float), tensor(double), tensor(string), tensor(bool), tensor(complex64), tensor(complex128)
- Constrain to any tensor type. If the dtype attribute is not provided this must be a valid output type.
### **com.microsoft.FastGelu**
GELU (Gaussian Error Linear Unit) approximation: Y=0.5*X*(1+tanh(0.797885*X+0.035677*X*X*X)) with an optional input of bias that will be added to X before GELU.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (1 - 2)
- X : T
- input tensor
- bias (optional) : T
- bias tensor
#### Outputs
- Y : T
- output tensor
#### Type Constraints
- T : tensor(float), tensor(double), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float or half tensors.
### **com.microsoft.FusedConv**
The fused convolution operator schema is the same as Conv besides it includes an attribute
activation.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : string
- activation_params : list of floats
- auto_pad : string
- dilations : list of ints
- group : int
- kernel_shape : list of ints
- pads : list of ints
- strides : list of ints
#### Inputs (2 - 4)
- X : T
- W : T
- B (optional) : T
- Z (optional) : T
#### Outputs
- Y : T
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double)
- Constrain input and output types to float tensors
### **com.microsoft.FusedGemm**
The FusedGemm operator schema is the same as Gemm besides it includes attributes
activation and leaky_relu_alpha.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : string
- activation_alpha : float
- activation_beta : float
- activation_gamma : float
- alpha : float
- Scalar multiplier for the product of input tensors A * B.
- beta : float
- Scalar multiplier for input tensor C.
- transA : int
- Whether A should be transposed
- transB : int
- Whether B should be transposed
#### Inputs (2 - 3)
- A : T
- Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.
- B : T
- Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.
- C (optional) : T
- Input tensor C. The shape of C should be unidirectional broadcastable to (M, N).
#### Outputs
- Y : T
- Output tensor of shape (M, N).
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(uint32), tensor(uint64), tensor(int32), tensor(int64)
- Constrain input and output types to float/int tensors.
### **com.microsoft.FusedMatMul**
Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- alpha : float
- Scalar multiplier for the product of the input tensors.
- transA : int
- Whether A should be transposed on the last two dimensions before doing multiplication
- transB : int
- Whether B should be transposed on the last two dimensions before doing multiplication
- transBatchA : int
- Whether A should be transposed on the 1st dimension and batch dimensions (dim-1 to dim-rank-2) before doing multiplication
- transBatchB : int
- Whether B should be transposed on the 1st dimension and batch dimensions (dim-1 to dim-rank-2) before doing multiplication
#### Inputs
- A : T
- N-dimensional matrix A
- B : T
- N-dimensional matrix B
#### Outputs
- Y : T
- Matrix multiply results
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.FusedMatMulActivation**
Executes the same operation as FusedMatMul, but also has an activation function fused to its output.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : string (required)
- activation_alpha : float
- activation_axis : int
- activation_beta : float
- activation_gamma : float
- alpha : float
- Scalar multiplier for the product of the input tensors.
- transA : int
- Whether A should be transposed on the last two dimensions before doing multiplication
- transB : int
- Whether B should be transposed on the last two dimensions before doing multiplication
- transBatchA : int
- Whether A should be transposed on the 1st dimension and batch dimensions (dim-1 to dim-rank-2) before doing multiplication
- transBatchB : int
- Whether B should be transposed on the 1st dimension and batch dimensions (dim-1 to dim-rank-2) before doing multiplication
#### Inputs
- A : T
- N-dimensional matrix A
- B : T
- N-dimensional matrix B
#### Outputs
- Y : T
- Matrix multiply results
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.GatedAdd**
Adds one tensor to another tensor scaled by a per-row gate:
output = X + round_to_T(Y * gate)
X and Y have shape (..., C), and gate has shape (..., 1). The gate is broadcast
over C. For reduced-precision types, the product is rounded to T before the add,
matching separate ONNX Mul and Add operators.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- X : T
- Unscaled input with shape (..., C).
- Y : T
- Input scaled by gate, with the same shape as X.
- gate : T
- Per-row gate with shape (..., 1).
#### Outputs
- output : T
- Gated sum with the same shape as X.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.GatedDeltaNet**
Packed (token-major) gated delta network / linear attention with an explicit recurrent state.
Implemented by CUDA and native WebGPU execution providers. WebGPU supports float and float16
with scalar decay, `head_size_qk <= 256`, and compact state updates.
Layout. Query, key and value are token-major, so head counts are derived from the shapes
rather than from attributes:
query [total_tokens, num_heads_q, head_size_qk]
key [total_tokens, num_heads_k, head_size_qk]
value [total_tokens, num_heads_v, head_size_v]
Alternatively, key and value may be omitted and query contains packed QKV with shape
`[total_tokens, 2 * num_heads_q * head_size_qk + num_heads_v * head_size_v]`.
`initial_state` is required for packed QKV to determine the head counts and head sizes.
The leading token axis may instead be spelled as an explicit `[batch_size, sequence_length]`
pair, making query/key/value (and the output) rank 4 and decay/beta rank 3. The memory layout
is identical; the rank-4 spelling exists so an exporter can round-trip a `[B, S, H*D]`
activation with static Reshape targets instead of Shape-derived ones. Ragged packing
(`cu_seqlens`) requires the rank-3 spelling.
`num_heads_q` must equal `num_heads_k`, and `num_heads_v` must be a positive multiple of
`num_heads_q` (inverse grouped-query attention: each query/key head is shared by
`num_heads_v / num_heads_q` value heads). Decay, beta, the state and the output are all at
`num_heads_v`.
Sequence packing. When `cu_seqlens` is provided it is a device int32 tensor of length
`batch_size + 1` holding the exclusive prefix sums of the per-request token counts, so
requests may have different lengths. When it is absent the packing is uniform and the batch
size is taken from `initial_state`, which is then required.
State. `initial_state` and `final_state` are V-major, `[batch_size, num_heads_v, head_size_v,
head_size_qk]`, and always float regardless of the query/key/value type: the recurrence
boundary is where reduced precision hurts most. The two may be the same allocation; the
implementation reads the whole incoming state before writing any of it.
Compact state updates. When `state_update_capacity` C is greater than zero, `capture_count`
is required with shape `[batch_size]`. For request b, the first `capture_count[b]` local token
transitions (clamped on device to `[0, min(C, sequence_length)]`) are emitted in one `state_update`
float tensor `[batch_size, C * (num_heads_v + num_heads_k * head_size_qk + num_heads_v * head_size_v)]`.
Each row is struct-of-arrays: all decay values, then all keys, then all deltas. Entries at positions
greater than or equal to `min(capture_count[b], C, sequence_length)` are unspecified; consumers must
read only the captured prefix. The key retains its shared `num_heads_k` representation. For scalar
decay the decoded factors replay one transition as `S *= decay; S += outer(key, delta)`.
Per-key-dimension decay is not supported when compact updates are enabled. `capture_count` is
forbidden when C is zero.
The optional CPU input `state_update_active` has shape `[1]`. When zero, transition capture is
disabled, `capture_count` is ignored, `state_update` is zero-filled, and the planner may use an
engine that cannot emit compact updates. Omitting it preserves the conservative behavior of
treating capture as active.
Recurrence, per value head, with S the [head_size_qk x head_size_v] state:
S_t = exp(g_t) S_{t-1} + k_t (beta_t (v_t - exp(g_t) S_{t-1}^T k_t))^T
o_t = scale * S_t^T q_t
`update_rule` selects which terms are present: 'linear' drops both the decay and the delta
retrieval, 'gated' keeps only the decay, 'delta' keeps only the retrieval, and 'gated_delta'
keeps both.
The delta family ('delta' and 'gated_delta') requires L2-normalized keys. Without them the
per-chunk system (I + M) is arbitrarily ill-conditioned and the recurrence diverges. Either
normalize upstream or set `qk_l2_norm=1` to have the operator do it.
Fused activations. `gate_activation='qwen'` computes the effective decay in float32 from the
raw projection carried by `decay`:
g = -exp(a_log) * Softplus(decay + dt_bias)
`beta_activation='sigmoid'` applies a sigmoid to `beta`, and `qk_l2_norm=1` L2-normalizes each
query and key head vector. Folding these in avoids materializing the intermediates and keeps
the gate arithmetic in float32 independent of the input type.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- beta_activation : string
- 'none' (default) treats `beta` as the effective update rate. 'sigmoid' applies a sigmoid.
- chunk_size : int
- Tuning hint for the chunk-parallel prefill algorithm. On CUDA, 32 pins the narrow chunk and any other value lets the implementation select the widest chunk the device can hold. On WebGPU, 16 opts into the chunkwise prefill route on supported Apple silicon; default 64 retains recurrent execution. Default 64.
- gate_activation : string
- 'none' (default) treats `decay` as the effective log-space decay. 'qwen' computes -exp(a_log) * Softplus(decay + dt_bias) in float32.
- qk_l2_norm : int
- When 1, L2-normalize each query and key head vector before the recurrence. Default 0.
- scale : float
- Output scaling factor. When 0.0 (default) uses 1/sqrt(head_size_qk).
- state_update_capacity : int
- Capacity C for compact contiguous-prefix transition capture, in [0, 8]. 0 (default) disables compact state-update outputs.
- update_rule : string
- One of: 'linear', 'gated', 'delta', 'gated_delta'. Default is 'gated_delta'.
#### Inputs (1 - 11)
- query : T
- Query or packed QKV, shaped as described above.
- key (optional) : T
- Key, shape (total_tokens, num_heads_k, head_size_qk)
- value (optional) : T
- Value, shape (total_tokens, num_heads_v, head_size_v)
- cu_seqlens (optional) : TI
- Exclusive prefix sums of the per-request token counts, shape (batch_size + 1). Absent means uniform packing.
- decay (optional) : TS
- Log-space decay, shape (total_tokens, num_heads_v) for a scalar per-head decay or (total_tokens, num_heads_v, head_size_qk) for a per-key-dimension decay.
- beta (optional) : TS
- Update rate, shape (total_tokens, num_heads_v)
- initial_state (optional) : TS
- Recurrent state, shape (batch_size, num_heads_v, head_size_v, head_size_qk), V-major. Required for packed QKV. May alias final_state.
- a_log (optional) : TS
- Per-head A_log, shape (num_heads_v). Requires gate_activation=qwen.
- dt_bias (optional) : TS
- Per-head gate bias, shape (num_heads_v). Requires gate_activation=qwen.
- capture_count (optional) : TI
- Number of leading local token transitions to capture for each request, shape (batch_size). Clamped on device to [0, min(state_update_capacity, sequence_length)]. Required exactly when state_update_capacity is positive.
- state_update_active (optional) : TI
- CPU int32 control with shape (1). Zero disables transition capture, ignores capture_count, and produces a zero-filled state_update. Omission is conservative.
#### Outputs (1 - 3)
- output : T
- Output, shape (total_tokens, max(num_heads_q, num_heads_v), head_size_v)
- final_state (optional) : TS
- State after the last token of each request, shape (batch_size, num_heads_v, head_size_v, head_size_qk)
- state_update (optional) : TS
- Struct-of-arrays compact transition factors, shape (batch_size, state_update_capacity * (num_heads_v + num_heads_k * head_size_qk + num_heads_v * head_size_v)).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain query/key/value/output types.
- TS : tensor(float)
- State, gate, beta and compact state-update tensors are always float.
- TI : tensor(int32)
- Constrain index and count tensors to int32.
### **com.microsoft.GatedRMSNorm**
Gated RMS normalization as used by Mamba2 / gated DeltaNet attention outputs:
Y = X * rsqrt(mean(X^2) + epsilon) * scale * gate_activation(gate)
where `gate_activation` is one of:
- `silu` or `swish`: `z * sigmoid(z)`
- `sigmoid`: `sigmoid(z)`
The mean of squares is taken over the trailing `C` elements of each row, where `C` is the
length of `scale`; the input's last dimension must be a multiple of `C`, which lets a
per-head norm run on a packed (B, T, H * C) tensor without any surrounding Reshape.
All arithmetic including gate activation is done in float32 regardless of the tensor type, matching
the reference implementation, so this replaces the exported
SimplifiedLayerNormalization -> Cast -> Sigmoid -> Mul -> Cast -> Mul -> Cast chain with a
single launch.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : string
- Fused gate activation. One of: 'silu', 'swish', 'sigmoid'. 'swish' is an alias of 'silu'.
- epsilon : float
- Epsilon added to the mean of squares before the reciprocal square root.
#### Inputs
- X : T
- Input tensor with shape (..., H * C). Normalization is applied over each contiguous group of C elements.
- scale : T
- Normalization weight with shape (C).
- gate : T
- Gate tensor with the same shape as X.
#### Outputs
- Y : T
- Output tensor with the same shape as X.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.GatedRelativePositionBias**
query_layer = (query_layer + query_bias).reshape(batch_size, seq_len, num_heads, head_size).transpose(1, 2)
gate_u, gate_r = torch.sigmoid(
self.gate_ur_linear(query_layer).view(batch_size, num_head, seq_len, 2, D/2).sum(-1, keepdim=False)
).chunk(2, dim=-1)
gate_u_1 = gate_u * (gate_r * self.eco_a - 1.0) + 2.0
rel_pos_bias = gate_u_1 * rel_pos
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- num_heads : int (required)
- Number of attention heads
#### Inputs (6 - 7)
- query_layer : T
- tensor with shape (batch_size, seq_len, num_heads x head_size) or (token_count, num_heads x head_size)
- query_bias : T
- 1-d tensor with shape (num_heads x head_size)
- rel_pos : T
- tensor with shape (1, num_head, seq_len, seq_len)
- weight : T
- gemm weight for the gated_ur_linear, shape (head_size, D), D is divisible by 2
- bias : T
- bias for the gated_ur_linear, shape (D)
- eco_a : T
- tensor of shape (1, num_heads, 1, 1)
- token_offset (optional) : M
- offset of each token with shape (batch_size, seq_len)
#### Outputs
- output : T
- output tensor with shape (batch_size, num_heads, seq_len, seq_len)
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output types to float tensors.
- M : tensor(int32)
- Constrain token_offset to integer types
### **com.microsoft.GatherBlockQuantized**
GatherBlockQuantized is a Gather with data quantized. It is similar to Gather (https://github.com/onnx/onnx/blob/main/docs/Operators.md#gather) with differences:
1. Input `data` is a constant. It is quantized block-wise along attribute `quantize_axis` with block size specified by attribute `block_size`.
`block_size` must be a power of 2 and not smaller than 16, like 16, 32, 64, 128, ...
For an FP8 or FP4 `data` type (see point 6 below), `block_size` may also be 0, meaning the entire `quantize_axis`
dimension forms a single block (i.e. one scale per row).
2. Input `data`'s scale and zero point are specified by input `scales` and `zero_points`. `scales` and `zero_points` are also constants.
If `zero_points` is not provided, the default value is 0 for int4/uint4, or 2^(bits-1) for uint8.
`zero_points` must not be provided when `data` is an FP8 or FP4 type: FP8/FP4 quantization is symmetric.
3. During the op execution, `data` and `indices` are first used to generate the quantized output. Then, `scales` and `zero_points` are used
to dequantize the output.
4. The `output` and `scales` have the same type. The `data` and `zero_points` have the same type.
5. For uint8 data, the `gather_axis` must be 0. The supported `bits` values for uint8 data are 2, 4, and 8;
for `bits` < 8 the values are packed along the last dimension (low-order bits first), and `gather_axis`
and `quantize_axis` must differ.
6. `data` may also be an FP8 type (float8e4m3fn, float8e4m3fnuz, float8e5m2 or float8e5m2fnuz) or an FP4 type
(float4e2m1), rather than an integer block-quantized type. In that case `bits` is ignored, there is
no `zero_points` input, and dequantization is simply `output[...] = float(data[...]) * scales[block_index(...)]`.
On any axis other than `quantize_axis`, the corresponding `scales` dimension must either equal `data`'s
dimension, or be 1, in which case the scale is broadcast along that axis (e.g. a single scale shared by
every row, as with a per-tensor scale applied to an entire embedding table).
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- bits : int
- Number of bits used for weight quantization. Must be 2, 4 or 8. Ignored when `data` is an FP8 or FP4 type.
- block_size : int
- (Optional) block size used for weight quantization. It needs to be a power of 2 and not smaller than 16, or 0. A value of 0 is only valid for an FP8 or FP4 `data` type and means the entire `quantize_axis` dimension forms a single block.
- gather_axis : int
- (Optional) Which axis to gather on. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).
- quantize_axis : int
- (Optional) Which axis to block-wise quantize. Negative value means counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(data).
#### Inputs (3 - 4)
- data : T1
- Tensor of rank r >= 1. Block-wise quantized.
- indices : Tind
- Tensor of int32/int64 indices, of any rank q. Values in [-s, s-1] select elements along an axis of size s. Unlike ONNX Gather, an out-of-range index produces zeros for the corresponding output slice.
- scales : T2
- quantization scale. Same rank as data. On axes other than quantize_axis, a dimension of 1 broadcasts the scale along that axis (e.g. a single per-tensor scale for the whole table); only applicable when `data` is an FP8 or FP4 type.
- zero_points (optional) : T1
- quantization zero points. Must not be provided when `data` is an FP8 or FP4 type.
#### Outputs
- output : T2
- Dequantized output tensor of rank q + (r - 1).
#### Type Constraints
- T1 : tensor(int4), tensor(uint4), tensor(uint8), tensor(float8e4m3fn), tensor(float8e4m3fnuz), tensor(float8e5m2), tensor(float8e5m2fnuz), tensor(float4e2m1)
- Constrain quantized types.
- T2 : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain dequantized types.
- Tind : tensor(int32), tensor(int64)
- Constrain indices to integer types.
### **com.microsoft.GatherND**
Given `data` tensor of rank r >= 1, and `indices` tensor of rank q >= 1, gather
slices of `data` into an output tensor of rank q - 1 + r - indices[-1].
Example 1:
data = [[0,1],[2,3]]
indices = [[0,0],[1,1]]
output = [0,3]
Example 2:
data = [[0,1],[2,3]]
indices = [[1],[0]]
output = [[2,3],[0,1]]
Example 3:
data = [[[0,1],[2,3]],[[4,5],[6,7]]]
indices = [[0,1],[1,0]]
output = [[2,3],[4,5]]
Example 4:
data = [[[0,1],[2,3]],[[4,5],[6,7]]]
indices = [[[0,1]],[[1,0]]]
output = [[[2,3]],[[4,5]]]
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- data : T
- Tensor of rank r >= 1.
- indices : Tind
- Tensor of rank q >= 1.
#### Outputs
- output : T
- Tensor of rank q-1+r-indices[-1].
#### Type Constraints
- T : tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64), tensor(int8), tensor(int16), tensor(int32), tensor(int64), tensor(float16), tensor(float), tensor(double), tensor(string), tensor(bool), tensor(complex64), tensor(complex128)
- Constrain input and output types to any tensor type.
- Tind : tensor(int32), tensor(int64)
- Constrain indice type to int32 or int64
### **com.microsoft.Gelu**
Gaussian Error Linear Unit.
A high-performing neural network activation function.The GELU nonlinearity is
the expected transformation of a stochastic regularizer which randomly applies
the identity or zero map to a neuron's input. The GELU nonlinearity weights
inputs by their magnitude, rather than gates inputs by their sign as in ReLUs.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- X : T
- The input data as Tensor.
#### Outputs
- Y : T
- The output.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.GemmFastGelu**
It's a fusion of MatMul and FastGelu.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (2 - 3)
- X : T
- input tensor
- W : T
- input tensor
- bias (optional) : T
- bias tensor
#### Outputs
- Y : T
- output tensor
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float or half tensors.
### **com.microsoft.GemmFloat8**
Generic Gemm for float and float 8.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : string
- Activation function, RELU or GELU or NONE (default).
- alpha : float
- Scalar multiplier for the product of input tensors A * B.
- beta : float
- Scalar multiplier for the product of input bias C.
- dtype : int
- Output Type. Same definition as attribute 'to' for operator Cast.
- transA : int
- Whether A should be transposed. Float 8 only supported transA=0.
- transB : int
- Whether B should be transposed. Float 8 only supported transB=1.
#### Inputs (2 - 6)
- A : TA
- Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.
- B : TB
- Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.
- C (optional) : TC
- Input tensor C.
- scaleA (optional) : TS
- Scale of tensor A if A is float 8 tensor
- scaleB (optional) : TS
- Scale of tensor B if B is float 8 tensor
- scaleY (optional) : TS
- Scale of the output tensor if A or B is float 8.
#### Outputs
- Y : TR
- Output tensor of shape (M, N).
#### Type Constraints
- TA : tensor(float8e4m3fn), tensor(float8e5m2), tensor(float16), tensor(bfloat16), tensor(float)
- Constrain type to input A.
- TB : tensor(float8e4m3fn), tensor(float8e5m2), tensor(float16), tensor(bfloat16), tensor(float)
- Constrain type to input B.
- TC : tensor(float16), tensor(bfloat16), tensor(float)
- Constrain type to input C.
- TR : tensor(float8e4m3fn), tensor(float8e5m2), tensor(float16), tensor(bfloat16), tensor(float)
- Constrain type to result type.
- TS : tensor(float)
- Constrain type for all input scales (scaleA, scaleB, scaleY).
### **com.microsoft.GemmaRotaryEmbedding**
GemmaRotaryEmbedding is the implementation of below part of rotary positional embeddings (RoPE). It implements below from modeling_gemma.py.
Here's onnxscript that was tested
from onnxscript import FLOAT, FLOAT16, script
from onnxscript import opset18 as op
@script()
def gemma_rotary_embedding(emb: FLOAT["bs", "seq_len", "dim"], q: FLOAT16["bs", "num_heads", "seq_len", "dim"], q_rot: FLOAT16["bs", "num_heads", "seq_len", "dim"], k: FLOAT16["bs", "num_heads", "seq_len", "dim"], k_rot: FLOAT16["bs", "num_heads", "seq_len", "dim"]):
sin_val = op.Sin(emb)
casted_sin = op.Cast(sin_val, to=10) # for fp16 mix-precision training. Other types are not supported.
cos_val = op.Cos(emb)
casted_cos = op.Cast(cos_val, to=10)
unsqueezed_sin = op.Unsqueeze(casted_sin, [1])
unsqueezed_cos = op.Unsqueeze(casted_cos, [1])
q_embed = (q * casted_cos) + (q_rot * casted_sin)
k_embed = (k * casted_cos) + (k_rot * casted_sin)
return q_embed, k_embed
onnx_model = gemma_rotary_embedding.to_model_proto()
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- emb : U
- embedding - 3D tensor with shape (batch_size, seq_len, dim)
- q : T
- q state - 4D tensor with shape (batch_size, num_heads, seq_len, dim)
- q_rot : T
- half rotated q state - 4D tensor with shape (batch_size, num_heads, seq_len, dim)
- k : T
- k state - 4D tensor with shape (batch_size, num_heads, seq_len, dim)
- k_rot : T
- k state - 4D tensor with shape (batch_size, num_heads, seq_len, dim)
#### Outputs
- output1 : T
- 4D tensor with shape (batch_size, num_heads, seq_len, dim)
- output2 : T
- 4D tensor with shape (batch_size, num_heads, seq_len, dim)
#### Type Constraints
- T : tensor(float16)
- Constrain input and output types to float16 tensors.
- U : tensor(float)
- Constrain input 0 type to float tensors
### **com.microsoft.GreedySearch**
Greedy Search for text generation.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- decoder : graph (required)
- Decoder subgraph to execute in a loop.
- decoder_start_token_id : int
- The id of the token that indicates decoding starts.
- encoder : graph
- The subgraph for initialization of encoder and decoder. It will be called once before `decoder` subgraph.
- eos_token_id : int (required)
- The id of the end-of-sequence token
- init_decoder : graph
- The subgraph for the first decoding run. It will be called once before `decoder` subgraph. This is relevant only for the GPT2 model. If this attribute is missing, the `decoder` subgraph will be used for all decoding runs
- model_type : int
- model type: 0 for decoder only like GPT-2; 1 for encoder decoder like Bart
- no_repeat_ngram_size : int
- no repeat ngrams size
- pad_token_id : int (required)
- The id of the padding token
- vocab_size : int
- Size of the vocabulary. If not provided, it will be inferred from the decoder subgraph's output shape
#### Inputs (2 - 7)
- input_ids : I
- The sequence used as a prompt for the generation. Shape is (batch_size, sequence_length)
- max_length : I
- The maximum length of the sequence to be generated. Shape is (1)
- min_length (optional) : I
- The minimum length below which the score of eos_token_id is set to -Inf. Shape is (1)
- repetition_penalty (optional) : T
- The parameter for repetition penalty. Default value 1.0 means no penalty. Accepts value > 0.0. Shape is (1)
- vocab_mask (optional) : I
- Mask of vocabulary. Words that masked with 0 are not allowed to be generated, and 1 is allowed. Shape is (vocab_size)
- prefix_vocab_mask (optional) : I
- Mask of vocabulary for first step. Words that masked with 0 are not allowed to be generated, and 1 is allowed. Shape is (batch_size, vocab_size)
- attention_mask (optional) : I
- Custom attention mask. Shape is (batch_size, sequence_length)
#### Outputs
- sequences : I
- Word IDs of generated sequences. Shape is (batch_size, max_sequence_length)
#### Type Constraints
- T : tensor(float)
- Constrain input and output types to float tensors.
- I : tensor(int32)
- Constrain to integer types
### **com.microsoft.GridSample**
Given an `input` and a flow-field `grid`, computes the `output` using `input` values and pixel locations from `grid`.
Currently, only spatial (4-D) inputs are supported. For `input` with shape (N, C, H, W) and `grid` with shape (N, H_out, W_out, 2),
the `output` will have shape (N, C, H_out, W_out).
For each output location `output[n, :, h, w]`, the size-2 vector `grid[n, h, w]` specifies `input` pixel locations `x` and `y`,
which are used to interpolate the output value `output[n, :, h, w]`.
The GridSample operator is often used in doing grid generator and sampler in the [Spatial Transformer Networks](https://arxiv.org/abs/1506.02025).
See also in [torch.nn.functional.grid_sample](https://pytorch.org/docs/master/generated/torch.nn.functional.grid_sample.html#torch-nn-functional-grid-sample).
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- align_corners : int
- If align_corners=1, the extrema (-1 and 1) are considered as referring to the center points of the input's corner pixels. If align_corners=0, they are instead considered as referring to the corner points of the input's corner pixels, making the sampling more resolution agnostic.
- mode : string
- Three interpolation modes: bilinear (default), nearest and bicubic.
- padding_mode : string
- Support padding modes for outside grid values: `zeros`(default), `border`, `reflection`. zeros: use 0 for out-of-bound grid locations, border: use border values for out-of-bound grid locations, reflection: use values at locations reflected by the border for out-of-bound grid locations.
#### Inputs
- X : T1
- 4-D tensor of shape (N, C, H, W), where N is the batch size, C is the numbers of channels, H and W are the height and width of the input data.
- Grid : T1
- Input offset, 4-D tensor of shape (N, H_out, W_out, 2), where H_out and W_out are the height and width of grid and output, Grid specifies the sampling pixel locations normalized by the input spatial dimensions. Therefore, it should have most values in the range of [-1, 1]. If grid has values outside the range of [-1, 1], the corresponding outputs will be handled as defined by padding_mode.
#### Outputs
- Y : T2
- 4-D tensor of shape (N, C, H_out, W_out).
#### Type Constraints
- T1 : tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64), tensor(int8), tensor(int16), tensor(int32), tensor(int64), tensor(float16), tensor(float), tensor(double), tensor(string), tensor(bool), tensor(complex64), tensor(complex128)
- Constrain input types to all tensor types.
- T2 : tensor(float16), tensor(float), tensor(double)
- Constrain output types to float tensors.
### **com.microsoft.GroupNorm**
Applies Group Normalization over a mini-batch of inputs as described in the paper Group Normalization (https://arxiv.org/abs/1803.08494).
This operator transforms input according to
y = gamma * (x - mean) / sqrt(variance + epsilon) + beta
The input channels are separated into num_groups groups, each containing num_channels / num_groups channels. num_channels must be divisible by num_groups. The mean and standard-deviation are calculated separately over the each group.
The weight and bias are per-channel affine transform parameter vectors of size num_channels.
The activation attribute can be used to enable activation after group normalization.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : int (required)
- Activation after group normalization: 0 for None, 1 for SiLU
- channels_last : int
- 1 if the input and output are in the NHWC layout, 0 if it is in the NCHW layout. Defaults to 1.
- epsilon : float
- The epsilon value to use to avoid division by zero
- groups : int (required)
- The number of groups of channels. It should be a divisor of the number of channels C
#### Inputs
- X : T
- Input data tensor. Dimensions are (N x H x W x C) when channels_last is 1 or (N x C x H x W) otherwise, where N is the batch size, C is the number of channels, and H and W are the height and width of the data
- gamma : M
- 1D gamma tensor for normalization with shape (C), where C is number of channels
- beta : M
- 1D beta tensor for normalization with shape (C), where C is number of channels
#### Outputs
- Y : T
- The output tensor of the same shape as X
#### Type Constraints
- T : tensor(float16), tensor(float)
- Constrain input X and output Y types to float tensors.
- M : tensor(float16), tensor(float)
- Constrain gamma and beta to float tensors.
### **com.microsoft.GroupQueryAttention**
Group Query Self/Cross Attention with KV Cache Quantization Support.
This operator implements grouped-query attention with past state (KV cache) support.
It also supports optional float8, int8 or int4 quantization for the KV cache to reduce memory footprint.
**Cache Format:**
The past and present KV cache tensors are expected in a BNSH format: `(batch_size, num_heads, cache_sequence_length, head_size)`, where `cache_sequence_length` is the length of the cached key/value sequences, or the maximum sequence length when past and present buffer sharing is used.
**Windowed KV Cache (`sliding_window_cache` attribute):**
When `sliding_window_cache` is 1, the past/present buffers are window-sized instead of full-length and the operator evicts internally. Let `C` be the cache capacity (dimension 2 of `past_key`, which is also the sequence dimension of `present_key`), `W` be `local_window_size`, and `T` be the absolute number of tokens processed so far by this batch entry, i.e. `seqlens_k[b] + 1`. The scalar `total_sequence_length` input is only the batch maximum of `T`; the layout below is per batch entry, so a ragged batch gets a different resident range per entry. `C` must be at least `W`.
After a step, rows `[0, L)` of `present_key` and `present_value` hold the `L` most recent positions in increasing position order, so row `i` holds absolute position `T - L + i`. The retained positions are always physically contiguous and start at row 0; the layout never wraps around, so a ring-buffer layout cannot be exposed through these outputs. Rows `[L, C)` are unspecified. The resident count `L` is a function of `T` alone:
```
G = C - W + 1
L(T) = T if T <= C
L(T) = T - G * ceil((T - C) / G) otherwise
```
Hence `min(T, W) <= L(T) <= min(T, C)`: the whole window stays resident, and eviction reclaims `G` positions at once rather than one position per step, so consumers must not assume that the cache is kept full at `min(T, C)`.
Because `L` depends only on `T`, the resulting layout is independent of how the tokens were split into steps: a multi-token step of `S` tokens (speculative decoding, chunked prefill) leaves exactly the layout that the same tokens would produce one at a time. Any `S >= 1` is accepted, including `S > C`; a step that would evict positions it still has to read is staged internally, so the capacity does not have to cover the step. When past context is present, the existing operator restriction still applies: `sequence_length > 1` requires `batch_size == 1`.
An execution provider may accept only part of the `C >= W` range. A configuration with `C < W` (equivalently, `W > C`) is invalid and is rejected with `INVALID_ARGUMENT`. The CUDA implementation requires `C == W`, so there `G` is 1 and `L(T)` is `min(T, C)`; a larger capacity is rejected. The CPU implementation accepts any `C >= W`, and slack above the window amortizes compaction over `G` steps.
To drop the last `k` tokens, for example after rejecting speculative draft tokens, re-run with the smaller `total_sequence_length` and `seqlens_k` and leave the buffer untouched. That is exact when `L(T - k) == L(T) - k`, which callers can evaluate with the formula above. Otherwise the shorter layout needs positions that have already been evicted, and the window has to be re-materialized.
**Quantization:**
When quantization is enabled, `past_key` and `past_value` inputs can be of type `float8e4m3fn`, `uint8` or `int8`. The corresponding `k_scale` and `v_scale` tensors must be provided.
The operator will output `present_key` and `present_value` in same format as the `past_key` and `past_value`.
For 4-bit quantization, the data type is uint8 where each byte contains two 4-bit values. The bit width of quantized KV cache can be set using `kv_cache_bit_width` attribute.
The shapes of the k_scale, v_scale tensors shall be broadcastable to present_key shape.
**Quantization Modes (`k_quant_type`, `v_quant_type` attributes):**
- **"NONE"**: No quantization.
- **"PER_TENSOR"**: A single scale for the entire tensor. Scale example shape: `[1]`.
- **"PER_CHANNEL"**: A scale for each channel. Scale example shape: `[1, num_heads_k, 1, head_size]`.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- causal : int
- Whether to apply a causal mask. Must be 0 or 1. Default value is 1. Set to 0 for bidirectional attention.
- do_rotary : int
- Whether to use rotary position embedding. Default value is 0.
- k_quant_type : string
- Quantization type for K cache. One of 'NONE', 'PER_TENSOR', 'PER_CHANNEL'.
- kv_cache_bit_width : int
- Bit width of quantized KV cache. Supported values are 8 and 4.
- kv_num_heads : int (required)
- Number of attention heads for k and v
- local_window_size : int
- left_window_size for causal local attention (like Mistral). Must be -1 when causal is 0. Default value is -1 meaning unused.
- num_heads : int (required)
- Number of attention heads for q
- qk_norm_epsilon : float
- Epsilon used by the per-head RMS norm applied to Q and K when q_norm_weight and k_norm_weight inputs are provided. Default value is 1e-6.
- qk_output : int
- Output values of QK matrix multiplication before (1) or after (2) softmax normalization. Default value is 0 (don't output).
- rotary_interleaved : int
- Rotate using interleaved pattern. Default value is 0 (False).
- scale : float
- Custom scale will be used if specified. Default value is 1/sqrt(head_size)
- sliding_window_cache : int
- Set to 1 when the past/present KV buffers are window-sized instead of holding the whole sequence. The op then evicts internally and indexes the buffers in cache-relative coordinates, keeping the most recent positions contiguously at rows [0, L) with min(T, local_window_size) <= L <= min(T, capacity), where T is seqlens_k[b] + 1 for that batch entry. Requires local_window_size > 0 and a cache capacity of at least local_window_size; a smaller capacity (W > C) is rejected with INVALID_ARGUMENT. The CUDA implementation additionally requires the capacity to equal local_window_size. Multi-token steps of any length are supported and produce the same layout as single-token steps, so the capacity need not cover the entire step. When past context is present, sequence_length > 1 requires batch_size == 1. See the Windowed KV Cache section of the operator description for the exact resident-range, eviction and rollback contract. Default value is 0 (full-length cache).
- smooth_softmax : int
- Use a smooth factor in softmax.
- softcap : float
- Softcap value for attention weights. Default value is 0.
- v_quant_type : string
- Quantization type for V cache. One of 'NONE', 'PER_TENSOR', 'PER_CHANNEL'.
#### Inputs (7 - 16)
- query : T
- Query with shape (batch_size, sequence_length, hidden_size), or packed QKV with shape(batch_size, sequence_length, d) where d is (num_heads * head_size + 2 * kv_num_heads * head_size).
- key (optional) : T
- Key with shape (batch_size, kv_sequence_length, kv_hidden_size)
- value (optional) : T
- Value with shape (batch_size, kv_sequence_length, kv_hidden_size)
- past_key (optional) : T_CACHE
- past state key with support for format BNSH. When past_key uses same tensor as present_key(k-v cache), it is of length max_sequence_length... otherwise of length past_sequence_length. When sliding_window_cache is 1 this length is the window cache capacity C, which is chosen by the caller independently of the sequence length and must be at least local_window_size.
- past_value (optional) : T_CACHE
- past state value with support for format BNSH. When past_value uses same tensor as present_value(k-v cache), it is of length max_sequence_length... otherwise of length past_sequence_length. When sliding_window_cache is 1 this length is the window cache capacity C, which is chosen by the caller independently of the sequence length and must be at least local_window_size.
- seqlens_k : M
- 1D Tensor of shape (batch_size). Equivalent to (total_sequence_lengths - 1).
- total_sequence_length : M
- Scalar tensor equivalent to the maximum total sequence length (past + new) of the batch. Used for checking inputs and determining prompt vs token generation case.
- cos_cache (optional) : T
- 2D tensor with shape (max_sequence_length, head_size / 2).
- sin_cache (optional) : T
- 2D tensor with shape (max_sequence_length, head_size / 2).
- position_ids (optional) : tensor(int64)
- 2D tensor with shape (batch_size, sequence_length). When processing the first prompt the kernel uses only the first element
- attention_bias (optional) : T
- additional add to QxK' with shape (batch_size or 1, num_heads or 1, sequence_length, total_sequence_length). The last dimension is indexed by absolute key position and stays total_sequence_length when sliding_window_cache is 1: it is not reduced to the cache capacity or to local_window_size. The operator reads the columns of the positions that are resident in the cache and ignores the rest. CPU supports this windowed absolute-column indexing; CUDA rejects attention_bias when sliding_window_cache is 1.
- head_sink (optional) : T
- 1D tensor with shape (num_heads). Each head has a smooth factor adding to the denominator of softmax.
- k_scale (optional) : T_KV_SCALE
- Scale tensor for past_key.
- v_scale (optional) : T_KV_SCALE
- Scale tensor for past_value.
- q_norm_weight (optional) : T
- Optional 1D tensor of shape (head_size). When provided together with k_norm_weight, the kernel applies a per-head RMS normalization to Q (and K) before any rotary embedding. Used by Qwen3-style models that wrap their Q/K projections in a Reshape -> SimplifiedLayerNormalization -> Reshape stack; downstream graph fusion folds that pattern into this input. Currently honored by the CUDA and native WebGPU execution providers; JSEP WebGPU/JS and other EPs must reject the node when this input is set.
- k_norm_weight (optional) : T
- Optional 1D tensor of shape (head_size). See q_norm_weight. Must be provided together with q_norm_weight.
#### Outputs (1 - 4)
- output : T
- 3D output tensor with shape (batch_size, sequence_length, hidden_size)
- present_key (optional) : T_CACHE
- present state key with support for format BNSH. When past_key uses same tensor as present_key(k-v buffer), it is of length max_sequence_length... otherwise of length past_sequence_length +kv_sequence_length.
- present_value (optional) : T_CACHE
- present state value with support for format BNSH. When past_value uses same tensor as present_value(k-v buffer), it is of length max_sequence_length... otherwise of length past_sequence_length +kv_sequence_length.
- output_qk (optional) : T
- Values of QK matrix multiplication, either before or after softmax normalization
#### Type Constraints
- T : tensor(float16), tensor(bfloat16), tensor(float)
- Constrain input and output to float tensors.
- T_CACHE : tensor(float), tensor(float16), tensor(bfloat16), tensor(uint8), tensor(int8), tensor(float8e4m3fn)
- Constrain KV cache types.
- T_KV_SCALE : tensor(float)
- Constrain KV cache scale types.
- M : tensor(int32)
- Constrain mask to int tensor.
### **com.microsoft.HyperConnectionPostMix**
Mixes existing streams and injects one branch output:
Y[..., k, h] = sum_c(stream_mix[..., c, k] * streams[..., c, h])
+ post_mix[..., k, h] * block_output[..., h].
stream_mix is optional and defaults to the identity. post_mix has shape
(..., C), (..., C, 1), or (..., C, H). No activation is applied.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- num_branches : int
- Number of branches for flattened streams. Omit or set to zero for grouped streams.
#### Inputs (3 - 4)
- streams : T
- Grouped (..., C, H) or flattened (..., C * H) streams.
- block_output : T
- Feature tensor with shape (..., H).
- post_mix : M
- Branch or feature injection gates.
- stream_mix (optional) : M
- Optional stream matrix with shape (..., C, C).
#### Outputs
- output : T
- Mixed streams with the same shape as streams.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain streams, block output, and output to floating-point tensors.
- M : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain mixing weights to floating-point tensors.
### **com.microsoft.HyperConnectionPreMix**
Reduces C streams to one feature tensor without applying an activation:
Y[..., h] = reduction_scale * sum_c(X[..., c, h] * pre_mix[..., c, h]).
pre_mix may have shape (..., C), (..., C, 1), (..., C, H), or (..., C * H)
for flattened X. X may be grouped (..., C, H), or flattened (..., C * H)
when num_branches is specified.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- num_branches : int
- Number of branches for flattened streams. Omit or set to zero for grouped streams.
- reduction_scale : float
- Multiplier applied to the branch reduction.
#### Inputs
- streams : T
- Grouped (..., C, H) or flattened (..., C * H) streams.
- pre_mix : M
- Branch or feature gates with shape (..., C), (..., C, 1), (..., C, H), or (..., C * H) for flattened streams.
#### Outputs
- output : T
- Reduced feature tensor with shape (..., H).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain streams and output to floating-point tensors.
- M : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain mixing weights to floating-point tensors.
### **com.microsoft.Inverse**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- X : T
- Input tensor. Every matrix in the batch must be invertible.
#### Outputs
- Y : T
- Output tensor of the same type and shape as the input tensor.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double)
- Constrain input and output types to float tensors.
### **com.microsoft.Irfft**
This function computes the inverse of the one-dimensional n-point RFFT computed in 'com.microsoft.rfft'.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- normalized : int
- must be 0, normalization currently not supported
- onesided : int
- must be 1, only one sided FFTs supported
- signal_ndim : int (required)
- number of dimensions comprising the signal
#### Inputs
- X : T
- input tensor with size (n//2 + 1) in the signal dim and 2 in the last dimension for the real and complex parts
#### Outputs
- Y : T
- output tensor with size n in the signal dim
#### Type Constraints
- T : tensor(float), tensor(double), tensor(float16)
- Constrain input and output types to float or half tensors.
### **com.microsoft.LinearAttention**
Unified linear attention operator for autoregressive decoding (T=1) and prefill (T>1).
All inputs use 3D packed format [B, T, H*D]; q_num_heads and kv_num_heads are always
required. The op internally unpacks to 4D for computation.
The update_rule attribute selects the recurrence type:
- "linear": S_t = S_{t-1} + k_t ⊗ v_t; o_t = scale * q_t^T S_t
- "gated": S_t = exp(g_t) * S_{t-1} + k_t ⊗ v_t; o_t = scale * q_t^T S_t
- "delta": S_t = S_{t-1} + β_t * k_t ⊗ (v_t - S_{t-1}^T k_t); o_t = scale * q_t^T S_t
- "gated_delta": S_t = exp(g_t) * S_{t-1} + β_t * k_t ⊗ (v_t - exp(g_t) * S_{t-1}^T k_t); o_t = scale * q_t^T S_t
where g_t is the decay (in log-space), β_t is the update rate, and ⊗ denotes outer product.
Semantics: Equivalent to running the recurrent update sequentially for each token,
but may be implemented using chunk-parallel algorithms for GPU efficiency.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- chunk_size : int
- Chunk size for the chunk-parallel WY decomposition during prefill (T>1). Tuning hint; does not affect output correctness.
- kv_num_heads : int (required)
- Number of key/value heads. Always required.
- q_num_heads : int (required)
- Number of query heads. Always required.
- scale : float
- Output scaling factor. When 0.0 (default), derives d_k = query.shape[-1] / q_num_heads and uses 1/sqrt(d_k). Set explicitly to override.
- state_window : int
- Number of trailing per-token recurrent states held by past_state and present_state. When 0 (default) the state tensors are 4D and hold only the state after the last token, i.e. the backward-compatible (B, H_kv, d_k, d_v). When W > 0 both are 5D with a LEADING axis of extent W, right-aligned: slot j is the state after token (T - W + j), so slot W-1 is always the state after the last token (identical to the W = 0 tensor) and is the slot past_state is read from. The window axis leads the batch axis so that each slot is one contiguous (B, H_kv, d_k, d_v) block. Slots below max(0, W - T) hold no token from this call and are filled with zeros. A window lets a speculative decoder roll the state back to an accepted prefix without replaying the forward. Valid range is [0, 8].
- update_rule : string
- The update rule for the linear attention recurrence. One of: 'linear', 'gated', 'delta', 'gated_delta'. Default is 'gated_delta'.
#### Inputs (3 - 6)
- query : T
- Query vectors with 3D packed shape (B, T, H_q * d_k). Heads are packed into the last dimension.
- key : T
- Key vectors with 3D packed shape (B, T, H_kv * d_k). Should be L2-normalized for delta/gated_delta modes.
- value : T
- Value vectors with 3D packed shape (B, T, H_kv * d_v).
- past_state (optional) : S
- Recurrent state from previous step with shape (B, H_kv, d_k, d_v), or (W, B, H_kv, d_k, d_v) when state_window = W > 0, in which case only slot W-1 is read. If not provided, defaults to zeros.
- decay (optional) : T
- Exponential decay gate in log-space. 3D packed shape: (B, T, H_kv * d_k) for per-key-dimension decay (GLA/RWKV-6), or (B, T, H_kv) for per-head scalar decay (DeltaNet/RetNet). Required for 'gated' and 'gated_delta' modes.
- beta (optional) : T
- Update rate (sigmoid output). 3D packed shape: (B, T, H_kv) or (B, T, 1). Required for 'delta' and 'gated_delta' modes.
#### Outputs
- output : T
- Attention output with 3D packed shape (B, T, max(H_q, H_kv) * d_v). Standard GQA emits one output per query head; inverse GQA, where H_kv exceeds H_q, emits one per KV head.
- present_state : S
- Updated recurrent state with shape (B, H_kv, d_k, d_v), or (W, B, H_kv, d_k, d_v) when state_window = W > 0. Slot W-1 is the state after the last token; slot j is the state after token (T - W + j).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
- S : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain state types to float tensors.
### **com.microsoft.LinearAttentionGate**
Fuses the gate projections that feed LinearAttention's gated-delta recurrence:
decay = decay_scale * Softplus(a + dt_bias)
beta = Sigmoid(b) (only when b is provided)
Reference implementations compute the decay in float32 because exp(decay) inside the
recurrence exponentially amplifies any precision loss. Exporters therefore emit
Cast -> Add -> Softplus -> Mul -> Cast, which is five kernel launches on a tensor with
only num_heads elements per token. This operator keeps the intermediates in float32
registers so a single launch replaces the whole chain.
dt_bias and decay_scale are float32 per-head vectors of length H. decay_scale is the
already-negated -exp(A_log) factor.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (3 - 4)
- a : T
- Decay gate projection with shape (B, T, H).
- dt_bias : TF
- Per-head float32 bias added to a, with shape (H).
- decay_scale : TF
- Per-head float32 multiplier applied to Softplus(a + dt_bias), with shape (H). For gated DeltaNet this is -exp(A_log).
- b (optional) : T
- Update-rate projection with shape (B, T, H). Required when the beta output is requested.
#### Outputs (1 - 2)
- decay : T
- decay_scale * Softplus(a + dt_bias) with shape (B, T, H).
- beta (optional) : T
- Sigmoid(b) with shape (B, T, H).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain gate input and output types to float tensors.
- TF : tensor(float)
- Constrain the per-head parameters to float32.
### **com.microsoft.LongformerAttention**
Longformer Self Attention with a local context and a global context. Tokens attend locally: Each token
attends to its W previous tokens and W succeeding tokens with W being the window length. A selected few tokens
attend globally to all other tokens.
The attention mask is of shape (batch_size, sequence_length), where sequence_length is a multiple of 2W after padding.
Mask value < 0 (like -10000.0) means the token is masked, 0 otherwise.
Global attention flags have value 1 for the tokens attend globally and 0 otherwise.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- num_heads : int (required)
- Number of attention heads
- window : int (required)
- One sided attention windows length W, or half of total window length
#### Inputs
- input : T
- 3D input tensor with shape (batch_size, sequence_length, hidden_size), hidden_size = num_heads * head_size
- weight : T
- 2D input tensor with shape (hidden_size, 3 * hidden_size)
- bias : T
- 1D input tensor with shape (3 * hidden_size)
- mask : T
- Attention mask with shape (batch_size, sequence_length)
- global_weight : T
- 2D input tensor with shape (hidden_size, 3 * hidden_size)
- global_bias : T
- 1D input tensor with shape (3 * hidden_size)
- global : G
- Global attention flags with shape (batch_size, sequence_length)
#### Outputs
- output : T
- 3D output tensor with shape (batch_size, sequence_length, hidden_size)
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output types to float tensors.
- G : tensor(int32)
- Constrain to integer types
### **com.microsoft.MRotaryEmbedding**
MRotaryEmbedding is the fused implementation of Multimodal Rotary Positional Embeddings (M-RoPE) used by the
Qwen family of vision-language models (Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-VL-MoE, Qwen3.5, Qwen3.5-MoE).
Unlike standard RoPE which uses a single 1D position per token, M-RoPE derives three positions per token
(temporal T, height H, width W), each of which indexes into the same cos/sin cache. The half_rotary_embedding_dim
axis of the cache is partitioned into 3 contiguous or interleaved sections (specified by `mrope_section`); each
section is populated using the cos/sin values gathered with the corresponding T/H/W position, and the sections
are then concatenated (or interleaved) to produce a single per-token cos/sin vector of length
half_rotary_embedding_dim. The standard RoPE rotation (as in RotaryEmbedding) is then applied using this
combined vector.
For text-only tokens, T == H == W (all three position streams collapse to the ordinary sequential position),
so this op is a strict superset of RotaryEmbedding: setting `mrope_section` to a single full-width section
reduces this op to standard RoPE.
`mrope_layout` selects how the three sections are combined:
- 0 (Sectioned / Chunked): the half_rotary_embedding_dim axis is split into 3 contiguous chunks according to
`mrope_section` (i.e. [T]*section[0] + [H]*section[1] + [W]*section[2]). This is used by Qwen2-VL and
Qwen2.5-VL.
- 1 (Interleaved): the half_rotary_embedding_dim axis is filled starting from T at every position, then H
overwrites every 3rd position starting at offset 1 for the first `section[1]*3` positions, and W overwrites
every 3rd position starting at offset 2 for the first `section[2]*3` positions. This is used by Qwen3-VL,
Qwen3-VL-MoE, Qwen3.5, and Qwen3.5-MoE.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- interleaved : int
- Indicates whether the input has real and imaginary parts interleaved along the last (head_size) axis. Default value is 0 (False), meaning the first half of the rotary portion consists of real values and the second half consists of imaginary values.
- is_packed_batching : int
- ragged batch inputs or not. Default value is 0
- mrope_layout : int
- How the 3 sections are combined to form the per-token cos/sin vector: 0 (default) for Sectioned/Chunked layout (Qwen2-VL, Qwen2.5-VL) or 1 for Interleaved layout (Qwen3-VL, Qwen3-VL-MoE, Qwen3.5, Qwen3.5-MoE).
- mrope_section : list of ints (required)
- 3 non-negative integers [section_t, section_h, section_w] describing how the half_rotary_embedding_dim axis of the cos/sin cache is divided among the temporal, height, and width position streams. section_t + section_h + section_w must equal rotary_embedding_dim / 2 (or head_size / 2 when rotary_embedding_dim is 0). Required.
- num_heads : int
- Number of attention heads. Default value is 0. Must use with rotary_embedding_dim
- rotary_embedding_dim : int
- Rotary embedding dimension. Default value is 0, meaning the whole head_size is rotated.
- scale : float
- Custom scale will be used if specified. Default value is 1.0
#### Inputs
- input : T
- 3D tensor with shape (batch_size, sequence_length, hidden_size) or 4D with shape (batch_size, num_heads, sequence_length, head_size)
- position_ids : M
- 3D tensor with shape (3, batch_size, sequence_length) containing the temporal, height, and width position id streams (in that order along dim 0).
- cos_cache : T
- 2D tensor with shape (max_sequence_length, head_size / 2) or (max_sequence_length, rotary_embedding_dim / 2)
- sin_cache : T
- 2D tensor with shape (max_sequence_length, head_size / 2) or (max_sequence_length, rotary_embedding_dim / 2)
#### Outputs
- output : T
- tensor with same shape as input.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
- M : tensor(int64)
- Constrain position_ids to integer tensors
### **com.microsoft.MatMulBlockQuantizedFp4Weight**
Weight-only NVFP4 (E2M1) matrix multiplication.
The weight tensor B is stored as packed NVFP4: two E2M1 values per byte (low nibble first).
The dequantized weight value is `e2m1(B) * weight_scale_2 * e4m3(weight_scale[n, k / block_size])`,
where `weight_scale` holds one E4M3 scale per `block_size` (default 16) consecutive K values and
`weight_scale_2` is a single global fp32 scale. The weight is dequantized to the activation type
(FP16/BF16) and multiplied with the FP16/BF16 activation. This path is architecture independent and
runs on Hopper (SM90) as well as Blackwell.
The output columns `N` and the contraction dimension `K` are derived from the weight shape:
`N = B.shape[0]` and `K = 2 * B.shape[1]`. `K` must therefore be even.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- block_size : int
- Number of consecutive K values that share one E4M3 weight scale. Default 16.
#### Inputs (4 - 6)
- A : T
- Row-major FP16/BF16 activation of shape [..., K].
- B : T1
- Packed NVFP4 weight of shape [N, K/2] stored as uint8 (two E2M1 values per byte, low nibble first).
- weight_scale : T2
- Per-block E4M3 weight scales of shape [N, ceil(K / block_size)] stored as raw uint8 bytes.
- weight_scale_2 : T3
- Global fp32 weight scale (scalar).
- input_scale (optional) : T3
- Optional global fp32 activation scale (scalar). Accepted for parity with quantized checkpoints; it is a no-op on the weight-only FP16/BF16 path and is reserved for the native NVFP4 path on Blackwell.
- bias (optional) : T
- Optional bias of shape [N].
#### Outputs
- Y : T
- Output of shape [..., N] in the activation type.
#### Type Constraints
- T : tensor(float16), tensor(bfloat16)
- Constrain activation, bias and output to FP16 or BF16.
- T1 : tensor(uint8)
- Constrain packed NVFP4 weight to uint8.
- T2 : tensor(uint8)
- Constrain E4M3 weight scales to uint8.
- T3 : tensor(float)
- Constrain scalar scales to FP32.
### **com.microsoft.MatMulBlockQuantizedFp8Weight**
Block-scaled FP8 (E4M3) matrix multiplication with optional FP8 activation quantization.
The weight tensor B has shape [N, K] with one FP32 scale per `block_size` consecutive K values
(`b_scale` of shape [N, ceil(K / block_size)]). The scaled weight value is
`B_scaled[n, k] = fp8_e4m3(B[n, k]) * b_scale[n, k / block_size]`.
When the optional scalar `a_scale` is provided, the activation values used in the multiplication
are `A_scaled = fp8_e4m3(A / a_scale) * a_scale` (W8A8). Otherwise, A retains its FP16/BF16
precision (weight-only W8A16).
The operator multiplies the activation by the transpose of B_scaled and adds the optional bias.
The output has shape [..., N] and the same element type as A.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- block_size : int
- Number of consecutive K values that share one weight scale. Default 128.
#### Inputs (3 - 5)
- A : T
- Row-major FP16/BF16 activation of shape [..., K].
- B : T1
- Row-major FP8 E4M3 weight of shape [N, K].
- b_scale : T2
- Per-block FP32 weight scales of shape [N, ceil(K / block_size)].
- a_scale (optional) : T2
- Optional global fp32 activation scale (scalar). When present, A is statically quantized to FP8 E4M3 with this scale (W8A8 numerics); when absent, A retains its FP16/BF16 precision.
- bias (optional) : T
- Optional bias of shape [N].
#### Outputs
- Y : T
- Output of shape [..., N] in the activation type.
#### Type Constraints
- T : tensor(float16), tensor(bfloat16)
- Constrain activation, bias and output to FP16 or BF16.
- T1 : tensor(float8e4m3fn)
- Constrain weight to FP8 E4M3.
- T2 : tensor(float)
- Constrain scales to FP32.
### **com.microsoft.MatMulBnb4**
MatMulBnb4 is a MatMul with weight quantized with 4 bits using either FP4 or NF4 data type (https://arxiv.org/pdf/2305.14314.pdf). It does Matrix Multiplication like MatMul (https://github.com/onnx/onnx/blob/main/docs/Operators.md#matmul) with differences:
1. Input B is a 2D constant Matrix. Its input feature count and output feature count are specified by attribute 'K' and 'N'.
2. Input B is quantized with 4 bits with quantization data type specified by attribute 'quant_type'. It is transposed, flattened and quantized blockwisely with block size specified by attribute 'block_size'.
And block_size is not an arbitrary number and must be a power of 2 and not smaller than 16, like 16, 32, 64, 128,..
3. Input B's quantization constants or scales are specified by input 'absmax'.
Input B is stored as uint8_t with shape: [(N * K + 1) / 2].
Input absmax is stored in same type as original type of B(float32, float16) with shape like: [(N * K + block_size - 1) / block_size].
1. (Default value) transB=True (Majorly used for forward pass)
Shape of A: [D0, D1, ..., Dn, K]
Shape of Dequanted B: [N, K], this is aligned with how PyTorch defined the linear weight, .e.g [out_features, in_features].
The computation math:
dequant_B = dequant(B, absmax, quant_type, block_size)
transposed_dequant_B = dequant_B^T
output = A @ transposed_dequant_B
Shape of output: [D0, D1, ..., Dn, N]
2. transB=False (Majorly used for backward pass)
Shape of A: [D0, D1, ..., Dn, N]
Shape of Dequanted B: [N, K], this is aligned with how PyTorch defined the linear weight, .e.g [out_features, in_features].
The computation math:
dequant_B = dequant(B, absmax, quant_type, block_size)
output = A @ dequant_B
Shape of output: [D0, D1, ..., Dn, K]
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- K : int (required)
- size of each input feature
- N : int (required)
- size of each output feature
- block_size : int (required)
- number of groupsize used for weight quantization. It needs to be a power of 2 and not smaller than 16.
- quant_type : int (required)
- quantization data type. 0 for FP4, 1 for NF4.
- training_mode : int
- Indicate if the ops run in training_mode, by default, False.
- transB : int
- Whether B should be transposed on the last two dimensions before doing multiplication. Default to be 1.
#### Inputs
- A : T1
- The input tensor, not quantized
- B : T2
- 1-dimensional quantized data for weight
- absmax : T1
- quantization constants
#### Outputs
- Y : T1
- tensor. The output tensor has the same rank as the input.
#### Type Constraints
- T1 : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float/half_float/brain_float tensors.
- T2 : tensor(uint8)
- Constrain quantized weight types to uint8.
### **com.microsoft.MatMulFpQ4**
Matrix product with right hand matrix being pre-packed and quantized int4 data blob.
During quantization, the matrix is divided into blocks, where each block is a
contiguous subset inside each column. Each block is quantized into a
sequence of 4b integers with a scaling factor and an optional offset.
Currently 3 quantization types are supported:
(0): block size 32, no offset, (1): block size 32, with offset, (2): block size 64,
no offset
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- blk_quant_type : int
- Quantization type
#### Inputs
- A : T1
- N-dimensional matrix A
- B : T2
- 1-dimensional data blob
- B_shape : T3
- Shape information of B
#### Outputs
- Y : T1
- Matrix multiply results from A * B
#### Type Constraints
- T1 : tensor(float)
- Constrain input matrix data types as single precision float tensor
- T2 : tensor(uint8)
- Constrain input B data types as data blob
- T3 : tensor(int64)
- Constrain shape of B must be int64 tensor.
### **com.microsoft.MatMulInteger16**
Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html.
The production MUST never overflow. The accumulation may overflow if and only if in 32 bits.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- A : T1
- N-dimensional matrix A
- B : T2
- N-dimensional matrix B
#### Outputs
- Y : T3
- Matrix multiply results from A * B
#### Type Constraints
- T1 : tensor(int16), tensor(uint16)
- Constrain input A data types as 16-bit integer tensor
- T2 : tensor(int16), tensor(uint16)
- Constrain input B data types as 16-bit integer tensor
- T3 : tensor(int32), tensor(uint32)
- Constrain output Y data types as 32-bit integer tensor.T3 must be tensor(uint32) when both T1 and T2 are tensor(uint16),or must be tensor(int32) when either T1 or T2 is tensor(int16).
### **com.microsoft.MatMulIntegerToFloat**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (4 - 7)
- A : T1
- N-dimensional matrix A
- B : T2
- N-dimensional matrix B
- a_scale : T3
- Scale of quantized input 'A'. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'A'.
- b_scale : T3
- Scale of quantized input 'B'. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'B'.
- a_zero_point (optional) : T1
- Zero point tensor for input 'A'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'A'.
- b_zero_point (optional) : T2
- Zero point tensor for input 'B'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'B'.
- bias (optional) : T3
- 1D input tensor, whose dimension is same as B's last dimension
#### Outputs
- Y : T3
- Matrix multiply results from A * B
#### Type Constraints
- T1 : tensor(int8), tensor(uint8)
- Constrain input A data type to 8-bit integer tensor.
- T2 : tensor(int8), tensor(uint8)
- Constrain input B data type to 8-bit integer tensor.
- T3 : tensor(float), tensor(float16)
- Constrain input a_scale, b_scale and output Y data type as float tensor.
### **com.microsoft.MatMulNBits**
MatMulNBits performs a matrix multiplication where the right-hand-side matrix (weights) is quantized to N bits.
It is a fusion of two operations:
1. Linear dequantization of the quantized weights using scale and (optionally) zero-point with formula:
dequantized_weight = (quantized_weight - zero_point) * scale
2. Matrix multiplication between the input matrix A and the dequantized weight matrix.
The weight matrix is a 2D constant matrix with the input feature count and output feature count specified by attributes 'K' and 'N'.
It is quantized block-wise along the K dimension with a block size specified by the 'block_size' attribute.
The block size must be a power of 2 and not smaller than 16 (e.g., 16, 32, 64, 128). Each block has its own scale and zero-point.
The quantization is performed using a bit-width specified by the 'bits' attribute, which can take values from 2 to 8.
The quantized weights are stored in a bit-packed format along the K dimension, with each block being represented by a blob of uint8.
For example, for 4 bits, the first 4 bits are stored in the lower 4 bits of a byte, and the second 4 bits are stored in the higher 4 bits of a byte.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- K : int (required)
- Input feature dimension of the weight matrix.
- N : int (required)
- Output feature dimension of the weight matrix.
- accuracy_level : int
- The minimum accuracy level of input A, can be: 0(unset), 1(fp32), 2(fp16), 3(bf16), or 4(int8) (default unset). It is used to control how input A is quantized or downcast internally while doing computation, for example: 0 means input A will not be quantized or downcast while doing computation. 4 means input A can be quantized with the same block_size to int8 internally from type T1.
- bits : int
- Bit-width used to quantize the weights (supported values: 2, 4, 8)
- block_size : int (required)
- Size of each quantization block along the K (input feature) dimension. Must be a power of two and ≥ 16 (e.g., 16, 32, 64, 128).
- weight_prepacked : int
- If set, input B is already prepacked into an EP-specific layout and the EP skips runtime weight prepacking. 0 (default): not prepacked. 1: prepacked in the CUDA SM80 fpA_intB layout. 2: prepacked in the CUDA SM90 (Hopper) fpA_intB layout, consumed by the native SM90 kernel (requires a compute capability 9.0 device and block_size in {64, 128}).
#### Inputs (3 - 6)
- A : T1
- The input tensor, not quantized.
- B : T2
- Packed uint8 tensor of shape (N, k_blocks, blob_size), where k_blocks = ceil(K / block_size) and blob_size = (block_size * bits / 8). The quantized weights are stored in a bit-packed format along the K dimension, packed within each block_size.
- scales : T1
- Per-block scaling factors for dequantization with shape (N, k_blocks) and same data type as input A.
- zero_points (optional) : T3
- Per-block zero point for dequantization. It can be either packed or unpacked: Packed (uint8) format has shape (N, ceil(k_blocks * bits / 8)), and it uses same bit-packing method as Input B. Unpacked (same type as A) format has shape (N, k_blocks). If not provided, a default zero point is used: 2^(bits - 1) (e.g., 8 for 4-bit quantization, 128 for 8-bit).
- g_idx (optional) : T4
- group_idx. This input is deprecated
- bias (optional) : T1
- Bias to add to result. It should have shape [N].
#### Outputs
- Y : T1
- tensor. The output tensor has the same rank as the input.
#### Type Constraints
- T1 : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
- T2 : tensor(uint8)
- Constrain quantized weight types to uint8.
- T3 : tensor(uint8), tensor(float16), tensor(float), tensor(bfloat16)
- Constrain quantized zero point types to uint8 or float tensors.
- T4 : tensor(int32)
- the index tensor.
### **com.microsoft.MatMulNBitsMlp**
MatMulNBitsMlp fuses two MatMulNBits projections that share the same input and computes
gate = MatMulNBits(A, gate_weight) + gate_bias
up = MatMulNBits(A, up_weight) + up_bias
Y = activation(gate) * up
It can also optionally fuse SimplifiedLayerNormalization or SkipSimplifiedLayerNormalization before the
two projections:
A_norm = SimplifiedLayerNormalization(A, norm_scale, epsilon)
gate = MatMulNBits(A_norm, gate_weight) + gate_bias
up = MatMulNBits(A_norm, up_weight) + up_bias
Y = activation(gate) * up
A_norm = SkipSimplifiedLayerNormalization(A, skip, norm_scale, epsilon)
gate = MatMulNBits(A_norm, gate_weight) + gate_bias
up = MatMulNBits(A_norm, up_weight) + up_bias
Y = activation(gate) * up
This operator is intended for decoder MLP patterns such as Qwen-style gate and up projections, but it remains
semantically valid for both prefill and decode because the output shape is the standard MatMul result shape
derived from the runtime shape of A and the shared attributes K and N.
The operator contract includes a string attribute describing the fused gate activation.
When fused from SkipSimplifiedLayerNormalization, the optional residual-sum output may also be materialized:
A_norm, input_skip_bias_sum = SkipSimplifiedLayerNormalization(A, skip, norm_scale, epsilon)
gate = MatMulNBits(A_norm, gate_weight) + gate_bias
up = MatMulNBits(A_norm, up_weight) + up_bias
Y = activation(gate) * up
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- K : int (required)
- Input feature dimension shared by both quantized weight matrices.
- N : int (required)
- Output feature dimension shared by both quantized weight matrices.
- accuracy_level : int
- The minimum accuracy level of input A. It follows the same semantics as MatMulNBits.
- activation : string (required)
- Activation applied to the gate projection.
- bits : int
- Bit-width used to quantize both weight matrices. Currently only bits=4 is supported by the WebGPU kernel.
- block_size : int (required)
- Size of each quantization block along the K dimension. Currently only block_size=32 is supported by the WebGPU kernel.
- epsilon : float
- Epsilon used by the optional fused (Skip)SimplifiedLayerNormalization. Defaults to 1e-5.
#### Inputs (8 - 9)
- A : T1
- The shared input tensor.
- skip (optional) : T1
- Optional skip input used by SkipSimplifiedLayerNormalization.
- norm_scale (optional) : T1
- Optional RMSNorm scale with shape [K] used by SimplifiedLayerNormalization or SkipSimplifiedLayerNormalization.
- gate_B : T2
- Packed uint8 tensor for the gate projection weights.
- gate_scales : T1
- Per-block scaling factors for the gate projection.
- gate_bias (optional) : T1
- Optional bias for the gate projection with shape [N].
- up_B : T2
- Packed uint8 tensor for the up projection weights.
- up_scales : T1
- Per-block scaling factors for the up projection.
- up_bias (optional) : T1
- Optional bias for the up projection with shape [N].
#### Outputs (1 - 2)
- Y : T1
- The fused gated MLP output tensor.
- input_skip_bias_sum (optional) : T1
- Optional residual-sum output for SkipSimplifiedLayerNormalization.
#### Type Constraints
- T1 : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
- T2 : tensor(uint8)
- Constrain quantized weight types to uint8.
### **com.microsoft.MatMulNBitsQkv**
MatMulNBitsQkv fuses either SimplifiedLayerNormalization (RMSNorm)
or SkipSimplifiedLayerNormalization with three MatMulNBits projections that share the
same normalized activation.
A_norm = SimplifiedLayerNormalization(A, norm_scale, epsilon)
Q = MatMulNBits(A_norm, q_weight) + q_bias
K = MatMulNBits(A_norm, k_weight) + k_bias
V = MatMulNBits(A_norm, v_weight) + v_bias
If skip is provided, the operator computes the SkipSimplifiedLayerNormalization variant
and may also return the input+skip residual sum as output 3.
This operator is intended as a decode-oriented QKV fusion primitive.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- K : int (required)
- Input feature dimension shared by the normalized input and all projection weights.
- Nkv : int (required)
- Output feature dimension shared by the K and V projections.
- Nq : int (required)
- Output feature dimension of the Q projection.
- accuracy_level : int
- The minimum accuracy level of input A. It follows the same semantics as MatMulNBits.
- bits : int
- Bit-width used to quantize all weight matrices. Currently only bits=4 is supported by the WebGPU kernel.
- block_size : int (required)
- Size of each quantization block along the K dimension. Currently only block_size=32 is supported by the WebGPU kernel.
- epsilon : float
- Epsilon used by the simplified layer norm reduction.
#### Inputs (11 - 12)
- A : T1
- The shared input tensor.
- skip (optional) : T1
- Optional residual input for SkipSimplifiedLayerNormalization.
- norm_scale : T1
- Scale input for the simplified layer norm with shape [K].
- q_B : T2
- Packed uint8 tensor for the Q projection weights.
- q_scales : T1
- Per-block scaling factors for the Q projection.
- q_bias (optional) : T1
- Optional bias for the Q projection with shape [Nq].
- k_B : T2
- Packed uint8 tensor for the K projection weights.
- k_scales : T1
- Per-block scaling factors for the K projection.
- k_bias (optional) : T1
- Optional bias for the K projection with shape [Nkv].
- v_B : T2
- Packed uint8 tensor for the V projection weights.
- v_scales : T1
- Per-block scaling factors for the V projection.
- v_bias (optional) : T1
- Optional bias for the V projection with shape [Nkv].
#### Outputs (3 - 4)
- Q : T1
- The Q projection output tensor.
- K : T1
- The K projection output tensor.
- V : T1
- The V projection output tensor.
- input_skip_bias_sum (optional) : T1
- Optional residual-sum output for SkipSimplifiedLayerNormalization.
#### Type Constraints
- T1 : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
- T2 : tensor(uint8)
- Constrain quantized weight types to uint8.
### **com.microsoft.MaxpoolWithMask**
For internal use.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- auto_pad : string
- kernel_shape : list of ints
- pads : list of ints
- storage_order : int
- strides : list of ints
#### Inputs
- X : T
- M : tensor(int32)
- mask
#### Outputs
- Y : T
#### Type Constraints
- T : tensor(float)
- Constrain input0 and output types to float tensors
### **com.microsoft.MoE**
Mixture of experts. Examples: Switch transformer(https://arxiv.org/pdf/2101.03961.pdf) use top 1,
GLaM(https://arxiv.org/abs/2112.06905) activates top 2 FFN, Vision MOE(https://arxiv.org/pdf/2106.05974.pdf)
usually uses top 32 experts and Mixtral(https://huggingface.co/blog/mixtral).
A 2D input is the packed token-major form used by continuous-batching engines: tokens from
different requests are concatenated along dimension 0 without padding. MoE is token-local,
so request boundaries do not affect the result and no cumulative sequence-length input is
required. A 3D input is the dense convenience form and is processed as batch_size *
sequence_length independent token rows. router_probs must contain one corresponding row per
token in either form.
The SwiGLU (Swish-Gated Linear Unit) activation function is like:
g = xW + b
l = xV + c
G = clamp(g, max=limit)
L = clamp(l, min=-limit, max=limit)
swiglu = G * sigmoid(alpha * G) * (L + beta)
where x is the input, W and V are weight matrices, b and c are bias vectors, and alpha, beta and limit are constant float parameters.
When swiglu_fusion=0, two GEMMs are not fused, and they are FC1 and FC3 in the inputs.
When swiglu_fusion=1, two GEMMs are fused so that g and l are computed in a single GEMM (FC1), and g and l are interleaved on each row of size 2 * inter_size.
When swiglu_fusion=2, two GEMMs are fused, and g and l are concatenated on each row.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation_alpha : float
- Alpha parameter used in activation function.
- activation_beta : float
- Beta parameter used in activation function.
- activation_type : string
- Activation function to use. Choose from relu, gelu, silu, swiglu and identity. Default is relu
- k : int
- Number of top experts to select from expert pool
- normalize_routing_weights : int
- Whether to normalize routing weights
- swiglu_fusion : int
- 0: not fused, 1: fused and interleaved. 2: fused and not interleaved.
- swiglu_limit : float
- The limit used to clamp in SwiGLU. No clamp when limit is not provided.
- use_sparse_mixer : int
- Whether to use sparse mixer
#### Inputs (5 - 8)
- input : T
- 2D packed token tensor with shape (total_tokens, hidden_size), where tokens from ragged sequences may be concatenated without padding, or 3D input tensor with shape (batch_size, sequence_length, hidden_size)
- router_probs : T
- 2D input tensor with shape (total_tokens, num_experts), where total_tokens must match the flattened token count of input
- fc1_experts_weights : T
- 3D input tensor with shape (num_experts, fusion_size * inter_size, hidden_size), where fusion_size is 2 for fused swiglu, and 1 otherwise
- fc1_experts_bias (optional) : T
- 2D optional input tensor with shape (num_experts, fusion_size * inter_size)
- fc2_experts_weights : T
- 3D input tensor with shape (num_experts, hidden_size, inter_size)
- fc2_experts_bias (optional) : T
- 2D optional input tensor with shape (num_experts, hidden_size)
- fc3_experts_weights (optional) : T
- 3D optional input tensor with shape (num_experts, inter_size, hidden_size)
- fc3_experts_bias (optional) : T
- 2D optional input tensor with shape (num_experts, inter_size)
#### Outputs
- output : T
- Same shape as input: packed (total_tokens, hidden_size) or padded (batch_size, sequence_length, hidden_size)
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.MulInteger**
Performs element-wise binary quantized multiplication (with Numpy-style broadcasting support).
"This operator supports **multidirectional (i.e., Numpy-style) broadcasting**"
The output of this op is the int32 accumulated result of the mul operation
```
C (int32) = (A - A_zero_point) * (B - B_zero_point)
```
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (3 - 4)
- A : T
- First operand.
- A_zero_point (optional) : T
- Input A zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
- B : T
- Second operand.
- B_zero_point (optional) : T
- Input B zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
#### Outputs
- C : T1
- Constrain output to 32 bit tensor
#### Type Constraints
- T : tensor(uint8), tensor(int8)
- Constrain input types to 8 bit signed and unsigned tensors.
- T1 : tensor(int32)
- Constrain output types to 32 bit tensors.
### **com.microsoft.MultiHeadAttention**
Multi-Head Self/Cross Attention. Bias from input projection is included.
The key padding mask is optional. When its shape is (batch_size, kv_sequence_length), value 0
means padding or 1 otherwise. When key has right-side padding, its shape could be (batch_size): it is actual length of
each key sequence excluding paddings.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- mask_filter_value : float
- The value to be filled in the attention mask. Default value is -10000.0f
- num_heads : int (required)
- Number of attention heads
- scale : float
- Custom scale will be used if specified. Default value is 1/sqrt(head_size)
- unidirectional : int
- Whether every token can only attend to previous tokens. Default value is 0.
#### Inputs (1 - 10)
- query : T
- Query with shape (batch_size, sequence_length, hidden_size), or packed QKV with shape (batch_size, kv_sequence_length, num_heads, 3, head_size)
- key (optional) : T
- Key with shape (batch_size, kv_sequence_length, hidden_size), or packed KV with shape (batch_size, kv_sequence_length, num_heads, 2, head_size), or past_key with shape (batch_size, num_heads, kv_sequence_length, head_size)
- value (optional) : T
- Value with shape (batch_size, kv_sequence_length, v_hidden_size), or past_value with shape (batch_size, num_heads, kv_sequence_length, head_size)
- bias (optional) : T
- Bias tensor with shape (hidden_size + hidden_size + v_hidden_size) from input projection
- key_padding_mask (optional) : M
- Key padding mask with shape (batch_size), (3 * batch_size + 2), (batch_size, kv_sequence_length), (batch_size, total_sequence_length), or (batch_size, sequence_length, total_sequence_length)
- attention_bias (optional) : T
- bias added to QxK' with shape (batch_size or 1, num_heads or 1, sequence_length, total_sequence_length)
- past_key (optional) : T
- past state for key with shape (batch_size, num_heads, past_sequence_length, head_size) or (batch_size, num_heads, max_sequence_length, head_size) when buffer sharing is used
- past_value (optional) : T
- past state for value with shape (batch_size, num_heads, past_sequence_length, head_size) or (batch_size, num_heads, max_sequence_length, head_size) when buffer sharing is used
- past_sequence_length (optional) : M
- The past_sequence_length buffer sharing is used with
- cache_indirection (optional) : M
- A buffer of shape [batch_size, beam_width, max_sequence_length] where an [i, j, k] entry specifieswhich beam the 'k' th token came from for the 'j' th beam for batch 'i' in the current iteration
#### Outputs (1 - 4)
- output : T
- 3D output tensor with shape (batch_size, sequence_length, v_hidden_size)
- present_key (optional) : T
- present state for key with shape (batch_size, num_heads, total_sequence_length, head_size) or (batch_size, num_heads, max_sequence_length, head_size) when buffer sharing is used
- present_value (optional) : T
- present state for value with shape (batch_size, num_heads, total_sequence_length, head_size) or (batch_size, num_heads, max_sequence_length, head_size) when buffer sharing is used
- qk (optional) : QK
- normalized Q * K, of shape (batch_size, num_heads, sequence_length, total_sequence_length).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output to float tensors.
- QK : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain QK output to float32 or float16 tensors, independent of input type or output type.
- M : tensor(int32)
- Constrain mask to integer types
### **com.microsoft.MurmurHash3**
The underlying implementation is MurmurHash3_x86_32 generating low latency 32bits hash suitable for implementing lookup tables, Bloom filters, count min sketch or feature hashing.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- positive : int
- If value is 1, output type is uint32_t, else int32_t. Default value is 1.
- seed : int
- Seed for the hashing algorithm, unsigned 32-bit integer, default to 0.
#### Inputs
- X : T1
- An input tensor to hash.
#### Outputs
- Y : T2
- 32-bit hash value.
#### Type Constraints
- T1 : tensor(uint32), tensor(int32), tensor(uint64), tensor(int64), tensor(float), tensor(double), tensor(string)
- Constrain input type to unsigned or signed 32-bit integer tensor, or string tensor. It should be utf-8 encoded if using unicode.
- T2 : tensor(uint32), tensor(int32)
- Constrain output type to unsigned and signed 32-bit integer tensor.
### **com.microsoft.NGramHashMapping**
Computes Engram n-gram hash ids from pre-compressed tokenizer ids.
For n in [2, max_ngram_size], the op creates causal shifts of input_ids, padding positions before the
sequence with pad_id, and computes
mix = shifted_0 * multipliers[0] xor ... xor shifted_(n-1) * multipliers[n-1].
For every head of that n-gram order it emits mix modulo the corresponding head vocabulary size.
The output layout is (batch_size, sequence_length, (max_ngram_size - 1) * n_head_per_ngram), with
heads for n=2 first, then n=3, and so on.
An n-gram window reaches max_ngram_size - 1 positions before the current token. To keep the op causal
across invocations (chunked prefill or autoregressive decode), the optional past_ids input carries
those preceding ids and present_ids returns the ids to pass to the next call. Both have shape
(batch_size, max_ngram_size - 1) and are right-aligned, so the last slot is the most recent id.
Positions before the start of the whole sequence use pad_id, or eos_token_id when it is provided.
Running the op once over a full sequence and running it over consecutive chunks while threading
present_ids into past_ids produce identical hash ids, including when reset_on_eos is enabled. When
segment_ids is used, segment boundaries are applied only within the current input_ids chunk and are
not inferred from past_ids. When past_ids is omitted the missing history is pad_id, or eos_token_id
when it is provided.
past_ids and present_ids may use the same allocation. Such in-place execution is transaction-safe
only when the whole operator call is unconditionally committed; a caller that may select a prefix or
roll back must preserve past_ids.
Optional inputs add packed-sequence and Qwen4-Exp-style n-gram embedding support:
- eos_token_id, when provided together with reset_on_eos != 0, causes causal history to reset at EOS
boundaries: any shifted position at or before the most recent EOS strictly before the current
position is replaced with eos_token_id instead of the real token.
- segment_ids, when provided, additionally resets causal history at any position whose segment id
differs from the immediately preceding position's segment id within input_ids. Segment boundaries
are not checked against past_ids history.
- head_offsets, when provided, adds a fixed per-output-head offset after the modulo by the head's
vocabulary size, letting all heads across all n-gram orders share one flat embedding table.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- max_ngram_size : int (required)
- Maximum n-gram order. Must be at least 2.
- n_head_per_ngram : int (required)
- Number of hash heads emitted for each n-gram order.
- pad_id : int (required)
- Compressed tokenizer id used to pad causal shifts before the beginning of a sequence.
- reset_on_eos : int
- When non-zero and the eos_token_id input is provided, reset causal n-gram history at EOS boundaries as described in the op doc. Default is 0 (disabled), which preserves the original pad_id-only behavior.
#### Inputs (3 - 7)
- input_ids : M
- Compressed tokenizer ids with shape (batch_size, sequence_length).
- multipliers : M
- Per-shift hash multipliers with shape at least (max_ngram_size). Conventionally odd, but any value is accepted.
- vocab_sizes : M
- Per-output-head vocabulary sizes, conventionally prime, with shape ((max_ngram_size - 1) * n_head_per_ngram). Every entry must be strictly positive. The CPU implementation rejects a non-positive entry; GPU implementations guard the modulo to avoid a device-side division by zero and emit a hash id of 0 for that head.
- past_ids (optional) : M
- Optional compressed tokenizer ids for the max_ngram_size - 1 positions that precede this call, with shape (batch_size, max_ngram_size - 1). Right-aligned, so the last slot is the most recent id. If omitted the history is pad_id, or eos_token_id when provided.
- head_offsets (optional) : M
- Optional per-output-head additive offset with shape ((max_ngram_size - 1) * n_head_per_ngram), added after the modulo.
- eos_token_id (optional) : M
- Optional scalar end-of-sequence token id, same type as input_ids. Required for reset_on_eos to take effect and for EOS-based substitution of unavailable prior context; see the op doc.
- segment_ids (optional) : tensor(int32)
- Optional per-token segment id with shape (batch_size, sequence_length), used to reset causal history at packed-sequence boundaries within input_ids.
#### Outputs (1 - 2)
- hash_ids : M
- Hash ids with shape (batch_size, sequence_length, (max_ngram_size - 1) * n_head_per_ngram).
- present_ids (optional) : M
- Trailing max_ngram_size - 1 ids of past_ids followed by input_ids, with shape (batch_size, max_ngram_size - 1). Feed this back as past_ids on the next call.
#### Type Constraints
- M : tensor(int32), tensor(int64)
- Constrain ids, multipliers, vocabulary sizes, and output ids to integer tensors.
### **com.microsoft.NGramRepeatBlock**
Enforce no repetition of n-grams. Scores are set to `-inf` for tokens that form a repeated n-gram if added to the back of the input_ids.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- ngram_size : int (required)
- The NGram size.
#### Inputs
- input_ids : Tid
- 2D input tensor with shape (batch_size, sequence_length)
- scores : T
- 2D input tensor with shape (batch_size, vocab_size)
#### Outputs
- scores_out : T
- 2D output tensor with shape (batch_size, vocab_size)
#### Type Constraints
- Tid : tensor(int64)
- Constrain indices to integer types
- T : tensor(float)
- Constrain scores input and output types to float tensors.
### **com.microsoft.NhwcConv**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- auto_pad : string
- dilations : list of ints
- dilation value along each spatial axis of the filter. If not present, the dilation defaults is 1 along each spatial axis.
- group : int
- number of groups input channels and output channels are divided into.
- kernel_shape : list of ints
- The shape of the convolution kernel. If not present, should be inferred from input W.
- pads : list of ints
- strides : list of ints
- Stride along each spatial axis. If not present, the stride defaults is 1 along each spatial axis.
#### Inputs (2 - 3)
- X : T
- Input data tensor from previous layer; has size (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and width. Note that this is for the 2D image. Otherwise the size is (N x C x D1 x D2 ... x Dn). Optionally, if dimension denotation is in effect, the operation expects input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].
- W : T
- The weight tensor that will be used in the convolutions; has size (M x C/group x kH x kW), where C is the number of channels, and kH and kW are the height and width of the kernel, and M is the number of feature maps. For more than 2 dimensions, the kernel shape will be (M x C/group x k1 x k2 x ... x kn), where (k1 x k2 x ... kn) is the dimension of the kernel. Optionally, if dimension denotation is in effect, the operation expects the weight tensor to arrive with the dimension denotation of [FILTER_OUT_CHANNEL, FILTER_IN_CHANNEL, FILTER_SPATIAL, FILTER_SPATIAL ...]. Assuming zero based indices for the shape array, X.shape[1] == (W.shape[1] * group) == C and W.shape[0] mod G == 0. Or in other words FILTER_IN_CHANNEL multiplied by the number of groups should be equal to DATA_CHANNEL and the number of feature maps M should be a multiple of the number of groups G.
- B (optional) : T
- Optional 1D bias to be added to the convolution, has size of M.
#### Outputs
- Y : T
- Output data tensor that contains the result of the convolution. The output dimensions are functions of the kernel size, stride size, and pad lengths.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double)
- Constrain input and output types to float tensors.
### **com.microsoft.NhwcFusedConv**
NhwcFusedConv is a Conv operator with optional activation and add operators fused in.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : string
- activation_params : list of floats
- auto_pad : string
- dilations : list of ints
- group : int
- kernel_shape : list of ints
- pads : list of ints
- strides : list of ints
#### Inputs (2 - 4)
- X : T
- Input activation tensor in channels-last layout. For 2D convolution this is [N, H, W, C], where N is batch size, H/W are spatial dimensions, and C is the number of input channels.
- W : T
- Convolution weight tensor in the standard ONNX Conv filter layout [M, C/group, kH, kW], where M is the number of output channels.
- B (optional) : T
- Optional 1D bias tensor of shape [M].
- Z (optional) : T
- Optional residual/add tensor in the same channels-last layout and shape as the output tensor Y. For 2D convolution this is [N, out_H, out_W, M].
#### Outputs
- Y : T
- Output tensor in channels-last layout. For 2D convolution this is [N, out_H, out_W, M], where M is the number of output channels.
#### Type Constraints
- T : tensor(float16), tensor(float)
- Constrain input and output types to float tensors
### **com.microsoft.NhwcMaxPool**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- auto_pad : string
- ceil_mode : int
- dilations : list of ints
- kernel_shape : list of ints (required)
- pads : list of ints
- strides : list of ints
#### Inputs
- x : T
#### Outputs
- y : T
#### Type Constraints
- T : tensor(int8), tensor(uint8)
### **com.microsoft.PackedAttention**
This is the packed version of Attention.
Sequences in one batch usually don't have same length and they are padded to have same length,
e.g., below is a batch with 3 sequences and tokens* are padded.
Sequence_0: 0, 1*, 2*, 3*
Sequence_1: 4, 5, 6*, 7*
Sequence_2: 8, 9, 10, 11
PackedAttention is designed to takes in packed input, i.e., only the real tokens without padding.
An input as above will be packed into 3 tensors like below:
- input ([h0, h4, h5, h8, h9, h10, h11])
- token_offset: 0, 4, 5, 8, 9, 10, 11, 1*, 2*, 3*, 6*, 7*
- cumulated_token_count: 0, 1, 1+2, 1+2+4
Input tensors contains the hidden embedding of real tokens.
Token_offset records the offset of token in the unpacked input.
cumulated_token_count records cumulated length of each sequence length.
The operator only supports BERT like model with padding on right now.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- num_heads : int (required)
- Number of attention heads
- qkv_hidden_sizes : list of ints
- Hidden dimension of Q, K, V: hidden_size, hidden_size and v_hidden_size
- scale : float
- Custom scale will be used if specified. Default value is 1/sqrt(head_size)
#### Inputs (5 - 6)
- input : T
- Input tensor with shape (token_count, input_hidden_size)
- weights : T
- Merged Q/K/V weights with shape (input_hidden_size, hidden_size + hidden_size + v_hidden_size)
- bias : T
- Bias tensor with shape (hidden_size + hidden_size + v_hidden_size) for input projection
- token_offset : M
- In packing mode, it specifies the offset of each token(batch_size, sequence_length).
- cumulative_sequence_length : M
- A tensor with shape (batch_size + 1). It specifies the cumulative sequence length.
- attention_bias (optional) : T
- A tensor with shape (batch_size or 1, num_heads or 1, sequence_length, sequence_length).It specifies the additional bias to QxK'
#### Outputs
- output : T
- 2D output tensor with shape (token_count, v_hidden_size)
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output types to float tensors.
- M : tensor(int32)
- Constrain mask index to integer types
### **com.microsoft.PackedMultiHeadAttention**
This is the packed version of MultiHeadAttention.
Sequences in one batch usually don't have same length and they are padded to have same length,
e.g., below is a batch with 3 sequences and * is padding token.
Sequence_0: 0, 1*, 2*, 3*
Sequence_1: 4, 5, 6*, 7*
Sequence_2: 8, 9, 10, 11
PackedMultiHeadAttention is designed to takes in packed input, i.e., only the real tokens without padding.
An input as above will be packed into 3 tensors like below:
- query ([q0, q4, q5, q8, q9, q10, q11])
- key ([k0, k4, k5, k8, k9, k10, k11])
- value ([v0, v4, v5, v8, v9, v10, v11])
- token_offset: 0, 4, 5, 8, 9, 10, 11, 1*, 2*, 3*, 6*, 7*
- cumulative_sequence_length: 0, 1, 1+2, 1+2+4
The query, key and value tensors contain result of hidden embedding of real tokens after input projections.
Token_offset records the offset of token in the unpacked input.
cumulative_sequence_length records cumulated length of each sequence length.
The operator only supports BERT like model with padding on right now.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- mask_filter_value : float
- The value to be filled in the attention mask. Default value is -10000.0f
- num_heads : int (required)
- Number of attention heads
- scale : float
- Custom scale will be used if specified. Default value is 1/sqrt(head_size)
#### Inputs (6 - 7)
- query : T
- Query with shape (token_count, hidden_size) or packed qkv with shape (token_count, num_heads, 3, head_size)
- key (optional) : T
- Key with shape (token_count, hidden_size)
- value (optional) : T
- Value with shape (token_count, v_hidden_size)
- bias (optional) : T
- Bias tensor with shape (hidden_size + hidden_size + v_hidden_size) from input projection
- token_offset : M
- Offset of each token before packing, with shape (batch_size, sequence_length).
- cumulative_sequence_length : M
- A tensor with shape (batch_size + 1). It specifies the cumulative sequence length.
- attention_bias (optional) : T
- It specifies the additional bias to QxK'. The shape is (batch_size or 1, num_heads or 1, sequence_length, sequence_length)
#### Outputs
- output : T
- output tensor with shape (token_count, v_hidden_size)
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output to float tensors.
- M : tensor(int32)
- Constrain mask, offset and sequence length to integer types
### **com.microsoft.PackedSparseAttentionIndexer**
Packed/variable-length counterpart of SparseAttentionIndexer, for continuous-batching engines
(such as an OgaEngine-style PagedAttention model) that flatten every request's tokens into one
[total_tokens, ...] axis instead of a dense [batch_size, sequence_length, ...] axis. It selects, for
every packed query token, the sparse-attention candidates that a following SparsePagedAttention (or
similar) operator is allowed to read.
Unlike SparseAttentionIndexer, this operator:
* takes packed query/key tensors plus cumulative_sequence_lengths (request boundaries) and
past_sequence_lengths (per-request past length) instead of a dense batch and a dense mask;
* derives ordinary causal visibility purely from that packed metadata -- there is no mask input;
* uses a single generic set of state slots (past_key_state / past_kv_buffer / past_gate_buffer /
past_state_lengths) for both policy_mode values, each with a shape that is fixed across calls
(state never grows and is never concatenated); a step that would overflow the fixed capacity is
rejected as a deterministic no-op on state rather than truncated or allowed to corrupt memory;
* additionally emits selected_counts, the exact number of active (non -1) entries per query, so
that no downstream consumer needs to scan selected_indices for its query's true count.
Both policy_mode values keep the semantics of SparseAttentionIndexer, applied independently to each
request's own packed token range and fixed-capacity state slice:
policy_mode = "qsa" ("query sparse attention" token indexer)
Processes each request's new tokens sequentially: appends raw indexer keys to the generic
pending buffer, and whenever it reaches compress_ratio tokens, mean-pools it, applies RMSNorm
and key_norm_weight, applies the leading/split-half rotary convention at the block's first
logical token position, and appends the prepared (already normalized and rotated) key to
key_state. Queries are scored against every causally visible complete block with
sum_h ReLU(q_h . k), the token_budget / compress_ratio highest scoring blocks are kept, and
their token indices are emitted (request-local logical positions, i.e. the same numbering as
past_sequence_lengths + local offset) followed by the causally visible tokens of the trailing
incomplete block. QSA positions are the request-local logical cache positions derived from
past_sequence_lengths and cumulative_sequence_lengths; position_ids must be omitted.
policy_mode = "csa" ("compressed sparse attention" block indexer)
Applies the same window-plan arithmetic as SparseAttentionIndexer (overlap/leftover/new window
count) independently per request, using that request's own buffer_length and new token count;
every newly closed window is compressed with the softmax-gated Ca/Cb pooling, normalized,
rotated and appended to key_state. Queries are scored against every causally visible compressed
entry with sum_h w_h * ReLU(q_h . k) and the index_topk highest scoring entry indices are
emitted.
Common contract:
* selected_indices is int32 with a fixed capacity that only depends on attributes:
token_budget + compress_ratio - 1 for "qsa" (values are request-local token positions into the
main key/value cache, directly consumable by SparsePagedAttention configured with
attention_mode="selected_only", selected_kv_source="main") and index_topk for "csa" (values are
compressed-entry indices into key_state, directly consumable by SparsePagedAttention configured
with attention_mode="local_plus_selected", selected_kv_source="auxiliary"; key_state is
layout-compatible with a [batch_size, capacity, 1, head_size] auxiliary cache when K = V).
Unused entries are -1 and selected_counts holds the exact number of used entries.
* query_norm_weight and key_norm_weight are the effective RMSNorm multipliers, exactly as in
SparseAttentionIndexer.
* Accumulation, pooling, softmax, normalization and scoring are performed in float32 and the
result is rounded once to the tensor element type.
* Ties in the top-k selection are broken by the smaller entry index, and the emitted entries are
ordered by decreasing score, so the result is deterministic.
* cos_cache / sin_cache may be shared across the batch ([max_position, rotary_width]) or
request-specific ([batch_size, max_position, rotary_width]).
* cumulative_sequence_lengths, past_sequence_lengths and past_state_lengths are read directly by
the device kernel; a zero-token request row (a repeated cumulative offset) is valid and simply
contributes no query rows for that request.
OgaEngine integration note: this operator only defines the ORT contrib op; wiring
past_key_state / past_kv_buffer / past_gate_buffer / past_state_lengths as Engine-managed,
per-request fixed-size state (analogous to a paged auxiliary cache) is expected to happen in the
OgaEngine / Model Builder integration, which is out of scope for this operator definition.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- compress_ratio : int (required)
- Number of consecutive tokens folded into one compressed/pooled entry. Must be > 0 and 2 * compress_ratio - 1 must not exceed INT_MAX.
- epsilon : float
- Epsilon of the RMS normalization applied to queries and compressed keys. Default is 1e-6.
- head_weight_scale : float
- Only for policy_mode 'csa': scale applied to head_weights. Default is 1/sqrt(num_heads). Must be omitted when policy_mode is 'qsa'.
- index_topk : int
- Only for policy_mode 'csa': number of compressed entries selected per query. Must be > 0. Must be omitted when policy_mode is 'qsa'.
- policy_mode : string (required)
- Indexer policy. Must be exactly 'qsa' (token indexer) or 'csa' (compressed block indexer).
- scale : float
- Scale applied to the per-head ReLU scores. Default is 1/sqrt(head_size).
- state_capacity : int (required)
- Fixed capacity (number of entries) of past_key_state / present_key_state. Must be > 0.
- state_update_capacity : int
- Only for policy_mode 'qsa': maximum number of leading token transitions captured per request. Must be in [0, 8]. Default is 0.
- token_budget : int
- Only for policy_mode 'qsa': maximum number of tokens selected from complete blocks. Must be > 0 and divisible by compress_ratio. Must be omitted when policy_mode is 'csa'.
#### Inputs (16 - 18)
- query : T
- Packed indexer queries with shape (total_tokens, num_heads * head_size), before normalization, logical reshape, and rotary embedding. For policy_mode 'qsa', key may be omitted and query then contains row-wise concatenated query and key projections with shape (total_tokens, (num_heads + 1) * head_size).
- key (optional) : T
- Packed indexer key projection of the new tokens. Shape is (total_tokens, head_size) for policy_mode 'qsa' and (total_tokens, 2 * head_size) for policy_mode 'csa', where the first head_size channels are the Ca series and the last head_size channels the Cb series. May be omitted for policy_mode 'qsa' when query contains the packed query/key projection.
- query_norm_weight : T
- Effective RMSNorm multiplier of the queries, with shape (head_size).
- key_norm_weight : T
- Effective RMSNorm multiplier of the compressed keys, with shape (head_size).
- cos_cache : T
- Cosine rotary table indexed by absolute key position, shared across the batch with shape (max_rotary_sequence_length, rotary_width) or request-specific with shape (batch_size, max_rotary_sequence_length, rotary_width).
- sin_cache : T
- Sine rotary table with the same shape as cos_cache.
- cumulative_sequence_lengths : M
- Device-resident packed request boundaries with shape (batch_size + 1); cumulative_sequence_lengths[0] must be 0 and cumulative_sequence_lengths[batch_size] must equal total_tokens. Request b owns rows [cumulative_sequence_lengths[b], cumulative_sequence_lengths[b + 1]) of query/key (a repeated offset is a valid zero-token row).
- past_sequence_lengths : M
- Device-resident number of tokens already processed for each request before this call, with shape (batch_size). Used to derive request-local logical query positions for policy_mode 'qsa' and to validate state consistency.
- gate (optional) : T
- Only for policy_mode 'csa': gate projection of the new tokens with shape (total_tokens, 2 * head_size).
- position_bias (optional) : T
- Only for policy_mode 'csa': per-slot gate bias with shape (compress_ratio, 2 * head_size).
- head_weights (optional) : T
- Only for policy_mode 'csa': per-head score weights with shape (total_tokens, num_heads).
- position_ids (optional) : I
- Only for policy_mode 'csa': absolute position of every packed query, with shape (total_tokens).
- past_key_state : T
- Generic fixed-capacity state: policy_mode 'qsa' stores prepared complete-block keys; policy_mode 'csa' stores compressed keys. Shape is (batch_size, state_capacity, head_size) and never changes across calls.
- past_kv_buffer : T
- Generic fixed-capacity pending-token buffer. Shape is (batch_size, 2 * compress_ratio - 1, head_size) for policy_mode 'qsa' (which only ever uses up to compress_ratio - 1 of these entries) and (batch_size, 2 * compress_ratio - 1, 2 * head_size) for policy_mode 'csa'.
- past_gate_buffer (optional) : T
- Only for policy_mode 'csa': buffered gate projections with the same shape as past_kv_buffer.
- past_state_lengths : M
- Generic per-request state length with shape (batch_size, 2). Column 0 is the key_state entry count (policy_mode 'qsa': complete-block count; 'csa': compressed-entry count); column 1 is the pending-buffer length (policy_mode 'qsa': incomplete-block length in [0, compress_ratio); 'csa': buffer length in [0, 2 * compress_ratio)).
- state_update_capture_count (optional) : M
- Only for policy_mode 'qsa': number of leading token transitions to capture for each request, with shape (batch_size). Values are clamped to the request length and state_update_capacity. Required when state_update_capacity is positive.
- state_update_active (optional) : M
- Only for policy_mode 'qsa': optional capture gate with shape (1). A zero value disables capture.
#### Outputs (6 - 7)
- selected_indices : M
- Selected entries with shape (total_tokens, capacity). capacity is token_budget + compress_ratio - 1 for policy_mode 'qsa' (request-local token positions into the main key/value cache) and index_topk for policy_mode 'csa' (compressed entry indices into key_state). Unused entries are -1.
- selected_counts : M
- Exact number of used (non -1) entries of selected_indices for every query, with shape (total_tokens).
- present_key_state : T
- Updated generic key state, with the same fixed shape as past_key_state.
- present_kv_buffer : T
- Updated generic pending-token buffer, with the same fixed shape as past_kv_buffer.
- present_gate_buffer (optional) : T
- Only for policy_mode 'csa': updated gate buffer with the same fixed shape as past_gate_buffer.
- present_state_lengths : M
- Updated generic per-request state length, with the same fixed shape as past_state_lengths.
- state_update (optional) : T
- Only for policy_mode 'qsa': compact transition payloads with shape (batch_size, state_update_capacity, head_size). A token that completes a compression block stores the prepared block representative; any other captured token stores its raw key. Inactive and unused slots are zero.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain floating point tensors to float, float16 and bfloat16.
- I : tensor(int64)
- Constrain position ids to 64-bit integer tensors.
- M : tensor(int32)
- Constrain packed metadata, generic state lengths and selected indices/counts to 32-bit integer tensors.
### **com.microsoft.Pad**
Given `data` tensor, pads, mode, and value.
Example:
Insert 0 pads to the beginning of the second dimension.
data = [
[1.0, 1.2],
[2.3, 3.4],
[4.5, 5.7],
]
pads = [0, 2, 0, 0]
output = [
[
[0.0, 0.0, 1.0, 1.2],
[0.0, 0.0, 2.3, 3.4],
[0.0, 0.0, 4.5, 5.7],
],
]
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- mode : string
- Three modes: `constant`(default) - pads with a given constant value, `reflect` - pads with the reflection of the vector mirrored on the first and last values of the vector along each axis, `edge` - pads with the edge values of array
#### Inputs (2 - 3)
- data : T
- Input tensor.
- pads : tensor(int64)
- Tensor of integers indicating the number of padding elements to add or remove (if negative) at the beginning and end of each axis. For 2D input tensor, it is the number of pixels. `pads` should be a 1D tensor of shape [2 * input_rank] or a 2D tensor of shape [1, 2 * input_rank]. `pads` format (1D example) should be as follow [x1_begin, x2_begin,...,x1_end, x2_end,...], where xi_begin is the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`.
- value (optional) : T
- (Optional) A scalar or rank 1 tensor containing a single value to be filled if the mode chosen is `constant` (by default it is 0.0).
#### Outputs
- output : T
- Tensor after padding.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double)
- Constrain input and output types to float tensors.
### **com.microsoft.PagedAttention**
Paged Attention.
This op leverages a block-based KV cache to enable continuous batching for LLMs. Currently, it is designed to work with
the CUDA Execution Provider only.
In other attention ops, batch entries typically aren't of the same length, so they are padded.
Below is a batch with 3 sequences where * denotes a padding token.
Sequence_0: 0, 1*, 2*, 3*
Sequence_1: 4, 5, 6*, 7*
Sequence_2: 8, 9, 10, 11
PagedAttention is designed to take in packed input, i.e., only the real tokens without padding.
For example, the input shown above will be packed into 3 tensors like below:
- query ([q0, q4, q5, q8, q9, q10, q11])
- key ([k0, k4, k5, k8, k9, k10, k11])
- value ([v0, v4, v5, v8, v9, v10, v11])
- cumulative_sequence_length: 0, 1, 1+2, 1+2+4
This packing omits padding tokens.
The query, key and value tensors contain result of hidden embedding of real tokens after input projections.
cumulative_sequence_length records cumulated length of each sequence length.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- do_rotary : int
- Whether to use rotary position embedding. Default value is 0.
- is_causal : int
- Whether the attention mask is causal (bottom-right aligned). Default value is 1. Set to 0 for a block drafter whose query tokens attend to each other bidirectionally; local_window_size then bounds the mask on the left only.
- k_cache_dtype : string
- Logical element type stored in 'key_cache', named after the ONNX element type it denotes: '' (the default) means the cache tensor's own element type is also the logical type. 'float16', 'bfloat16', 'int8' and 'float8e4m3fn' name that same type explicitly and must agree with the tensor. 'int4' and 'float4e2m1' name sub-byte types packed two per byte into a uint8 cache, where the last cache dimension holds (head_size + 1) / 2 bytes and logical element 2*i occupies the low-order bits of byte i. Every value is a signed, zero-symmetric type: quantization uses a scale with no zero point, so unsigned logical types are not expressible.
- k_quant_type : string
- Quantization granularity of the key cache: 'NONE', 'PER_TENSOR' or 'PER_CHANNEL'. Must be non-'NONE' exactly when 'key_cache' has a quantized element type, and then 'k_scale' is required. Default value is 'NONE'.
- kv_cache_layout : string
- Physical layout of the KV cache: 'SEPARATE' or 'LATENT'. 'SEPARATE' (the default) uses distinct 'key_cache' and 'value_cache' tensors. 'LATENT' selects absorbed Multi-head Latent Attention: there is a single cache, 'value' and 'value_cache' must be absent, 'kv_num_heads' must be 1, and V for every head is the leading 'v_head_size' channels of the same 'key_cache' row that supplies K. Default value is 'SEPARATE'.
- kv_num_heads : int (required)
- Number of attention heads for k and v
- local_window_size : int
- left_window_size for local attention (like Mistral). Default value is -1 meaning unused.
- num_heads : int (required)
- Number of attention heads for q
- qk_norm_epsilon : float
- Epsilon used by the Q/K RMSNorm when 'q_norm_weight' and 'k_norm_weight' are provided. Default value is 1e-6.
- rotary_interleaved : int
- Rotate using interleaved pattern. Default value is 0 (False).
- rotary_offset : int
- First channel within head_size covered by rotary embedding, so RoPE is applied to [rotary_offset, rotary_offset + rotary_dim) and channels outside that range are copied through. Must be a multiple of 8. MLA sets this to kv_lora_rank so that RoPE only touches the positional suffix of the latent row. Default value is 0.
- scale : float
- Custom scale will be used if specified. Default value is 1/sqrt(head_size)
- softcap : float
- Softcap value for attention weights. Default value is 0.
- v_cache_dtype : string
- Logical element type stored in 'value_cache', with the same values and packing rule as 'k_cache_dtype'. Default value is '' (use the cache tensor's element type).
- v_head_size : int
- Width of the value head, which may be narrower than head_size. Only valid when 'kv_cache_layout' is 'LATENT' (DeepSeek-V3 uses head_size=576 and v_head_size=512). When v_head_size differs from head_size the 'scale' attribute is required, because the 1/sqrt(head_size) default no longer matches the pre-absorption head width. Default value is 0, meaning the same as head_size.
- v_quant_type : string
- Quantization granularity of the value cache: 'NONE', 'PER_TENSOR' or 'PER_CHANNEL'. Must be non-'NONE' exactly when 'value_cache' has a quantized element type, and then 'v_scale' is required. Default value is 'NONE'.
#### Inputs (8 - 17)
- query : T
- Query with shape (num_tokens, hidden_size), or packed QKV with shape (num_tokens, d) where d is (num_heads * head_size + 2 * kv_num_heads * head_size).
- key (optional) : T
- Key with shape (num_tokens, kv_hidden_size)
- value (optional) : T
- Value with shape (num_tokens, kv_hidden_size). Must be absent when 'kv_cache_layout' is 'LATENT'.
- key_cache : T_CACHE
- Block-based key cache with shape (num_blocks, block_size, kv_num_heads, cache_head_size), where cache_head_size is (head_size + 1) / 2 for packed INT4 and head_size otherwise. This is updated in place within the op. When 'kv_cache_layout' is 'LATENT' this is the only cache, and V is read from its leading v_head_size channels.
- value_cache (optional) : T_CACHE
- Block-based value cache with shape (num_blocks, block_size, kv_num_heads, cache_head_size), where cache_head_size is (head_size + 1) / 2 for packed INT4 and head_size otherwise. This is updated in place within the op. This should be the same shape as key_cache. Must be absent when 'kv_cache_layout' is 'LATENT'.
- cumulative_sequence_length : S
- A tensor with shape (batch_size + 1). It specifies the cumulative sequence lengths between the packed entries in Q/K/V.
- past_seqlens : S
- A tensor with shape (batch_size). It specifies the past lengths of cached sequence in the KV cache.
- block_table : S
- 2D tensor with shape (batch_size, max_blocks_per_sequence) that maps each sequence in the batch to itscorresponding blocks in the KV cache.
- cos_cache (optional) : T
- 2D tensor with shape (max total seqlen, head_size / 2).
- sin_cache (optional) : T
- 2D tensor with shape (max total seqlen, head_size / 2).
- slot_mapping (optional) : S
- 1D tensor with shape (num_tokens). For each query token, the flat slot index (block_id * block_size + offset_in_block) at which its key/value is written into the KV cache. A value of -1 skips the cache write for that token, which lets a scheduler suppress stores for prefix-cache hits or rejected speculative tokens. When absent, slots are derived from 'past_seqlens', 'cumulative_sequence_length' and 'block_table' as before. 'block_table' is still required, because it defines the read path.
- head_sink (optional) : T
- 1D tensor with shape (num_heads). Each head has a learnable sink logit that participates in the softmax denominator but contributes no value, so attention can 'do nothing'.
- q_norm_weight (optional) : T
- 1D tensor with shape (head_size). RMSNorm gain applied to each query head before rotary embedding. Must be provided together with 'k_norm_weight'.
- k_norm_weight (optional) : T
- 1D tensor with shape (head_size). RMSNorm gain applied to each key head before rotary embedding and before the key is written to the KV cache. Must be provided together with 'q_norm_weight'.
- k_scale (optional) : T_KV_SCALE
- Dequantization scale of the key cache. Shape is (1) when 'k_quant_type' is 'PER_TENSOR' and (kv_num_heads, 1, head_size) when it is 'PER_CHANNEL'. Quantization is symmetric (no zero point).
- v_scale (optional) : T_KV_SCALE
- Dequantization scale of the value cache. Shape is (1) when 'v_quant_type' is 'PER_TENSOR' and (kv_num_heads, 1, head_size) when it is 'PER_CHANNEL'. Quantization is symmetric (no zero point).
- attention_metadata (optional) : S
- 1D tensor with shape (2) or (3) holding [max_query_len_bound, max_kv_len_bound, optional max_kv_len_lower_bound] in CPU memory. max_query_len_bound is an upper bound on the number of new tokens any one sequence contributes; max_kv_len_bound is an upper bound on past_seqlens[i] + query_len[i]. Both are replay-wide upper bounds, never exact per-step values: they must hold for every step this node -- or a CUDA Graph capturing it -- will serve, and 0 means 'unknown'. They may only select the backend and size launch dimensions and workspaces; they never enter a mask comparison, so over-estimating only costs empty work. max_kv_len_lower_bound is a replay-wide lower bound on the largest per-sequence KV length in the batch and 0 means 'unknown'. It is a provider-neutral performance hint; omitting it preserves the shape-(2) contract and disables optimizations that require a lower bound unless the op reads exact lengths back from the device. The op can otherwise obtain the upper bounds only by copying 'cumulative_sequence_length' and 'past_seqlens' back from the device and synchronizing the stream on every call, which stalls the pipeline once per node per step and makes the op impossible to capture into a CUDA Graph. Schedulers already track these bounds on the host, so supplying them is normally free. When absent, the op falls back to the device readback. The upper bounds are trusted: an under-sized bound violates the contract and may omit attention work.
#### Outputs (1 - 3)
- output : T
- 2D output tensor with shape (num_tokens, num_heads * v_head_size), which is (num_tokens, hidden_size) unless 'kv_cache_layout' is 'LATENT' with a narrower v_head_size.
- key_cache_out (optional) : T_CACHE
- Aliases key_cache with the same shape and element type, including its packed dimension for INT4.
- value_cache_out (optional) : T_CACHE
- Aliases value_cache with the same shape and element type, including its packed dimension for INT4. Must be absent when 'kv_cache_layout' is 'LATENT'.
#### Type Constraints
- T : tensor(float16), tensor(bfloat16)
- Constrain input and output to float tensors.
- T_CACHE : tensor(float16), tensor(bfloat16), tensor(int8), tensor(float8e4m3fn), tensor(uint8)
- Constrain the KV cache to float or quantized tensors.
- T_KV_SCALE : tensor(float)
- Constrain KV cache scales to float tensors.
- S : tensor(int32)
- Constrain Positional inputs to int tensor.
### **com.microsoft.QAttention**
Quantization of Multi-Head Self Attention.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- do_rotary : int
- Whether to use rotary position embedding. Default value is 0.
- mask_filter_value : float
- The value to be filled in the attention mask. Default value is -10000.0f
- num_heads : int (required)
- Number of attention heads
- past_present_share_buffer : int
- Corresponding past and present are same tensor, its shape is (2, batch_size, num_heads, max_sequence_length, head_size)
- scale : float
- Custom scale will be used if specified. Default value is 1/sqrt(head_size)
- unidirectional : int
- Whether every token can only attend to previous tokens. Default value is 0.
#### Inputs (5 - 9)
- input : T1
- 3D input tensor with shape (batch_size, sequence_length, input_hidden_size)
- weight : T2
- 2D input tensor with shape (input_hidden_size, 3 * hidden_size), hidden_size = num_heads * head_size
- bias : T3
- 1D input tensor with shape (3 * hidden_size)
- input_scale : T3
- scale of quantized input tensor. It's a scalar, which means a per-tensor/layer quantization.
- weight_scale : T3
- scale of weight scale. It's a scalar or a 1D tensor, which means a per-tensor/per-column quantization.Its size should be 3 * hidden_size if it is per-column quantization
- mask_index (optional) : T4
- Attention mask index with shape (batch_size)
- input_zero_point (optional) : T1
- zero point of quantized input tensor.It's a scalar, which means a per-tensor/layer quantization.
- weight_zero_point (optional) : T2
- zero point of quantized weight tensor. It's a scalar or a 1D tensor, which means a per-tensor/per-column quantization.Its size should be 3 * hidden_size if it is per-column quantization
- past (optional) : T3
- past state for key and value with shape (2, batch_size, num_heads, past_sequence_length, head_size).
#### Outputs (1 - 2)
- output : T3
- 3D output tensor with shape (batch_size, sequence_length, hidden_size)
- present (optional) : T3
- present state for key and value with shape (2, batch_size, num_heads, past_sequence_length + sequence_length, head_size)
#### Type Constraints
- T1 : tensor(int8), tensor(uint8)
- Constrain input and output types to int8 tensors.
- T2 : tensor(int8), tensor(uint8)
- Constrain input and output types to int8 tensors.
- T3 : tensor(float), tensor(float16)
- Constrain input and output types to float tensors.
- T4 : tensor(int32)
- Constrain mask index to integer types
### **com.microsoft.QGemm**
Quantized Gemm
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- alpha : float
- Scalar multiplier for the product of input tensors A * B.
- transA : int
- Whether A should be transposed
- transB : int
- Whether B should be transposed
#### Inputs (6 - 9)
- A : TA
- Input tensor A. The shape of A should be (M, K) if transA is 0, or (K, M) if transA is non-zero.
- a_scale : T
- Scale of quantized input 'A'. It is a scalar,which means a per-tensor quantization.
- a_zero_point : TA
- Zero point tensor for input 'A'. It is a scalar.
- B : TB
- Input tensor B. The shape of B should be (K, N) if transB is 0, or (N, K) if transB is non-zero.
- b_scale : T
- Scale of quantized input 'B'. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'B'.
- b_zero_point : TB
- Zero point tensor for input 'B'. It's optional and default value is 0. It could be a scalar or a 1-D tensor, which means a per-tensor or per-column quantization. If it's a 1-D tensor, its number of elements should be equal to the number of columns of input 'B'.
- C (optional) : TC
- Optional input tensor C. If not specified, the computation is done as if C is a scalar 0. The shape of C should be unidirectional broadcastable to (M, N). Its type is int32_t and must be quantized with zero_point = 0 and scale = alpha / beta * a_scale * b_scale.
- y_scale (optional) : T
- Scale of output 'Y'. It is a scalar, which means a per-tensor quantization. It is optional. The output is full precision(float32) if it is not provided. Or the output is quantized.
- y_zero_point (optional) : TYZ
- Zero point tensor for output 'Y'. It is a scalar, which means a per-tensor quantization. It is optional. The output is full precision(float32) if it is not provided. Or the output is quantized.
#### Outputs
- Y : TY
- Output tensor of shape (M, N).
#### Type Constraints
- T : tensor(float)
- Constrain scale types to float tensors.
- TA : tensor(uint8), tensor(int8)
- Constrain input A and its zero point types to 8 bit tensors.
- TB : tensor(uint8), tensor(int8)
- Constrain input B and its zero point types to 8 bit tensors.
- TC : tensor(int32)
- Constrain input C to 32 bit integer tensors.
- TYZ : tensor(uint8), tensor(int8)
- Constrain output zero point types to 8 bit tensors.
- TY : tensor(float), tensor(uint8), tensor(int8)
- Constrain output type to float32 or 8 bit tensors.
### **com.microsoft.QLinearAdd**
Performs element-wise binary addition on 8 bit data types (with Numpy-style broadcasting support).
C = (A_scale * (A - A_zero_point) + B_scale * (B - B_zero_point))/C_scale + C_zero_point
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (7 - 8)
- A : T
- First operand.
- A_scale : tensor(float)
- Input A's scale. It's a scalar, which means a per-tensor/layer quantization.
- A_zero_point (optional) : T
- Input A zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
- B : T
- Second operand.
- B_scale : tensor(float)
- Input B's scale. It's a scalar, which means a per-tensor/layer quantization.
- B_zero_point (optional) : T
- Input B zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
- C_scale : tensor(float)
- Output scale. It's a scalar, which means a per-tensor/layer quantization.
- C_zero_point (optional) : T
- Output zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
#### Outputs
- C : T
- Result, has same element type as two inputs
#### Type Constraints
- T : tensor(uint8), tensor(int8)
- Constrain input and output types to 8 bit signed and unsigned tensors.
### **com.microsoft.QLinearAveragePool**
QLinearAveragePool consumes an input tensor X and applies average pooling across
the tensor according to kernel sizes, stride sizes, and pad lengths.
average pooling consisting of computing the average on all values of a
subset of the input tensor according to the kernel size and downsampling the
data into the output tensor Y for further processing. The output spatial shape will be following:
```
output_spatial_shape[i] = floor((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)
```
or
```
output_spatial_shape[i] = ceil((input_spatial_shape[i] + pad_shape[i] - kernel_spatial_shape[i]) / strides_spatial_shape[i] + 1)
```
if ceil_mode is enabled
```
* pad_shape[i] is sum of pads along axis i
```
`auto_pad` is a DEPRECATED attribute. If you are using them currently, the output spatial shape will be following:
```
VALID: output_spatial_shape[i] = ceil((input_spatial_shape[i] - kernel_spatial_shape[i] + 1) / strides_spatial_shape[i])
SAME_UPPER or SAME_LOWER: output_spatial_shape[i] = ceil(input_spatial_shape[i] / strides_spatial_shape[i])
```
And pad shape will be following if `SAME_UPPER` or `SAME_LOWER`:
```
pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial_shape[i] + kernel_spatial_shape[i] - input_spatial_shape[i]
```
The output of each pooling window is divided by the number of elements (exclude pad when attribute count_include_pad is zero).
Input and output scales and zero points are used to convert the output to a new quantization range.
Output = Dequantize(Input) -> AveragePool on fp32 data -> Quantize(output)
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- auto_pad : string
- auto_pad must be either NOTSET, SAME_UPPER, SAME_LOWER or VALID. Where default value is NOTSET, which means explicit padding is used. SAME_UPPER or SAME_LOWER mean pad the input so that the output spatial size match the input.In case of odd number add the extra padding at the end for SAME_UPPER and at the beginning for SAME_LOWER. VALID mean no padding.
- ceil_mode : int
- Whether to use ceil or floor (default) to compute the output shape.
- channels_last : int
- Works on NHWC layout or not? Default not.
- count_include_pad : int
- Whether include pad pixels when calculating values for the edges. Default is 0, doesn't count include pad.
- kernel_shape : list of ints (required)
- The size of the kernel along each axis.
- pads : list of ints
- Padding for the beginning and ending along each spatial axis, it can take any value greater than or equal to 0. The value represent the number of pixels added to the beginning and end part of the corresponding axis. `pads` format should be as follow [x1_begin, x2_begin...x1_end, x2_end,...], where xi_begin the number of pixels added at the beginning of axis `i` and xi_end, the number of pixels added at the end of axis `i`. This attribute cannot be used simultaneously with auto_pad attribute. If not present, the padding defaults to 0 along start and end of each spatial axis.
- strides : list of ints
- Stride along each spatial axis. If not present, the stride defaults to 1 along each spatial axis.
#### Inputs (4 - 5)
- X : T
- Input data tensor from the previous operator; dimensions for image case are (N x C x H x W), where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), where N is the batch size. Optionally, if dimension denotation is in effect, the operation expects the input data tensor to arrive with the dimension denotation of [DATA_BATCH, DATA_CHANNEL, DATA_FEATURE, DATA_FEATURE ...].
- x_scale : tensor(float)
- Input scale. It's a scalar, which means a per-tensor/layer quantization.
- x_zero_point (optional) : T
- Input zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
- y_scale : tensor(float)
- Output scale. It's a scalar, which means a per-tensor/layer quantization.
- y_zero_point (optional) : T
- Output zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
#### Outputs
- Y : T
- Output data tensor from average or max pooling across the input tensor. Dimensions will vary based on various kernel, stride, and pad sizes. Floor value of the dimension is used
#### Type Constraints
- T : tensor(uint8), tensor(int8)
- Constrain input and output types to 8 bit tensors.
### **com.microsoft.QLinearConcat**
Concatenate a list of tensors into a single tensor.All input tensors must have the same shape, except for the dimension size of the axis to concatenate on.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- axis : int (required)
- Which axis to concat on
#### Inputs (3 - ∞)
- Y_scale : TF
- Y's scale.
- Y_zero_point : T8
- Y's zero point.
- inputs (variadic, heterogeneous) : TV
- List of tensors/scale/zero_point for concatenation
#### Outputs
- Y : T8
- Concatenated tensor
#### Type Constraints
- T8 : tensor(uint8), tensor(int8)
- Constrain input and output types to 8 bit signed and unsigned tensors.
- TF : tensor(float)
- Constrain scale types to any float tensor type.
- TV : tensor(uint8), tensor(int8), tensor(float)
- Sequence of (Tensor, Scale, ZeroPoint) tuples. The type is sequence of (T8, TF, T8).
### **com.microsoft.QLinearConv**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- auto_pad : string
- channels_last : int
- dilations : list of ints
- group : int
- kernel_shape : list of ints
- pads : list of ints
- strides : list of ints
#### Inputs (8 - 9)
- x : T1
- x_scale : tensor(float)
- x_zero_point : T1
- w : T2
- w_scale : tensor(float)
- w_zero_point : T2
- y_scale : tensor(float)
- y_zero_point : T3
- B (optional) : T4
#### Outputs
- y : T3
#### Type Constraints
- T1 : tensor(int8), tensor(uint8)
- T2 : tensor(int8), tensor(uint8)
- T3 : tensor(int8), tensor(uint8)
- T4 : tensor(int32)
### **com.microsoft.QLinearGlobalAveragePool**
QLinearGlobalAveragePool consumes an input tensor X and applies Average pooling across
the values in the same channel. This is equivalent to AveragePool with kernel size
equal to the spatial dimension of input tensor. Input is of type uint8_t or int8_t.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- channels_last : int
#### Inputs
- X : T
- Input data tensor from the previous operator; According to channels_last, dimensions for image case are (N x C x H x W), or (N x H x W x C) where N is the batch size, C is the number of channels, and H and W are the height and the width of the data. For non image case, the dimensions are in the form of (N x C x D1 x D2 ... Dn), or (N x D1 X D2 ... Dn x C) where N is the batch size.
- x_scale : tensor(float)
- Scale of quantized input 'X'. It must be a scalar.
- x_zero_point : T
- Zero point tensor for input 'X'. It must be a scalar.
- y_scale : tensor(float)
- Scale of quantized output 'Y'. It must be a scalar.
- y_zero_point : T
- Zero point tensor for output 'Y'. It must be a scalar.
#### Outputs
- Y : T
- Output data tensor from pooling across the input tensor. The output tensor has the same rank as the input. with the N and C value keep it value, while the otherdimensions are all 1.
#### Type Constraints
- T : tensor(uint8), tensor(int8)
- Constrain input and output types to signed/unsigned int8 tensors.
### **com.microsoft.QLinearLeakyRelu**
QLinearLeakyRelu takes quantized input data (Tensor), an argument alpha, and quantize parameter for output,
and produces one output data (Tensor) where the function `f(x) = quantize(alpha * dequantize(x)) for dequantize(x) < 0`,
`f(x) = quantize(dequantize(x)) for dequantize(x) >= 0`, is applied to the data tensor elementwise.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- alpha : float
- Coefficient of leakage.
#### Inputs (4 - 5)
- X : T
- Input tensor
- X_scale : tensor(float)
- Input X's scale. It's a scalar, which means a per-tensor/layer quantization.
- X_zero_point (optional) : T
- Input X's zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
- Y_scale : tensor(float)
- Output Y's scale. It's a scalar, which means a per-tensor/layer quantization.
- Y_zero_point (optional) : T
- Output Y's zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
#### Outputs
- Y : T
- Output tensor
#### Type Constraints
- T : tensor(uint8), tensor(int8)
- Constrain input and output types to 8 bit tensors.
### **com.microsoft.QLinearMul**
Performs element-wise binary multiplication on 8 bit data types (with Numpy-style broadcasting support).
C = ((A - A_zero_point) * (B - B_zero_point)) * (A_scale * B_scale)/C_scale + C_zero_point
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (7 - 8)
- A : T
- First operand.
- A_scale : tensor(float)
- Input A's scale. It's a scalar, which means a per-tensor/layer quantization.
- A_zero_point (optional) : T
- Input A zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
- B : T
- Second operand.
- B_scale : tensor(float)
- Input B's scale. It's a scalar, which means a per-tensor/layer quantization.
- B_zero_point (optional) : T
- Input B zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
- C_scale : tensor(float)
- Output scale. It's a scalar, which means a per-tensor/layer quantization.
- C_zero_point (optional) : T
- Output zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
#### Outputs
- C : T
- Result, has same element type as two inputs
#### Type Constraints
- T : tensor(uint8), tensor(int8)
- Constrain input and output types to 8 bit signed and unsigned tensors.
### **com.microsoft.QLinearReduceMean**
Computes the mean of the low-precision input tensor's element along the provided axes.
The resulting tensor has the same rank as the input if keepdims equal 1. If keepdims equal 0,
then the resulting tensor have the reduced dimension pruned. The above behavior is similar to numpy,
with the exception that numpy default keepdims to False instead of True.
Input and Output scales and zero points are used to requantize the output in a new range.
This helps to improve accuracy as after ReduceMean operation the range of the output is expected to decrease.
```
"Output = Dequantize(Input) -> ReduceMean on fp32 data -> Quantize(output)",
```
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- axes : list of ints (required)
- A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.
- keepdims : int (required)
- Keep the reduced dimension or not, default 1 mean keep reduced dimension.
#### Inputs (4 - 5)
- data : T
- An input tensor.
- data_scale : tensor(float)
- Input scale. It's a scalar, which means a per-tensor/layer quantization.
- data_zero_point (optional) : T
- Input zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
- reduced_scale : tensor(float)
- Output scale. It's a scalar, which means a per-tensor/layer quantization.
- reduced_zero_point (optional) : T
- Output zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
#### Outputs
- reduced : T
- Reduced output tensor.
#### Type Constraints
- T : tensor(uint8), tensor(int8)
- Constrain input types to 8 bit signed and unsigned tensors.
### **com.microsoft.QLinearSigmoid**
QLinearSigmoid takes quantized input data (Tensor), and quantize parameter for output, and produces one output data
(Tensor) where the function `f(x) = quantize(Sigmoid(dequantize(x)))`, is applied to the data tensor elementwise.
Wwhere the function `Sigmoid(x) = 1 / (1 + exp(-x))`
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (4 - 5)
- X : T
- Input tensor
- X_scale : tensor(float)
- Input X's scale. It's a scalar, which means a per-tensor/layer quantization.
- X_zero_point (optional) : T
- Input X's zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
- Y_scale : tensor(float)
- Output Y's scale. It's a scalar, which means a per-tensor/layer quantization.
- Y_zero_point (optional) : T
- Output Y's zero point. Default value is 0 if it's not specified. It's a scalar, which means a per-tensor/layer quantization.
#### Outputs
- Y : T
- Output tensor
#### Type Constraints
- T : tensor(uint8), tensor(int8)
- Constrain input and output types to 8 bit tensors.
### **com.microsoft.QLinearSoftmax**
QLinearSoftmax computes the normalized exponential values for the given input:
Softmax(input, axis) = Exp(input) / ReduceSum(Exp(input), axis=axis, keepdims=1)
The input does not need to explicitly be a 2D vector. The "axis" attribute
indicates the dimension along which QLinearSoftmax will be performed for onnx v.13+.
or the dimension coerced to NxD Matrix for onnx v.12-.
The output tensor has the same shape.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- axis : int
- apply softmax to elements for dimensions axis,or all dims along with axis according to op-version
- opset : int (required)
- opset version of corresponding SoftMax.
#### Inputs
- X : T
- The input tensor
- X_scale : tensor(float)
- Scale of quantized input 'X'. It must be a scalar.
- x_zero_point (optional) : T
- Zero point tensor for input 'X'.It must be a scalar.
- y_scale : tensor(float)
- Scale of quantized output 'Y'. It must be a scalar.
- y_zero_point : T
- Zero point tensor for output 'Y'. It must be a scalar.
#### Outputs
- Y : T
- Output data tensor from pooling across the input tensor. The output tensor has the same rank as the input.
#### Type Constraints
- T : tensor(uint8), tensor(int8)
- Constrain input and output types to signed/unsigned int8 tensors.
### **com.microsoft.QLinearWhere**
Return elements, either from X or Y, depending on condition.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- condition : B
- When True (nonzero), yield x, otherwise yield y
- X : T
- Y's zero point.
- x_scale : TF
- X's scale.
- x_zero_point : T
- X's zero point.
- Y : T
- Y's zero point.
- y_scale : TF
- Y's scale.
- y_zero_point : T
- Y's zero point.
- z_scale : TF
- Z's scale.
- z_zero_point : T
- Z's zero point.
#### Outputs
- Z : T
- Tensor of shape equal to the broadcasted shape of condition, X, and Y
#### Type Constraints
- B : tensor(bool)
- Constrain input and output types to 8 bit signed and unsigned tensors.
- TF : tensor(float)
- Constrain scale types to any float tensor type.
- T : tensor(uint8), tensor(int8)
- Constrain input and output types to 8 bit signed and unsigned tensors.
### **com.microsoft.QMoE**
Quantized mixture of experts (MoE).
A 2D input is the packed token-major form used by continuous-batching engines: tokens from
different requests are concatenated along dimension 0 without padding. QMoE is token-local,
so request boundaries do not affect the result and no cumulative sequence-length input is
required. A 3D input is the dense convenience form and is processed as batch_size *
sequence_length independent token rows. router_probs and optional router_weights must contain
one corresponding row per token in either form.
The quantized weights are stored in column major order per expert.
The quantization block size can be specified. If not provided, column wise quantization is used.
For integer quantization, the formula of linear dequantization using scale and (optionally) zero-point is:
dequantized_weight = (quantized_weight - zero_point) * scale
When zero_point is not provided, the default value is 2^(bits-1): 2 for 2 bits, 8 for 4 bits, 128 for 8 bits.
For integer quantization, if block_size is provided, both hidden_size and inter_size must be divisible by the block size, and
the dequantization is performed per block of size block_size along the K (input feature) dimension.
For quant_type='fp8', weights instead use row-major float8e4m3fn tensors shaped [num_experts, N, K].
A positive block_size selects square block scaling with float32, float16, or bfloat16 fc*_scales tensors shaped
[num_experts, ceil(N / block_size), ceil(K / block_size)]:
dequantized_weight[e, n, k] = float(weight[e, n, k]) * scale[e, n / block_size, k / block_size]
Partial edge blocks are allowed. No zero points or activation scales are accepted.
Without a positive block_size, FP8 uses the legacy per-expert fc*_global_scale inputs instead.
Block-scaled FP8 does not use global scales. Activations retain the input type (weight-only quantization).
The WebGPU block-FP8 kernel supports block_size=128 with float32 scales and rejects projections
that exceed 32-bit shader addressing or the device's per-dimension dispatch limit.
Packed byte dimensions are computed as logical_element_count * effective_expert_weight_bits / 8.
Weight rows must be byte-aligned. Zero-point rows are padded to a whole byte when necessary.
fc1_expert_weight_bits, fc2_expert_weight_bits, and fc3_expert_weight_bits optionally override
expert_weight_bits for the corresponding projection. An omitted override inherits expert_weight_bits.
When SwiGLU is fused, FC3 is stored in FC1 and fc3_expert_weight_bits must be omitted or equal to
fc1_expert_weight_bits after inheritance.
The SwiGLU (Swish-Gated Linear Unit) activation function is like:
g = xW + b
l = xV + c
G = clamp(g, max=limit)
L = clamp(l, min=-limit, max=limit)
swiglu = G * sigmoid(alpha * G) * (L + beta)
where x is the input, W and V are weight matrices, b and c are bias vectors, and alpha, beta and limit are constant float parameters.
When swiglu_fusion=0, two GEMMs are not fused, and they are FC1 and FC3 in the inputs.
When swiglu_fusion=1, two GEMMs are fused so that g and l are computed in a single GEMM (FC1), and g and l are interleaved on each row of size 2 * inter_size.
When swiglu_fusion=2, two GEMMs are fused, and g and l are concatenated on each row.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- accuracy_level : int
- Minimum accuracy level of the expert GEMMs on CPU, with the MatMulNBits meaning. For block-wise 4-bit experts, 0 (default) or 1 keeps fp32 activations and 4 allows int8 activations (int8 dot-product kernels). Block-wise 8-bit experts have no fp32 kernel and use int8 activations at every level. Other values are treated as 0.
- activation_alpha : float
- Alpha parameter used in activation function.
- activation_beta : float
- Beta parameter used in activation function.
- activation_type : string
- Activation function to use. Choose from relu, gelu, silu, swiglu and identity. Default is relu
- block_size : int
- For integer quantization, size of each quantization block along the K (input feature) dimension. Must be power of two and ≥ 16 (e.g., 16, 32, 64, 128). For integer and FP4 quantization, both hidden_size and inter_size must be divisible by the block size. FP8 with block_size=128 supports partial 128x128 tiles. The FP4 modes always use blocking: MXFP4 ('fp4'/'wfp4afp8') is normalized to block_size 32 and NVFP4 ('nvfp4') to block_size 16, even when block_size is omitted. For FP8 ('fp8'), a positive value instead specifies square blocks along both N and K, with floating-point scales shaped [E, ceil(N/block_size), ceil(K/block_size)]; partial blocks are allowed. Without a positive value, FP8 uses per-expert global scales. For integer quantization ('int'), omitting block_size means there is no blocking and a whole column shares one scaling factor.
- expert_weight_bits : int
- Number of bits used in quantized weights. Supported values are 2, 4, and 8. Default is 4 bits
- fc1_expert_weight_bits : int
- Optional FC1 override for expert_weight_bits. Inherits expert_weight_bits when omitted.
- fc2_expert_weight_bits : int
- Optional FC2 override for expert_weight_bits. Inherits expert_weight_bits when omitted.
- fc3_expert_weight_bits : int
- Optional FC3 override for expert_weight_bits. Inherits expert_weight_bits when omitted. For fused SwiGLU, the effective FC3 width must equal the effective FC1 width.
- k : int
- Number of top experts to select from expert pool
- normalize_routing_weights : int
- Whether to normalize routing weights
- quant_type : string
- Quantization type: 'int' for integer quantization (default), 'fp4' for MXFP4 quantization, 'nvfp4' for NVFP4 quantization, 'fp8' for FP8 e4m3 weight-only quantization, or 'wfp4afp8' for MXFP4 weight with FP8 activation. When quant_type is 'fp4' or 'nvfp4', weights are stored in E2M1 FP4 format (2 values per byte), fc*_scales inputs contain the FP4 block scales, and fc*_global_scale inputs must be provided. 'fp4' uses Float8E8M0 block scales with block_size 32; 'nvfp4' uses Float8E4M3FN block scales with block_size 16. 'fp8' uses float8e4m3fn weights and, when block_size > 0, float32, float16, or bfloat16 square-block scales in fc*_scales instead of fc*_global_scale.
- swiglu_fusion : int
- 0: not fused, 1: fused and interleaved. 2: fused and not interleaved.
- swiglu_limit : float
- The limit used to clamp inputs in SwiGLU. It is infinite when limit is not provided.
- use_sparse_mixer : int
- Whether to use sparse mixer
- weights_prepacked : int
- Only meaningful when quant_type='int'. Tri-state control over the layout of the int4/int8 fc1/fc2 weight initializers. The concrete prepacked layouts selected by -1 and 1 are determined by the execution provider. 0: the initializers are raw, un-prepacked [E, N, K/pack] tensors as produced by quantize_matmul_{4,8}bits. Defaults to -1.
#### Inputs (6 - 21)
- input : T
- 2D packed token tensor with shape (total_tokens, hidden_size), where tokens from ragged sequences may be concatenated without padding, or 3D tensor with shape (batch_size, sequence_length, hidden_size)
- router_probs : T
- 2D tensor with shape (total_tokens, num_experts), where total_tokens must match the flattened token count of input
- fc1_experts_weights : T1
- 3D tensor with shape (num_experts, fusion_size * inter_size, hidden_size * effective_fc1_bits / 8). The last dimension must be byte-aligned. The fusion_size is 2 for fused swiglu, or 1 otherwise. effective_fc1_bits is fc1_expert_weight_bits when provided, otherwise expert_weight_bits.
- fc1_scales (optional) : T2
- Optional weight scales. For quant_type='int', this is a 2D tensor with shape (num_experts, fusion_size * inter_size), or a 3D tensor with shape (num_experts, fusion_size * inter_size, hidden_size / block_size) when block_size is provided. For quant_type='fp4' or 'wfp4afp8', this is a float8e8m0 MXFP block-scale tensor with shape (num_experts, fusion_size * inter_size, hidden_size / 32). For quant_type='nvfp4', this is a float8e4m3fn NVFP4 block-scale tensor with shape (num_experts, fusion_size * inter_size, hidden_size / 16). For quant_type='fp8' and block_size > 0, required float32, float16, or bfloat16 scales with shape (num_experts, ceil(fusion_size * inter_size / block_size), ceil(hidden_size / block_size)).
- fc1_experts_bias (optional) : T
- 2D optional tensor with shape (num_experts, fusion_size * inter_size)
- fc2_experts_weights : T1
- 3D tensor with shape (num_experts, hidden_size, inter_size * effective_fc2_bits / 8). The last dimension must be byte-aligned. effective_fc2_bits is fc2_expert_weight_bits when provided, otherwise expert_weight_bits.
- fc2_scales (optional) : T2
- Optional weight scales. For quant_type='int', this is a 2D tensor with shape (num_experts, hidden_size), or a 3D tensor with shape (num_experts, hidden_size, inter_size / block_size) when block_size is provided. For quant_type='fp4' or 'wfp4afp8', this is a float8e8m0 MXFP block-scale tensor with shape (num_experts, hidden_size, inter_size / 32). For quant_type='nvfp4', this is a float8e4m3fn NVFP4 block-scale tensor with shape (num_experts, hidden_size, inter_size / 16). For quant_type='fp8' and block_size > 0, required float32, float16, or bfloat16 scales with shape (num_experts, ceil(hidden_size / block_size), ceil(inter_size / block_size)).
- fc2_experts_bias (optional) : T
- 2D optional tensor with shape (num_experts, hidden_size)
- fc3_experts_weights (optional) : T1
- 3D optional tensor with shape (num_experts, inter_size, hidden_size * effective_fc3_bits / 8). The last dimension must be byte-aligned. effective_fc3_bits is fc3_expert_weight_bits when provided, otherwise expert_weight_bits.
- fc3_scales (optional) : T2
- Optional weight scales. For quant_type='int', this is a 2D tensor with shape (num_experts, inter_size), or a 3D tensor with shape (num_experts, inter_size, hidden_size / block_size) when block_size is provided. For quant_type='fp4' or 'wfp4afp8', this is a float8e8m0 MXFP block-scale tensor with shape (num_experts, inter_size, hidden_size / 32). For quant_type='fp8' and block_size > 0, required when FC3 is present, with floating-point scales shaped (num_experts, ceil(inter_size / block_size), ceil(hidden_size / block_size)).
- fc3_experts_bias (optional) : T
- 2D optional tensor with shape (num_experts, inter_size)
- fc1_zero_points (optional) : T1
- 2D tensor with shape (num_experts, ceil(fusion_size * inter_size * effective_fc1_bits / 8)), or 3D tensor with shape (num_experts, fusion_size * inter_size, ceil((hidden_size / block_size) * effective_fc1_bits / 8)) when block_size is provided.
- fc2_zero_points (optional) : T1
- 2D tensor with shape (num_experts, ceil(hidden_size * effective_fc2_bits / 8)), or 3D tensor with shape (num_experts, hidden_size, ceil((inter_size / block_size) * effective_fc2_bits / 8)) when block_size is provided.
- fc3_zero_points (optional) : T1
- 2D optional tensor with shape (num_experts, ceil(inter_size * effective_fc3_bits / 8)), or 3D optional tensor with shape (num_experts, inter_size, ceil((hidden_size / block_size) * effective_fc3_bits / 8)) when block_size is provided.
- router_weights (optional) : T
- 2D optional tensor with shape (num_tokens, num_experts). When provided, router_probs is used only for Top-K expert selection, and router_weights is used for aggregating expert outputs (the values at the selected expert indices are gathered and used as mixing weights). This enables DeepSeek-style noaux_tc routing where different tensors are used for selection and aggregation. When not provided, router_probs is used for both selection and aggregation (backward compatible).
- fc1_global_scale (optional) : T4
- 1D optional tensor with shape (num_experts,). Per-expert global weight scale for FC1. Required when quant_type is 'fp4', 'nvfp4', or 'wfp4afp8', or 'fp8' with block_size <= 0. Not used for block-scaled FP8.
- fc2_global_scale (optional) : T4
- 1D optional tensor with shape (num_experts,). Per-expert global weight scale for FC2. Required when quant_type is 'fp4', 'nvfp4', or 'wfp4afp8', or 'fp8' with block_size <= 0. Not used for block-scaled FP8.
- fc1_act_scale (optional) : T4
- 1D optional tensor with shape (1,) or (num_experts,). Activation scale for FC1 FP8 activation modes.
- fc2_act_scale (optional) : T4
- 1D optional tensor with shape (1,) or (num_experts,). Activation scale for FC2 FP8 activation modes.
- fc1_act_block_scale (optional) : T2
- 3D optional float8e8m0 MXFP activation block-scale tensor for FC1 FP8 activation modes.
- fc2_act_block_scale (optional) : T2
- 3D optional float8e8m0 MXFP activation block-scale tensor for FC2 FP8 activation modes.
#### Outputs
- output : T
- output tensor with same shape of input
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
- T1 : tensor(uint8), tensor(float8e4m3fn)
- Constrain quantized weight types. Integer and FP4 weights use uint8. FP8 weights use float8e4m3fn.
- T2 : tensor(float), tensor(float16), tensor(bfloat16), tensor(float8e8m0), tensor(float8e4m3fn)
- Constrain scale types. Float tensors are used for integer quantization and FP8 square-block scales. Float8e8m0 tensors are used for MXFP4 block scales; float8e4m3fn tensors are used for NVFP4 block scales.
- T4 : tensor(float)
- Constrain FP4 global scale type to float32 tensors.
### **com.microsoft.QOrderedAttention**
Quantized version of simplified Multi-Head Self Attention(using int8 with specific matrix Layout).
Multi-Head Self Attention that can be either unidirectional (like GPT-2) or bidirectional (like BERT).
The mask_index input is optional. Besides raw attention mask with shape (batch_size, past_sequence_length + sequence_length)
or (batch_size, sequence_length, past_sequence_length + sequence_length) with value 0 for masked and 1 otherwise,
we also support other two formats: When input has right-side padding, mask_index is one dimension with shape (batch_size),
where value of each element is the end position, or valid length of actual sequence excluding padding. When input has
left-side padding, mask_index has shape (2 * batch_size), where the values are the exclusive end positions followed by
the inclusive start positions. When unidirectional is 1, and each token only attend to previous tokens. For GPT-2, both past
and present state are optional. Present state could appear in output even when past state is not in input.
Current version does not support past/present, attention_bias and qkv_hidden_sizes.
TODO: Support them if needed in the future.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- num_heads : int (required)
- Number of attention heads
- order_input : int (required)
- cublasLt order of input matrix. See the schema of QuantizeWithOrder for order definition.
- order_output : int (required)
- cublasLt order of global bias
- order_weight : int (required)
- cublasLt order of weight matrix
- qkv_hidden_sizes : list of ints
- Hidden layer sizes of Q, K, V paths in Attention
- unidirectional : int
- Whether every token can only attend to previous tokens. Default value is 0.
#### Inputs (17 - 20)
- input : Q
- 3D input tensor with shape (batch_size, sequence_length, input_hidden_size)
- scale_input : S
- scale of the input, scalar value (per tensor) currently.
- scale_Q_gemm : S
- scale of the gemm - scalar (per-tensor quantization)
- scale_K_gemm : S
- scale of the gemm - scalar (per-tensor quantization)
- scale_V_gemm : S
- scale of the gemm - scalar (per-tensor quantization)
- Q_weight : Q
- 2D input tensor with shape (input_hidden_size, hidden_size), where hidden_size = num_heads * head_size
- K_weight : Q
- 2D input tensor with shape (input_hidden_size, hidden_size), where hidden_size = num_heads * head_size
- V_weight : Q
- 2D input tensor with shape (input_hidden_size, hidden_size), where hidden_size = num_heads * head_size
- scale_Q_weight : S
- scale of the weight (scalar for per-tensor quantization or 1-D of dims [hidden_size] for per-channel quantization)
- scale_K_weight : S
- scale of the weight (scalar for per-tensor quantization or 1-D of dims [hidden_size] for per-channel quantization)
- scale_V_weight : S
- scale of the weight (scalar for per-tensor quantization or 1-D of dims [hidden_size] for per-channel quantization)
- Q_bias : S
- 1D input tensor with shape (hidden_size)
- K_bias : S
- 1D input tensor with shape (hidden_size)
- V_bias : S
- 1D input tensor with shape (hidden_size)
- scale_QKT_gemm (optional) : S
- scale of the gemm - scalar (per-tensor quantization)
- scale_QKT_softmax (optional) : S
- scale of the softmax result - scalar (per-tensor quantization)
- scale_values_gemm : S
- scale of the gemm - scalar (per-tensor quantization). Also this is the output scale for the operator.
- mask_index (optional) : G
- Attention mask with shape (batch_size, 1, max_sequence_length, max_sequence_length), (batch_size, past_sequence_length + sequence_length)or (batch_size, sequence_length, past_sequence_length + sequence_length), or index with shape (batch_size) or (2 * batch_size).
- past (optional) : Q
- past state for key and value with shape (2, batch_size, num_heads, past_sequence_length, head_size).
- attention_bias (optional) : S
- additional add to QxK' with shape (batch_size or 1, num_heads or 1, sequence_length, total_sequence_length).
#### Outputs
- output : Q
- 3D output tensor with shape (batch_size, sequence_length, hidden_size)
#### Type Constraints
- Q : tensor(int8)
- Constrain input and output types to int8 tensors.
- S : tensor(float)
- Constrain scales to float32 tensors.
- G : tensor(int32)
- Constrain to integer types
### **com.microsoft.QOrderedGelu**
Ordered Quantize Gelu.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- order_X : int
- cublasLt order of input X. Optional. See the schema of QuantizeWithOrder for order definition.
- order_Y : int
- cublasLt order of matrix Y, must be same as order_X if specified together. Optional.
#### Inputs
- X : Q
- N-dimensional input A
- scale_X : S
- scale of the input A
- scale_Y : S
- scale of the output Y
#### Outputs
- Y : Q
- Output of the Gelu
#### Type Constraints
- Q : tensor(int8)
- Constrain input and output types to int8 tensors.
- S : tensor(float)
- Constrain scales to float32
### **com.microsoft.QOrderedLayerNormalization**
QOrderedLayerNormalization
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- axis : int
- The first normalization dimension: normalization will be performed along dimensions axis : rank(inputs).
- epsilon : float
- The epsilon value to use to avoid division by zero.
- order_X : int
- cublasLt order of input X. Default is ROW MAJOR. See the schema of QuantizeWithOrder for order definition.
- order_Y : int
- cublasLt order of matrix Y, must be same as order_X. Default is ROW MAJOR.
#### Inputs
- X : Q
- Input data tensor from the previous layer.
- scale_X : S
- scale of the quantized X
- scale : F
- Scale tensor, i.e., gamma vector.
- B (optional) : F
- Bias tensor.
- scale_Y : S
- scale of the quantized X
#### Outputs
- Y : Q
- Output data tensor.
#### Type Constraints
- F : tensor(float16), tensor(float)
- Constrain input gamma and bias could be float16/float tensors. float may get better precision, float16 runs faster.
- S : tensor(float)
- quantization scale must be float tensors.
- Q : tensor(int8)
- quantization tensor must be int8 tensors.
### **com.microsoft.QOrderedLongformerAttention**
Quantized version of Longformer Self Attention (using int8 with specific matrix Layout).
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- num_heads : int (required)
- Number of attention heads
- order_global_weight : int (required)
- cublasLt order of weight matrix
- order_input : int (required)
- cublasLt order of input matrix. See the schema of QuantizeWithOrder for order definition.
- order_output : int (required)
- cublasLt order of global bias
- order_weight : int (required)
- cublasLt order of weight matrix
- window : int (required)
- One sided attention windows length W, or half of total window length
#### Inputs
- input : Q
- 3D input tensor with shape (batch_size, sequence_length, hidden_size), hidden_size = num_heads * head_size
- scale_input : S
- scale of the input
- weight : Q
- 2D input tensor with shape (hidden_size, 3 * hidden_size)
- scale_weight : S
- scale of the weight
- bias : S
- 1D input tensor with shape (3 * hidden_size), fp32 only currently.
- scale_bias : S
- reserved. (not used as add bias need float value in cublasLt for normal order.)
- scale_qkv_gemm : S
- scale of the output for fused kqv gemm
- mask : F
- Attention mask with shape (batch_size, sequence_length)
- global_weight : Q
- 2D input tensor with shape (hidden_size, 3 * hidden_size)
- scale_global_weight : S
- scale of the global_weight
- global_bias : S
- 1D input tensor with shape (3 * hidden_size)
- scale_global_gemm : S
- scale of the global_qkv_gemm
- global : G
- Global attention flags with shape (batch_size, sequence_length)
- scale_output : S
- scale of the output
#### Outputs
- output : Q
- 3D output tensor with shape (batch_size, sequence_length, hidden_size)
#### Type Constraints
- Q : tensor(int8)
- Constrain input and output types to int8 tensors.
- S : tensor(float)
- Constrain scales to float32 tensors.
- G : tensor(int32)
- Constrain to integer types
- F : tensor(float16)
- Be compatible with float version.
### **com.microsoft.QOrderedMatMul**
Quantize (Int8) MatMul with order. Implement Y = alpha * A * B + bias + beta * C. Matrix A, B, C, Y are all int8 matrix.
Two type of order combination supported:
*) When order_B is ORDER_COL, order_A must be ORDER_ROW.
bias is vector of {#cols of Y} of float32, C should be batch 1/batch_A. B could be of batch 1 or batch_A.
Note B is reorder to ORDER_COL, or Transposed. Not Transposed first and then Reordered here.
*) When order_B is specify ORDER_COL4_4R2_8C or ORDER_COL32_2R_4R4, orderA must be ORDER_COL32.
MatMul will be implemented using alpha(A * B) + beta * C => Y.
bias is not supported here. B in fact is transposed first then reordered into ORDER_COL4_4R2_8C or ORDER_COL32_2R_4R4 here.
order_Y and order_C will be same as order_A.
Support per column quantized weight, ie, scale_B is 1-D vector of size [#cols of matrix B].
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- order_A : int (required)
- cublasLt order of matrix A. See the schema of QuantizeWithOrder for order definition.
- order_B : int (required)
- cublasLt order of matrix B
- order_Y : int (required)
- cublasLt order of matrix Y and optional matrix C
#### Inputs (5 - 8)
- A : Q
- 3-dimensional matrix A
- scale_A : S
- scale of the input A.
- B : Q
- 2-dimensional matrix B. Transposed if order_B is ORDER_COL.
- scale_B : S
- scale of the input B. Scalar or 1-D float32.
- scale_Y : S
- scale of the output Y.
- bias (optional) : S
- 1d bias, not scaled with scale_Y.
- C (optional) : Q
- 3d or 2d matrix C. if 2d expand to 3d first. Shape[0] should be 1 or same as A.shape[0]
- scale_C (optional) : S
- scale of the input A.
#### Outputs
- Y : Q
- Matrix multiply results from A * B
#### Type Constraints
- Q : tensor(int8)
- Constrain input and output types to int8 tensors.
- S : tensor(float)
- Constrain bias and scales to float32
### **com.microsoft.QuantizeBFP**
The BFP quantization operator. It consumes a full precision tensor and computes an BFP tensor.
More documentation on the BFP format can be found in this paper: https://www.microsoft.com/en-us/research/publication/pushing-the-limits-of-narrow-precision-inferencing-at-cloud-scale-with-microsoft-floating-point/
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- bfp_type : int (required)
- The type of BFP - must match with the BFPType enum
- block_dim : int
- Each bounding box spans this dimension.Typically, the block dimension corresponds to the reduction dimension of the matrix multipication that consumes the output of this operator.For example, for a 2D matrix multiplication A@W, QuantizeBFP(A) would use block_dim 1 and QuantizeBFP(W) would use block_dim 0.The default is the last dimension.
#### Inputs
- x : T1
- N-D full precision input tensor to be quantized.
#### Outputs
- y : T2
- 1-D, contiguous BFP data
- shape : T3
- Shape of x
- strides : T3
- Strides of x
#### Type Constraints
- T1 : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain the input to float and bfloat.
- T2 : tensor(uint8)
- Constrain y to uint8.
- T3 : tensor(int64)
- Constrain shape and strides to uint64.
### **com.microsoft.QuantizeLinear**
The linear quantization operator. It consumes a full precision data, a scale, a zero point to compute the low precision / quantized tensor.
The quantization formula is y = saturate ((x / y_scale) + y_zero_point). For saturation, it saturates to [0, 255] if it's uint8, [-128, 127] if it's int8,
[0, 65,535] if it's uint16, and [-32,768, 32,767] if it's int16. For (x / y_scale), it's rounding to nearest ties to even.
Refer to https://en.wikipedia.org/wiki/Rounding for details.
Scale and zero point must have same shape. They must be either scalar (per tensor) or 1-D tensor (per 'axis').
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- axis : int
- The axis along which same quantization parameters are applied. It's optional.If it's not specified, it means per-tensor quantization and input 'x_scale' and 'x_zero_point' must be scalars.If it's specified, it means per 'axis' quantization and input 'x_scale' and 'x_zero_point' must be 1-D tensors.
#### Inputs (2 - 3)
- x : T1
- N-D full precision Input tensor to be quantized.
- y_scale : T1
- Scale for doing quantization to get 'y'. It can be a scalar, which means per-tensor/layer quantization, or a 1-D tensor for per-axis quantization.
- y_zero_point (optional) : T2
- Zero point for doing quantization to get 'y'. Shape must match y_scale. Default is uint8 with zero point of 0 if it's not specified.
#### Outputs
- y : T2
- N-D quantized output tensor. It has same shape as input 'x'.
#### Type Constraints
- T1 : tensor(float16), tensor(float)
- Constrain 'x', 'y_scale' to float tensors.
- T2 : tensor(int8), tensor(uint8), tensor(int16), tensor(uint16), tensor(int4), tensor(uint4)
- Constrain 'y_zero_point' and 'y' to 8-bit and 16-bit integer tensors.
### **com.microsoft.QuantizeWithOrder**
Quantize input matrix to specific layout used in cublaslt.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- order_input : int (required)
- cublasLt order of input matrix. ORDER_COL = 0, ORDER_ROW = 1, ORDER_COL32 = 2, ORDER_COL4_4R2_8C = 3, ORDER_COL32_2R_4R4 = 4. Please refer https://docs.nvidia.com/cuda/cublas/index.html#cublasLtOrder_t for their meaning.
- order_output : int (required)
- cublasLt order of output matrix.
#### Inputs
- input : F
- TODO: input tensor of (ROWS, COLS). if less than 2d, will broadcast to (1, X). If 3d, it is treated as (B, ROWS, COS)
- scale_input : S
- scale of the input
#### Outputs
- output : Q
- output tensor
#### Type Constraints
- Q : tensor(int8)
- Constrain input and output types to int8 tensors.
- F : tensor(float16), tensor(float)
- Constrain to float types
- S : tensor(float)
- Constrain Scale to float32 types
### **com.microsoft.QuickGelu**
Compute x * Sigmoid(alpha * x).
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- alpha : float
- Alpha value.
#### Inputs
- X : T
- The input data as Tensor.
#### Outputs
- Y : T
- The output.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.Range**
Creates a sequence of numbers that begins at `start` and extends by increments of `delta`
up to but not including `limit`.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (2 - 3)
- start : T
- Tensor(scalar, or dims=[1]). First entry in the range.
- limit : T
- Tensor(scalar, or dims=[1]). Upper limit of sequence, exclusive.
- delta (optional) : T
- Tensor(scalar, or dims=[1]). Number that increments start. Defaults to 1.
#### Outputs
- Y : T
- 1-D Tensor of the range.
#### Type Constraints
- T : tensor(float), tensor(double), tensor(int16), tensor(int32), tensor(int64)
- Constrain input and output types.
### **com.microsoft.ReduceSumInteger**
Computes the sum of the low-precision input tensor's element along the provided axes.
The resulting tensor has the same rank as the input if keepdims equal 1. If keepdims equal 0,
then the resulting tensor have the reduced dimension pruned. The above behavior is similar to numpy,
with the exception that numpy default keepdims to False instead of True.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- axes : list of ints (required)
- A list of integers, along which to reduce. The default is to reduce over all the dimensions of the input tensor.
- keepdims : int (required)
- Keep the reduced dimension or not, default 1 mean keep reduced dimension.
#### Inputs
- data : T1
- An input tensor.
#### Outputs
- reduced : T2
- Reduced output tensor.
#### Type Constraints
- T1 : tensor(int8), tensor(uint8)
- Constrain input type to 8-bit integer tensor.
- T2 : tensor(int32), tensor(uint32)
- Constrain output data type to 32-bit integer tensor.T2 must be tensor(uint32) when T1 is tensor(uint8),or must be tensor(int32) when T1 is tensor(int8).
### **com.microsoft.RelativePositionBias**
Compute binned relative position bias for T5 model. ref: https://arxiv.org/abs/1803.02155v2
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- is_bidirectional : int
- Default value is 0.
- max_distance : int (required)
- Max distance
#### Inputs
- bias_table : T
- 2D input tensor with shape (num_buckets, num_heads), COL-major(See UT for example)
- query_length : U
- The length of query. Self Attention requires query_length = key_length
- key_length : U
- The length of key.
#### Outputs
- output : T
- 4D output tensor with shape (1, num_heads, sequence_length, sequence_length)
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output types to float or half tensors.
- U : tensor(int64)
- Constrain sequence_length to int tensors.
### **com.microsoft.RemovePadding**
Compress transformer input by removing paddings. It assumes padding is on the right side of sequence.
The input has padding with shape (batch_size, sequence_length, hidden_size). This will generate two outputs:
output has shape (total_tokens, hidden_size); token_offset with shape (batch_size, sequence_length).
token_offset has offsets of all non-padding tokens first, then offset of all padding tokens. It is
a list of batch_size * sequence_length elements, which is reshaped to 2D for convenience of shape inference.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- input : T
- Input tensor with shape (batch_size, sequence_length, hidden_size)
- sequence_token_count : M
- Number of non-padding tokens in each sequence with shape (batch_size).
#### Outputs
- output : T
- output tensor with shape (total_tokens, hidden_size)
- token_offset : M
- Offset of non-padding tokens, and those of padding tokens. Its shape is (batch_size, sequence_length)
- cumulated_seq_len : M
- Cumulated sequence lengths. Its shape is (batch_size + 1)
- max_seq_len : M
- Max sequence length without padding. Its shape is (1)
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output types to float tensors.
- M : tensor(int32)
- Constrain sequence_token_count and token_offset to integer types
### **com.microsoft.RestorePadding**
Restore paddings and fill padding with zeros.
The input has padding with shape (total_tokens, hidden_size) and token_offset with shape (batch_size, sequence_length).
The output has shape (batch_size, sequence_length, hidden_size).
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- input : T
- Input tensor with shape (total_tokens, hidden_size)
- token_offset : M
- Offset of non-padding tokens and paddings. Its shape is (batch_size, sequence_length)
#### Outputs
- output : T
- output tensor with shape (batch_size, sequence_length, hidden_size)
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain input and output types to float tensors.
- M : tensor(int32)
- Constrain token_offset to integer types
### **com.microsoft.Rfft**
This function computes the n-point one dimensional Fourier transform for a real-valued input where n is an even number.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- normalized : int
- must be 0, normalization currently not supported
- onesided : int
- must be 1, only one sided FFTs supported
- signal_ndim : int
- number of dimensions comprising the signal, collected in reverse order (e.g. 1 = last dimension is the signal)
#### Inputs
- X : T
- input tensor of size n in the signal dim
#### Outputs
- Y : T
- output tensor of size (n//2 + 1) in the signal dim and 2 in the last dimension for the real and complex parts
#### Type Constraints
- T : tensor(float), tensor(double), tensor(float16)
- Constrain input and output types to float or half tensors.
### **com.microsoft.RotaryEmbedding**
RotaryEmbedding is the implementation of rotary positional embeddings (RoPE). The positions are represented as rotation matrices
that are multiplied to query and key before the inner product of query and key is taken.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- interleaved : int
- Indicates whether the input has real and imaginary parts interleaved. Default value is 0 (False), meaning the first half of the input consists of real values and the second half consists of imaginary values.
- is_packed_batching : int
- ragged batch inputs or not. Default value is 0
- num_heads : int
- Number of attention heads. Default value is 0. Must use with rotary_embedding_dim
- rotary_embedding_dim : int
- Rotary embedding dimension. Default value is 0.
- scale : float
- Custom scale will be used if specified. Default value is 1.0
#### Inputs
- input : T
- 3D tensor with shape (batch_size, sequence_length, hidden_size) or 4D with shape (batch_size, num_heads, sequence_length, head_size)
- position_ids : M
- 1D tensor with shape (1) or 2D tensor with shape (batch_size, sequence_length)
- cos_cache : T
- 2D tensor with shape (max_sequence_length, head_size / 2) or (max_sequence_length, rotary_embedding_dim / 2)
- sin_cache : T
- 2D tensor with shape (max_sequence_length, head_size / 2) or (max_sequence_length, rotary_embedding_dim / 2)
#### Outputs
- output : T
- tensor with same shape as input.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
- M : tensor(int64)
- Constrain input and output types to integer tensors
### **com.microsoft.SampleOp**
Sample echo operator.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- X : T
- input
#### Outputs
- Y : T
- output
#### Type Constraints
- T : tensor(uint32), tensor(uint64), tensor(int32), tensor(int64), tensor(float16), tensor(float), tensor(double)
- Constrain to any tensor type. If the dtype attribute is not provided this must be a valid output type.
### **com.microsoft.Sampling**
Greedy Sampling for text generation.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- custom : int
- If 1 custom sampling logic
- decoder : graph (required)
- Decoder subgraph to execute in a loop.
- decoder_start_token_id : int
- The id of the token that indicates decoding starts.
- encoder : graph
- The subgraph for initialization of encoder and decoder. It will be called once before decoder subgraph.
- eos_token_id : int (required)
- The id of the end-of-sequence token
- filter_value : float
- All filtered values will be set to this float value.
- init_decoder : graph
- The subgraph for the first decoding run. It will be called once before `decoder` subgraph. This is relevant only for the GPT2 model. If this attribute is missing, the `decoder` subgraph will be used for all decoding runs
- min_tokens_to_keep : int
- Minimumber of tokens we keep per batch example in the output.
- model_type : int
- Model type: 0 for decoder only like GPT-2; 1 for encoder decoder like Bart
- no_repeat_ngram_size : int
- no repeat ngrams size
- pad_token_id : int (required)
- The id of the padding token
- presence_penalty : float
- Presence penalty for custom sampling
- temperature : float
- The value used to module the next token probabilities.
- top_p : float
- If set to float < 1, only the smallest set of most probable tokens with probabilities that add up to `top_p` or higher are kept for generation.
- vocab_size : int
- Size of the vocabulary. If not provided, it will be inferred from the decoder subgraph's output shape
#### Inputs (2 - 9)
- input_ids : I
- The sequence used as a prompt for the generation. Shape is (batch_size, sequence_length)
- max_length : I
- The maximum length of the sequence to be generated. Shape is (1)
- min_length (optional) : I
- The minimum length below which the score of eos_token_id is set to -Inf. Shape is (1)
- repetition_penalty (optional) : T
- The parameter for repetition penalty. Default value 1.0 means no penalty. Accepts value > 0.0. Shape is (1)
- vocab_mask (optional) : I
- Mask of vocabulary. Words that masked with 0 are not allowed to be generated, and 1 is allowed. Shape is (vocab_size)
- prefix_vocab_mask (optional) : I
- Mask of vocabulary for first step. Words that masked with 0 are not allowed to be generated, and 1 is allowed. Shape is (batch_size, vocab_size)
- attention_mask (optional) : I
- Custom attention mask. Shape is (batch_size, sequence_length)
- presence_mask (optional) : I
- Presence penalty mask. Shape is (batch_size, vocab_size)
- seed (optional) : I
- Seed for random number generator. Shape is (1)
#### Outputs (1 - 2)
- sequences : I
- Word IDs of generated sequences. Shape is (batch_size, max_sequence_length)
- filtered_logits (optional) : T
- Filtered logits as input to the mutinomial function for debug purpose. Shape is (batch_size, vocab_size)
#### Type Constraints
- T : tensor(float)
- Constrain input and output types to float tensors.
- I : tensor(int32)
- Constrain to integer types
### **com.microsoft.ScaledSiLU**
Computes SiLU after scaling, with explicit T rounding:
Z_T = cast_T(effective_scale * X), S_T = cast_T(sigmoid(Z_T)), and
Y = cast_T(Z_T * S_T). effective_scale is the scalar input when present,
otherwise it is the alpha attribute.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- alpha : float
- Scale used when the optional scale input is absent.
#### Inputs (1 - 2)
- X : T
- Input tensor.
- scale (optional) : M
- Optional scalar scale that overrides alpha.
#### Outputs
- Y : T
- Output with the same shape as X.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output to floating-point tensors.
- M : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain the optional scale to floating-point tensors.
### **com.microsoft.SkipGroupNorm**
This operator element-wise adds x, skip and bias, then apply group normalization and optional activation.
This operator transforms input according to
s = x + skip + bias
y = gamma * (s - mean) / sqrt(variance + epsilon) + beta
The input channels are separated into num_groups groups, each containing num_channels / num_groups channels.
The num_channels must be divisible by num_groups.
The mean and standard-deviation of s are calculated separately over the each group.
The weight and bias are per-channel affine transform parameter vectors of size num_channels.
The activation attribute can be used to enable activation after group normalization.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : int (required)
- Activation after group normalization: 0 for None, 1 for SiLU
- channels_last : int
- 1 if the input and output are in the NHWC layout, 0 if it is in the NCHW layout. Defaults to 1.
- epsilon : float
- The epsilon value to use to avoid division by zero
- groups : int (required)
- The number of groups of channels. It should be a divisor of the number of channels C
#### Inputs (4 - 5)
- X : T
- Input data tensor. Dimensions are (N x H x W x C) when channels_last is 1 or (N x C x H x W) otherwise, where N is the batch size, C is the number of channels, and H and W are the height and width of the data
- gamma : M
- 1D gamma tensor for normalization with shape (C), where C is number of channels
- beta : M
- 1D beta tensor for normalization with shape (C), where C is number of channels
- skip : T
- 4D or 2D skip tensor. The shape can be (N x H x W x C) or (N x 1 x 1 x C) or (N x C)
- bias (optional) : T
- 1D bias tensor. Dimensions are (C), where C is number of channels
#### Outputs (1 - 2)
- Y : T
- The output tensor of the same shape as X
- S (optional) : T
- The element-wise sum of input x, skip and bias tensors. It has the same shape as X
#### Type Constraints
- T : tensor(float16), tensor(float)
- Constrain input X, skip, bias and output Y, S types to float tensors.
- M : tensor(float16), tensor(float)
- Constrain gamma and beta to float tensors.
### **com.microsoft.SkipLayerNormalization**
Skip and Layer Normalization Fusion
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- epsilon : float
- The epsilon value to use to avoid division by zero.
#### Inputs (3 - 5)
- input : T
- 3D input tensor with shape (batch_size, sequence_length, hidden_size)
- skip : T
- 3D skip tensor with shape (batch_size, sequence_length, hidden_size) or (1, sequence_length, hidden_size) or (sequence_length, hidden_size)
- gamma : T
- 1D input tensor with shape (hidden_size)
- beta (optional) : T
- 1D skip tensor with shape (hidden_size
- bias (optional) : T
- 1D bias tensor with shape (hidden_size
#### Outputs (1 - 4)
- output : T
- 3D output tensor with shape (batch_size, sequence_length, hidden_size)
- mean (optional) : U
- Saved mean used during training to speed up gradient computation
- inv_std_var (optional) : U
- Saved inverse standard variance used during training to speed up gradient computation.
- input_skip_bias_sum (optional) : T
- Sum of the input and skip inputs (and bias if it exists) with shape (batch_size, sequence_length, hidden_size).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float or half tensors.
- U : tensor(float)
- Constrain mean and inv_std_var to float tensors.
### **com.microsoft.SkipSimplifiedLayerNormalization**
Skip and Root Mean Square Layer Normalization
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- epsilon : float
- The epsilon value to use to avoid division by zero.
#### Inputs (3 - 4)
- input : T
- 3D input tensor with shape (batch_size, sequence_length, hidden_size)Or 2D input tensor with shape (token_count, hidden_size)
- skip : T
- 3D input tensor with shape (batch_size, sequence_length, hidden_size)Or 2D input tensor with shape (token_count, hidden_size)
- gamma : T
- 1D input tensor with shape (hidden_size)
- bias (optional) : T
- 1D bias tensor with shape (hidden_size
#### Outputs (1 - 4)
- output : T
- 3D output tensor with shape (batch_size, sequence_length, hidden_size)Or 2D output tensor with shape (token_count, hidden_size)
- mean (optional) : U
- Saved mean used during training to speed up gradient computation
- inv_std_var (optional) : U
- Saved inverse standard variance used during training to speed up gradient computation.
- input_skip_bias_sum (optional) : T
- Sum of the input and skip inputs (and bias if it exists)with shape (batch_size, sequence_length, hidden_size) or (token_count, hidden_size).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output to float tensors.
- U : tensor(float)
- Constrain mean and inv_std_var to float tensors.
### **com.microsoft.Snpe**
Onnx node for SNPE.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- DLC : string (required)
- payload of the SNPE DLC file.
- notes : string
- (Optional) Some notes for the model
- snpe_version : string
- (Optional) SNPE version used to convert the model.
- target_device : string
- (Optional) Target device like CPU, DSP, etc.
#### Inputs (1 - ∞)
- inputs (variadic) : T
- List of tensors for SNPE DLC input
#### Outputs (1 - ∞)
- outputs (variadic) : T
- One or more outputs, list of tensors for DLC output
#### Type Constraints
- T : tensor(uint8), tensor(uint16), tensor(float)
- Constrain input and output types to uint8, uint16, float tensors.
### **com.microsoft.SparseAttention**
Block Sparse Attention used in Phi-3-small (https://arxiv.org/pdf/2404.14219).
It is inspired by Sparse Transformers (https://arxiv.org/pdf/1904.10509) and BigBird (https://arxiv.org/pdf/2007.14062).
block_mask can be used to configure sparse layout for different head.
When number of sparse layout is 1, all heads have same sparse layout. Otherwise, different layouts are used cyclically.
For example, given 4 layouts (S0, S1, S2, S3), 8 heads will have layouts like (S0, S1, S2, S3, S0, S1, S2, S3).
The block_row_indices and block_col_indices are the CSR representation of block mask. The block_col_indices might contain
paddings at the right side when different layout has different number of non-zeros in block mask.
An example of block mask with 2 layouts where each layout is 4 x 4 blocks:
[[[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 1, 1, 1]],
[[1, 0, 0, 0],
[1, 1, 0, 0],
[1, 1, 1, 0],
[1, 0, 1, 1]]]
The corresponding CSR format:
block_col_indices = [[0, 0, 1, 1, 2, 1, 2, 3, -1], [0, 0, 1, 0, 1, 2, 0, 2, 3]]
block_row_indices = [[0, 1, 3, 5, 8], [0, 1, 3, 6, 9]]
When do_rotary is True, cos_cache and sin_cache are required. Note that the maximum sequence length supported by cos
or sin cache can be different from the maximum sequence length used by kv cache.
Only supports unidirectional attention with cache of past key and value in linear buffers.
For performance, past_key and present_key share same memory buffer, and past_value and present_value too.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- do_rotary : int
- Whether to use rotary position embedding. Default value is 0.
- kv_num_heads : int (required)
- Number of attention heads for key and value
- num_heads : int (required)
- Number of attention heads for query
- rotary_interleaved : int
- Rotary use interleaved pattern or not. Default value is 0.
- scale : float
- Scaling factor applied prior to softmax. The default value is 1/sqrt(head_size)
- sparse_block_size : int (required)
- Number of tokens per sparse block. Choices: 16, 32, 64, 128
#### Inputs (9 - 11)
- query : T
- Query with shape (batch_size, sequence_length, num_heads * head_size), or packed QKV with shape is(batch_size, sequence_length, d) where d is (num_heads + 2 * kv_num_heads) * head_size.
- key (optional) : T
- Key with shape (batch_size, sequence_length, kv_num_heads * head_size)
- value (optional) : T
- Value with shape (batch_size, sequence_length, kv_num_heads * head_size)
- past_key : T
- Key cache with shape (batch_size, kv_num_heads, max_cache_sequence_length, head_size)
- past_value : T
- Value cache with shape (batch_size, kv_num_heads, max_cache_sequence_length, head_size)
- block_row_indices : M
- The row indices of CSR format of block mask with shape (num_layout, max_blocks + 1).The num_heads is divisible by num_layout, and max_blocks is max_sequence_length / sparse_block_size.
- block_col_indices : M
- The col indices of CSR format of block mask with shape (num_layout, max_nnz_blocks).The max_nnz_blocks is the maximum number of non-zeros per layout in block mask.
- total_sequence_length : M
- Scalar tensor of maximum total sequence length (past_sequence_length + sequence_length) among keys.
- key_total_sequence_lengths : M
- 1D tensor with shape (batch_size) where each value is total sequence length of key excluding paddings.
- cos_cache (optional) : T
- Cos cache of rotary with shape (max_rotary_sequence_length, head_size / 2).
- sin_cache (optional) : T
- Sin cache of rotary with shape (max_rotary_sequence_length, head_size / 2).
#### Outputs
- output : T
- 3D output tensor with shape (batch_size, sequence_length, num_heads * head_size)
- present_key : T
- Updated key cache with shape (batch_size, kv_num_heads, max_cache_sequence_length, head_size).
- present_value : T
- Updated value cache with shape (batch_size, kv_num_heads, max_cache_sequence_length, head_size).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output to float tensors.
- M : tensor(int32)
- Constrain integer type.
### **com.microsoft.SparseAttentionIndexer**
Selects, for every query token, the sparse-attention candidates that the following attention
operator is allowed to read. It covers the two indexer flavours used by recent sparse-attention
decoders, chosen with the policy_mode attribute:
policy_mode = "qsa" ("query sparse attention" token indexer)
Groups the tokens that are visible to a query into complete blocks of compress_ratio tokens,
mean-pools the indexer keys of every block, normalizes and rotates the pooled key, scores it
against the query heads with sum_h ReLU(q_h . k), keeps the token_budget / compress_ratio
highest scoring blocks and emits the token indices of those blocks followed by the visible
tokens of the trailing incomplete block.
policy_mode = "csa" ("compressed sparse attention" block indexer)
Compresses every compress_ratio consecutive tokens into one entry with a softmax-gated pooling
over a window of 2 * compress_ratio slots (the previous window contributes its "Ca" half and
the current window its "Cb" half), normalizes and rotates the entry, appends it to the
compressed-key state, scores the queries against every compressed entry with
sum_h w_h * ReLU(q_h . k), masks the entries a query may not attend to and emits the index_topk
highest scoring entry indices. If a channel's softmax denominator is non-positive or non-finite
(for example, all logits are -inf or any logit is +inf), its pooled value is zero.
Common contract:
* selected_indices is int32 with a fixed capacity that only depends on attributes:
token_budget + compress_ratio - 1 for "qsa" and index_topk for "csa". Unused entries are -1,
so no output size depends on the data and no device-to-host synchronization is required.
* All state is explicit in the graph. Nothing is cached inside the operator.
* Rotary embeddings reuse the precomputed cos_cache / sin_cache tables, which are indexed by
absolute key position. "qsa" applies the half-rotation of the model's (M)RoPE to the leading
rotary_dim = cos_cache.shape[2] channels. "csa" applies its trailing rotary to the last
2 * cos_cache.shape[2] channels, with each cos/sin entry covering two consecutive channels.
* query_norm_weight and key_norm_weight are the effective RMSNorm multipliers. Models that store a zero-centered gamma
(the normalized value is multiplied by 1 + gamma) must fold the addition into this initializer.
* Accumulation, pooling, softmax, normalization and scoring are performed in float32 and the
result is rounded once to the tensor element type.
* Ties in the top-k selection are broken by the smaller entry index, and the emitted entries are
ordered by decreasing score, so the result is deterministic.
State layout for policy_mode = "csa": the two slices of past_proj_buffer hold the key and gate
projections that have not been folded into a compressed entry yet. When their length is >=
compress_ratio, the first compress_ratio tokens are the previous complete window (the "Ca" operand
of the next window) and the remainder is the current incomplete window; when it is < compress_ratio
there is no previous complete window and the whole buffer is the incomplete window. The length is
therefore always in [0, 2 * compress_ratio), and the number of compressed entries emitted by a call
is known from the input shapes alone. position_bias is re-applied to the buffered gates, so the gate
projection plane stores the raw projection.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- compress_ratio : int (required)
- Number of consecutive tokens folded into one compressed block. Must be > 0.
- epsilon : float
- Epsilon of the RMS normalization applied to queries and compressed keys. Default is 1e-6.
- head_weight_scale : float
- Only for policy_mode 'csa': scale applied to head_weights. Default is 1/sqrt(num_heads). Must be omitted when policy_mode is 'qsa'.
- index_topk : int
- Only for policy_mode 'csa': number of compressed entries selected per query. Must be > 0. Must be omitted when policy_mode is 'qsa'.
- policy_mode : string (required)
- Indexer policy. Must be exactly 'qsa' (token indexer) or 'csa' (compressed block indexer).
- scale : float
- Scale applied to the per-head ReLU scores. Default is 1/sqrt(head_size).
- token_budget : int
- Only for policy_mode 'qsa': maximum number of tokens selected from complete blocks. Must be > 0 and divisible by compress_ratio. Must be omitted when policy_mode is 'csa'.
#### Inputs (8 - 14)
- query : T
- Indexer queries with shape (batch_size, sequence_length, num_heads * head_size), before normalization, logical reshape, and rotary embedding. For policy_mode 'qsa', when key is omitted, this input instead packs query followed by key along the last dimension and has shape (batch_size, sequence_length, (num_heads + 1) * head_size).
- key (optional) : T
- Indexer key projection of the new tokens. Shape is (batch_size, sequence_length, head_size) for policy_mode 'qsa' and (batch_size, sequence_length, 2 * head_size) for policy_mode 'csa', where the first head_size channels are the Ca series and the last head_size channels the Cb series. May be omitted for policy_mode 'qsa' when query contains packed QK.
- query_norm_weight : T
- Effective RMSNorm multiplier of the queries, with shape (head_size).
- key_norm_weight : T
- Effective RMSNorm multiplier of the compressed keys, with shape (head_size).
- cos_cache : T
- Cosine rotary table indexed by absolute key position, shared across the batch with shape (max_rotary_sequence_length, rotary_width) or request-specific with shape (batch_size, max_rotary_sequence_length, rotary_width).
- sin_cache : T
- Sine rotary table with the same shape as cos_cache.
- mask (optional) : TB
- Only for policy_mode 'qsa': INT64 padding mask with shape (batch_size, total_sequence_length). Nonzero entries are visible subject to causal masking. total_sequence_length is past_sequence_length + sequence_length. When omitted, every position through past_sequence_length plus the current query index is visible.
- past_key : T
- Cached indexer keys. For policy_mode 'qsa', these are raw keys; for 'csa', they are compressed keys. Shape is (batch_size, past_sequence_length, head_size), or (batch_size, max_cache_length, head_size) when a valid past_sequence_length is provided.
- gate (optional) : T
- Only for policy_mode 'csa': gate projection of the new tokens with shape (batch_size, sequence_length, 2 * head_size).
- position_bias (optional) : T
- Only for policy_mode 'csa': per-slot gate bias with shape (compress_ratio, 2 * head_size).
- head_weights (optional) : T
- Only for policy_mode 'csa': per-head score weights with shape (batch_size, sequence_length, num_heads).
- position_ids (optional) : I
- Only for policy_mode 'csa': absolute position of every query with shape (batch_size, sequence_length).
- past_sequence_length (optional) : M
- Optional one-element CPU tensor containing the number of valid rows in past_key. For policy_mode 'csa', the value is the number of compressed keys. When provided, past_key and present_key have the same max-capacity shape and may share their buffer.
- past_proj_buffer (optional) : T
- Only for policy_mode 'csa': buffered key and gate projections packed along dimension 0, with shape (2, batch_size, buffer_length, 2 * head_size). Slice 0 contains keys and slice 1 contains gates. buffer_length is in [0, 2 * compress_ratio).
#### Outputs (2 - 3)
- selected_indices : M
- Selected entries with shape (batch_size, sequence_length, capacity). capacity is token_budget + compress_ratio - 1 for policy_mode 'qsa', where the values are token indices into the key cache, and index_topk for policy_mode 'csa', where the values are compressed entry indices. Unused entries are -1.
- present_key : T
- Updated raw key cache for policy_mode 'qsa' or compressed-key cache for 'csa'. Without past_sequence_length its sequence dimension grows by the entries emitted by this call. When past_sequence_length is provided, its shape matches the max-capacity past_key and the two tensors may share a buffer.
- present_proj_buffer (optional) : T
- Only for policy_mode 'csa': updated packed key/gate projection buffer with shape (2, batch_size, present_buffer_length, 2 * head_size).
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain floating point tensors to float, float16 and bfloat16.
- TB : tensor(int64)
- Constrain the mask to 64-bit integer tensors.
- I : tensor(int64)
- Constrain position ids to 64-bit integer tensors.
- M : tensor(int32)
- Constrain indices and cache lengths to 32-bit integer tensors.
### **com.microsoft.SparsePagedAttention**
Selected-index attention over the PagedAttention main K/V cache.
Selection is supplied by an external indexer. selected_only attends selected entries;
local_plus_selected combines a main-cache local window and selected entries in one softmax.
Selected indices are request-local logical positions in the main cache or in a contiguous
auxiliary cache, according to selected_kv_source.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- attention_mode : string
- 'selected_only' or 'local_plus_selected'.
- auxiliary_cache_layout : string
- Version 1 supports only 'contiguous'.
- auxiliary_kv_shared : int
- When 1, auxiliary_key supplies both K and V.
- do_rotary : int
- Apply rotary embedding to current Q/K.
- is_causal : int
- Apply causal filtering to main-cache reads.
- k_quant_type : string
- Main key-cache quantization: NONE, PER_TENSOR, or PER_CHANNEL.
- kv_num_heads : int (required)
- Number of main K/V heads.
- local_window_size : int
- Left main-cache window size; -1 means all visible tokens.
- num_heads : int (required)
- Number of query heads.
- qk_norm_epsilon : float
- QK RMSNorm epsilon.
- rotary_interleaved : int
- Use interleaved rotary embedding.
- rotary_offset : int
- First head channel covered by rotary embedding.
- scale : float
- Attention scale; defaults to 1/sqrt(head_size).
- selected_kv_source : string
- 'main' or 'auxiliary'.
- softcap : float
- Optional tanh softcap for attention logits.
- v_quant_type : string
- Main value-cache quantization: NONE, PER_TENSOR, or PER_CHANNEL.
#### Inputs (11 - 22)
- query : T
- Query or packed QKV, shaped as for PagedAttention.
- key (optional) : T
- Current key.
- value (optional) : T
- Current value.
- key_cache : T_CACHE
- Paged main key cache.
- value_cache : T_CACHE
- Paged main value cache.
- cumulative_sequence_length : S
- Packed query offsets.
- past_seqlens : S
- Past main-cache lengths.
- block_table : S
- Logical-to-physical main-cache block table.
- slot_mapping (optional) : S
- Optional main-cache write slots; -1 suppresses a write.
- selected_indices : S
- Request-local positions, shape (token_count, max_selected_entries); unused entries are -1.
- selected_counts : S
- Selected entry count per query token.
- auxiliary_key (optional) : T
- Shape (batch_size, capacity, kv_num_heads_or_one, head_size).
- auxiliary_value (optional) : T
- Same shape as auxiliary_key.
- auxiliary_lengths (optional) : S
- Valid auxiliary length per request.
- cos_cache (optional) : T
- Rotary cosine cache.
- sin_cache (optional) : T
- Rotary sine cache.
- head_sink (optional) : T
- Optional softmax sink logit per query head.
- q_norm_weight (optional) : T
- QK-Norm query weight.
- k_norm_weight (optional) : T
- QK-Norm key weight.
- k_scale (optional) : T_KV_SCALE
- Main key-cache quantization scale.
- v_scale (optional) : T_KV_SCALE
- Main value-cache quantization scale.
- attention_metadata (optional) : S
- CPU tensor [max_query_len, max_local_main_len, max_selected_entries, max_auxiliary_len, max_combined_attention_len].
#### Outputs (1 - 3)
- output : T
- Shape (token_count, num_heads * head_size).
- key_cache_out (optional) : T_CACHE
- In-place alias of key_cache.
- value_cache_out (optional) : T_CACHE
- In-place alias of value_cache.
#### Type Constraints
- T : tensor(float16), tensor(bfloat16)
- Activation type.
- T_CACHE : tensor(float16), tensor(bfloat16), tensor(int8)
- Main cache storage type.
- T_KV_SCALE : tensor(float)
- Main cache scale type.
- S : tensor(int32)
- Index and length type.
### **com.microsoft.SparseToDenseMatMul**
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- alpha : float
- Scalar multiplier for the product of the input tensors.
- transA : int
- Whether A should be transposed on the last two dimensions before doing multiplication
- transB : int
- Whether B should be transposed on the last two dimensions before doing multiplication
#### Inputs
- A : T
- 2-dimensional sparse matrix A. Either COO or CSR format
- B : T1
- N-dimensional dense matrix B
#### Outputs
- Y : T1
- Matrix multiply results
#### Type Constraints
- T : sparse_tensor(float), sparse_tensor(double), sparse_tensor(int64), sparse_tensor(int32), sparse_tensor(uint64), sparse_tensor(uint32)
- Constrain input and output types to float tensors.
- T1 : tensor(float), tensor(double), tensor(int64), tensor(int32), tensor(uint64), tensor(uint32)
- Constrain input and output types to float tensors.
### **com.microsoft.Tokenizer**
Tokenizer divides each string in X into a vector of strings along the last axis. Allowed input shapes are [C] and [N, C].
If the maximum number of tokens found per input string is D, the output shape would be [N, C, D] when input shape is [N, C].
Similarly, if input shape is [C] then the output should be [C, D]. Tokenizer has two different operation modes.
The first mode is selected when "tokenexp" is not set and "separators" is set. If "tokenexp" is set and "separators" is not set,
the second mode will be used. The first mode breaks each input string into tokens by matching and removing separators.
"separators" is a list of strings which are RE2 regular expressions. "tokenexp" is a single RE2 regular expression.
Let's assume "separators" is [" "] and consider an example.
If input is
["Hello World", "I love computer science !"] whose shape is [2],
then the output would be
[["Hello", "World", padvalue, padvalue, padvalue],
["I", "love", "computer", "science", "!"]]
whose shape is [2, 5] because you can find at most 5 tokens per input string.
Note that the input at most can have two axes, so 3-D and higher dimension are not supported.
If "separators" contains a single empty string, the Tokenizer will enter into character tokenization mode. This means all strings
will be broken apart into individual characters.
Similarly, if "tokenexp" is set to "." (match any single character), character tokenization mode is used.
For each input string, the second mode searches matches of "tokenexp" and each match will be a token in Y.
The matching of "tokenexp" is conducted greedily (i.e., a match should be as long as possible).
This operator searches for the first match starting from the beginning of the considered string,
and then launches another search starting from the first remained character after the first matched token.
If no match found, this operator will remove the first character from the remained string and do another search.
This procedure will be repeated until reaching the end of the considered string.
Let's consider another example to illustrate the effect of setting "mark" to true.
If input is ["Hello", "World"],
then the corresponding output would be [0x02, "Hello", "World", 0x03].
This implies that if mark is true, [C]/[N, C] - input's output shape becomes [C, D+2]/[N, C, D+2].
If tokenizer removes the entire content of [C]-input, it will produce [[]].
I.e. the output shape should be [C][0] or [N][C][0] if input shape was [N][C].
If the tokenizer receives empty input of [0] then the output is [0] if empty input
of [N, 0] then [N, 0].
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- mark : int (required)
- Boolean whether to mark the beginning/end character with start of text character (0x02)/end of text character (0x03).
- mincharnum : int (required)
- Minimum number of characters allowed in the output. For example, if mincharnum is 2, tokens such as "A" and "B" would be ignored
- pad_value : string (required)
- The string used to pad output tensors when the tokens extracted doesn't match the maximum number of tokens found. If start/end markers are needed, padding will appear outside the markers.
- separators : list of strings
- an optional list of strings attribute that contains a list of separators - RE2 regular expressions to match separators. Two consecutive segments in X connected by a separator would be divided into two tokens. For example, if the input is "Hello World!" and this attribute contains only one space character, the corresponding output would be ["Hello", "World!"]. To achieve character-level tokenization, one should set the 'separators' to [""], which contains an empty string.
- tokenexp : string
- An optional string. Token's regular expression in RE2 format (https://github.com/google/re2/wiki/Syntax). If set, tokenizer may produce tokens matching the specified pattern. Note that one and only one of 'tokenexp' and 'separators' should be set. If tokenexp is ".", the tokenizer enters character tokenization mode.
#### Inputs
- X : T
- Strings to tokenize
#### Outputs
- Y : T
- Tokenized strings
#### Type Constraints
- T : tensor(string)
- Input/Output is a string tensor
### **com.microsoft.TorchEmbedding**
Based on Torch operator Embedding, creates a lookup table of embedding vectors of fixed size,
for a dictionary of fixed size.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs (2 - 4)
- weight : T
- The embedding matrix of size N x M. 'N' is equal to the maximum possible index + 1, and 'M' is equal to the embedding size
- indices : tensor(int64)
- Long tensor containing the indices to extract from embedding matrix.
- padding_idx (optional) : tensor(int64)
- A 0-D scalar tensor. If specified, the entries at `padding_idx` do not contribute to the gradient; therefore, the embedding vector at `padding_idx` is not updated during training, i.e. it remains as a fixed pad.
- scale_grad_by_freq (optional) : tensor(bool)
- A 0-D bool tensor. If given, this will scale gradients by the inverse of frequency of the indices (words) in the mini-batch. Default is ``False``
#### Outputs
- Y : T
- Output tensor of the same type as the input tensor. Shape of the output is * x M, where '*' is the shape of input indices, and 'M' is the embedding size.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16), tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64), tensor(int8), tensor(int16), tensor(int32), tensor(int64)
- Constrain input and output types to all numeric tensors.
### **com.microsoft.TransposeMatMul**
Duplicate of FusedMatMul. Going forward FusedMatMul should be used. This OP will be supported for backward compatibility.
Matrix product that behaves like numpy.matmul: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.matmul.html
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- alpha : float
- Scalar multiplier for the product of the input tensors.
- transA : int
- Whether A should be transposed on the last two dimensions before doing multiplication
- transB : int
- Whether B should be transposed on the last two dimensions before doing multiplication
#### Inputs
- A : T
- N-dimensional matrix A
- B : T
- N-dimensional matrix B
#### Outputs
- Y : T
- Matrix multiply results
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
### **com.microsoft.Trilu**
Returns the upper or lower triangular part of a 2-D matrix, or batches of 2-D matrices. If the attribute "upper" is set to true,
the upper triangular matrix is retained. Lower triangular matrix is retained otherwise. Default value for upper is true.
Trilu takes one input tensor of shape [*, N, M], where * is zero or more batch dimensions. The upper triangular part consists
of the elements on and above the given diagonal (k). The lower triangular part consists of elements on and below the diagonal.
All other elements in the matrix are set to zero.
If k = 0, the triangular part on and above/below the main diagonal is retained.
If upper is set to true, a positive k retains the upper triangular matrix excluding k diagonals above
the main diagonal. A negative k value includes as many diagonals below the main diagonal.
If upper is set to false, a positive k retains the lower triangular matrix including k diagonals above
the main diagonal. A negative k value excludes as many diagonals below the main diagonal.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- upper : int
- Boolean. Indicates whether upper or lower part of matrix is retained. Default is true.
#### Inputs (1 - 2)
- X : T
- Input tensor of rank 2 or higher.
- k (optional) : tensor(int64)
- A 0-D tensor containing a single value corresponding to the number diagonals above or the main diagonal to exclude or include.Default value is 0 if it's not specified.
#### Outputs
- Y : T
- Output tensor of the same type and shape as the input tensor.
#### Type Constraints
- T : tensor(float16), tensor(float), tensor(double), tensor(bfloat16), tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64), tensor(int8), tensor(int16), tensor(int32), tensor(int64), tensor(bool)
- Constrain input and output types to all numeric tensors and bool tensors.
### **com.microsoft.UnfoldTensor**
Returns a tensor which contains all slices of size `size` from input tensor in the dimension `dim`. Step between two slices is given by `step`. If `sizedim` is the size of dimension `dim` for input tensor, the size of dimension `dim` in the returned tensor will be `(sizedim - size) / step + 1`. An additional dimension of size `size` is appended in the returned tensor.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- dim : int
- specify the dimension to unfold
- size : int (required)
- specify the size
- step : int
- specify the step.
#### Inputs
- input : T
- input tensor
#### Outputs
- output : T
- Output tensor.
#### Type Constraints
- T : tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64), tensor(int8), tensor(int16), tensor(int32), tensor(int64), tensor(bfloat16), tensor(float16), tensor(float), tensor(double), tensor(string), tensor(bool), tensor(complex64), tensor(complex128)
- Allow inputs and outputs to be any kind of tensor.
### **com.microsoft.Unique**
Finds all the unique values (deduped list) present in the given input tensor.
This operator returns 3 outputs.
The first output tensor 'uniques' contains all of the unique elements of the input,
sorted in the same order that they occur in the input.
The second output tensor 'idx' is the same size as the input and it contains the index
of each value of the input in 'uniques'.
The third output tensor 'counts' contains the count of each element of 'uniques' in the input.
Example:
input_x = [2, 1, 1, 3, 4, 3]
output_uniques = [2, 1, 3, 4]
output_idx = [0, 1, 1, 2, 3, 2]
output_counts = [1, 2, 2, 1]
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Inputs
- x : T
- A 1-D input tensor that is to be processed.
#### Outputs
- y : T
- A 1-D tensor of the same type as 'x' containing all the unique values in 'x' sorted in the same order that they occur in the input 'x'
- idx : tensor(int64)
- A 1-D INT64 tensor of the same size as 'x' containing the indices for each value in 'x' in the output 'uniques'
- counts : tensor(int64)
- A 1-D INT64 tensor containing the the count of each element of 'uniques' in the input 'x'
#### Type Constraints
- T : tensor(uint8), tensor(uint16), tensor(uint32), tensor(uint64), tensor(int8), tensor(int16), tensor(int32), tensor(int64), tensor(float16), tensor(float), tensor(double), tensor(string), tensor(bool), tensor(complex64), tensor(complex128)
- Input can be of any tensor type.
### **com.microsoft.VarlenCausalConvWithState**
Stateful causal depthwise convolution over a packed, token-major batch of variable-length
sequences (CUDA and WebGPU).
input and output have shape (total_tokens, channels). cumulative_sequence_length is a
device-resident int32 tensor of shape (batch_size + 1); sequence i occupies
[cumulative_sequence_length[i], cumulative_sequence_length[i + 1]). Every sequence contributes
at least one token. weight has shape (channels, 1, kernel_size), and optional bias has shape
(channels). The convolution never reads across a sequence boundary.
initial_state is required and has shape (batch_size, channels, state_length), where
state_length = (kernel_size - 1) * dilation. It contains
the committed raw activation samples immediately preceding this call. final_state has the same
shape and type and is fully written with the state after each sequence's final token. State
uses the activation type because it stores raw samples, not accumulated convolution values.
initial_state and final_state may use the same allocation. Such in-place execution is
transaction-safe only when the whole operator call is unconditionally committed; a caller that
may select a prefix or roll back must preserve initial_state and replay the compact state update.
When state_update_capacity is positive, capture_count is required with shape (batch_size), and
state_update has shape (batch_size, state_update_capacity, channels).
For request b, slots [0, clamp(capture_count[b], 0,
min(state_update_capacity, sequence_length[b]))) contain the original local input token values.
These values represent the append component of each shift-left-and-append state transition.
All remaining slots are zero. capture_count is forbidden when state_update_capacity is zero.
For memory-safety containment, each GPU work item validates cumulative_sequence_length[0] == 0,
cumulative_sequence_length[batch_size] == total_tokens, and its local range
0 <= start < end <= total_tokens before accessing input, state, or output.
Malformed offsets cause affected work to return without those accesses; outputs are unspecified.
This device-side containment is not a synchronous validation or rejection mechanism.
The optional activation attribute supports none, SiLU, and Swish.
The dilation attribute spaces the kernel taps along the sequence axis: local token t of a request
reads that request's local positions t - (kernel_size - 1 - j) * dilation for tap j, and positions
before the request's first token come from the carry state. The carry state therefore holds
state_length = (kernel_size - 1) * dilation positions per request instead of kernel_size - 1.
Dilation 1 (the default) is the undilated case and keeps the original state length, so models
exported before the attribute existed are unaffected. input and output are already token-major
(sequence-major, channels-last), so this op needs no separate layout attribute.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- activation : string
- Fused activation function. One of: 'silu', 'swish', 'none'. Default is 'none'.
- dilation : int
- Spacing between kernel taps along the sequence axis. The receptive field spans (kernel_size - 1) * dilation positions before the current token, and initial_state / final_state hold that many positions per request. Must be >= 1. Default is 1 (undilated).
- state_update_capacity : int
- Static number of compact contiguous-prefix transition values to expose per request. Valid range is [0, 8]. capture_count is required exactly when this is positive.
#### Inputs (5 - 6)
- input : T
- Token-major packed input with shape (total_tokens, channels).
- weight : T
- Depthwise convolution kernel with shape (channels, 1, kernel_size).
- cumulative_sequence_length : M
- Device tensor with shape (batch_size + 1) giving the half-open packed token range of each sequence.
- bias (optional) : T
- Optional per-channel bias with shape (channels). Because the following initial_state input is required, an omitted bias must still occupy this position as an empty input name so initial_state stays at input index 4.
- initial_state : T
- Required committed carry state with shape (batch_size, channels, (kernel_size - 1) * dilation).
- capture_count (optional) : M
- Optional device int32 tensor with shape (batch_size). For each request, captures that many local tokens from the contiguous prefix, clamped to the sequence length and state_update_capacity. Required exactly when state_update_capacity is positive.
#### Outputs (2 - 3)
- output : T
- Token-major convolution output with the same shape as input.
- final_state : T
- Fully written state after each sequence's final token, with shape (batch_size, channels, (kernel_size - 1) * dilation).
- state_update (optional) : T
- Optional compact transition values with shape (batch_size, state_update_capacity, channels). Inactive slots are zero.
#### Type Constraints
- T : tensor(float), tensor(float16), tensor(bfloat16)
- Constrain input and output types to float tensors.
- M : tensor(int32)
- Constrain cumulative_sequence_length and capture_count to device int32 tensors.
### **com.microsoft.VarlenNGramHashMapping**
Computes Engram n-gram hash ids from pre-compressed tokenizer ids over a packed, token-major batch
of variable-length sequences.
input_ids has shape (total_tokens) and hash_ids has shape (total_tokens, (max_ngram_size - 1) *
n_head_per_ngram). cumulative_sequence_length is a device-resident int32 tensor of shape
(batch_size + 1); request i occupies [cumulative_sequence_length[i], cumulative_sequence_length[i +
1]) of the packed buffer. Every request contributes at least one token.
For n in [2, max_ngram_size], the op creates causal shifts of each request's own tokens, padding
positions before that request's start with pad_id (or its own past_ids history, see below), and
computes mix = shifted_0 * multipliers[0] xor ... xor shifted_(n-1) * multipliers[n-1]. For every
head of that n-gram order it emits mix modulo the corresponding head vocabulary size. The n-gram
window never reads tokens belonging to a different packed request; it is clamped at each request's
own boundary exactly like VarlenCausalConvWithState clamps its causal convolution.
An n-gram window reaches max_ngram_size - 1 positions before the current token. To keep the op
causal across invocations (chunked prefill or autoregressive decode) for every concurrent request in
the packed batch, the optional past_ids input carries those preceding ids per request and
present_ids returns the ids to pass to the next call. Both have shape (batch_size, max_ngram_size -
1) and are right-aligned, so the last slot is the most recent id, and are indexed by request
(batch_size), not by position in the packed buffer. Positions before the start of a request's whole
sequence use pad_id, or eos_token_id when provided. Running NGramHashMapping once per sequence and running this op once over those
sequences packed together (optionally split into packed chunks with present_ids threaded into
past_ids) produce identical hash ids.
Optional inputs add Qwen4-Exp-style n-gram embedding support:
- eos_token_id, when provided together with reset_on_eos != 0, causes causal history to reset at EOS
boundaries. Missing history is also filled with eos_token_id.
- segment_ids, when provided, additionally resets causal history when adjacent tokens within one
packed request have different segment ids. Thread present_segment_ids into past_segment_ids on
subsequent calls to preserve boundaries across chunked prefill and decode calls.
- head_offsets, when provided, adds a fixed per-output-head offset after the modulo. Addition wraps
in the input id type on overflow.
- capture_count enables compact prefix state capture when state_update_capacity is positive. For
each request, state_update contains the trailing state after each captured prefix token.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- max_ngram_size : int (required)
- Maximum n-gram order. Must be at least 2.
- n_head_per_ngram : int (required)
- Number of hash heads emitted for each n-gram order.
- pad_id : int (required)
- Compressed tokenizer id used to pad causal shifts before the beginning of a request's sequence.
- reset_on_eos : int
- When non-zero and eos_token_id is provided, reset causal n-gram history at EOS boundaries. Default is 0.
- state_update_capacity : int
- Static number of compact contiguous-prefix states to expose per request. Valid range is [0, 8]. capture_count is required exactly when this is positive.
#### Inputs (4 - 10)
- input_ids : M
- Token-major packed compressed tokenizer ids with shape (total_tokens).
- multipliers : M
- Per-shift hash multipliers with at least max_ngram_size elements. Conventionally odd, but any value is accepted.
- vocab_sizes : M
- Per-output-head vocabulary sizes, conventionally prime, with shape ((max_ngram_size - 1) * n_head_per_ngram). Every entry must be strictly positive. The CPU implementation rejects a non-positive entry; GPU implementations guard the modulo to avoid a device-side division by zero and emit a hash id of 0 for that head.
- cumulative_sequence_length : S
- Device tensor with shape (batch_size + 1) giving the half-open packed token range of each request.
- past_ids (optional) : M
- Optional compressed tokenizer ids for the max_ngram_size - 1 positions that precede this call, with shape (batch_size, max_ngram_size - 1). Right-aligned, so the last slot is the most recent id, and indexed by request rather than by packed position. If omitted the history is pad_id, or eos_token_id when provided.
- head_offsets (optional) : M
- Optional per-output-head additive offset with shape ((max_ngram_size - 1) * n_head_per_ngram), added after the modulo with wrapping arithmetic in the input id type.
- eos_token_id (optional) : M
- Optional scalar end-of-sequence token id. When provided it replaces pad_id for missing history and enables reset_on_eos.
- segment_ids (optional) : tensor(int32)
- Optional token-major segment ids with shape (total_tokens), used to reset causal history at segment boundaries within each packed request.
- past_segment_ids (optional) : S
- Optional segment ids corresponding to past_ids, with shape (batch_size, max_ngram_size - 1). Thread present_segment_ids from the previous call into this input to preserve segment boundaries across calls.
- capture_count (optional) : S
- Optional device int32 tensor with shape (batch_size). For each request, captures that many local prefix states, clamped to the request length and state_update_capacity. Required exactly when state_update_capacity is positive.
#### Outputs (1 - 4)
- hash_ids : M
- Token-major packed hash ids with shape (total_tokens, (max_ngram_size - 1) * n_head_per_ngram).
- present_ids (optional) : M
- Trailing max_ngram_size - 1 ids of past_ids followed by each request's own tokens, with shape (batch_size, max_ngram_size - 1). Feed this back as past_ids on the next call.
- present_segment_ids (optional) : S
- Trailing max_ngram_size - 1 segment ids corresponding to present_ids, with shape (batch_size, max_ngram_size - 1). Feed this back as past_segment_ids on the next call.
- state_update (optional) : M
- Optional trailing id states after each captured prefix token, with shape (batch_size, state_update_capacity, max_ngram_size - 1). Unused slots are pad_id.
#### Type Constraints
- M : tensor(int32), tensor(int64)
- Constrain ids, multipliers, vocabulary sizes, and output ids to integer tensors.
- S : tensor(int32)
- Constrain cumulative_sequence_length and segment ids to device int32 tensors.
### **com.microsoft.WhisperBeamSearch**
Beam Search for whisper model, especially with cross_qk features etc.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- beginning_timestamp_token_id : int
- The id of the first timestamp
- decoder : graph (required)
- Decoder subgraph to execute in a loop.
- decoder_output_cross_qk : int
- If nozero, decoder subgraph contains output Q*K from cross attentions. Default 0.
- decoder_start_token_id : int
- The id of the token that indicates decoding starts (i.e. the start of transcription token id)
- early_stopping : int
- early stop or not
- encoder : graph
- The subgraph for initialization of encoder and decoder. It will be called once before decoder subgraph.
- eos_token_id : int (required)
- The id of the end-of-sequence token
- init_decoder : graph
- The subgraph for the first decoding run. It will be called once before `decoder` subgraph. This is relevant only for the GPT2 model. If this attribute is missing, the `decoder` subgraph will be used for all decoding runs
- model_type : int
- Must be 2 for whisper
- no_repeat_ngram_size : int
- no repeat ngrams size
- no_speech_token_id : int
- The token in whisper model that marks all sequence empty. With this model, whisper could output no_speech_prob after. Default -1.
- no_timestamps_token_id : int
- The id of the token that indicates no timestamps
- pad_token_id : int (required)
- The id of the padding token
- start_of_lm_token_id : int
- The id of the token that indicates LM starts
- transcribe_token_id : int
- The id of the transcribe task
- translate_token_id : int
- The id of the translate task
- vocab_size : int
- Size of the vocabulary. If not provided, it will be inferred from the decoder subgraph's output shape
#### Inputs (5 - 15)
- input_ids : F
- The sequence used as a prompt for the generation in the encoder subgraph. Shape is (batch_size, sequence_length)
- max_length : I
- The maximum length of the sequence to be generated. Shape is (1)
- min_length (optional) : I
- The minimum length below which the score of eos_token_id is set to -Inf. Shape is (1)
- num_beams : I
- Number of beams for beam search. 1 means no beam search. Shape is (1)
- num_return_sequences : I
- The number of returned sequences in the batch. Shape is (1)
- length_penalty (optional) : T
- Exponential penalty to the length. Default value 1.0 means no penalty. Value > 1.0 encourages longer sequences, while values < 1.0 produces shorter sequences. Shape is (1,)
- repetition_penalty (optional) : T
- The parameter for repetition penalty. Default value 1.0 means no penalty. Accepts value > 0.0. Shape is (1)
- vocab_mask (optional) : M
- Mask of vocabulary. Words that masked with 0 are not allowed to be generated, and 1 is allowed. Shape is (vocab_size)
- prefix_vocab_mask (optional) : M
- Mask of vocabulary for first step. Words that masked with 0 are not allowed to be generated, and 1 is allowed. Shape is (batch_size, vocab_size)
- attention_mask (optional) : I
- Custom attention mask. Shape is (batch_size, sequence_length)
- decoder_input_ids (optional) : I
- The forced input id sequence for the decoder subgraph. Shape is (batch_size, initial_sequence_length)
- logits_processor (optional) : I
- Specific logits processor for different types of beamsearch models. Default value 0 means no specific logit processor. Accepts value >= 0. Shape is (1)
- cross_qk_layer_head (optional) : I
- Only keep this list of (layer, head) of QK in the final cross_qk output when use_cross_qk is set. Default collect all its shape is (number of (layer, head) to keep, 2), i.e., [[layer_id1, head_id1], [layer_id2, head_id2]......]
- extra_decoding_ids (optional) : I
- Part of the decoder_input_ids that we need cross qk for it. it is of shape (batch_size, extra_decoding_ids_len).In such case, we should remove this from the tail of the decoder_input_ids, and put it here. ids < 0 in it (for multiple batch) are treated as stop of the extra_decoding_ids for corresponding batch.
- temperature (optional) : T
- Temperature value to apply to logits processing during this execution's decoding. Shape is (1)
#### Outputs (1 - 5)
- sequences : I
- Word IDs of generated sequences. Shape is (batch_size, num_return_sequences, max_sequence_length)
- sequences_scores (optional) : T
- Final beam score of the generated sequences. Shape is (batch_size, num_return_sequences)
- scores (optional) : T
- Processed beam scores for each vocabulary token at each generation step. Beam scores consisting of log softmax scores for each vocabulary token and sum of log softmax of previously generated tokens in this beam. Shape is (max_length - sequence_length, batch_size, num_beams, vocab_size)
- cross_qk (optional) : V
- Output the accumulated stacked Q*K in cross attentions. Let H = number of Head of cross attention, F = the frames or kv-seq-len of the cross attention input, T = real decoded token length, L = number of layers, B = batch size, R = num_return_sequences. It then should return tensor of shape [B, R, L*H, T, F]. If cross_qk_layer_head is given, shape is [B, R, cross_qk_layer_head.shape[0], T, F]
- non_speech_probs (optional) : T
- For whisper model, output the probabilities from logits after encoder and context decoding for the no_speech_token_id. The shape of non_speech_probs is [B]
#### Type Constraints
- T : tensor(float), tensor(float16)
- Constrain to float tensors.
- F : tensor(float), tensor(int32), tensor(float16)
- Constrain input type to float or int tensors.
- I : tensor(int32)
- Constrain to integer types
- M : tensor(int32)
- Constrain mask to integer types
- V : tensor(float)
- Constrain cross_qk to float32 tensors.
### **com.microsoft.WordConvEmbedding**
The WordConvEmbedding takes in a batch of sequence words and embed each word to a vector.
#### Version
This version of the operator has been available since version 1 of the 'com.microsoft' operator set.
#### Attributes
- char_embedding_size : int
- Integer representing the embedding vector size for each char.If not provide, use the char embedding size of embedding vector.
- conv_window_size : int
- This operator applies convolution to word from left to right with window equal to conv_window_size and stride to 1.Take word 'example' for example, with conv_window_size equal to 2, conv is applied to [ex],[xa], [am], [mp]...If not provide, use the first dimension of conv kernel shape.
- embedding_size : int
- Integer representing the embedding vector size for each word.If not provide, use the filter size of conv weight
#### Inputs
- Sequence : T
- Specify batchs of sequence words to embedding
- W : T1
- Specify weights of conv
- B : T1
- Specify bias of conv
- C : T1
- Specify embedding vector of char
#### Outputs
- Y : T1
- output
#### Type Constraints
- T : tensor(int32)
- Constrain to tensor(int32).
- T1 : tensor(float)
- Constrain to tensor(float).
### experimental **com.microsoft.IsAllFinite**
IsAllFinite
#### Version
No versioning maintained for experimental ops.
#### Attributes
- isinf_only : int
- If true, check only for Inf, -Inf.
- isnan_only : int
- If true, check only for NaN.
#### Inputs (1 - ∞)
- input (variadic) : V
- Input tensors to check.
#### Outputs
- output : T
- The output scalar. Its value is true if all input tensors are finite. Otherwise, the output value would be false.
#### Type Constraints
- V : tensor(float16), tensor(float), tensor(double), tensor(bfloat16)
- Constrain input and output types to float tensors.
- T : tensor(bool)
- Constrain the output to a boolean tensor.
### experimental **com.microsoft.QEmbedLayerNormalization**
QEmbedLayerNormalization is the quantized fusion of embedding layer in BERT model, with optional mask processing.
The embedding layer takes input_ids (word IDs) and segment_ids (sentence IDs) to look up word_embedding, position_embedding,
and segment_emedding; the embeddings are added then applied layer normalization using gamma and beta tensors. The input_ids
and segment_ids remain int32. All embeddings, gamma, and beta tensors are converted to int8/uint8. The last input mask is optional.
segment_ids, segment_embedding, segment_embedding_scale, and segment_embedding_zero_point must either all be provided or all
be omitted.
If mask is provided, mask index (that is position of first 0 in mask, or number of words will be calculated.
#### Version
No versioning maintained for experimental ops.
#### Attributes
- epsilon : float
- The epsilon value to use to avoid division by zero.
#### Inputs
- input_ids : T1
- 2D words IDs with shape (batch_size, sequence_length)
- segment_ids (optional) : T1
- 2D segment IDs with shape (batch_size, sequence_length). Part of the all-or-none segment input group.
- word_embedding_quant : T2
- 2D with shape (,hidden_size)
- position_embedding_quant : T2
- 2D with shape (, hidden_size)
- segment_embedding (optional) : T2
- 2D with shape (, hidden_size). Part of the all-or-none segment input group.
- gamma_quant : T2
- 1D gamma tensor for layer normalization with shape (hidden_size)
- beta_quant : T2
- 1D beta tensor for layer normalization with shape (hidden_size)
- mask (optional) : T1
- Mask
- word_embedding_scale : T
- Scale for word embeddings
- position_embedding_scale : T
- Scale for position embeddings
- segment_embedding_scale (optional) : T
- Scale for segment embeddings. Part of the all-or-none segment input group.
- gamma_scale : T
- Scale for 1D gamma tensor
- beta_scale : T
- Scale for 1D beta tensor
- word_embedding_zero_point : T2
- Zero point for word embeddings
- position_embedding_zero_point : T2
- Zero point for position embeddings
- segment_embedding_zero_point (optional) : T2
- Zero Point for segment embeddings. Part of the all-or-none segment input group.
- gamma_zero_point : T2
- Zero Point for 1D gamma tensor
- beta_zero_point : T2
- Zero Point for 1D beta tensor
#### Outputs
- layernorm_out : T
- LayerNorm Output
- mask_index_out : T1
- Mask Index Output
#### Type Constraints
- T1 : tensor(int32)
- Constrain mask index to integer types
- T2 : tensor(int8), tensor(uint8)
- Constrain input and output types to int8 tensors.
- T : tensor(float)
- Constrain input and output types to float32 tensors.