Skip to content

vllm.model_executor.models.phi4mm_utils

Classes:

Functions:

  • adaptive_enc_mask –

    The function is very important for Transformer Transducer Streaming mode

  • calc_length_int –

    Integer-only variant of calc_length for meta-safe shape computation.

  • get_activation –

    Select an activation function by name.

  • get_offset –

    Get an offset. We will use the offset for determining #frames of a

  • unfold_tensor –

    For a given tensor with shape of (N, T, D), if sequence length T is

AbsolutePositionalEncoding

Bases: Module

Absolute Positional encoding module. This module implement Absolute sinusoidal positional encoding from: https://arxiv.org/pdf/1706.03762.pdf

Parameters:

  • d_model

    (int) –

    int Input embedding size.

  • dropout_rate

    (float) –

    float dropout rate

  • max_len

    (int, default: 5000 ) –

    int, optional Maximum input length sequence, Default 5000

Methods:

  • __init__ –

    Construct an PositionalEncoding object.

  • extend_pe –

    Reset the positional encodings.

  • forward –

    Add positional encoding.

__init__(d_model, dropout_rate, max_len=5000)

Construct an PositionalEncoding object.

extend_pe(x)

Reset the positional encodings.

Parameters:

forward(x)

Add positional encoding.

Parameters:

  • x

    (Tensor) –

    Input tensor. shape is (batch, time, ...)

Returns:

  • Tensor –

    Encoded tensor. Its shape is (batch, time, ...)

CausalConv1D

Bases: Conv1d

A causal version of nn.Conv1d where each step would have limited access to locations on its right or left All arguments are the same as nn.Conv1d except padding.

If padding is set None, then paddings are set automatically to make it a causal convolution where each location would not see any steps on its right.

If padding is set as a list (size of 2), then padding[0] would be used as left padding and padding[1] as right padding. It would make it possible to control the number of steps to be accessible on the right and left. This mode is not supported when stride > 1. padding[0]+padding[1] should be equal to (kernel_size - 1).

CausalConv2D

Bases: Conv2d

A causal version of nn.Conv2d where each location in the 2D matrix would have no access to locations on its right or down All arguments are the same as nn.Conv2d except padding which should be set as None

ConvModule

Bases: Module

ConvModule Module for the conformer block. for more details see: https://arxiv.org/pdf/2005.08100v1.pdf

Parameters:

  • input_dim

    (int) –

    int input channel size.

  • ext_pw_out_channel

    (int) –

    int if > 0, ext_pw_out_channel is a dim channel size for the last pointwise conv after swish activation.

  • depthwise_seperable_out_channel

    (int) –

    int if set different to 0, the number of depthwise_seperable_out_channel will be used as a channel_out of the second conv1d layer. otherwise, it equal to 0, the second conv1d layer is skipped.

  • ext_pw_kernel_size

    (int) –

    int kernel size of the conv pointwise of the conformer.

  • kernel_size

    (int) –

    int kernel size.

  • depthwise_multiplier

    (int) –

    int number of input_dim channels duplication. this value will be used to compute the hidden channels of the Conv1D.

  • dropout_rate

    (float) –

    float dropout rate.

  • causal

    (bool, default: False ) –

    bool, optional if set to True, convolution have no access to future frames. default False.

  • batch_norm

    (bool, default: False ) –

    bool, optional if set to True, apply batchnorm before activation. default False

  • chunk_se

    (int, default: 0 ) –

    int, optional 0 for offline SE. 1 for streaming SE, where mean is computed by accumulated history until current chunk_se. 2 for streaming SE, where mean is computed by only the current chunk.

  • chunk_size

    (int | list[int], default: 18 ) –

    int, optional chunk size for cnn. default 18

  • activation

    (str, default: 'relu' ) –

    str, optional activation function used in ConvModule, default: "relu".

  • glu_type

    (str, default: 'sigmoid' ) –

    str, optional activation function used for the glu, default: "sigmoid".

  • bias_in_glu

    (bool, default: True ) –

    bool, optional if set to True, use additive bias in the weight module before GLU.

  • linear_glu_in_convm

    (bool, default: False ) –

    bool, optional if set to True, use GLULinear module, otherwise, used GLUPointWiseConv module. default to False.

  • export

    (bool, default: False ) –

    bool, optional, if set to True, padding is equal to 0. This is for inference, or onnx export. Typically this is set by the export program or the decoder program, and it isn't present in your config file. default False

