mamba3-ssm 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aiyoniganmaaiya
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OTHER LIABILITY,
19
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
20
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.4
2
+ Name: mamba3-ssm
3
+ Version: 0.1.0
4
+ Summary: Mamba-3: Improved Sequence Modeling using State Space Principles
5
+ Home-page: https://github.com/Aiyoniganmaaiya/mamba3-ssm
6
+ Author: Aiyoniganmaaiya
7
+ Author-email: Aiyoniganmaaiya <gerintacc004@gmail.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/Aiyoniganmaaiya/mamba3-ssm
10
+ Project-URL: Repository, https://github.com/Aiyoniganmaaiya/mamba3-ssm
11
+ Keywords: mamba,ssm,state-space-model,transformer,pytorch
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: torch>=2.0
21
+ Requires-Dist: einops>=0.7
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest; extra == "dev"
24
+ Dynamic: author
25
+ Dynamic: home-page
26
+ Dynamic: license-file
27
+ Dynamic: requires-python
28
+
29
+ # Mamba-3: Improved Sequence Modeling using State Space Principles
30
+
31
+ A clean, readable, from-scratch PyTorch implementation of **Mamba-3** — a selective state space model that addresses three core limitations of Mamba-2. No Triton/CUDA kernels; designed for understanding and reproducing the algorithm.
32
+
33
+ **Paper:** [Mamba-3: Improved Sequence Modeling using State Space Principles](https://arxiv.org/abs/2603.15569)
34
+ **Authors:** Aakash Lahoti, Kevin Y. Li, Berlin Chen, Caitlin Wang, Aviv Bick, J. Zico Kolter, Tri Dao, Albert Gu
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install mamba3-ssm
40
+ ```
41
+
42
+ Or install from source:
43
+
44
+ ```bash
45
+ pip install git+https://github.com/Aiyoniganmaaiya/mamba3-ssm.git
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ```python
51
+ import torch
52
+ from mamba3_ssm import Mamba3, MambaLMHeadModel, MambaConfig
53
+
54
+ # ── SISO mode (standard) ──────────────────────────────
55
+ model = Mamba3(
56
+ d_model=256,
57
+ d_state=64,
58
+ expand=2,
59
+ headdim=32,
60
+ is_mimo=False,
61
+ )
62
+ x = torch.randn(2, 128, 256)
63
+ y = model(x) # (2, 128, 256)
64
+
65
+ # ── MIMO mode (better decode efficiency) ──────────────
66
+ model_mimo = Mamba3(
67
+ d_model=256,
68
+ d_state=64,
69
+ expand=2,
70
+ headdim=32,
71
+ is_mimo=True,
72
+ mimo_rank=4,
73
+ )
74
+ y = model_mimo(x) # same I/O shape
75
+
76
+ # ── Autoregressive decode (one token at a time) ───────
77
+ angle_state, ssm_state, bx_prev = model.allocate_inference_cache(batch_size=2)
78
+ u = torch.randn(2, 256)
79
+ out, angle_state, ssm_state, bx_prev = model.step(
80
+ u, angle_state, ssm_state, bx_prev
81
+ )
82
+
83
+ # ── Full language model ───────────────────────────────
84
+ cfg = MambaConfig(
85
+ d_model=2048,
86
+ n_layer=24,
87
+ vocab_size=50277,
88
+ ssm_cfg={"is_mimo": True, "mimo_rank": 4},
89
+ )
90
+ lm = MambaLMHeadModel(cfg)
91
+ logits = lm(torch.randint(0, 50277, (1, 512))) # (1, 512, vocab_size)
92
+ ```
93
+
94
+ ## Core Ideas
95
+
96
+ ### 1. Exponential-Trapezoidal Discretization
97
+
98
+ Mamba-2 used Zero-Order Hold (exponential-Euler), a first-order approximation. Mamba-3 adopts the **trapezoidal rule**, averaging the `B*x` contribution at times `t-1` and `t`:
99
+
100
+ ```
101
+ h_t = exp(A·dt_t) · h_{t-1} + dt_t · σ(trap_t) · (B_t·x_t + B_{t-1}·x_{t-1}) / 2
102
+ ```
103
+
104
+ `trap` is a learned sigmoid gate blending between Euler (`trap≈0`) and full trapezoidal (`trap≈1`).
105
+
106
+ ### 2. Complex-Valued (Rotary) State Space
107
+
108
+ Real-valued SSM hidden states cannot easily represent oscillatory patterns. Mamba-3 applies **RoPE** to B and C projections, giving the state an effective complex-valued structure that tracks phase-dependent dependencies.
109
+
110
+ ### 3. Multi-Input Multi-Output (MIMO) Formulation
111
+
112
+ Mamba-2 is SISO with state `(H, P, D)` — during decode the GPU is memory-bandwidth bound. **MIMO** reuses a shared `(H, D)` state for `R` rank streams, multiplying FLOPs/byte by `R`:
113
+
114
+ | | SISO | MIMO |
115
+ |---|---|---|
116
+ | State shape | `(H, P, D)` | `(H, D)` |
117
+ | Update | outer product `x ⊗ B` | sum of R rank-1 terms |
118
+
119
+ ## Project Structure
120
+
121
+ ```
122
+ mamba3_ssm/
123
+ ├── __init__.py # Public API
124
+ ├── config.py # MambaConfig / SSMConfig dataclasses
125
+ ├── ops.py # RMSNorm, RoPE, SSM scan (SISO + MIMO)
126
+ ├── layer.py # Mamba3 module (forward + step + inference cache)
127
+ ├── block.py # MambaBlock, MLPBlock, MambaLMHeadModel
128
+ ├── tests.py # 10 sanity checks
129
+ └── utils.py # Parameter counting
130
+ ```
131
+
132
+ ## Key Parameters
133
+
134
+ | Parameter | Default | Description |
135
+ |-----------|---------|-------------|
136
+ | `d_model` | — | Token embedding dimension |
137
+ | `d_state` | 128 | SSM state size per head (D) |
138
+ | `expand` | 2 | Inner dim multiplier; `d_inner = expand * d_model` |
139
+ | `headdim` | 64 | Features per SSM head (P) |
140
+ | `is_mimo` | False | Enable MIMO formulation |
141
+ | `mimo_rank` | 4 | Number of parallel MIMO streams (R) |
142
+ | `rope_fraction` | 0.5 | Fraction of state dims that rotate |
143
+
144
+ ## Testing
145
+
146
+ ```bash
147
+ python -m mamba3_ssm.tests
148
+ ```
149
+
150
+ 10/10 sanity checks pass, including shape tests, numerical consistency (step-by-step decode matches forward), gradient flow, and edge cases.
151
+
152
+ ## Dependencies
153
+
154
+ - `torch>=2.0`
155
+ - `einops>=0.7`
156
+
157
+ ## License
158
+
159
+ MIT
160
+
161
+ ## References
162
+
163
+ - Lahoti et al., *Mamba-3: Improved Sequence Modeling using State Space Principles*, 2026. [arXiv:2603.15569](https://arxiv.org/abs/2603.15569)
164
+ - Official implementation: [state-spaces/mamba](https://github.com/state-spaces/mamba)
@@ -0,0 +1,136 @@
1
+ # Mamba-3: Improved Sequence Modeling using State Space Principles
2
+
3
+ A clean, readable, from-scratch PyTorch implementation of **Mamba-3** — a selective state space model that addresses three core limitations of Mamba-2. No Triton/CUDA kernels; designed for understanding and reproducing the algorithm.
4
+
5
+ **Paper:** [Mamba-3: Improved Sequence Modeling using State Space Principles](https://arxiv.org/abs/2603.15569)
6
+ **Authors:** Aakash Lahoti, Kevin Y. Li, Berlin Chen, Caitlin Wang, Aviv Bick, J. Zico Kolter, Tri Dao, Albert Gu
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ pip install mamba3-ssm
12
+ ```
13
+
14
+ Or install from source:
15
+
16
+ ```bash
17
+ pip install git+https://github.com/Aiyoniganmaaiya/mamba3-ssm.git
18
+ ```
19
+
20
+ ## Quick Start
21
+
22
+ ```python
23
+ import torch
24
+ from mamba3_ssm import Mamba3, MambaLMHeadModel, MambaConfig
25
+
26
+ # ── SISO mode (standard) ──────────────────────────────
27
+ model = Mamba3(
28
+ d_model=256,
29
+ d_state=64,
30
+ expand=2,
31
+ headdim=32,
32
+ is_mimo=False,
33
+ )
34
+ x = torch.randn(2, 128, 256)
35
+ y = model(x) # (2, 128, 256)
36
+
37
+ # ── MIMO mode (better decode efficiency) ──────────────
38
+ model_mimo = Mamba3(
39
+ d_model=256,
40
+ d_state=64,
41
+ expand=2,
42
+ headdim=32,
43
+ is_mimo=True,
44
+ mimo_rank=4,
45
+ )
46
+ y = model_mimo(x) # same I/O shape
47
+
48
+ # ── Autoregressive decode (one token at a time) ───────
49
+ angle_state, ssm_state, bx_prev = model.allocate_inference_cache(batch_size=2)
50
+ u = torch.randn(2, 256)
51
+ out, angle_state, ssm_state, bx_prev = model.step(
52
+ u, angle_state, ssm_state, bx_prev
53
+ )
54
+
55
+ # ── Full language model ───────────────────────────────
56
+ cfg = MambaConfig(
57
+ d_model=2048,
58
+ n_layer=24,
59
+ vocab_size=50277,
60
+ ssm_cfg={"is_mimo": True, "mimo_rank": 4},
61
+ )
62
+ lm = MambaLMHeadModel(cfg)
63
+ logits = lm(torch.randint(0, 50277, (1, 512))) # (1, 512, vocab_size)
64
+ ```
65
+
66
+ ## Core Ideas
67
+
68
+ ### 1. Exponential-Trapezoidal Discretization
69
+
70
+ Mamba-2 used Zero-Order Hold (exponential-Euler), a first-order approximation. Mamba-3 adopts the **trapezoidal rule**, averaging the `B*x` contribution at times `t-1` and `t`:
71
+
72
+ ```
73
+ h_t = exp(A·dt_t) · h_{t-1} + dt_t · σ(trap_t) · (B_t·x_t + B_{t-1}·x_{t-1}) / 2
74
+ ```
75
+
76
+ `trap` is a learned sigmoid gate blending between Euler (`trap≈0`) and full trapezoidal (`trap≈1`).
77
+
78
+ ### 2. Complex-Valued (Rotary) State Space
79
+
80
+ Real-valued SSM hidden states cannot easily represent oscillatory patterns. Mamba-3 applies **RoPE** to B and C projections, giving the state an effective complex-valued structure that tracks phase-dependent dependencies.
81
+
82
+ ### 3. Multi-Input Multi-Output (MIMO) Formulation
83
+
84
+ Mamba-2 is SISO with state `(H, P, D)` — during decode the GPU is memory-bandwidth bound. **MIMO** reuses a shared `(H, D)` state for `R` rank streams, multiplying FLOPs/byte by `R`:
85
+
86
+ | | SISO | MIMO |
87
+ |---|---|---|
88
+ | State shape | `(H, P, D)` | `(H, D)` |
89
+ | Update | outer product `x ⊗ B` | sum of R rank-1 terms |
90
+
91
+ ## Project Structure
92
+
93
+ ```
94
+ mamba3_ssm/
95
+ ├── __init__.py # Public API
96
+ ├── config.py # MambaConfig / SSMConfig dataclasses
97
+ ├── ops.py # RMSNorm, RoPE, SSM scan (SISO + MIMO)
98
+ ├── layer.py # Mamba3 module (forward + step + inference cache)
99
+ ├── block.py # MambaBlock, MLPBlock, MambaLMHeadModel
100
+ ├── tests.py # 10 sanity checks
101
+ └── utils.py # Parameter counting
102
+ ```
103
+
104
+ ## Key Parameters
105
+
106
+ | Parameter | Default | Description |
107
+ |-----------|---------|-------------|
108
+ | `d_model` | — | Token embedding dimension |
109
+ | `d_state` | 128 | SSM state size per head (D) |
110
+ | `expand` | 2 | Inner dim multiplier; `d_inner = expand * d_model` |
111
+ | `headdim` | 64 | Features per SSM head (P) |
112
+ | `is_mimo` | False | Enable MIMO formulation |
113
+ | `mimo_rank` | 4 | Number of parallel MIMO streams (R) |
114
+ | `rope_fraction` | 0.5 | Fraction of state dims that rotate |
115
+
116
+ ## Testing
117
+
118
+ ```bash
119
+ python -m mamba3_ssm.tests
120
+ ```
121
+
122
+ 10/10 sanity checks pass, including shape tests, numerical consistency (step-by-step decode matches forward), gradient flow, and edge cases.
123
+
124
+ ## Dependencies
125
+
126
+ - `torch>=2.0`
127
+ - `einops>=0.7`
128
+
129
+ ## License
130
+
131
+ MIT
132
+
133
+ ## References
134
+
135
+ - Lahoti et al., *Mamba-3: Improved Sequence Modeling using State Space Principles*, 2026. [arXiv:2603.15569](https://arxiv.org/abs/2603.15569)
136
+ - Official implementation: [state-spaces/mamba](https://github.com/state-spaces/mamba)
@@ -0,0 +1,23 @@
1
+ """
2
+ Mambo-3: Improved Sequence Modeling using State Space Principles
3
+
4
+ Clean PyTorch implementation of the Mamba-3 SSM architecture.
5
+ Paper: https://arxiv.org/abs/2603.15569
6
+ """
7
+
8
+ from .config import MambaConfig, SSMConfig
9
+ from .layer import Mamba3
10
+ from .block import MambaLMHeadModel, MambaBlock
11
+ from .ops import RMSNorm, apply_rope, ssm_scan_siso, ssm_scan_mimo
12
+
13
+ __all__ = [
14
+ "MambaConfig",
15
+ "SSMConfig",
16
+ "Mamba3",
17
+ "MambaLMHeadModel",
18
+ "MambaBlock",
19
+ "RMSNorm",
20
+ "apply_rope",
21
+ "ssm_scan_siso",
22
+ "ssm_scan_mimo",
23
+ ]
@@ -0,0 +1,101 @@
1
+ """
2
+ Building blocks for stacking Mamba-3 layers into a full model:
3
+ - MambaBlock: RMSNorm → Mamba3 → residual add
4
+ - MLPBlock: SwiGLU feed-forward (optional)
5
+ - Embed / LMHead: Token embedding and language-model head
6
+ """
7
+
8
+ from typing import Optional
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from dataclasses import dataclass, field
14
+
15
+ from .ops import RMSNorm
16
+ from .layer import Mamba3
17
+ from .config import MambaConfig
18
+
19
+
20
+ class MambaBlock(nn.Module):
21
+ """Single Mamba-3 residual block: Norm → Mixer → residual."""
22
+
23
+ def __init__(self, d_model: int, ssm_cfg: dict, device=None, dtype=None):
24
+ super().__init__()
25
+ self.norm = RMSNorm(d_model)
26
+ self.mixer = Mamba3(d_model=d_model, **ssm_cfg, device=device, dtype=dtype)
27
+
28
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
29
+ return x + self.mixer(self.norm(x))
30
+
31
+
32
+ class MLPBlock(nn.Module):
33
+ """SwiGLU-style feed-forward layer. Used when d_intermediate > 0."""
34
+
35
+ def __init__(self, d_model: int, d_intermediate: int, device=None, dtype=None):
36
+ super().__init__()
37
+ factory = {"device": device, "dtype": dtype}
38
+ self.fc1 = nn.Linear(d_model, 2 * d_intermediate, bias=False, **factory)
39
+ self.fc2 = nn.Linear(d_intermediate, d_model, bias=False, **factory)
40
+
41
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
42
+ gate, val = self.fc1(x).chunk(2, dim=-1)
43
+ return self.fc2(F.silu(gate) * val)
44
+
45
+
46
+ class MambaLMHeadModel(nn.Module):
47
+ """Stacked Mamba-3 language model.
48
+
49
+ Architecture:
50
+ Embedding → n_layer × (MambaBlock [+ MLPBlock]) → RMSNorm → LMHead
51
+
52
+ The LM head weight can be tied to the embedding weight.
53
+ Vocab size is padded up to the nearest multiple of pad_vocab_size_multiple.
54
+ """
55
+
56
+ def __init__(self, config: MambaConfig, device=None, dtype=None):
57
+ factory = {"device": device, "dtype": dtype}
58
+ super().__init__()
59
+ self.config = config
60
+
61
+ # Pad vocab size
62
+ vocab_size = config.vocab_size
63
+ r = vocab_size % config.pad_vocab_size_multiple
64
+ if r != 0:
65
+ vocab_size += config.pad_vocab_size_multiple - r
66
+ self.vocab_size = vocab_size
67
+
68
+ self.embedding = nn.Embedding(vocab_size, config.d_model, **factory)
69
+
70
+ self.layers = nn.ModuleList([
71
+ MambaBlock(config.d_model, config.ssm_cfg, **factory)
72
+ for _ in range(config.n_layer)
73
+ ])
74
+
75
+ if config.d_intermediate > 0:
76
+ self.mlp_norms = nn.ModuleList(
77
+ [RMSNorm(config.d_model) for _ in range(config.n_layer)]
78
+ )
79
+ self.mlp_layers = nn.ModuleList([
80
+ MLPBlock(config.d_model, config.d_intermediate, **factory)
81
+ for _ in range(config.n_layer)
82
+ ])
83
+ else:
84
+ self.mlp_norms = None
85
+ self.mlp_layers = None
86
+
87
+ self.norm_f = RMSNorm(config.d_model)
88
+ # LM head: projects from vocab_size to d_model (tied with embedding)
89
+ self.lm_head = nn.Linear(vocab_size, config.d_model, bias=False, **factory)
90
+ if config.tie_embeddings:
91
+ self.lm_head.weight = self.embedding.weight
92
+
93
+ def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
94
+ """Args: input_ids (batch, seq_len) → logits (batch, seq_len, vocab_size)"""
95
+ x = self.embedding(input_ids)
96
+ for i, block in enumerate(self.layers):
97
+ x = block(x)
98
+ if self.mlp_layers is not None:
99
+ x = x + self.mlp_layers[i](self.mlp_norms[i](x))
100
+ x = self.norm_f(x)
101
+ return self.lm_head(x)
@@ -0,0 +1,61 @@
1
+ """
2
+ Configuration dataclasses for Mamba-3 models.
3
+
4
+ Paper reference: arXiv.2603.15569
5
+ """
6
+
7
+ from dataclasses import dataclass, field
8
+ from typing import Dict, List, Optional, Any
9
+
10
+
11
+ @dataclass
12
+ class SSMConfig:
13
+ """Configuration for the SSM core inside Mamba-3."""
14
+
15
+ # State dimensions
16
+ d_state: int = 128 # D: SSM state size per head
17
+ expand: int = 2 # Inner dimension multiplier; d_inner = expand * d_model
18
+ headdim: int = 64 # P: per-head feature dimension; nheads = d_inner / headdim
19
+ ngroups: int = 1 # G: number of groups for B/C projection sharing
20
+
21
+ # RoPE
22
+ rope_fraction: float = 0.5 # Fraction of state dims that rotate (0.5 or 1.0)
23
+
24
+ # Time step bounds
25
+ dt_min: float = 0.001
26
+ dt_max: float = 0.1
27
+ dt_init_floor: float = 1e-4
28
+ A_floor: float = 1e-4
29
+
30
+ # MIMO
31
+ is_mimo: bool = False
32
+ mimo_rank: int = 4 # R: number of MIMO streams
33
+
34
+ def to_dict(self) -> Dict[str, Any]:
35
+ return {
36
+ k: v for k, v in self.__dict__.items()
37
+ }
38
+
39
+
40
+ @dataclass
41
+ class MambaConfig:
42
+ """Full model configuration for Mamba-3 language models."""
43
+
44
+ d_model: int = 2560
45
+ d_intermediate: int = 0 # >0 adds an MLP sub-layer after each SSM block
46
+ n_layer: int = 64
47
+ vocab_size: int = 50277
48
+
49
+ # SSM config (passed to each Mamba3 layer)
50
+ ssm_cfg: Dict[str, Any] = field(default_factory=dict)
51
+
52
+ # Norm / residual options
53
+ rms_norm: bool = True
54
+ residual_in_fp32: bool = True
55
+ fused_add_norm: bool = True
56
+ pad_vocab_size_multiple: int = 8
57
+ tie_embeddings: bool = True
58
+
59
+ # Layer configuration
60
+ attn_layer_idx: List[int] = field(default_factory=list)
61
+ attn_cfg: Dict[str, Any] = field(default_factory=dict)