syclient-sara 0.1.0__py3-none-any.whl
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.
- sara/__init__.py +175 -0
- sara/attention.py +177 -0
- sara/baselines/__init__.py +277 -0
- sara/baselines/gla_ref.py +351 -0
- sara/baselines/mamba2_ref.py +385 -0
- sara/baselines/transformer_baseline.py +275 -0
- sara/blocks.py +194 -0
- sara/cache.py +187 -0
- sara/cli/__init__.py +33 -0
- sara/cli/bench.py +458 -0
- sara/config.py +159 -0
- sara/configuration_sara.py +284 -0
- sara/connectome.py +2148 -0
- sara/core/__init__.py +31 -0
- sara/core/config.py +93 -0
- sara/core/modeling_sara.py +1238 -0
- sara/core/tokenizer_sara.py +397 -0
- sara/data/__init__.py +39 -0
- sara/data/dataset.py +414 -0
- sara/data/prepare.py +297 -0
- sara/data/synthetic.py +277 -0
- sara/data/tokenizer.py +253 -0
- sara/data/train_tokenizer.py +103 -0
- sara/diagnostics/__init__.py +23 -0
- sara/diagnostics/benchmark_architectures.py +1136 -0
- sara/diagnostics/verify_sara_brain.py +875 -0
- sara/engine/__init__.py +34 -0
- sara/engine/generate_with_thinking.py +62 -0
- sara/engine/train_mag1.py +511 -0
- sara/generate.py +250 -0
- sara/horizon/__init__.py +21 -0
- sara/horizon/config.py +146 -0
- sara/horizon/esl.py +260 -0
- sara/horizon/gaspo.py +406 -0
- sara/lobes/__init__.py +37 -0
- sara/lobes/basal_ganglia.py +404 -0
- sara/lobes/curiosity_engine.py +379 -0
- sara/lobes/metacognitive_lobe.py +538 -0
- sara/lobes/predictive_cortex.py +484 -0
- sara/lobes/sleep_consolidator.py +563 -0
- sara/mag/__init__.py +60 -0
- sara/mag/blocks.py +473 -0
- sara/mag/config.py +374 -0
- sara/mag/delta_rule.py +414 -0
- sara/mag/episodic_memory.py +321 -0
- sara/mag/guard.py +340 -0
- sara/mag/model.py +1130 -0
- sara/mag/vault.py +366 -0
- sara/mixer.py +864 -0
- sara/modeling_sara.py +831 -0
- sara/nervous_system/__init__.py +25 -0
- sara/nervous_system/amygdala_shield.py +534 -0
- sara/nervous_system/synaptic_bus.py +740 -0
- sara/nervous_system/temporal_clock.py +375 -0
- sara/scan.py +434 -0
- sara/state.py +207 -0
- sara/train/__init__.py +19 -0
- sara/train/config.py +157 -0
- sara/train/evaluator.py +140 -0
- sara/train/trainer.py +594 -0
- sara/utils.py +137 -0
- sara/vpu2.py +195 -0
- syclient_sara-0.1.0.dist-info/METADATA +214 -0
- syclient_sara-0.1.0.dist-info/RECORD +68 -0
- syclient_sara-0.1.0.dist-info/WHEEL +5 -0
- syclient_sara-0.1.0.dist-info/entry_points.txt +5 -0
- syclient_sara-0.1.0.dist-info/licenses/LICENSE +220 -0
- syclient_sara-0.1.0.dist-info/top_level.txt +1 -0
sara/__init__.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""SARA — Unified Sara Artificial Brain & Syclient Associative Recall Architecture.
|
|
2
|
+
|
|
3
|
+
This package exposes the verified Sara-Brain v1 core, 9 synaptic/cognitive
|
|
4
|
+
nervous-system & lobe modules, the unified ``SaraConnectome``, the thinking
|
|
5
|
+
generation & MAG1 training engine, and CLI diagnostics tools, while preserving
|
|
6
|
+
backward-compatible access to the SARA SSM architecture SDK.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import importlib
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from sara.connectome import (
|
|
15
|
+
CompiledStepRunner,
|
|
16
|
+
ConnectomeOutput,
|
|
17
|
+
ConnectomeState,
|
|
18
|
+
SaraConnectome,
|
|
19
|
+
)
|
|
20
|
+
from sara.core.config import SaraBrainConfig
|
|
21
|
+
from sara.core.modeling_sara import (
|
|
22
|
+
HippocampalSelectiveCore,
|
|
23
|
+
InternalVerifierHead,
|
|
24
|
+
PrefrontalThinkingLoop,
|
|
25
|
+
RMSNorm,
|
|
26
|
+
SaraBrainBlock,
|
|
27
|
+
SaraBrainForCausalLM,
|
|
28
|
+
SaraBrainModel,
|
|
29
|
+
SaraBrainOutput,
|
|
30
|
+
SwiGLUFFN,
|
|
31
|
+
SynapticFastWeights,
|
|
32
|
+
)
|
|
33
|
+
from sara.core.tokenizer_sara import SaraMathTokenizer
|
|
34
|
+
from sara.engine.generate_with_thinking import generate_with_thinking
|
|
35
|
+
from sara.lobes import (
|
|
36
|
+
BasalGangliaLobe,
|
|
37
|
+
BasalGangliaOutput,
|
|
38
|
+
CognitiveAction,
|
|
39
|
+
CuriosityOutput,
|
|
40
|
+
IntrinsicCuriosityLobe,
|
|
41
|
+
MetacognitiveLobe,
|
|
42
|
+
MetacognitiveOutput,
|
|
43
|
+
PredictiveCortexLobe,
|
|
44
|
+
PredictiveCortexOutput,
|
|
45
|
+
SleepConsolidatorLobe,
|
|
46
|
+
SleepCycleReport,
|
|
47
|
+
)
|
|
48
|
+
from sara.nervous_system import (
|
|
49
|
+
AmygdalaHomeostaticShield,
|
|
50
|
+
BusRMSNorm,
|
|
51
|
+
CircadianTemporalClock,
|
|
52
|
+
NeuromodulatorBus,
|
|
53
|
+
ShieldOutput,
|
|
54
|
+
SynapticPacket,
|
|
55
|
+
TemporalClockOutput,
|
|
56
|
+
)
|
|
57
|
+
from sara.vpu2 import Vpu2PatchReport, patch_vpu2, vpu2_backend
|
|
58
|
+
|
|
59
|
+
__version__ = "0.1.0"
|
|
60
|
+
__author__ = "Syclient Labs"
|
|
61
|
+
|
|
62
|
+
_LEGACY_SSM_EXPORTS: dict[str, tuple[str, str]] = {
|
|
63
|
+
"SaraConfig": ("sara.config", "SaraConfig"),
|
|
64
|
+
"SaraLMConfig": ("sara.configuration_sara", "SaraLMConfig"),
|
|
65
|
+
"SaraMixer": ("sara.mixer", "SaraMixer"),
|
|
66
|
+
"SaraBlock": ("sara.blocks", "SaraBlock"),
|
|
67
|
+
"SaraSwiGLUMLP": ("sara.blocks", "SaraSwiGLUMLP"),
|
|
68
|
+
"SaraLocalAttention": ("sara.attention", "SaraLocalAttention"),
|
|
69
|
+
"SaraState": ("sara.state", "SaraState"),
|
|
70
|
+
"LocalAttnState": ("sara.state", "LocalAttnState"),
|
|
71
|
+
"SaraCache": ("sara.cache", "SaraCache"),
|
|
72
|
+
"SaraPreTrainedModel": ("sara.modeling_sara", "SaraPreTrainedModel"),
|
|
73
|
+
"SaraModel": ("sara.modeling_sara", "SaraModel"),
|
|
74
|
+
"SaraForCausalLM": ("sara.modeling_sara", "SaraForCausalLM"),
|
|
75
|
+
"SaraModelOutput": ("sara.modeling_sara", "SaraModelOutput"),
|
|
76
|
+
"SaraCausalLMOutput": ("sara.modeling_sara", "SaraCausalLMOutput"),
|
|
77
|
+
"validate_no_left_padding": ("sara.modeling_sara", "validate_no_left_padding"),
|
|
78
|
+
"generate": ("sara.generate", "generate"),
|
|
79
|
+
"ssm_scan_chunkwise": ("sara.scan", "ssm_scan_chunkwise"),
|
|
80
|
+
"ssm_scan_reference": ("sara.scan", "ssm_scan_reference"),
|
|
81
|
+
"ssm_scan_delta": ("sara.scan", "ssm_scan_delta"),
|
|
82
|
+
"compute_rotation_powers": ("sara.scan", "compute_rotation_powers"),
|
|
83
|
+
"build_block_diagonal": ("sara.utils", "build_block_diagonal"),
|
|
84
|
+
"cayley": ("sara.utils", "cayley"),
|
|
85
|
+
"init_half_life_bias": ("sara.utils", "init_half_life_bias"),
|
|
86
|
+
"inv_softplus": ("sara.utils", "inv_softplus"),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def __getattr__(name: str) -> Any:
|
|
91
|
+
if name in _LEGACY_SSM_EXPORTS:
|
|
92
|
+
module_path, attr_name = _LEGACY_SSM_EXPORTS[name]
|
|
93
|
+
module = importlib.import_module(module_path)
|
|
94
|
+
value = getattr(module, attr_name)
|
|
95
|
+
globals()[name] = value
|
|
96
|
+
return value
|
|
97
|
+
raise AttributeError(f"module 'sara' has no attribute {name!r}")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def __dir__() -> list[str]:
|
|
101
|
+
return sorted(set(__all__) | set(_LEGACY_SSM_EXPORTS))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
__all__ = [
|
|
105
|
+
"__author__",
|
|
106
|
+
"__version__",
|
|
107
|
+
# Sara Artificial Brain Core
|
|
108
|
+
"SaraBrainConfig",
|
|
109
|
+
"SaraBrainForCausalLM",
|
|
110
|
+
"SaraBrainModel",
|
|
111
|
+
"SaraBrainOutput",
|
|
112
|
+
"SaraMathTokenizer",
|
|
113
|
+
"RMSNorm",
|
|
114
|
+
"SwiGLUFFN",
|
|
115
|
+
"HippocampalSelectiveCore",
|
|
116
|
+
"SynapticFastWeights",
|
|
117
|
+
"InternalVerifierHead",
|
|
118
|
+
"PrefrontalThinkingLoop",
|
|
119
|
+
"SaraBrainBlock",
|
|
120
|
+
# Connectome & Engine
|
|
121
|
+
"SaraConnectome",
|
|
122
|
+
"ConnectomeState",
|
|
123
|
+
"ConnectomeOutput",
|
|
124
|
+
"CompiledStepRunner",
|
|
125
|
+
"generate_with_thinking",
|
|
126
|
+
# Public VPU-2 open-core runtime API
|
|
127
|
+
"patch_vpu2",
|
|
128
|
+
"vpu2_backend",
|
|
129
|
+
"Vpu2PatchReport",
|
|
130
|
+
# Nervous System
|
|
131
|
+
"SynapticPacket",
|
|
132
|
+
"BusRMSNorm",
|
|
133
|
+
"NeuromodulatorBus",
|
|
134
|
+
"CircadianTemporalClock",
|
|
135
|
+
"TemporalClockOutput",
|
|
136
|
+
"AmygdalaHomeostaticShield",
|
|
137
|
+
"ShieldOutput",
|
|
138
|
+
# Cognitive Lobes
|
|
139
|
+
"CognitiveAction",
|
|
140
|
+
"BasalGangliaLobe",
|
|
141
|
+
"BasalGangliaOutput",
|
|
142
|
+
"IntrinsicCuriosityLobe",
|
|
143
|
+
"CuriosityOutput",
|
|
144
|
+
"MetacognitiveLobe",
|
|
145
|
+
"MetacognitiveOutput",
|
|
146
|
+
"PredictiveCortexLobe",
|
|
147
|
+
"PredictiveCortexOutput",
|
|
148
|
+
"SleepConsolidatorLobe",
|
|
149
|
+
"SleepCycleReport",
|
|
150
|
+
# Legacy SARA SSM SDK (lazy-resolved via __getattr__)
|
|
151
|
+
"SaraConfig",
|
|
152
|
+
"SaraLMConfig",
|
|
153
|
+
"SaraMixer",
|
|
154
|
+
"SaraBlock",
|
|
155
|
+
"SaraSwiGLUMLP",
|
|
156
|
+
"SaraLocalAttention",
|
|
157
|
+
"SaraState",
|
|
158
|
+
"LocalAttnState",
|
|
159
|
+
"SaraCache",
|
|
160
|
+
"SaraPreTrainedModel",
|
|
161
|
+
"SaraModel",
|
|
162
|
+
"SaraForCausalLM",
|
|
163
|
+
"SaraModelOutput",
|
|
164
|
+
"SaraCausalLMOutput",
|
|
165
|
+
"validate_no_left_padding",
|
|
166
|
+
"generate",
|
|
167
|
+
"ssm_scan_chunkwise",
|
|
168
|
+
"ssm_scan_reference",
|
|
169
|
+
"ssm_scan_delta",
|
|
170
|
+
"compute_rotation_powers",
|
|
171
|
+
"build_block_diagonal",
|
|
172
|
+
"cayley",
|
|
173
|
+
"init_half_life_bias",
|
|
174
|
+
"inv_softplus",
|
|
175
|
+
]
|
sara/attention.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Sliding-window causal local attention used by SARA's optional hybrid layers.
|
|
2
|
+
|
|
3
|
+
The branch is deliberately small and self-contained: a standard multi-head
|
|
4
|
+
scaled-dot-product attention with a *causal, window-limited* mask and an
|
|
5
|
+
$O(W)$ fixed-size KV cache, so a hybrid `SaraBlock` keeps the same
|
|
6
|
+
prefill/decode semantics as the pure-SSM blocks (`SaraCache` compatible).
|
|
7
|
+
|
|
8
|
+
For a query at absolute position `t` and a key at absolute position `s`, the
|
|
9
|
+
attention weight is allowed only when
|
|
10
|
+
|
|
11
|
+
t - W < s <= t (causal, at most W tokens back; W = `local_attn_window`)
|
|
12
|
+
|
|
13
|
+
which is the standard sliding-window ("streaming") attention pattern.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import torch
|
|
19
|
+
import torch.nn as nn
|
|
20
|
+
import torch.nn.functional as F
|
|
21
|
+
|
|
22
|
+
from sara.configuration_sara import SaraLMConfig
|
|
23
|
+
from sara.state import LocalAttnState
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SaraLocalAttention(nn.Module):
|
|
27
|
+
"""Causal sliding-window multi-head attention with an O(W) KV cache.
|
|
28
|
+
|
|
29
|
+
Shapes:
|
|
30
|
+
Input `x`: (B, L, D_model)
|
|
31
|
+
Per-head Q/K/V: (B, H_attn, L, D_head) with H_attn = `config.n_heads`
|
|
32
|
+
Output: (B, L, D_model)
|
|
33
|
+
|
|
34
|
+
The module exposes both a sequence path (`forward`, used for training and
|
|
35
|
+
prefill) and a single-token path (`step`), and both update the same
|
|
36
|
+
`LocalAttnState` ring buffer, so `generate()` stays exact.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, config: SaraLMConfig) -> None:
|
|
40
|
+
"""Initialize projections from a `SaraLMConfig`.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
config: `SaraLMConfig` providing `d_model`, `n_heads` and
|
|
44
|
+
`local_attn_window`.
|
|
45
|
+
|
|
46
|
+
Raises:
|
|
47
|
+
ValueError: If `d_model` is not divisible by `n_heads`.
|
|
48
|
+
"""
|
|
49
|
+
super().__init__()
|
|
50
|
+
if config.d_model % config.n_heads != 0:
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"d_model ({config.d_model}) must be divisible by n_heads "
|
|
53
|
+
f"({config.n_heads}) for hybrid local attention"
|
|
54
|
+
)
|
|
55
|
+
self.d_model = int(config.d_model)
|
|
56
|
+
self.n_heads = int(config.n_heads)
|
|
57
|
+
self.d_head = self.d_model // self.n_heads
|
|
58
|
+
self.window = int(config.local_attn_window)
|
|
59
|
+
|
|
60
|
+
self.q_proj = nn.Linear(self.d_model, self.d_model, bias=False)
|
|
61
|
+
self.k_proj = nn.Linear(self.d_model, self.d_model, bias=False)
|
|
62
|
+
self.v_proj = nn.Linear(self.d_model, self.d_model, bias=False)
|
|
63
|
+
self.out_proj = nn.Linear(self.d_model, self.d_model, bias=False)
|
|
64
|
+
# Residual output projection: scaled by 1 / sqrt(2 * n_layers) in _init_weights.
|
|
65
|
+
self.out_proj._sara_residual_scale = True # type: ignore[attr-defined]
|
|
66
|
+
|
|
67
|
+
def _split_heads(self, tensor: torch.Tensor, batch_size: int, seq_len: int) -> torch.Tensor:
|
|
68
|
+
"""(B, L, D) -> (B, H, L, P)."""
|
|
69
|
+
return tensor.view(batch_size, seq_len, self.n_heads, self.d_head).transpose(1, 2)
|
|
70
|
+
|
|
71
|
+
def _merge_heads(self, tensor: torch.Tensor, batch_size: int, seq_len: int) -> torch.Tensor:
|
|
72
|
+
"""(B, H, L, P) -> (B, L, D)."""
|
|
73
|
+
return tensor.transpose(1, 2).reshape(batch_size, seq_len, self.d_model)
|
|
74
|
+
|
|
75
|
+
@staticmethod
|
|
76
|
+
def _window_mask(
|
|
77
|
+
num_keys: int, num_queries: int, window: int, device: torch.device
|
|
78
|
+
) -> torch.Tensor:
|
|
79
|
+
"""Build the (L_q, L_k) boolean causal sliding-window mask.
|
|
80
|
+
|
|
81
|
+
The last `num_queries` key slots are the current tokens; earlier slots are
|
|
82
|
+
cached history. `True` marks keys a query may attend to.
|
|
83
|
+
"""
|
|
84
|
+
first_query_pos = num_keys - num_queries
|
|
85
|
+
query_pos = torch.arange(
|
|
86
|
+
first_query_pos, first_query_pos + num_queries, device=device
|
|
87
|
+
)
|
|
88
|
+
key_pos = torch.arange(num_keys, device=device)
|
|
89
|
+
return (key_pos.unsqueeze(0) <= query_pos.unsqueeze(1)) & (
|
|
90
|
+
key_pos.unsqueeze(0) > (query_pos.unsqueeze(1) - window)
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def _trim(self, cache: torch.Tensor) -> torch.Tensor:
|
|
94
|
+
"""Keep the newest `window` slots, left-padding with zeros if necessary."""
|
|
95
|
+
trimmed = cache[:, :, -self.window :]
|
|
96
|
+
missing = self.window - trimmed.shape[2]
|
|
97
|
+
if missing > 0:
|
|
98
|
+
trimmed = F.pad(trimmed, (0, 0, missing, 0))
|
|
99
|
+
return trimmed
|
|
100
|
+
|
|
101
|
+
def forward(
|
|
102
|
+
self,
|
|
103
|
+
x: torch.Tensor,
|
|
104
|
+
state: LocalAttnState | None = None,
|
|
105
|
+
return_state: bool = False,
|
|
106
|
+
) -> torch.Tensor | tuple[torch.Tensor, LocalAttnState]:
|
|
107
|
+
"""Run causal sliding-window attention over a sequence (or a single step).
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
x: Input hidden states of shape (B, L, D_model).
|
|
111
|
+
state: Optional incoming `LocalAttnState` with the cached window.
|
|
112
|
+
return_state: If True, returns `(y, new_state)`.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
Output of shape (B, L, D_model), or `(y, new_state)` when `return_state`.
|
|
116
|
+
"""
|
|
117
|
+
if x.ndim != 3 or x.shape[-1] != self.d_model:
|
|
118
|
+
raise ValueError(
|
|
119
|
+
f"SaraLocalAttention expects (B, L, {self.d_model}), got {tuple(x.shape)}"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
batch_size, seq_len, _ = x.shape
|
|
123
|
+
q = self._split_heads(self.q_proj(x), batch_size, seq_len)
|
|
124
|
+
k = self._split_heads(self.k_proj(x), batch_size, seq_len)
|
|
125
|
+
v = self._split_heads(self.v_proj(x), batch_size, seq_len)
|
|
126
|
+
|
|
127
|
+
filled = int(state.filled) if state is not None else 0
|
|
128
|
+
filled = max(0, min(filled, self.window))
|
|
129
|
+
if state is not None and filled > 0:
|
|
130
|
+
k_all = torch.cat([state.k[:, :, self.window - filled :], k], dim=2)
|
|
131
|
+
v_all = torch.cat([state.v[:, :, self.window - filled :], v], dim=2)
|
|
132
|
+
else:
|
|
133
|
+
k_all, v_all = k, v
|
|
134
|
+
|
|
135
|
+
num_keys = k_all.shape[2]
|
|
136
|
+
mask = self._window_mask(num_keys, seq_len, self.window, x.device)
|
|
137
|
+
|
|
138
|
+
attended = F.scaled_dot_product_attention(
|
|
139
|
+
q,
|
|
140
|
+
k_all,
|
|
141
|
+
v_all,
|
|
142
|
+
attn_mask=mask,
|
|
143
|
+
is_causal=False,
|
|
144
|
+
dropout_p=0.0,
|
|
145
|
+
) # (B, H, L, P)
|
|
146
|
+
y = self.out_proj(self._merge_heads(attended, batch_size, seq_len))
|
|
147
|
+
|
|
148
|
+
new_state = LocalAttnState(
|
|
149
|
+
k=self._trim(k_all),
|
|
150
|
+
v=self._trim(v_all),
|
|
151
|
+
filled=min(self.window, num_keys),
|
|
152
|
+
)
|
|
153
|
+
if return_state:
|
|
154
|
+
return y, new_state
|
|
155
|
+
return y
|
|
156
|
+
|
|
157
|
+
def step(
|
|
158
|
+
self, x_t: torch.Tensor, state: LocalAttnState | None = None
|
|
159
|
+
) -> tuple[torch.Tensor, LocalAttnState]:
|
|
160
|
+
"""Run a single-token step, updating the sliding-window KV cache.
|
|
161
|
+
|
|
162
|
+
Args:
|
|
163
|
+
x_t: Single-token input of shape (B, D_model).
|
|
164
|
+
state: Optional incoming `LocalAttnState`.
|
|
165
|
+
|
|
166
|
+
Returns:
|
|
167
|
+
Tuple `(y_t, new_state)` with `y_t` of shape (B, D_model).
|
|
168
|
+
"""
|
|
169
|
+
if x_t.ndim != 2 or x_t.shape[-1] != self.d_model:
|
|
170
|
+
raise ValueError(
|
|
171
|
+
f"SaraLocalAttention.step expects (B, {self.d_model}), got {tuple(x_t.shape)}"
|
|
172
|
+
)
|
|
173
|
+
y, new_state = self.forward(x_t.unsqueeze(1), state=state, return_state=True)
|
|
174
|
+
return y[:, 0, :], new_state
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
__all__ = ["SaraLocalAttention"]
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
"""Baselines for SARA: Mamba-2 reference, decoder-only Transformer, and parameter/state matching utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from typing import Any, Literal, Sequence
|
|
7
|
+
import torch
|
|
8
|
+
import torch.nn as nn
|
|
9
|
+
|
|
10
|
+
from sara.baselines.mamba2_ref import (
|
|
11
|
+
Mamba2Block,
|
|
12
|
+
Mamba2Config,
|
|
13
|
+
Mamba2ForCausalLM,
|
|
14
|
+
Mamba2Mixer,
|
|
15
|
+
Mamba2State,
|
|
16
|
+
count_params as mamba2_count_params,
|
|
17
|
+
mamba2_state_bytes,
|
|
18
|
+
)
|
|
19
|
+
from sara.baselines.gla_ref import (
|
|
20
|
+
GLABlock,
|
|
21
|
+
GLAConfig,
|
|
22
|
+
GLAForCausalLM,
|
|
23
|
+
GLAMixer,
|
|
24
|
+
GLAOutput,
|
|
25
|
+
gla_state_bytes,
|
|
26
|
+
)
|
|
27
|
+
from sara.baselines.transformer_baseline import (
|
|
28
|
+
CausalSelfAttention,
|
|
29
|
+
TransformerBlock,
|
|
30
|
+
TransformerConfig,
|
|
31
|
+
TransformerForCausalLM,
|
|
32
|
+
count_params as transformer_count_params,
|
|
33
|
+
transformer_state_bytes,
|
|
34
|
+
)
|
|
35
|
+
from sara.cache import SaraCache
|
|
36
|
+
from sara.configuration_sara import SaraLMConfig
|
|
37
|
+
from sara.modeling_sara import SaraForCausalLM
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def count_params(model: nn.Module) -> int:
|
|
41
|
+
"""Return total trainable parameter count."""
|
|
42
|
+
return sum(p.numel() for p in model.parameters() if p.requires_grad)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def state_bytes(model: nn.Module, seq_len: int = 128, dtype_bytes: int = 4) -> int:
|
|
46
|
+
"""Calculate inference state memory in bytes held per sequence at sequence length `seq_len`.
|
|
47
|
+
|
|
48
|
+
Accounting:
|
|
49
|
+
- SARA: Fixed O(1) recurrent state across all layers in float32.
|
|
50
|
+
state_bytes = n_layers * dtype_bytes * (2 * H * (nb * k) * P + D_inner * (d_conv - 1)).
|
|
51
|
+
- Mamba-2: Fixed O(1) recurrent state across all layers in float32.
|
|
52
|
+
state_bytes = n_layers * dtype_bytes * (H * d_state * P + D_inner * (d_conv - 1)).
|
|
53
|
+
- Transformer: Linear O(L) KV cache across all layers in float32.
|
|
54
|
+
state_bytes(L) = n_layers * dtype_bytes * (2 * L * H * P).
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
model: Model instance (SaraForCausalLM, Mamba2ForCausalLM, or TransformerForCausalLM).
|
|
58
|
+
seq_len: Sequence length L (relevant for Transformer KV cache).
|
|
59
|
+
dtype_bytes: Bytes per element (default 4 for float32).
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
Exact memory held in bytes per sequence.
|
|
63
|
+
"""
|
|
64
|
+
if isinstance(model, SaraForCausalLM):
|
|
65
|
+
cfg = model.config
|
|
66
|
+
p = cfg.d_head
|
|
67
|
+
h = cfg.n_heads
|
|
68
|
+
n = cfg.nb * cfg.k
|
|
69
|
+
d_inner = getattr(cfg, "d_inner", h * p)
|
|
70
|
+
d_conv = cfg.d_conv
|
|
71
|
+
per_layer = (2 * h * n * p) + (d_inner * (d_conv - 1))
|
|
72
|
+
total = cfg.n_layers * per_layer * dtype_bytes
|
|
73
|
+
# Hybrid local-attention layers additionally hold an O(W) fixed KV window.
|
|
74
|
+
hybrid_layers = tuple(getattr(cfg, "hybrid_local_attn_layers", ()) or ())
|
|
75
|
+
if hybrid_layers:
|
|
76
|
+
window = int(getattr(cfg, "local_attn_window", 0))
|
|
77
|
+
attn_head_dim = cfg.d_model // cfg.n_heads
|
|
78
|
+
total += len(hybrid_layers) * 2 * cfg.n_heads * window * attn_head_dim * dtype_bytes
|
|
79
|
+
return int(total)
|
|
80
|
+
|
|
81
|
+
if isinstance(model, Mamba2ForCausalLM):
|
|
82
|
+
return mamba2_state_bytes(model, seq_len=seq_len, dtype_bytes=dtype_bytes)
|
|
83
|
+
|
|
84
|
+
if isinstance(model, GLAForCausalLM):
|
|
85
|
+
return gla_state_bytes(model, seq_len=seq_len, dtype_bytes=dtype_bytes)
|
|
86
|
+
|
|
87
|
+
if isinstance(model, TransformerForCausalLM):
|
|
88
|
+
return transformer_state_bytes(model, seq_len=seq_len, dtype_bytes=dtype_bytes)
|
|
89
|
+
|
|
90
|
+
raise TypeError(f"Unsupported model type for state_bytes: {type(model).__name__}")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def match_parameters(
|
|
94
|
+
sara_model: SaraForCausalLM,
|
|
95
|
+
baseline_type: Literal["mamba2", "transformer"],
|
|
96
|
+
tolerance: float = 0.03,
|
|
97
|
+
) -> nn.Module:
|
|
98
|
+
"""Instantiate a baseline model matching total parameter count of `sara_model` within `tolerance`.
|
|
99
|
+
|
|
100
|
+
Searches across candidate `d_model` and `mlp_ratio` adjustments while keeping
|
|
101
|
+
`n_layers`, `vocab_size`, and attention head divisibility valid.
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
sara_model: Reference `SaraForCausalLM` model.
|
|
105
|
+
baseline_type: `'mamba2'` or `'transformer'`.
|
|
106
|
+
tolerance: Maximum relative parameter discrepancy (default 0.03 = 3%).
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
Parameter-matched baseline model instance.
|
|
110
|
+
"""
|
|
111
|
+
target_params = count_params(sara_model)
|
|
112
|
+
sara_cfg = sara_model.config
|
|
113
|
+
|
|
114
|
+
best_model: nn.Module | None = None
|
|
115
|
+
best_diff: float = float("inf")
|
|
116
|
+
|
|
117
|
+
if baseline_type == "mamba2":
|
|
118
|
+
# Candidate search for Mamba-2: match state_bytes to SARA by setting d_state ~ 2 * (nb * k)
|
|
119
|
+
target_d_state = 2 * (sara_cfg.nb * sara_cfg.k)
|
|
120
|
+
step_h = sara_cfg.n_heads
|
|
121
|
+
base_dm = sara_cfg.d_model
|
|
122
|
+
candidates_d_model = sorted(list({
|
|
123
|
+
d for d in [
|
|
124
|
+
base_dm, base_dm - 2 * step_h, base_dm - step_h,
|
|
125
|
+
base_dm + step_h, base_dm + 2 * step_h, base_dm + 4 * step_h,
|
|
126
|
+
base_dm + 6 * step_h
|
|
127
|
+
] if d > 0 and d % step_h == 0
|
|
128
|
+
}))
|
|
129
|
+
candidates_mlp_ratio = [sara_cfg.mlp_ratio, 2.0, 2.2, 2.4, 2.6666666666666665, 2.8, 3.0, 3.2]
|
|
130
|
+
|
|
131
|
+
for d_m in candidates_d_model:
|
|
132
|
+
for r in candidates_mlp_ratio:
|
|
133
|
+
cfg = Mamba2Config(
|
|
134
|
+
d_model=d_m,
|
|
135
|
+
n_heads=sara_cfg.n_heads,
|
|
136
|
+
d_state=target_d_state,
|
|
137
|
+
d_conv=sara_cfg.d_conv,
|
|
138
|
+
vocab_size=sara_cfg.vocab_size,
|
|
139
|
+
n_layers=sara_cfg.n_layers,
|
|
140
|
+
use_mlp=sara_cfg.use_mlp,
|
|
141
|
+
mlp_ratio=r,
|
|
142
|
+
rms_norm_eps=sara_cfg.rms_norm_eps,
|
|
143
|
+
tie_word_embeddings=sara_cfg.tie_word_embeddings,
|
|
144
|
+
)
|
|
145
|
+
cand = Mamba2ForCausalLM(cfg)
|
|
146
|
+
p = count_params(cand)
|
|
147
|
+
rel_diff = abs(p - target_params) / target_params
|
|
148
|
+
if rel_diff < best_diff:
|
|
149
|
+
best_diff = rel_diff
|
|
150
|
+
best_model = cand
|
|
151
|
+
if rel_diff <= tolerance:
|
|
152
|
+
return cand
|
|
153
|
+
|
|
154
|
+
elif baseline_type == "transformer":
|
|
155
|
+
step_h = sara_cfg.n_heads
|
|
156
|
+
base_dm = sara_cfg.d_model
|
|
157
|
+
candidates_d_model = sorted(list({
|
|
158
|
+
d for d in [
|
|
159
|
+
base_dm, base_dm - 2 * step_h, base_dm - step_h,
|
|
160
|
+
base_dm + step_h, base_dm + 2 * step_h, base_dm + 3 * step_h,
|
|
161
|
+
base_dm + 4 * step_h, base_dm + 6 * step_h, base_dm + 8 * step_h,
|
|
162
|
+
base_dm + 10 * step_h, base_dm + 12 * step_h
|
|
163
|
+
] if d > 0 and d % step_h == 0
|
|
164
|
+
}))
|
|
165
|
+
candidates_mlp_ratio = [sara_cfg.mlp_ratio, 2.0, 2.2, 2.4, 2.6666666666666665, 2.8, 3.0, 3.2]
|
|
166
|
+
|
|
167
|
+
for d_m in candidates_d_model:
|
|
168
|
+
for r in candidates_mlp_ratio:
|
|
169
|
+
cfg = TransformerConfig(
|
|
170
|
+
d_model=d_m,
|
|
171
|
+
n_heads=sara_cfg.n_heads,
|
|
172
|
+
vocab_size=sara_cfg.vocab_size,
|
|
173
|
+
n_layers=sara_cfg.n_layers,
|
|
174
|
+
use_mlp=sara_cfg.use_mlp,
|
|
175
|
+
mlp_ratio=r,
|
|
176
|
+
rms_norm_eps=sara_cfg.rms_norm_eps,
|
|
177
|
+
tie_word_embeddings=sara_cfg.tie_word_embeddings,
|
|
178
|
+
)
|
|
179
|
+
cand = TransformerForCausalLM(cfg)
|
|
180
|
+
p = count_params(cand)
|
|
181
|
+
rel_diff = abs(p - target_params) / target_params
|
|
182
|
+
if rel_diff < best_diff:
|
|
183
|
+
best_diff = rel_diff
|
|
184
|
+
best_model = cand
|
|
185
|
+
if rel_diff <= tolerance:
|
|
186
|
+
return cand
|
|
187
|
+
else:
|
|
188
|
+
raise ValueError(f"Unknown baseline_type: {baseline_type}")
|
|
189
|
+
|
|
190
|
+
if best_model is None or best_diff > tolerance:
|
|
191
|
+
raise RuntimeError(
|
|
192
|
+
f"Could not match parameters for {baseline_type} within tolerance {tolerance:.1%}. "
|
|
193
|
+
f"Best relative difference was {best_diff:.2%} (target: {target_params:,}, "
|
|
194
|
+
f"candidate: {count_params(best_model) if best_model else 0:,})"
|
|
195
|
+
)
|
|
196
|
+
return best_model
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def match_gla_to_sara(
|
|
200
|
+
sara_model: SaraForCausalLM,
|
|
201
|
+
tolerance: float = 0.03,
|
|
202
|
+
mlp_ratio_candidates: Sequence[float] = (0.9, 1.5, 2.0, 2.4, 8.0 / 3.0, 3.2),
|
|
203
|
+
) -> GLAConfig:
|
|
204
|
+
"""Return a `GLAConfig` whose parameter count matches `sara_model` within `tolerance`.
|
|
205
|
+
|
|
206
|
+
The GLA state dimension is fixed to ``d_state = 2 * nb * k`` so that its O(1) state
|
|
207
|
+
bytes are **exactly** equal to SARA's dual-memory state, then the MLP width is chosen
|
|
208
|
+
to land the parameter count inside the tolerance.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
sara_model: Reference `SaraForCausalLM`.
|
|
212
|
+
tolerance: Maximum relative parameter discrepancy (default 3%).
|
|
213
|
+
mlp_ratio_candidates: MLP widths to try, in preference order.
|
|
214
|
+
|
|
215
|
+
Returns:
|
|
216
|
+
The best `GLAConfig` found.
|
|
217
|
+
|
|
218
|
+
Raises:
|
|
219
|
+
RuntimeError: If no candidate satisfies `tolerance`.
|
|
220
|
+
"""
|
|
221
|
+
cfg = sara_model.config
|
|
222
|
+
target = count_params(sara_model)
|
|
223
|
+
d_state = 2 * int(cfg.nb) * int(cfg.k)
|
|
224
|
+
best: tuple[float, GLAConfig | None] = (float("inf"), None)
|
|
225
|
+
|
|
226
|
+
for ratio in mlp_ratio_candidates:
|
|
227
|
+
candidate = GLAConfig(
|
|
228
|
+
vocab_size=cfg.vocab_size,
|
|
229
|
+
d_model=cfg.d_model,
|
|
230
|
+
expand=cfg.expand,
|
|
231
|
+
n_heads=cfg.n_heads,
|
|
232
|
+
d_state=d_state,
|
|
233
|
+
n_layers=cfg.n_layers,
|
|
234
|
+
d_conv=cfg.d_conv,
|
|
235
|
+
half_life_range=(float(cfg.working_half_life_range[0]), float(cfg.working_half_life_range[1])),
|
|
236
|
+
use_output_gate=True,
|
|
237
|
+
use_mlp=bool(cfg.use_mlp),
|
|
238
|
+
mlp_ratio=float(ratio),
|
|
239
|
+
rms_norm_eps=cfg.rms_norm_eps,
|
|
240
|
+
tie_word_embeddings=cfg.tie_word_embeddings,
|
|
241
|
+
)
|
|
242
|
+
params = count_params(GLAForCausalLM(candidate))
|
|
243
|
+
diff = abs(params - target) / target
|
|
244
|
+
if diff < best[0]:
|
|
245
|
+
best = (diff, candidate)
|
|
246
|
+
if diff <= tolerance:
|
|
247
|
+
return candidate
|
|
248
|
+
|
|
249
|
+
if best[1] is None or best[0] > tolerance:
|
|
250
|
+
raise RuntimeError(
|
|
251
|
+
f"Could not match GLA parameters to SARA within {tolerance:.1%} "
|
|
252
|
+
f"(best relative difference {best[0]:.2%})"
|
|
253
|
+
)
|
|
254
|
+
return best[1]
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
__all__ = [
|
|
258
|
+
"Mamba2Config",
|
|
259
|
+
"Mamba2Mixer",
|
|
260
|
+
"Mamba2Block",
|
|
261
|
+
"Mamba2ForCausalLM",
|
|
262
|
+
"Mamba2State",
|
|
263
|
+
"TransformerConfig",
|
|
264
|
+
"CausalSelfAttention",
|
|
265
|
+
"TransformerBlock",
|
|
266
|
+
"TransformerForCausalLM",
|
|
267
|
+
"GLAConfig",
|
|
268
|
+
"GLAMixer",
|
|
269
|
+
"GLABlock",
|
|
270
|
+
"GLAForCausalLM",
|
|
271
|
+
"GLAOutput",
|
|
272
|
+
"gla_state_bytes",
|
|
273
|
+
"count_params",
|
|
274
|
+
"state_bytes",
|
|
275
|
+
"match_parameters",
|
|
276
|
+
"match_gla_to_sara",
|
|
277
|
+
]
|