Methods:

_add_ext_pw_layer()

This function is an extension of init function and dedicated to the convolution module creation of the conformer.

forward(x)

ConvModule Forward.

Parameters:

DepthWiseSeparableConv1d

Bases: Module

DepthWiseSeparableConv1d module used in ConvNet module for the conformer, for more details see: https://arxiv.org/pdf/2005.08100v1.pdf

Parameters:

  • input_dim

    (int) –

    int input channel size.

  • depthwise_seperable_out_channel

    (int) –

    int if set different to 0, the number of depthwise_seperable_out_channel will be used as a channel_out of the second conv1d layer. otherwise, it equals to 0, the second conv1d layer is skipped.

  • kernel_size

    (int) –

    int kernel_size

  • depthwise_multiplier

    (int) –

    int number of input_dim channels duplication. this value will be used to compute the hidden channels of the Conv1D.

  • padding

    (int, default: 0 ) –

    int, optional padding for the conv1d, default: 0.

Methods:

forward(x)

Args: x: input tensor

FeedForward

Bases: Module

FeedForward Module. For more details see Conformer paper: https://arxiv.org/pdf/2005.08100.pdf

Parameters:

  • d_model

    (int) –

    int input size.

  • d_inner

    (int) –

    int output size.

  • dropout_rate

    (float) –

    float, dropout rate.

  • activation

    (str, default: 'sigmoid' ) –

    str, activation function name, one of ["relu", "swish", "sigmoid"], sigmoid activation is only used with "glu_in_fnn=True", default "sigmoid".

  • bias_in_glu

    (bool, default: True ) –

    bool, optional

Methods:

  • forward –

    FeedForward forward function.

forward(x)

FeedForward forward function.

Parameters:

GLU

Bases: Module

Implement Gated Linear Unit (GLU) module.

Methods:

forward(x)

GLU forward Apply Swish function on the first half of input matrices with sigmoid of the second half.

Parameters:

GLULinear

Bases: Module

Linear + GLU module.

Parameters:

  • input_dim

    (int) –

    int input size

  • output_dim

    (int) –

    int output size.

  • glu_type

    (str, default: 'sigmoid' ) –

    activation function name used in glu module. default "sigmoid" (swish function).

  • bias_in_glu

    (bool, default: True ) –

    bool, optional If True, the addtive bias is added. Default False.

Methods:

forward(x)

GLULinear forward.

Parameters:

GLUPointWiseConv

Bases: Module

GLUPointWiseConv module used for conformer architecture, for more details see: https://arxiv.org/pdf/2005.08100v1.pdf

Parameters:

  • input_dim

    (int) –

    int input channel size.

  • output_dim

    (int) –

    int output channel size.

  • kernel_size

    (int) –

    int kernel size

  • glu_type

    (str, default: 'sigmoid' ) –

    str, optional activation function one of ["sigmoid", "relu", "gelu"] default "sigmoid".

  • bias_in_glu

    (bool, default: True ) –

    bool, optional use addtive bias in glu

  • causal

    (bool, default: False ) –

    bool, optional if set to True, padding is set to the half of kernel size, ie, convolution can't see future frames. default False.

Methods:

forward(x)

Args: x: input tensor

MeanVarianceNormLayer

Bases: Module

Mean/variance normalization layer.

Will subtract mean and multiply input by inverted standard deviation. Typically used as a very first layer in a model.

Parameters:

  • input_size

    (int) –

    int layer input size.

Methods:

  • forward –

    MeanVarianceNormLayer Forward.

forward(input_)

MeanVarianceNormLayer Forward.

Parameters:

MultiHeadedAttention

Bases: Module

Multi-Head Attention layer with optional relative position embedding and GLU.

