core.models.audio.nemo_transformer_encoder#
Module Contents#
Classes#
Configuration for a GPT-style transformer (vendored NeMo helper). |
|
Configuration for the audio TransformerEncoder and its blocks. |
|
Two-layer position-wise feed-forward network with a 4x hidden expansion and GELU. |
|
Tanh-approximation GELU activation (vendored NeMo helper). |
|
Layer normalization with learnable scale and shift (upcasts to fp32 internally). |
|
Multi-head attention using the flash-attention |
|
Multi-head attention using Transformer Engine’s DotProductAttention in THD layout. |
|
Multi-head attention using PyTorch |
|
Multi-head attention with an explicit softmax and optional KV cache. |
|
Single transformer encoder block: attention, feed-forward, and residual norms. |
|
Convolutional subsampling that reduces the temporal dimension by 4x. |
|
Depthwise separable conv subsampling: reduces params by replacing standard Conv1d with depthwise (groups=channels) + pointwise (1x1) convolutions for the strided layers. |
|
Stacking subsampling which simply stacks consecutive frames to reduce the sampling rate |
|
Audio transformer encoder: subsampling front-end followed by a transformer stack. |
Functions#
Lazy import shim for flash_attn so this module imports without the package. |
|
Lazy import of transformer_engine.pytorch.DotProductAttention. |
|
Resolve ‘auto’ to ‘te’ if transformer_engine is importable, else ‘sdpa’. |
|
Return a bool mask where True means the key is not visible to the query. |
|
Precompute the rotary position embedding cosine and sine tables. |
|
Apply rotary position embeddings to |
Data#
API#
- core.models.audio.nemo_transformer_encoder.logger#
‘getLogger(…)’
- core.models.audio.nemo_transformer_encoder._flash_attn_func(*args, **kwargs)#
Lazy import shim for flash_attn so this module imports without the package.
- core.models.audio.nemo_transformer_encoder._get_te_dot_product_attention()#
Lazy import of transformer_engine.pytorch.DotProductAttention.
- core.models.audio.nemo_transformer_encoder._resolve_attn_impl(impl: str) str#
Resolve ‘auto’ to ‘te’ if transformer_engine is importable, else ‘sdpa’.
- class core.models.audio.nemo_transformer_encoder.GPTConfig#
Configuration for a GPT-style transformer (vendored NeMo helper).
- vocab_size: int#
50257
- context_length: int#
1024
- emb_dim: int#
768
- n_heads: int#
12
- n_layers: int#
12
- drop_rate: int#
0.1
- qkv_bias: bool#
False
- theta_base: int#
10000
- class core.models.audio.nemo_transformer_encoder.TransformerEncoderConfig#
Configuration for the audio TransformerEncoder and its blocks.
- n_mels: int#
80
- d_model: int#
512
- n_heads: int#
12
- n_layers: int#
12
- drop_rate: float#
0.1
- qkv_bias: bool#
False
- causal_mask: bool#
False
- theta_base: int#
10000
- context_length: int#
4096
- qk_norm: bool#
False
- attn_impl: str#
‘auto’
- recompute_layers: bool#
False
- left_context: Optional[int]#
None
- core.models.audio.nemo_transformer_encoder._normalize_left_context(
- left_context: Optional[int],
- core.models.audio.nemo_transformer_encoder._causal_window_size(
- causal_mask: bool,
- left_context: Optional[int],
- core.models.audio.nemo_transformer_encoder._causal_disallow_mask(
- query_len: int,
- key_len: int,
- left_context: Optional[int],
- device,
Return a bool mask where True means the key is not visible to the query.
- class core.models.audio.nemo_transformer_encoder.FeedForward(dim)#
Bases:
torch.nn.ModuleTwo-layer position-wise feed-forward network with a 4x hidden expansion and GELU.
Initialization
- forward(x)#
Apply the feed-forward network to
x.
- class core.models.audio.nemo_transformer_encoder.GELU#
Bases:
torch.nn.ModuleTanh-approximation GELU activation (vendored NeMo helper).
Initialization
- forward(x)#
Apply the tanh-approximation GELU to
x.
- class core.models.audio.nemo_transformer_encoder.LayerNorm(dim, eps=1e-05)#
Bases:
torch.nn.ModuleLayer normalization with learnable scale and shift (upcasts to fp32 internally).
Initialization
- forward(x)#
Normalize
xover its last dimension and apply scale and shift.
- core.models.audio.nemo_transformer_encoder.compute_rope_params(
- head_dim,
- theta_base=10000,
- context_length=4096,
- dtype=torch.float32,
Precompute the rotary position embedding cosine and sine tables.
- core.models.audio.nemo_transformer_encoder.apply_rope(x, cos, sin)#
Apply rotary position embeddings to
xusing precomputed cos and sin tables.
- class core.models.audio.nemo_transformer_encoder.MultiHeadAttentionWithFA(
- dim_in,
- dim_out,
- dropout=0.0,
- qkv_bias=False,
- context_length=1024,
- num_heads=8,
- causal_mask=False,
- left_context=None,
Bases:
torch.nn.ModuleMulti-head attention using the flash-attention
flash_attn_funcbackend.Initialization
- forward(x)#
Run flash-attention over
xand project the result.
- class core.models.audio.nemo_transformer_encoder.MultiHeadAttentionWithTE(
- dim_in,
- dim_out,
- dropout=0.0,
- qkv_bias=False,
- num_heads=8,
- causal_mask=False,
- left_context=None,
- qk_norm=False,
- **_,
Bases:
torch.nn.ModuleMulti-head attention using Transformer Engine’s DotProductAttention in THD layout.
Always runs attention in TE’s
thd(packed) format so flash-attention handles variable-length sequences efficiently. Two callsite modes:Unpacked: forward(x, lengths=…) where x is (B, T, C). The module packs valid tokens into THD using
lengths, runs TE attention, then scatters results back into a (B, T, C) tensor (padding positions remain zero).Packed: forward(x, packed_seq_params=…) where x is a flat (Ttot, C) (or (Ttot, 1, C)) tensor and the caller supplies cu_seqlens / max_seqlens. The module returns (Ttot, C) in the same packed layout.
Linear projection parameter names (
w_query,w_key,w_value,out_proj) match the SDPA/FA variants so .nemo checkpoints load into either backend.Initialization
- forward(x, lengths=None, packed_seq_params=None, **_)#
Run TE attention in THD layout, packing/unpacking as needed, and project.
- class core.models.audio.nemo_transformer_encoder.MultiHeadAttentionWithSDPA(
- dim_in,
- dim_out,
- dropout=0.0,
- qkv_bias=False,
- context_length=1024,
- num_heads=8,
- causal_mask=False,
- left_context=None,
- qk_norm=False,
Bases:
torch.nn.ModuleMulti-head attention using PyTorch
scaled_dot_product_attention.Initialization
- forward(x, attn_mask=None, use_cache=False)#
Run scaled-dot-product attention over
xand project the result.
- class core.models.audio.nemo_transformer_encoder.MultiHeadAttention(
- dim_in,
- dim_out,
- dropout=0.0,
- qkv_bias=False,
- context_length=1024,
- num_heads=8,
- causal_mask=False,
- left_context=None,
Bases:
torch.nn.ModuleMulti-head attention with an explicit softmax and optional KV cache.
Initialization
- forward(x, use_cache=False)#
Run masked multi-head attention over
x, optionally using the KV cache.
- reset_cache()#
Clear the cached keys and values.
- class core.models.audio.nemo_transformer_encoder.TransformerBlock( )#
Bases:
torch.nn.ModuleSingle transformer encoder block: attention, feed-forward, and residual norms.
Initialization
- forward(
- x,
- attn_mask=None,
- lengths=None,
- packed_seq_params=None,
- use_cache=False,
Apply attention and feed-forward sublayers with residual connections.
- reset_cache()#
Reset KV cache on the attention module if it supports it (e.g. MultiHeadAttention).
- class core.models.audio.nemo_transformer_encoder.ConvSubsampling(n_mels: int = 80, d_model: int = 512)#
Bases:
torch.nn.ModuleConvolutional subsampling that reduces the temporal dimension by 4x.
Initialization
- forward(x, length)#
Subsample
xby 4x and return the features and updated lengths.
- class core.models.audio.nemo_transformer_encoder.DepthwiseConvSubsampling(n_mels: int = 80, d_model: int = 512)#
Bases:
torch.nn.ModuleDepthwise separable conv subsampling: reduces params by replacing standard Conv1d with depthwise (groups=channels) + pointwise (1x1) convolutions for the strided layers.
Initialization
- forward(x, length)#
Subsample
xby 4x via depthwise separable convs and update lengths.
- class core.models.audio.nemo_transformer_encoder.NGPTStackingSubsampling(
- subsampling_factor: int,
- feat_in: int,
- feat_out: int,
- use_bias: bool = False,
Bases:
torch.nn.ModuleStacking subsampling which simply stacks consecutive frames to reduce the sampling rate
- Parameters:
subsampling_factor (int) – The subsampling factor
feat_in (int) – size of the input features
feat_out (int) – size of the output features
Initialization
- class core.models.audio.nemo_transformer_encoder.TransformerEncoder(
- n_mels: int = 80,
- d_model: int = 512,
- n_heads: int = 8,
- n_layers: int = 17,
- drop_rate: float = 0.1,
- qkv_bias: bool = False,
- causal_mask: bool = False,
- pre_encode: str = 'conv',
- nan_debug: bool = True,
- qk_norm: bool = False,
- subsampling_factor: int = 4,
- attn_impl: str = 'auto',
- recompute_layers: bool = False,
- left_context: Optional[int] = None,
Bases:
torch.nn.ModuleAudio transformer encoder: subsampling front-end followed by a transformer stack.
Initialization
- forward(
- audio_signal,
- length,
- packed_seq_params=None,
- return_packed: bool = False,
- Parameters:
audio_signal (torch.Tensor) – (B, C, T) audio features.
length (torch.Tensor) – (B,) input frame counts.
packed_seq_params – optional caller-supplied PackedSeqParams. Unused by production callers today; reserved for future dataloader-side packing. When None and attn_impl==”te”, the encoder builds its own PackedSeqParams from
lengthand runs the block stack on packed features for efficiency.
- Returns:
(B, D_model, T’) with zero-padded positions when
return_packedis false, otherwise(Ttot, D_model)with only valid post-subsampling positions. length (torch.Tensor): (B,) post-subsampling lengths.- Return type:
x (torch.Tensor)
- _check_nan(x, name)#
- reset_cache()#
Reset KV cache on every block (no-op for attention impls without cache).
- freeze()#
Disable gradients for all encoder parameters.
- unfreeze(partial=False)#
Enable gradients for all encoder parameters.