MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / DecoderOnlyTransformer

Class DecoderOnlyTransformer

monai/networks/nets/transformer.py:43–157  ·  view source on GitHub ↗

Decoder-only (Autoregressive) Transformer model. Args: num_tokens: Number of tokens in the vocabulary. max_seq_len: Maximum sequence length. attn_layers_dim: Dimensionality of the attention layers. attn_layers_depth: Number of attention layers. attn_layer

Source from the content-addressed store, hash-verified

41
42
43class DecoderOnlyTransformer(nn.Module):
44 """Decoder-only (Autoregressive) Transformer model.
45
46 Args:
47 num_tokens: Number of tokens in the vocabulary.
48 max_seq_len: Maximum sequence length.
49 attn_layers_dim: Dimensionality of the attention layers.
50 attn_layers_depth: Number of attention layers.
51 attn_layers_heads: Number of attention heads.
52 with_cross_attention: Whether to use cross attention for conditioning.
53 embedding_dropout_rate: Dropout rate for the embedding.
54 include_fc: whether to include the final linear layer. Default to True.
55 use_combined_linear: whether to use a single linear layer for qkv projection, default to True.
56 use_flash_attention: if True, use Pytorch's inbuilt flash attention for a memory efficient attention mechanism
57 (see https://pytorch.org/docs/2.2/generated/torch.nn.functional.scaled_dot_product_attention.html).
58 """
59
60 def __init__(
61 self,
62 num_tokens: int,
63 max_seq_len: int,
64 attn_layers_dim: int,
65 attn_layers_depth: int,
66 attn_layers_heads: int,
67 with_cross_attention: bool = False,
68 embedding_dropout_rate: float = 0.0,
69 include_fc: bool = True,
70 use_combined_linear: bool = False,
71 use_flash_attention: bool = False,
72 ) -> None:
73 super().__init__()
74 self.num_tokens = num_tokens
75 self.max_seq_len = max_seq_len
76 self.attn_layers_dim = attn_layers_dim
77 self.attn_layers_depth = attn_layers_depth
78 self.attn_layers_heads = attn_layers_heads
79 self.with_cross_attention = with_cross_attention
80
81 self.token_embeddings = nn.Embedding(num_tokens, attn_layers_dim)
82 self.position_embeddings = AbsolutePositionalEmbedding(max_seq_len=max_seq_len, embedding_dim=attn_layers_dim)
83 self.embedding_dropout = nn.Dropout(embedding_dropout_rate)
84
85 self.blocks = nn.ModuleList(
86 [
87 TransformerBlock(
88 hidden_size=attn_layers_dim,
89 mlp_dim=attn_layers_dim * 4,
90 num_heads=attn_layers_heads,
91 dropout_rate=0.0,
92 qkv_bias=False,
93 causal=True,
94 sequence_length=max_seq_len,
95 with_cross_attention=with_cross_attention,
96 include_fc=include_fc,
97 use_combined_linear=use_combined_linear,
98 use_flash_attention=use_flash_attention,
99 )
100 for _ in range(attn_layers_depth)

Calls

no outgoing calls

Used in the wild real call sites across dependent graphs

searching dependent graphs…