Parameters:

  • n_head

    (int) –

    int the number of heads.

  • n_feat

    (int) –

    int input size features.

  • dropout_rate

    (float) –

    float dropout rate.

  • attention_inner_dim

    (int, default: -1 ) –

    int, optional the attention dimension used in the class, it can be different from the input dimension n_feat. default: -1 (equal to n_feat).

  • use_pt_scaled_dot_product_attention

    (bool, default: True ) –

    bool, optional if set True, use pytorch scaled dot product attention in training. NOTE: this will NOT be used in ONNX decoding due to a lack of support. In that case, we use the original attention implementation, which shows no regression. default: True.

  • n_value

    (int, default: -1 ) –

    int, optional if set to values other than -1, use a different dimension for value. With the default value (i.e. -1), it is backward compatible.

  • group_size

    (int, default: 1 ) –

    int, optional. must divide n_head if group_size > 1: GQA if group_size = 1: MHA if group_size = n_head: MQA

Methods:

  • forward –

    Compute 'Scaled Dot Product Attention'.

forward(query, key, value, pos_k, pos_v, mask, relative_attention_bias=None)

Compute 'Scaled Dot Product Attention'.

Parameters:

  • query

    (Tensor) –

    query tensor (batch, time1, size)

  • key

    (Tensor) –

    key tensor (batch, time2, size)

  • value

    (Tensor) –

    value tensor (batch, time1, size)

  • pos_k

    (Tensor | None) –

    key tensor used for relative positional embedding.

  • pos_v

    (Tensor | None) –

    value tensor used for relative positional embedding.

  • mask

    (Tensor | None) –

    mask tensor (batch, time1, time2)

  • relative_attention_bias

    (Tensor | None, default: None ) –

    bias added to attention logits w.r.t. relative positions (1, n_head, time1, time2)

MultiSequential

Bases: Sequential

Multi-input multi-output torch.nn.Sequential.

Methods:

  • forward –

    Forward method implementation.

forward(*args)

Forward method implementation.

NemoConvSubsampling

Bases: Module

Convlutional subsampling module, taken from NeMo ASR (https://github.com/NVIDIA/NeMo/blob/b367413645d5c72db3c2c96e46e95a 34501479cf/nemo/collections/asr/parts/submodules/subsampling.py)

Striding Subsampling: "Speech-Transformer: A No-Recurrence Sequence-to-Sequence Model for Speech Recognition" by Linhao Dong et al. (https://ieeexplore.ieee.org/document/8462506)

Compared with the EncoderConv2D (input_layer: custom), this is a much simplified approach, and uses no LayerNorm and far fewer Conv2Ds. Moreover, depthwise convolutions are used to reduce FLOPs, but the first layer is kept as a regular convolution so as not to degrade accuracy.

Striding and dw_striding are the same except that the latter uses depthwise convolutions after the first layer, whereas the former does not.

Parameters:

  • subsampling_factor

    (int, default: 4 ) –

    Time reduction factor

  • feat_in

    (int) –

    size of the input features

  • feat_out

    (int) –

    size of the output features

  • subsampling

    (str, default: 'dw_striding' ) –

    The subsampling technique, choose from {"striding", "dw-striding", "striding_conv1d", "dw_striding_conv1d"}

  • conv_channels

    (int, default: 256 ) –

    Number of channels for the convolution layers, default is 256.

  • subsampling_conv_chunking_factor

    (int, default: 1 ) –

    Input chunking factor which can be -1 (no chunking) 1 (auto) or a power of 2. Default is 1

  • activation

    (Module, default: ReLU() ) –

    activation function, default is nn.ReLU()

  • is_causal

    (bool, default: False ) –

    whether to use causal Conv1/2D, where each step will have limited access to locations on its right or left

Methods:

channel_chunked_conv(conv, chunk_size, x)

Performs channel chunked convolution.

conv_split_by_batch(x)

Tries to split input by batch, run conv and concat results.

conv_split_by_channel(x)

For dw convs, tries to split input by time, run conv and concat results

forward(x, mask)

Forward method for NeMo subsampling.

Parameters:

Returns:

  • x ( Tensor ) –

    Resulting tensor from subsampling (B, T // time_reduction_factor, feat_out)

  • pad_mask ( Tensor | None ) –

    tensor of padded hidden state sequences (B, 1, T // time_reduction_factor)

T5RelativeAttentionLogitBias

Bases: Module

This module implements the relative position bias described in Section 2.1 of the T5 paper: https://arxiv.org/pdf/1910.10683.pdf

The Huggingface implementation is used as a reference https://github.com/huggingface/transformers/blob/v4.30.0/src/ transformers/models/t5/modeling_t5.py#L435

Modifies attention as Q*K^T + B, where B is a learned scalar bias based on relative position of the query and key. It is HxNxN, where H is the number of heads, N is the sequence length.

I've made these modifications to the original T5 bias: - Skipping of the bucketing step. Original T5 bias converted rel position distances into logarithmically increasing buckets. This is supposed to help with length generalization. - I just directly use rel position index as bias values, as we don't need length generalization (40s max is good enough for ASR encoder), and it keeps ONNX export simple. - I've also extended it so that biases can be asymmetric, the default implementation treats L->R and R->L the same. Asymmetric was found to yield better results in my experiments.

Parameters:

  • num_heads

    (int) –

    int Number of attention heads

  • num_buckets

    (int, default: -1 ) –

    int Number of buckets to use for relative attention bias. This is the size of the learnable bias parameter. Bucketing is not yet supported, so this defaults to -1 which means no bucketing is used (max_distance determines size of bias param).

  • max_distance

    (int, default: 1000 ) –

    int Maximum distance to use for relative attention bias. With num_buckets=-1, this directly controls the max size of the bias parameter. When num_buckets > 0 is supported, this will control the maximum distance for logarithmic bucketing after which all positions are in the same bucket.

  • symmetric

    (bool, default: False ) –

    bool Whether to use symmetric or asymmetric biases. symmetric=False uses 2x number of bias params to distinguish L->R from R->L. This was found to be better for the encoder.

_pre_hook(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)

Perform pre-hook in load_state_dict for backward compatibility.

Note

We saved self.pe until v.0.5.2 but we have omitted it later. Therefore, we remove the item "pe" from state_dict for backward compatibility.

adaptive_enc_mask(x_len, chunk_start_idx, left_window=0, right_window=0)

The function is very important for Transformer Transducer Streaming mode Args: x_len: sequence length chunk_start_idx: first idx of each chunk, such as [0,18,36,48]. It also supports adaptive chunk size [0,10,15,45] left_window: how many left chunks can be seen right_window: how many right chunks can be seen. It is used for chunk overlap model.

Returns:

  • mask ( Tensor ) –

    a mask tensor for streaming model

  • Tensor –

    Torch 1.0.1

  • Tensor –

    tensor([[1., 1., 0., 0.], [0., 1., 1., 0.], [0., 0., 1., 1.]])

  • Tensor –

    Torch 1.4.1

  • Tensor –

    tensor([[True., True., False., False.], [False., True., True., False.], [False., False., True., True.]])

calc_length_int(lengths, all_paddings, kernel_size, stride, ceil_mode, repeat_num=1)

Integer-only variant of calc_length for meta-safe shape computation.

Computes the output length of a 1D convolution / pooling stack using the same formula as calc_length, but operates purely on Python numbers so it can be safely used during meta tensor initialization.

get_activation(name='relu')

Select an activation function by name.

Parameters:

  • name

    (str, default: 'relu' ) –

    str activation function name, one of ["relu", "gelu", "swish", "sigmoid"], default "relu".

get_offset(input_layer, time_reduction)

Get an offset. We will use the offset for determining #frames of a subsampled feature.

Parameters:

  • input_layer

    (str) –

    Type of an input layer

  • time_reduction

    (int) –

    time reduction factor for downsampling a feature

Returns: int: offset

unfold_tensor(xs_pad, max_seq_len)

For a given tensor with shape of (N, T, D), if sequence length T is longer than max_seq_len, this function unfold it to a (NT', max_seq_len, D) where T' is T // max_seq_len.

Parameters:

  • xs_pad

    (Tensor) –

    input tensor with shape (N, T, D)

  • max_seq_len

    (int) –

    maximum sequence length